@utk09/ui-observability 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +114 -59
  3. package/dist/bus/bus.d.ts +10 -10
  4. package/dist/bus/links.d.ts +1 -1
  5. package/dist/bus-BTMuVkDk.js +378 -0
  6. package/dist/bus-BTMuVkDk.js.map +1 -0
  7. package/dist/bus-ChIXDAWD.cjs +2 -0
  8. package/dist/bus-ChIXDAWD.cjs.map +1 -0
  9. package/dist/capture/network.d.ts +2 -2
  10. package/dist/capture/types.d.ts +10 -10
  11. package/dist/capture/web-vitals.d.ts +7 -4
  12. package/dist/{constants-DVbpJ1tv.js → constants-0-YchbAL.js} +9 -8
  13. package/dist/constants-0-YchbAL.js.map +1 -0
  14. package/dist/constants-TUFcy95w.cjs +2 -0
  15. package/dist/constants-TUFcy95w.cjs.map +1 -0
  16. package/dist/constants.d.ts +55 -40
  17. package/dist/core/breadcrumbs.d.ts +14 -14
  18. package/dist/core/config.d.ts +5 -4
  19. package/dist/core/context.d.ts +2 -2
  20. package/dist/core/diagnostics.d.ts +10 -9
  21. package/dist/core/journey.d.ts +28 -22
  22. package/dist/core/logger.d.ts +29 -10
  23. package/dist/core/pipeline.d.ts +34 -29
  24. package/dist/core/record.d.ts +6 -6
  25. package/dist/core/runtime.d.ts +119 -35
  26. package/dist/core/sampling.d.ts +15 -16
  27. package/dist/core/sender.d.ts +58 -0
  28. package/dist/errors-DRXBRqvm.cjs +3 -0
  29. package/dist/errors-DRXBRqvm.cjs.map +1 -0
  30. package/dist/errors-Dwm2SzBa.js +76 -0
  31. package/dist/errors-Dwm2SzBa.js.map +1 -0
  32. package/dist/index.cjs +1 -3
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.ts +6 -5
  35. package/dist/index.js +476 -2247
  36. package/dist/index.js.map +1 -1
  37. package/dist/indexeddb-storage-B5dwq4hW.cjs +2 -0
  38. package/dist/indexeddb-storage-B5dwq4hW.cjs.map +1 -0
  39. package/dist/{indexeddb-storage-B6uqejZb.js → indexeddb-storage-DjY4Ml6t.js} +18 -22
  40. package/dist/indexeddb-storage-DjY4Ml6t.js.map +1 -0
  41. package/dist/interactions-DVom6eYn.cjs +2 -0
  42. package/dist/interactions-DVom6eYn.cjs.map +1 -0
  43. package/dist/interactions-DZmLu7l2.js +67 -0
  44. package/dist/interactions-DZmLu7l2.js.map +1 -0
  45. package/dist/models/batch.d.ts +12 -9
  46. package/dist/models/bus.d.ts +12 -13
  47. package/dist/models/config.d.ts +84 -49
  48. package/dist/models/log-record.d.ts +12 -10
  49. package/dist/models/serializer.d.ts +3 -2
  50. package/dist/models/storage.d.ts +2 -2
  51. package/dist/network-C4d2uw2Z.js +111 -0
  52. package/dist/network-C4d2uw2Z.js.map +1 -0
  53. package/dist/network-CuqWadNn.cjs +2 -0
  54. package/dist/network-CuqWadNn.cjs.map +1 -0
  55. package/dist/platform-CXio0W2n.cjs +2 -0
  56. package/dist/platform-CXio0W2n.cjs.map +1 -0
  57. package/dist/platform-CY8S3hUs.js +48 -0
  58. package/dist/platform-CY8S3hUs.js.map +1 -0
  59. package/dist/sampling-CEthcmEX.cjs +2 -0
  60. package/dist/sampling-CEthcmEX.cjs.map +1 -0
  61. package/dist/sampling-CJsI_24L.js +251 -0
  62. package/dist/sampling-CJsI_24L.js.map +1 -0
  63. package/dist/sender-ByFAkXVd.cjs +3 -0
  64. package/dist/sender-ByFAkXVd.cjs.map +1 -0
  65. package/dist/sender-dpvR_bHM.js +907 -0
  66. package/dist/sender-dpvR_bHM.js.map +1 -0
  67. package/dist/storage/emergency-queue.d.ts +2 -2
  68. package/dist/storage/factory.d.ts +2 -1
  69. package/dist/storage/idb-driver.d.ts +19 -19
  70. package/dist/storage/indexeddb-storage.d.ts +18 -17
  71. package/dist/storage/keys.d.ts +1 -1
  72. package/dist/storage/local-storage.d.ts +19 -18
  73. package/dist/storage/memory-storage.d.ts +12 -11
  74. package/dist/transport/compression.d.ts +2 -2
  75. package/dist/transport/errors.d.ts +8 -7
  76. package/dist/transport/exit-flush.d.ts +27 -24
  77. package/dist/transport/http-transport.d.ts +19 -10
  78. package/dist/transport/retry-engine.d.ts +33 -28
  79. package/dist/transport/serializers/ecs.d.ts +1 -1
  80. package/dist/transport/serializers/otlp.d.ts +1 -1
  81. package/dist/transport/serializers/select.d.ts +8 -0
  82. package/dist/unref-16maCyKA.js +8 -0
  83. package/dist/unref-16maCyKA.js.map +1 -0
  84. package/dist/unref-CU9Nyz_9.cjs +2 -0
  85. package/dist/unref-CU9Nyz_9.cjs.map +1 -0
  86. package/dist/utils/console.d.ts +11 -3
  87. package/dist/utils/identity.d.ts +53 -8
  88. package/dist/utils/lock.d.ts +4 -4
  89. package/dist/utils/platform.d.ts +5 -3
  90. package/dist/utils/sanitize.d.ts +5 -2
  91. package/dist/utils/sequence.d.ts +2 -2
  92. package/dist/utils/tracing.d.ts +14 -12
  93. package/dist/web-vitals-B2FYsEAU.cjs +2 -0
  94. package/dist/web-vitals-B2FYsEAU.cjs.map +1 -0
  95. package/dist/web-vitals-DHZ0yA_H.js +51 -0
  96. package/dist/web-vitals-DHZ0yA_H.js.map +1 -0
  97. package/package.json +21 -11
  98. package/dist/constants-DVbpJ1tv.js.map +0 -1
  99. package/dist/constants-tQpoTzkY.cjs +0 -2
  100. package/dist/constants-tQpoTzkY.cjs.map +0 -1
  101. package/dist/indexeddb-storage-B6uqejZb.js.map +0 -1
  102. package/dist/indexeddb-storage-CgT1GLYj.cjs +0 -2
  103. package/dist/indexeddb-storage-CgT1GLYj.cjs.map +0 -1
@@ -3,9 +3,18 @@ import type { LogLevel, LogRecord } from "./log-record";
3
3
  import type { LogSerializer } from "./serializer";
4
4
  /** Backing store for undelivered records. "auto" picks the best one the host supports. */
5
5
  export type StorageStrategy = "auto" | "indexeddb" | "localstorage" | "memory" | "none";
6
- /** What this context does with its records: `sender` delivers its own, `forwarder` hands them to another context, `auto` decides, `off` does neither. */
6
+ /** Selects where the library keeps session, tab and journey ids. "storage" uses browser storage. "memory" writes nothing. */
7
+ export type IdentityStrategy = "storage" | "memory";
8
+ /**
9
+ * What this context does with its records. `sender` delivers its own records.
10
+ * `forwarder` gives them to another context. `auto` selects a role at startup.
11
+ * `off` turns off the bus. The context then delivers its own records.
12
+ */
7
13
  export type BusMode = "auto" | "sender" | "forwarder" | "off";
8
- /** Structural type for the `web-vitals` package's metric shape, so this library has no hard dependency on the package. */
14
+ /**
15
+ * Structural type for the metric shape of the `web-vitals` package. With this type,
16
+ * the library has no hard dependency on the package.
17
+ */
9
18
  export interface WebVitalsMetric {
10
19
  /** Measurement value, in the metric's own unit. */
11
20
  value: number;
@@ -65,8 +74,8 @@ export interface OtelSpan {
65
74
  spanContext(): OtelSpanContext;
66
75
  }
67
76
  /**
68
- * The three `@opentelemetry/api` entry points this library uses, typed
69
- * structurally so the package stays an optional peer.
77
+ * The three `@opentelemetry/api` entry points that this library uses. The structural
78
+ * types keep the package an optional peer.
70
79
  */
71
80
  export interface OtelApi {
72
81
  /** Span lookup. */
@@ -81,7 +90,7 @@ export interface OtelApi {
81
90
  context: {
82
91
  /**
83
92
  * Reads the active context.
84
- * @returns Context, opaque to this library, understood by the propagator.
93
+ * @returns Context object that only the propagator reads.
85
94
  */
86
95
  active(): unknown;
87
96
  };
@@ -100,7 +109,7 @@ export interface OtelApi {
100
109
  * @returns A promise resolving to the module.
101
110
  */
102
111
  export type OtelLoader = () => Promise<OtelApi>;
103
- /** Sampling policy: which records survive. */
112
+ /** Sampling policy. It controls which records the library keeps. */
104
113
  export interface SamplingOptions {
105
114
  /**
106
115
  * Default fraction of records kept, 0 to 1.
@@ -108,7 +117,7 @@ export interface SamplingOptions {
108
117
  */
109
118
  defaultRate: number;
110
119
  /**
111
- * Per-namespace override, keyed by `app.namespace`. Most specific prefix wins.
120
+ * Rate override for each namespace, keyed by `app.namespace`. The most specific prefix applies.
112
121
  * @default {}
113
122
  */
114
123
  rates: Record<string, number>;
@@ -118,7 +127,7 @@ export interface SamplingOptions {
118
127
  */
119
128
  alwaysSampleTypes: string[];
120
129
  }
121
- /** Bus settings: how this context discovers, trusts, and messages the others. */
130
+ /** Bus settings. They control how this context finds, trusts, and sends messages to others. */
122
131
  export interface BusOptions {
123
132
  /**
124
133
  * This context's role.
@@ -126,20 +135,23 @@ export interface BusOptions {
126
135
  */
127
136
  mode: BusMode;
128
137
  /**
129
- * Origins allowed to send postMessage records to this document. Required for any document receiving them from a cross-origin iframe.
138
+ * Origins that can send postMessage records to this document.
139
+ * A document that gets records from a cross-origin iframe must list the iframe origin.
130
140
  * @default []
131
141
  */
132
142
  trustedOrigins: string[];
133
143
  /**
134
- * Which OpenFin context this is. Only the platform provider answers a
135
- * handshake, so setting this wrong makes every view send for itself.
136
- * "auto" treats the window whose name equals its application uuid as the
137
- * provider.
144
+ * Which OpenFin context this is. Only the platform provider answers a handshake.
145
+ * With an incorrect value, each view sends its own records. "auto" treats the
146
+ * window whose name equals its application uuid as the provider.
138
147
  * @default "auto"
139
148
  */
140
149
  openFinRole: "auto" | "provider" | "client";
141
150
  }
142
- /** What the library instruments automatically. Everything but errors and rejections is off by default. */
151
+ /**
152
+ * What the library instruments automatically. By default, only `errors` and `rejections`
153
+ * are on.
154
+ */
143
155
  export interface CaptureOptions {
144
156
  /**
145
157
  * Log uncaught errors from `window.onerror`.
@@ -157,7 +169,7 @@ export interface CaptureOptions {
157
169
  */
158
170
  resourceErrors: boolean;
159
171
  /**
160
- * Wrap `fetch` to log requests. The ingest endpoint itself is never logged.
172
+ * Wrap `fetch` to log requests. The library never logs requests to the ingest endpoint.
161
173
  * @default false
162
174
  */
163
175
  fetch: boolean;
@@ -177,23 +189,24 @@ export interface CaptureOptions {
177
189
  */
178
190
  navigation: boolean;
179
191
  /**
180
- * Report web vitals as metrics. Requires the `web-vitals` peer or `webVitalsLoader`.
192
+ * Report web vitals as metrics. This option requires `webVitalsLoader`.
181
193
  * @default false
182
194
  */
183
195
  webVitals: boolean;
184
196
  /**
185
197
  * Keep the query string and fragment on every URL the library records.
186
- * Off strips them from page URLs, request targets and failed resource URLs.
198
+ * When off, the library removes them from page URLs, request targets and failed resource URLs.
187
199
  * @default false
188
200
  */
189
201
  fullUrls: boolean;
190
202
  /**
191
- * URLs excluded from logging. The ingest endpoint is always included.
203
+ * URLs that the library does not log. The library always adds the ingest endpoint.
192
204
  * @default []
193
205
  */
194
206
  ignoreUrls: (string | RegExp)[];
195
207
  /**
196
- * Targets that receive a `traceparent` header. A catch-all breaks CORS on third-party endpoints.
208
+ * Targets that receive a `traceparent` header. A pattern that matches all URLs breaks
209
+ * CORS on third-party endpoints.
197
210
  * @default []
198
211
  */
199
212
  propagateTraceHeaderTo: (string | RegExp)[];
@@ -203,24 +216,34 @@ export interface CaptureOptions {
203
216
  */
204
217
  webVitalsLoader?: () => Promise<WebVitalsModule>;
205
218
  }
206
- /** Console mirroring. `false` is off, `true` mirrors from DEBUG, a level mirrors from that level up. */
219
+ /** Serializer option after resolution. A name stays a name. The transport selects the implementation. */
220
+ export type SerializerChoice = "otlp" | "ecs" | LogSerializer;
221
+ /**
222
+ * Console mirroring. `false` turns it off. `true` mirrors records at DEBUG and above.
223
+ * A level mirrors records at that level and above.
224
+ */
207
225
  export type ConsoleOption = boolean | LogLevel;
208
- /** Options passed to `configure()`. Only `endpoint` is required. */
226
+ /** Options passed to `configure()`. */
209
227
  export interface ObservabilityConfig {
210
- /** Ingest endpoint URL. Required. */
211
- endpoint: string;
212
228
  /**
213
- * Reported as `service.name`.
229
+ * Ingest endpoint URL. Set `null` for console-only mode.
230
+ * In console-only mode, the library sends nothing. It writes records to the console
231
+ * if you set `console`.
232
+ * If the key is missing or `""`, the library reports `config.invalid`.
233
+ */
234
+ endpoint?: string | null;
235
+ /**
236
+ * The library reports this value as `service.name`.
214
237
  * @default ""
215
238
  */
216
239
  serviceName?: string;
217
240
  /**
218
- * Reported as `service.version`.
241
+ * The library reports this value as `service.version`.
219
242
  * @default ""
220
243
  */
221
244
  serviceVersion?: string;
222
245
  /**
223
- * Reported as `deployment.environment`.
246
+ * The library reports this value as `deployment.environment`.
224
247
  * @default ""
225
248
  */
226
249
  environment?: string;
@@ -230,22 +253,24 @@ export interface ObservabilityConfig {
230
253
  */
231
254
  enabled?: boolean;
232
255
  /**
233
- * Min level logged.
256
+ * Minimum level that the library logs.
234
257
  * @default "INFO"
235
258
  */
236
259
  minLevel?: LogLevel;
237
260
  /**
238
- * Whether to gzip a payload past the compression threshold. Set "none" for an ingest endpoint that rejects gzip.
261
+ * Whether to gzip a payload that is larger than the compression threshold.
262
+ * Set "none" for an ingest endpoint that rejects gzip.
239
263
  * @default "gzip"
240
264
  */
241
265
  compression?: "gzip" | "none";
242
266
  /**
243
- * Wire format: a name, or a custom implementation.
267
+ * Payload format. Give a name or a custom implementation.
244
268
  * @default "otlp"
245
269
  */
246
- serializer?: "otlp" | "ecs" | LogSerializer;
270
+ serializer?: SerializerChoice;
247
271
  /**
248
- * Passed to `fetch`. Set "include" for an ingest endpoint that authenticates with cookies.
272
+ * The library passes this value to `fetch`. Set "include" for an ingest endpoint that
273
+ * authenticates with cookies.
249
274
  * @default "omit"
250
275
  */
251
276
  credentials?: RequestCredentials;
@@ -256,6 +281,14 @@ export interface ObservabilityConfig {
256
281
  * @default "auto"
257
282
  */
258
283
  storage?: StorageStrategy;
284
+ /**
285
+ * Selects where the library keeps session, tab and journey ids.
286
+ * Set "memory" to write no key to localStorage or sessionStorage.
287
+ * With "memory", each page load starts a new session.
288
+ * You cannot change this value after startup.
289
+ * @default "storage"
290
+ */
291
+ identity?: IdentityStrategy;
259
292
  /**
260
293
  * Sampling policy.
261
294
  * @see {@link SamplingOptions}
@@ -277,14 +310,14 @@ export interface ObservabilityConfig {
277
310
  */
278
311
  console?: ConsoleOption;
279
312
  /**
280
- * Supplies the `@opentelemetry/api` module. Omit it and the library imports
281
- * the package itself when it is installed.
313
+ * Loads the `@opentelemetry/api` module. Example: `() => import("@opentelemetry/api")`.
314
+ * If you do not set it, OTel is off.
282
315
  * @see {@link OtelLoader}
283
316
  */
284
317
  otelLoader?: OtelLoader;
285
318
  /**
286
- * Rewrites or drops a record before it's sent.
287
- * @param record The record about to be sent.
319
+ * Rewrites or drops a record before the library sends it.
320
+ * @param record The record that the library is about to send.
288
321
  * @returns The record to send, or `null` to drop it.
289
322
  */
290
323
  redact?: (record: LogRecord) => LogRecord | null;
@@ -294,26 +327,28 @@ export interface ObservabilityConfig {
294
327
  */
295
328
  onDiagnostic?: DiagnosticHandler;
296
329
  }
297
- /** Fully resolved config, held by the runtime. */
330
+ /** Fully resolved configuration that the runtime holds. */
298
331
  export interface ResolvedConfig {
299
- /** Ingest endpoint URL. */
300
- endpoint: string;
301
- /** Reported as `service.name`. */
332
+ /** Ingest endpoint URL, or null in console-only mode. */
333
+ endpoint: string | null;
334
+ /** The library reports this value as `service.name`. */
302
335
  serviceName: string;
303
- /** Reported as `service.version`. */
336
+ /** The library reports this value as `service.version`. */
304
337
  serviceVersion: string;
305
- /** Reported as `deployment.environment`. */
338
+ /** The library reports this value as `deployment.environment`. */
306
339
  environment: string;
307
340
  /** Master switch. False makes every log call a no-op. */
308
341
  enabled: boolean;
309
- /** Min level logged. */
342
+ /** Minimum level that the library logs. */
310
343
  minLevel: LogLevel;
311
- /** Whether to gzip a payload past the compression threshold. */
344
+ /** Whether to gzip a payload that is larger than the compression threshold. */
312
345
  compression: "gzip" | "none";
313
- /** Passed to `fetch`. */
346
+ /** The library passes this value to `fetch`. */
314
347
  credentials: RequestCredentials;
315
348
  /** Backing store for undelivered records. */
316
349
  storage: StorageStrategy;
350
+ /** Store for session, tab and journey ids. */
351
+ identity: IdentityStrategy;
317
352
  /**
318
353
  * Sampling policy.
319
354
  * @see {@link SamplingOptions}
@@ -329,17 +364,17 @@ export interface ResolvedConfig {
329
364
  * @see {@link CaptureOptions}
330
365
  */
331
366
  capture: CaptureOptions;
332
- /** Min level mirrored to the console, or null when mirroring is off. */
367
+ /** Minimum level that the library mirrors to the console, or null when mirroring is off. */
333
368
  console: LogLevel | null;
334
- /** Wire format implementation, resolved from a name or passed directly. */
335
- serializer: LogSerializer;
369
+ /** Payload format name, or a custom implementation. */
370
+ serializer: SerializerChoice;
336
371
  /** Extra request headers, or a function returning them. */
337
372
  headers?: ObservabilityConfig["headers"];
338
373
  /** Supplies the `@opentelemetry/api` module in place of importing it. */
339
374
  otelLoader?: OtelLoader;
340
375
  /**
341
- * Rewrites or drops a record before it's sent.
342
- * @param record The record about to be sent.
376
+ * Rewrites or drops a record before the library sends it.
377
+ * @param record The record that the library is about to send.
343
378
  * @returns The record to send, or `null` to drop it.
344
379
  */
345
380
  redact?: ObservabilityConfig["redact"];
@@ -8,20 +8,23 @@ export type LogLevel = "TRACE" | "DEBUG" | "INFO" | "WARN" | "ERROR" | "FATAL";
8
8
  export type LogType = "action" | "event" | "metric" | "system";
9
9
  /** Metric value type: level, running total, or distribution. */
10
10
  export type MetricType = "gauge" | "counter" | "histogram";
11
- /** Internal record shape, converted to wire format by a serializer. */
11
+ /** Internal record shape. A serializer converts it to the payload format. */
12
12
  export interface LogRecord {
13
13
  /**
14
14
  * Event time, nanoseconds since epoch, as a decimal string.
15
15
  * @see {@link nowUnixNano}
16
16
  */
17
17
  timeUnixNano: string;
18
- /** Time this library received the event, if different from `timeUnixNano` (e.g. on a forwarded record). */
18
+ /**
19
+ * Time when this library received the event, if it differs from `timeUnixNano`.
20
+ * For example, a forwarded record can have a different time.
21
+ */
19
22
  observedTimeUnixNano?: string;
20
23
  /** Distributed trace id. */
21
24
  traceId: string;
22
25
  /** Span id within the trace. */
23
26
  spanId: string;
24
- /** OpenTelemetry trace flags. Only the sampled bit is used. */
27
+ /** OpenTelemetry trace flags. The library uses only the sampled bit. */
25
28
  traceFlags: number;
26
29
  /** OpenTelemetry severity number for `severityText`. */
27
30
  severityNumber: number;
@@ -36,18 +39,17 @@ export interface LogRecord {
36
39
  }
37
40
  /**
38
41
  * Returns the current time as a Unix nanosecond timestamp.
39
- * Concatenates rather than multiplies: `Date.now() * 1e6` overflows
40
- * `Number.MAX_SAFE_INTEGER` and silently corrupts digits. Trailing zeros are
41
- * unknown precision, not real.
42
+ * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger
43
+ * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing
44
+ * zeros show unknown precision. They are not measured digits.
42
45
  * @returns Epoch timestamp in nanoseconds, as a decimal string.
43
46
  */
44
47
  export declare function nowUnixNano(): string;
45
48
  /**
46
49
  * Checks whether a value has the shape `LogRecord` requires.
47
- * Used to validate records arriving from another realm, since a malformed
48
- * one throws during serialization. `severityText` is checked as a string,
49
- * not a known level, so an unrecognised level from a newer version still
50
- * passes.
50
+ * Use it to validate records from another realm. A malformed record throws
51
+ * during serialization. The check accepts any string as `severityText`, not only
52
+ * a known level. Thus an unknown level from a newer version passes.
51
53
  * @param value The value to check.
52
54
  * @returns Whether `value` has the shape `LogRecord` requires.
53
55
  */
@@ -14,8 +14,9 @@ export interface LogSerializer {
14
14
  /** Serializer name used in configuration. */
15
15
  name: string;
16
16
  /**
17
- * Serializes a batch of records to wire-format bytes.
18
- * Called once per delivery attempt, not once per batch, so a retry re-encodes.
17
+ * Serializes a batch of records to payload bytes.
18
+ * The transport calls it one time for each delivery attempt, not one time for each batch.
19
+ * Thus each retry encodes the records again.
19
20
  * @param records Batch records, in log order.
20
21
  * @returns Serialized batch ready for transport.
21
22
  */
@@ -15,7 +15,7 @@ export interface StorageAdapter {
15
15
  */
16
16
  take(limit: number): Promise<LogBatch[]>;
17
17
  /**
18
- * Removes a batch by ID. Non-existent IDs resolve without error.
18
+ * Removes a batch by ID. A call with an unknown ID resolves without error.
19
19
  * @param id Batch identifier.
20
20
  */
21
21
  remove(id: string): Promise<void>;
@@ -52,7 +52,7 @@ export interface PruneResult {
52
52
  batches: number;
53
53
  /** Total records dropped within evicted batches. */
54
54
  records: number;
55
- /** Eviction reason that triggered the prune. If more than one rule fired, this is the last one. */
55
+ /** Eviction reason for the prune. If more than one rule applies, this is the last rule. */
56
56
  reason: "expired" | "over_capacity" | "quota";
57
57
  }
58
58
  /**
@@ -0,0 +1,111 @@
1
+ import { r as e } from "./platform-CY8S3hUs.js";
2
+ //#region src/capture/types.ts
3
+ function t(e, t) {
4
+ return t.some((t) => typeof t == "string" ? e.includes(t) : t.test(e));
5
+ }
6
+ //#endregion
7
+ //#region src/capture/network.ts
8
+ function n() {
9
+ return XMLHttpRequest.prototype;
10
+ }
11
+ var r = class {
12
+ ctx;
13
+ name = "network";
14
+ originalFetch = null;
15
+ originalOpen = null;
16
+ originalSend = null;
17
+ constructor(e) {
18
+ this.ctx = e;
19
+ }
20
+ install() {
21
+ this.ctx.config.capture.fetch && this.installFetch(), this.ctx.config.capture.xhr && this.installXhr();
22
+ }
23
+ uninstall() {
24
+ this.originalFetch &&= (globalThis.fetch = this.originalFetch, null), this.originalOpen &&= (n().open = this.originalOpen, null), this.originalSend &&= (n().send = this.originalSend, null);
25
+ }
26
+ ignored(e) {
27
+ return t(e, this.ctx.config.capture.ignoreUrls);
28
+ }
29
+ installFetch() {
30
+ if (typeof globalThis.fetch != "function" || this.originalFetch) return;
31
+ let e = globalThis.fetch.bind(globalThis);
32
+ this.originalFetch = globalThis.fetch;
33
+ let n = this.ctx, r = (e) => this.ignored(e), i = (e, t, n, r, i) => {
34
+ this.record(e, t, n, r, i);
35
+ };
36
+ globalThis.fetch = async function(a, o) {
37
+ let s = typeof a == "string" ? a : a instanceof URL ? a.href : a.url, c = (o?.method ?? (a instanceof Request ? a.method : "GET")).toUpperCase();
38
+ if (r(s)) return e(a, o);
39
+ let l = a, u = o;
40
+ if (t(s, n.config.capture.propagateTraceHeaderTo)) try {
41
+ let e = Object.entries(n.tracing.headers());
42
+ if (a instanceof Request) {
43
+ let t = new Headers(a.headers);
44
+ for (let [n, r] of e) t.set(n, r);
45
+ l = new Request(a, { headers: t });
46
+ } else {
47
+ let t = new Headers(o?.headers);
48
+ for (let [n, r] of e) t.set(n, r);
49
+ u = {
50
+ ...o,
51
+ headers: t
52
+ };
53
+ }
54
+ } catch (e) {
55
+ l = a, u = o, n.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: s }, e);
56
+ }
57
+ let d = performance.now();
58
+ try {
59
+ let t = await e(l, u);
60
+ return i(c, s, t.status, performance.now() - d, void 0), t;
61
+ } catch (e) {
62
+ throw i(c, s, 0, performance.now() - d, e), e;
63
+ }
64
+ };
65
+ }
66
+ installXhr() {
67
+ if (typeof XMLHttpRequest > "u" || this.originalOpen) return;
68
+ let e = (e) => this.ignored(e), t = (e, t, n, r) => {
69
+ this.record(e, t, n, r, void 0);
70
+ }, r = n(), i = r.open, a = r.send;
71
+ this.originalOpen = i, this.originalSend = a, r.open = function(e, t, ...n) {
72
+ this.__uiobs = {
73
+ method: e.toUpperCase(),
74
+ url: String(t),
75
+ startedAt: 0
76
+ }, i.apply(this, [
77
+ e,
78
+ t,
79
+ ...n
80
+ ]);
81
+ }, r.send = function(...n) {
82
+ let r = this.__uiobs;
83
+ r && !e(r.url) && (r.startedAt = performance.now(), this.addEventListener("loadend", () => {
84
+ t(r.method, r.url, this.status, performance.now() - r.startedAt);
85
+ })), a.apply(this, n);
86
+ };
87
+ }
88
+ record(t, n, r, i, a) {
89
+ let o = this.ctx.config.capture.fullUrls ? n : e(n);
90
+ this.ctx.diagnostics.guard("capture.record_failed", `The library could not record ${t} ${o}.`, () => {
91
+ let e = Math.round(i);
92
+ this.ctx.breadcrumbs.push({
93
+ t: Date.now(),
94
+ category: "http",
95
+ message: `${t} ${o} ${r === 0 ? "failed" : String(r)}`,
96
+ data: { durationMs: e }
97
+ });
98
+ let n = {
99
+ "http.request.method": t,
100
+ "url.full": o,
101
+ "http.response.status_code": r,
102
+ "http.duration_ms": e
103
+ };
104
+ r === 0 ? this.ctx.logger.error(`${t} ${o} failed`, a, n) : r >= 400 ? this.ctx.logger.warn(`${t} ${o} returned ${String(r)}`, n) : this.ctx.logger.debug(`${t} ${o}`, n);
105
+ });
106
+ }
107
+ };
108
+ //#endregion
109
+ export { r as NetworkCapture };
110
+
111
+ //# sourceMappingURL=network-C4d2uw2Z.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network-C4d2uw2Z.js","names":["stripUrlQuery","matchesAny","patterns","pattern","url","xhrMethods","NetworkCapture","ctx","original","ignored","record","method","status","durationMs","error","input","init","fetchInput","fetchInit","injected","headers","key","value","startedAt","response","proto","originalOpen","originalSend","rest","args","meta","target","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Evaluates whether a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: string, patterns: (string | RegExp)[]): boolean {\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: { method: string; url: string; startedAt: number };\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Original uninstrumented fetch implementation. */\n private originalFetch: FetchFn | null = null;\n\n /** Original uninstrumented XMLHttpRequest.open implementation. */\n private originalOpen: XhrMethods[\"open\"] | null = null;\n\n /** Original uninstrumented XMLHttpRequest.send implementation. */\n private originalSend: XhrMethods[\"send\"] | null = null;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /** Restores native network transport implementations and clears references. */\n uninstall(): void {\n if (this.originalFetch) {\n globalThis.fetch = this.originalFetch;\n this.originalFetch = null;\n }\n if (this.originalOpen) {\n xhrMethods().open = this.originalOpen;\n this.originalOpen = null;\n }\n if (this.originalSend) {\n xhrMethods().send = this.originalSend;\n this.originalSend = null;\n }\n }\n\n /**\n * Evaluates whether a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n return matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\" || this.originalFetch) {\n return;\n }\n\n const original = globalThis.fetch.bind(globalThis);\n this.originalFetch = globalThis.fetch;\n\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n globalThis.fetch = async function instrumentedFetch(input, init) {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n const requested = init?.method ?? (input instanceof Request ? input.method : \"GET\");\n const method = requested.toUpperCase();\n\n if (ignored(url)) {\n return original(input, init);\n }\n\n let fetchInput = input;\n let fetchInit = init;\n\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n if (matchesAny(url, ctx.config.capture.propagateTraceHeaderTo)) {\n try {\n const injected = Object.entries(ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A body that was read\n // before causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInput = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInit = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n fetchInput = input;\n fetchInit = init;\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n }\n\n const startedAt = performance.now();\n try {\n const response = await original(fetchInput, fetchInit);\n record(method, url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(method, url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\" || this.originalOpen) {\n return;\n }\n\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n const originalOpen = proto.open;\n const originalSend = proto.send;\n this.originalOpen = originalOpen;\n this.originalSend = originalSend;\n\n proto.open = function (this: Tracked, method: string, url: string | URL, ...rest: never[]) {\n this.__uiobs = {\n method: method.toUpperCase(),\n url: String(url),\n startedAt: 0,\n };\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n };\n\n proto.send = function (this: Tracked, ...args: never[]) {\n const meta = this.__uiobs;\n if (meta && !ignored(meta.url)) {\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n }\n originalSend.apply(this, args);\n };\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless fullUrls is set.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n"],"mappings":";;AA8GA,SAAgBC,EAAW,GAAa,GAAwC;CAC9E,OAAOC,EAAS,MAAM,MACpB,OAAOC,KAAY,WAAWC,EAAI,SAASD,CAAO,IAAIA,EAAQ,KAAKC,CAAG,CACxE;AACF;;;AC5FA,SAASC,IAAyB;CAChC,OAAO,eAAe;AACxB;AAGA,IAAaC,IAAb,MAA+C;CAgBhB;CAd7B,OAAgB;CAGhB,gBAAwC;CAGxC,eAAkD;CAGlD,eAAkD;CAKlD,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EAId,AAHI,KAAK,IAAI,OAAO,QAAQ,SAC1B,KAAK,aAAa,GAEhB,KAAK,IAAI,OAAO,QAAQ,OAC1B,KAAK,WAAW;CAEpB;CAGA,YAAkB;EAShB,AARA,AAEE,KAAK,mBADL,WAAW,QAAQ,KAAK,eACH,OAEvB,AAEE,KAAK,kBADL,EAAW,CAAC,CAAC,OAAO,KAAK,cACL,OAEtB,AAEE,KAAK,kBADL,EAAW,CAAC,CAAC,OAAO,KAAK,cACL;CAExB;CAOA,QAAgB,GAAsB;EAGpC,OAAON,EAAWG,GAAK,KAAK,IAAI,OAAO,QAAQ,UAAU;CAC3D;CAGA,eAA6B;EAC3B,IAAI,OAAO,WAAW,SAAU,cAAc,KAAK,eACjD;EAGF,IAAMI,IAAW,WAAW,MAAM,KAAK,UAAU;EACjD,KAAK,gBAAgB,WAAW;EAEhC,IAAMD,IAAM,KAAK,KACXE,KAAW,MAAyB,KAAK,QAAQL,CAAG,GACpDM,KACJ,GACA,GACA,GACA,GACA,MACS;GACT,KAAK,OAAOC,GAAQP,GAAKQ,GAAQC,GAAYC,CAAK;EACpD;EAEA,WAAW,QAAQ,eAAiC,GAAO,GAAM;GAC/D,IAAMV,IAAM,OAAOW,KAAU,WAAWA,IAAQA,aAAiB,MAAMA,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,KAAK,IAAI,OAAO,MAAM,GAAGD,EAAO,GAAGP,EAAI,UAAUU,GAAOmB,CAAU,IAGhErB,KAAU,MACZ,KAAK,IAAI,OAAO,KAAK,GAAGD,EAAO,GAAGP,EAAI,YAAY,OAAOQ,CAAM,KAAKqB,CAAU,IAMhF,KAAK,IAAI,OAAO,MAAM,GAAGtB,EAAO,GAAGP,KAAO6B,CAAU;EACtD,CACF;CACF;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./platform-CXio0W2n.cjs");function t(e,t){return t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}function n(){return XMLHttpRequest.prototype}var r=class{ctx;name=`network`;originalFetch=null;originalOpen=null;originalSend=null;constructor(e){this.ctx=e}install(){this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr()}uninstall(){this.originalFetch&&=(globalThis.fetch=this.originalFetch,null),this.originalOpen&&=(n().open=this.originalOpen,null),this.originalSend&&=(n().send=this.originalSend,null)}ignored(e){return t(e,this.ctx.config.capture.ignoreUrls)}installFetch(){if(typeof globalThis.fetch!=`function`||this.originalFetch)return;let e=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;let n=this.ctx,r=e=>this.ignored(e),i=(e,t,n,r,i)=>{this.record(e,t,n,r,i)};globalThis.fetch=async function(a,o){let s=typeof a==`string`?a:a instanceof URL?a.href:a.url,c=(o?.method??(a instanceof Request?a.method:`GET`)).toUpperCase();if(r(s))return e(a,o);let l=a,u=o;if(t(s,n.config.capture.propagateTraceHeaderTo))try{let e=Object.entries(n.tracing.headers());if(a instanceof Request){let t=new Headers(a.headers);for(let[n,r]of e)t.set(n,r);l=new Request(a,{headers:t})}else{let t=new Headers(o?.headers);for(let[n,r]of e)t.set(n,r);u={...o,headers:t}}}catch(e){l=a,u=o,n.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:s},e)}let d=performance.now();try{let t=await e(l,u);return i(c,s,t.status,performance.now()-d,void 0),t}catch(e){throw i(c,s,0,performance.now()-d,e),e}}}installXhr(){if(typeof XMLHttpRequest>`u`||this.originalOpen)return;let e=e=>this.ignored(e),t=(e,t,n,r)=>{this.record(e,t,n,r,void 0)},r=n(),i=r.open,a=r.send;this.originalOpen=i,this.originalSend=a,r.open=function(e,t,...n){this.__uiobs={method:e.toUpperCase(),url:String(t),startedAt:0},i.apply(this,[e,t,...n])},r.send=function(...n){let r=this.__uiobs;r&&!e(r.url)&&(r.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{t(r.method,r.url,this.status,performance.now()-r.startedAt)})),a.apply(this,n)}}record(t,n,r,i,a){let o=this.ctx.config.capture.fullUrls?n:e.r(n);this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${t} ${o}.`,()=>{let e=Math.round(i);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${t} ${o} ${r===0?`failed`:String(r)}`,data:{durationMs:e}});let n={"http.request.method":t,"url.full":o,"http.response.status_code":r,"http.duration_ms":e};r===0?this.ctx.logger.error(`${t} ${o} failed`,a,n):r>=400?this.ctx.logger.warn(`${t} ${o} returned ${String(r)}`,n):this.ctx.logger.debug(`${t} ${o}`,n)})}};exports.NetworkCapture=r;
2
+ //# sourceMappingURL=network-CuqWadNn.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network-CuqWadNn.cjs","names":["stripUrlQuery","require_platform","matchesAny","patterns","pattern","url","xhrMethods","NetworkCapture","ctx","original","ignored","record","method","status","durationMs","error","input","init","fetchInput","fetchInit","injected","headers","key","value","startedAt","response","proto","originalOpen","originalSend","rest","args","meta","target","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Evaluates whether a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: string, patterns: (string | RegExp)[]): boolean {\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: { method: string; url: string; startedAt: number };\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Original uninstrumented fetch implementation. */\n private originalFetch: FetchFn | null = null;\n\n /** Original uninstrumented XMLHttpRequest.open implementation. */\n private originalOpen: XhrMethods[\"open\"] | null = null;\n\n /** Original uninstrumented XMLHttpRequest.send implementation. */\n private originalSend: XhrMethods[\"send\"] | null = null;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /** Restores native network transport implementations and clears references. */\n uninstall(): void {\n if (this.originalFetch) {\n globalThis.fetch = this.originalFetch;\n this.originalFetch = null;\n }\n if (this.originalOpen) {\n xhrMethods().open = this.originalOpen;\n this.originalOpen = null;\n }\n if (this.originalSend) {\n xhrMethods().send = this.originalSend;\n this.originalSend = null;\n }\n }\n\n /**\n * Evaluates whether a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n return matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\" || this.originalFetch) {\n return;\n }\n\n const original = globalThis.fetch.bind(globalThis);\n this.originalFetch = globalThis.fetch;\n\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n globalThis.fetch = async function instrumentedFetch(input, init) {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n const requested = init?.method ?? (input instanceof Request ? input.method : \"GET\");\n const method = requested.toUpperCase();\n\n if (ignored(url)) {\n return original(input, init);\n }\n\n let fetchInput = input;\n let fetchInit = init;\n\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n if (matchesAny(url, ctx.config.capture.propagateTraceHeaderTo)) {\n try {\n const injected = Object.entries(ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A body that was read\n // before causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInput = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n fetchInit = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n fetchInput = input;\n fetchInit = init;\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n }\n\n const startedAt = performance.now();\n try {\n const response = await original(fetchInput, fetchInit);\n record(method, url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(method, url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\" || this.originalOpen) {\n return;\n }\n\n const ignored = (url: string): boolean => this.ignored(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n const originalOpen = proto.open;\n const originalSend = proto.send;\n this.originalOpen = originalOpen;\n this.originalSend = originalSend;\n\n proto.open = function (this: Tracked, method: string, url: string | URL, ...rest: never[]) {\n this.__uiobs = {\n method: method.toUpperCase(),\n url: String(url),\n startedAt: 0,\n };\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n };\n\n proto.send = function (this: Tracked, ...args: never[]) {\n const meta = this.__uiobs;\n if (meta && !ignored(meta.url)) {\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n }\n originalSend.apply(this, args);\n };\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless fullUrls is set.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n"],"mappings":"2CA8GA,SAAgBE,EAAW,EAAa,EAAwC,CAC9E,OAAOC,EAAS,KAAM,GACpB,OAAOC,GAAY,SAAWC,EAAI,SAASD,CAAO,EAAIA,EAAQ,KAAKC,CAAG,CACxE,CACF,CC5FA,SAASC,GAAyB,CAChC,OAAO,eAAe,SACxB,CAGA,IAAaC,EAAb,KAA+C,CAgBhB,IAd7B,KAAgB,UAGhB,cAAwC,KAGxC,aAAkD,KAGlD,aAAkD,KAKlD,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,IAAI,OAAO,QAAQ,OAC1B,KAAK,aAAa,EAEhB,KAAK,IAAI,OAAO,QAAQ,KAC1B,KAAK,WAAW,CAEpB,CAGA,WAAkB,CACh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AAK,OAAQ,YAAY,IAAI,EAAIA,EAAK,SAAS,CAC/E,CAAC,GAEHH,EAAa,MAAM,KAAME,CAAI,CAC/B,CACF,CAUA,OACE,EACA,EACA,EACA,EACA,EACM,CAGN,IAAMzB,EAAM,KAAK,IAAI,OAAO,QAAQ,SAAW2B,EAAShC,EAAAA,EAAcgC,CAAM,EAI5E,KAAK,IAAI,YAAY,MACnB,wBACA,gCAAgCpB,EAAO,GAAGP,EAAI,OACxC,CACJ,IAAM4B,EAAU,KAAK,MAAMnB,CAAU,EAErC,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,OACV,QAAS,GAAGF,EAAO,GAAGP,EAAI,GAAGQ,IAAW,EAAI,SAAW,OAAOA,CAAM,IACpE,KAAM,CAAE,WAAYoB,CAAQ,CAC9B,CAAC,EAED,IAAMC,EAAa,CACjB,sBAAuBtB,EACvB,WAAYP,EACZ,4BAA6BQ,EAC7B,mBAAoBoB,CACtB,EAEIpB,IAAW,EACb,KAAK,IAAI,OAAO,MAAM,GAAGD,EAAO,GAAGP,EAAI,SAAUU,EAAOmB,CAAU,EAGhErB,GAAU,IACZ,KAAK,IAAI,OAAO,KAAK,GAAGD,EAAO,GAAGP,EAAI,YAAY,OAAOQ,CAAM,IAAKqB,CAAU,EAMhF,KAAK,IAAI,OAAO,MAAM,GAAGtB,EAAO,GAAGP,IAAO6B,CAAU,CACtD,CACF,CACF,CACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-TUFcy95w.cjs");var t=null;function n(e,t){let n=e[t];return n!==void 0&&e instanceof n}function r(r){if(t)return t;let o=globalThis,s=o.navigator?.userAgent??``,c=`browser`,l,u,d=!1,f=o.fin?.me;return n(o,`ServiceWorkerGlobalScope`)?(c=`service_worker`,d=!0):n(o,`SharedWorkerGlobalScope`)?(c=`shared_worker`,d=!0):n(o,`WorkerGlobalScope`)?(c=`web_worker`,d=!0):f===void 0?o.Capacitor!==void 0||o.Ionic!==void 0?c=`ionic`:o.cordova!==void 0||i(s)?c=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(c=`node`):(c=e.gt.test(s)?`openfin`:`openfin_web`,r.guard(`openfin.unavailable`,`The library could not read fin.me.identity.`,()=>{let e=f.identity;l=e?.uuid,u=e?.name})),t={platform:c,openfinUuid:l,openfinName:u,userAgent:s,isWorker:d,isTopLevelDocument:a(r)},t}function i(t){return e.t.test(t)?!0:(e.et.test(t)||e.ct.test(t)&&e.dt.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function a(e){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return e.count(`platform.api_blocked`),!1}}function o(e){try{return typeof location<`u`?location.href:``}catch{return e.count(`platform.api_blocked`),``}}function s(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
2
+ //# sourceMappingURL=platform-CXio0W2n.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platform-CXio0W2n.cjs","names":["OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","require_constants","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** Indicates whether execution occurs inside any worker realm. */\n isWorker: boolean;\n /** Indicates whether this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Evaluates whether globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = (g.fin as FinLike | undefined)?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Evaluates whether a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Determines whether the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":"4CAiDA,IAAIM,EAAkC,KAWtC,SAASC,EAAc,EAAW,EAAuB,CACvD,IAAMC,EAAQC,EAAEC,GAIhB,OAHIF,IAAU,IAAA,IAGPC,aAAcD,CACvB,CAYA,SAAgBG,EAAe,EAA4C,CACzE,GAAIL,EACF,OAAOA,EAET,IAAMG,EAAI,WAEJG,EAAMH,EAAE,WAAqC,WAAa,GAC5DI,EAAyB,UACzBC,EACAC,EACAC,EAAW,GAETC,EAASR,EAAE,KAA6B,GAkC9C,OAhCIF,EAAcE,EAAG,0BAA0B,GAC7C,EAAW,iBACX,EAAW,IACFF,EAAcE,EAAG,yBAAyB,GACnD,EAAW,gBACX,EAAW,IACFF,EAAcE,EAAG,mBAAmB,GAC7C,EAAW,aACX,EAAW,IACFQ,IAAU,IAAA,GAOVR,EAAE,YAAc,IAAA,IAAaA,EAAE,QAAU,IAAA,GAClD,EAAW,QACFA,EAAE,UAAY,IAAA,IAAaS,EAAUN,CAAE,EAChD,EAAW,iBACF,OAAO,SAAa,KAAe,OAAO,QAAY,MAC/D,EAAW,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