@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.
- package/CHANGELOG.md +63 -0
- package/README.md +83 -52
- package/dist/batch-4xKzzSCj.js +31 -0
- package/dist/batch-4xKzzSCj.js.map +1 -0
- package/dist/batch-cys7e53Q.cjs +2 -0
- package/dist/batch-cys7e53Q.cjs.map +1 -0
- package/dist/{bus-CtJWf9QN.cjs → bus-B6vzPmQM.cjs} +2 -2
- package/dist/{bus-CtJWf9QN.cjs.map → bus-B6vzPmQM.cjs.map} +1 -1
- package/dist/{bus-D8kH58tb.js → bus-DrixwdiX.js} +10 -10
- package/dist/{bus-D8kH58tb.js.map → bus-DrixwdiX.js.map} +1 -1
- package/dist/capture/network.d.ts +2 -0
- package/dist/capture/types.d.ts +3 -0
- package/dist/{console-DjLbryED.js → console-B3vGRW5p.js} +3 -3
- package/dist/{console-DjLbryED.js.map → console-B3vGRW5p.js.map} +1 -1
- package/dist/{console-BpHfWstv.cjs → console-ChfuJlf9.cjs} +2 -2
- package/dist/{console-BpHfWstv.cjs.map → console-ChfuJlf9.cjs.map} +1 -1
- package/dist/constants-Be83LICb.cjs +2 -0
- package/dist/constants-Be83LICb.cjs.map +1 -0
- package/dist/constants-CQ_D7jIW.js +144 -0
- package/dist/constants-CQ_D7jIW.js.map +1 -0
- package/dist/constants.d.ts +44 -11
- package/dist/core/diagnostics.d.ts +1 -1
- package/dist/core/drops.d.ts +29 -0
- package/dist/core/hold-buffer.d.ts +27 -0
- package/dist/core/meter.d.ts +45 -0
- package/dist/core/pipeline.d.ts +7 -19
- package/dist/core/record.d.ts +7 -0
- package/dist/core/runtime.d.ts +61 -8
- package/dist/core/sampling.d.ts +2 -0
- package/dist/core/sender.d.ts +6 -1
- package/dist/deadline-5_PecIl5.js +26 -0
- package/dist/deadline-5_PecIl5.js.map +1 -0
- package/dist/deadline-XSnm95pg.cjs +2 -0
- package/dist/deadline-XSnm95pg.cjs.map +1 -0
- package/dist/{errors-DH4QJS0u.js → errors-BGs5NOrw.js} +4 -4
- package/dist/{errors-DH4QJS0u.js.map → errors-BGs5NOrw.js.map} +1 -1
- package/dist/{errors-CpGRhhIf.cjs → errors-BMJm7KZZ.cjs} +2 -2
- package/dist/{errors-CpGRhhIf.cjs.map → errors-BMJm7KZZ.cjs.map} +1 -1
- package/dist/identity-DXyV86o-.cjs +2 -0
- package/dist/identity-DXyV86o-.cjs.map +1 -0
- package/dist/{deadline-B5DINjD5.js → identity-rpEyjvVg.js} +3 -26
- package/dist/identity-rpEyjvVg.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +19 -0
- package/dist/index.js +683 -369
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-BXaPVPyG.cjs +2 -0
- package/dist/indexeddb-storage-BXaPVPyG.cjs.map +1 -0
- package/dist/{indexeddb-storage-n1qkFBGA.js → indexeddb-storage-Q9fDYlyn.js} +76 -47
- package/dist/indexeddb-storage-Q9fDYlyn.js.map +1 -0
- package/dist/{interactions-OU94MPXs.js → interactions-B8zjCjga.js} +2 -2
- package/dist/{interactions-OU94MPXs.js.map → interactions-B8zjCjga.js.map} +1 -1
- package/dist/{interactions-31eHGwEQ.cjs → interactions-BAGRmtrv.cjs} +2 -2
- package/dist/{interactions-31eHGwEQ.cjs.map → interactions-BAGRmtrv.cjs.map} +1 -1
- package/dist/journey-BGSyy8Es.cjs +2 -0
- package/dist/journey-BGSyy8Es.cjs.map +1 -0
- package/dist/{journey-CeJ1QoT2.js → journey-_dQQ1eMP.js} +27 -26
- package/dist/{journey-CeJ1QoT2.js.map → journey-_dQQ1eMP.js.map} +1 -1
- package/dist/library-request-BIG3Xpx3.cjs +2 -0
- package/dist/library-request-BIG3Xpx3.cjs.map +1 -0
- package/dist/library-request-DX6ev9oG.js +25 -0
- package/dist/library-request-DX6ev9oG.js.map +1 -0
- package/dist/{long-frames-C_7OutLs.js → long-frames-B0tKuChx.js} +3 -3
- package/dist/{long-frames-C_7OutLs.js.map → long-frames-B0tKuChx.js.map} +1 -1
- package/dist/{long-frames-B8VdA_ny.cjs → long-frames-Cq2LgNnp.cjs} +2 -2
- package/dist/{long-frames-B8VdA_ny.cjs.map → long-frames-Cq2LgNnp.cjs.map} +1 -1
- package/dist/models/batch.d.ts +14 -0
- package/dist/models/config.d.ts +169 -0
- package/dist/models/drop.d.ts +39 -0
- package/dist/models/metric.d.ts +50 -0
- package/dist/models/storage.d.ts +15 -3
- package/dist/network-C6kJbW6K.cjs +2 -0
- package/dist/network-C6kJbW6K.cjs.map +1 -0
- package/dist/network-CMnEvGJB.js +211 -0
- package/dist/network-CMnEvGJB.js.map +1 -0
- package/dist/{platform-D4wu1eIF.cjs → platform-DNOJjpOm.cjs} +2 -2
- package/dist/{platform-D4wu1eIF.cjs.map → platform-DNOJjpOm.cjs.map} +1 -1
- package/dist/{platform-IHBZGqUe.js → platform-j0uMPwHi.js} +3 -3
- package/dist/{platform-IHBZGqUe.js.map → platform-j0uMPwHi.js.map} +1 -1
- package/dist/{remote-rules-kuDf5gbe.cjs → remote-rules-DgoBJxZL.cjs} +2 -2
- package/dist/{remote-rules-kuDf5gbe.cjs.map → remote-rules-DgoBJxZL.cjs.map} +1 -1
- package/dist/{remote-rules-Bt1XsdEQ.js → remote-rules-UggoZqfP.js} +11 -11
- package/dist/{remote-rules-Bt1XsdEQ.js.map → remote-rules-UggoZqfP.js.map} +1 -1
- package/dist/{sampling-o0VY1mqQ.js → sampling-BLMD8EGM.js} +28 -27
- package/dist/sampling-BLMD8EGM.js.map +1 -0
- package/dist/sampling-MthcVXXU.cjs +2 -0
- package/dist/sampling-MthcVXXU.cjs.map +1 -0
- package/dist/{sanitize-B9UheVKc.js → sanitize-BNwgPj_B.js} +2 -2
- package/dist/{sanitize-B9UheVKc.js.map → sanitize-BNwgPj_B.js.map} +1 -1
- package/dist/{sanitize-DSIP7amZ.cjs → sanitize-BqzPc4Jg.cjs} +2 -2
- package/dist/{sanitize-DSIP7amZ.cjs.map → sanitize-BqzPc4Jg.cjs.map} +1 -1
- package/dist/sender--0_VzPbN.js +1249 -0
- package/dist/sender--0_VzPbN.js.map +1 -0
- package/dist/sender-SPGMqZjD.cjs +3 -0
- package/dist/sender-SPGMqZjD.cjs.map +1 -0
- package/dist/storage/emergency-queue.d.ts +4 -1
- package/dist/storage/eviction.d.ts +40 -0
- package/dist/storage/idb-driver.d.ts +6 -0
- package/dist/storage/indexeddb-storage.d.ts +13 -5
- package/dist/storage/local-storage.d.ts +24 -1
- package/dist/storage/memory-storage.d.ts +7 -0
- package/dist/{storm-Y-yuBhvv.cjs → storm-CTy1dfvs.cjs} +2 -2
- package/dist/{storm-Y-yuBhvv.cjs.map → storm-CTy1dfvs.cjs.map} +1 -1
- package/dist/{storm-BTw0J6eE.js → storm-knaj4GUH.js} +2 -2
- package/dist/{storm-BTw0J6eE.js.map → storm-knaj4GUH.js.map} +1 -1
- package/dist/transport/custom-transport.d.ts +3 -2
- package/dist/transport/exit-flush.d.ts +19 -2
- package/dist/transport/http-transport.d.ts +6 -4
- package/dist/transport/retry-engine.d.ts +9 -3
- package/dist/transport/serializers/otlp-metrics.d.ts +3 -0
- package/dist/transport/serializers/otlp.d.ts +30 -0
- package/dist/transport/serializers/select.d.ts +20 -4
- package/dist/transport/status-transport.d.ts +23 -12
- package/dist/utils/console.d.ts +4 -1
- package/dist/utils/library-request.d.ts +12 -0
- package/package.json +1 -1
- package/dist/constants-Br3b89Wg.cjs +0 -2
- package/dist/constants-Br3b89Wg.cjs.map +0 -1
- package/dist/constants-DM94FjVX.js +0 -96
- package/dist/constants-DM94FjVX.js.map +0 -1
- package/dist/deadline-B5DINjD5.js.map +0 -1
- package/dist/deadline-Cbg2cbUw.cjs +0 -2
- package/dist/deadline-Cbg2cbUw.cjs.map +0 -1
- package/dist/indexeddb-storage-DNdf1fmL.cjs +0 -2
- package/dist/indexeddb-storage-DNdf1fmL.cjs.map +0 -1
- package/dist/indexeddb-storage-n1qkFBGA.js.map +0 -1
- package/dist/journey-CE2EcwHW.cjs +0 -2
- package/dist/journey-CE2EcwHW.cjs.map +0 -1
- package/dist/library-request-C9uJFlbq.cjs +0 -2
- package/dist/library-request-C9uJFlbq.cjs.map +0 -1
- package/dist/library-request-DvhuplAB.js +0 -14
- package/dist/library-request-DvhuplAB.js.map +0 -1
- package/dist/network-BAV7ipyn.cjs +0 -2
- package/dist/network-BAV7ipyn.cjs.map +0 -1
- package/dist/network-D_lloS5t.js +0 -174
- package/dist/network-D_lloS5t.js.map +0 -1
- package/dist/sampling-BI15ds9D.cjs +0 -2
- package/dist/sampling-BI15ds9D.cjs.map +0 -1
- package/dist/sampling-o0VY1mqQ.js.map +0 -1
- package/dist/sender-BnNj9bOX.js +0 -1050
- package/dist/sender-BnNj9bOX.js.map +0 -1
- package/dist/sender-D0OsyB1c.cjs +0 -3
- package/dist/sender-D0OsyB1c.cjs.map +0 -1
package/dist/models/config.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { DiagnosticHandler } from "../core/diagnostics";
|
|
2
|
+
import type { DropSummary } from "./drop";
|
|
2
3
|
import type { LogLevel, LogRecord } from "./log-record";
|
|
3
4
|
import type { LogSerializer } from "./serializer";
|
|
4
5
|
/** Backing store for undelivered records. "auto" picks the best one the host supports. */
|
|
@@ -177,6 +178,110 @@ export interface JourneyOptions {
|
|
|
177
178
|
* @default "auto"
|
|
178
179
|
*/
|
|
179
180
|
scope: JourneyScope;
|
|
181
|
+
/**
|
|
182
|
+
* Maximum open time of a journey, in milliseconds. Then the library ends it. The range is
|
|
183
|
+
* 1 minute to 24 hours. You cannot change this value after startup.
|
|
184
|
+
* @default 1800000
|
|
185
|
+
*/
|
|
186
|
+
maxAgeMs: number;
|
|
187
|
+
}
|
|
188
|
+
/** Batch size and flush interval of each record stream. You cannot change them after startup. */
|
|
189
|
+
export interface BatchingOptions {
|
|
190
|
+
/**
|
|
191
|
+
* Maximum wait of a partial log batch, in milliseconds. The range is 100 to 60000.
|
|
192
|
+
* @default 2000
|
|
193
|
+
*/
|
|
194
|
+
logFlushIntervalMs: number;
|
|
195
|
+
/**
|
|
196
|
+
* Maximum records in one log batch. The range is 1 to 1000.
|
|
197
|
+
* @default 100
|
|
198
|
+
*/
|
|
199
|
+
logBatchSize: number;
|
|
200
|
+
/**
|
|
201
|
+
* Maximum wait of a partial metric batch, in milliseconds. The range is 100 to 60000.
|
|
202
|
+
* @default 10000
|
|
203
|
+
*/
|
|
204
|
+
metricFlushIntervalMs: number;
|
|
205
|
+
/**
|
|
206
|
+
* Maximum records in one metric batch. The range is 1 to 1000.
|
|
207
|
+
* @default 500
|
|
208
|
+
*/
|
|
209
|
+
metricBatchSize: number;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* How long the library keeps an undelivered batch.
|
|
213
|
+
* - "limited": the batch stays until `maxAgeMs` or `maxAttempts`.
|
|
214
|
+
* - "until-delivered": the batch has no age limit and no attempt limit. `maxBatches` still
|
|
215
|
+
* applies. A permanent error still drops the batch.
|
|
216
|
+
*/
|
|
217
|
+
export type RetentionMode = "limited" | "until-delivered";
|
|
218
|
+
/** Retention of undelivered batches. You cannot change it after startup. */
|
|
219
|
+
export interface RetentionOptions {
|
|
220
|
+
/**
|
|
221
|
+
* Retention rule.
|
|
222
|
+
* @default "limited"
|
|
223
|
+
*/
|
|
224
|
+
mode: RetentionMode;
|
|
225
|
+
/**
|
|
226
|
+
* Maximum stored batches. A new batch evicts the oldest batch without an action first. The
|
|
227
|
+
* range is 1 to 5000.
|
|
228
|
+
* @default 500
|
|
229
|
+
*/
|
|
230
|
+
maxBatches: number;
|
|
231
|
+
/**
|
|
232
|
+
* Maximum age of a stored batch, in milliseconds. The range is 1 minute to 7 days.
|
|
233
|
+
* @default 86400000
|
|
234
|
+
*/
|
|
235
|
+
maxAgeMs: number;
|
|
236
|
+
/**
|
|
237
|
+
* Maximum send attempts of a stored batch. The range is 1 to 20.
|
|
238
|
+
* @default 5
|
|
239
|
+
*/
|
|
240
|
+
maxAttempts: number;
|
|
241
|
+
}
|
|
242
|
+
/** Size limits for each record. You cannot change them after startup. */
|
|
243
|
+
export interface LimitOptions {
|
|
244
|
+
/**
|
|
245
|
+
* Maximum body length, in characters. The range is 256 to 65536.
|
|
246
|
+
* @default 4096
|
|
247
|
+
*/
|
|
248
|
+
maxBodyChars: number;
|
|
249
|
+
/**
|
|
250
|
+
* Maximum length of a string attribute, in characters. The range is 256 to 65536.
|
|
251
|
+
* @default 8192
|
|
252
|
+
*/
|
|
253
|
+
maxAttributeChars: number;
|
|
254
|
+
/**
|
|
255
|
+
* Maximum keys in one object. The range is 1 to 1024.
|
|
256
|
+
* @default 128
|
|
257
|
+
*/
|
|
258
|
+
maxAttributeCount: number;
|
|
259
|
+
/**
|
|
260
|
+
* Maximum length of an error stack, in characters. The range is 256 to 65536.
|
|
261
|
+
* @default 8192
|
|
262
|
+
*/
|
|
263
|
+
maxStackChars: number;
|
|
264
|
+
/**
|
|
265
|
+
* Maximum depth of a nested value. The range is 1 to 16.
|
|
266
|
+
* @default 6
|
|
267
|
+
*/
|
|
268
|
+
maxDepth: number;
|
|
269
|
+
/**
|
|
270
|
+
* Maximum items in one array, set or map. The range is 1 to 10000.
|
|
271
|
+
* @default 100
|
|
272
|
+
*/
|
|
273
|
+
maxArrayLength: number;
|
|
274
|
+
/**
|
|
275
|
+
* Maximum values in one sanitize pass. The range is 100 to 100000.
|
|
276
|
+
* @default 10000
|
|
277
|
+
*/
|
|
278
|
+
maxNodes: number;
|
|
279
|
+
/**
|
|
280
|
+
* Maximum attribute bytes of one record. Above it, the library drops the caller attributes.
|
|
281
|
+
* The range is 1024 to 60000.
|
|
282
|
+
* @default 32768
|
|
283
|
+
*/
|
|
284
|
+
maxRecordBytes: number;
|
|
180
285
|
}
|
|
181
286
|
/** Console method that the console capture can wrap. */
|
|
182
287
|
export type CapturedConsoleMethod = "error" | "warn" | "info" | "log";
|
|
@@ -210,6 +315,12 @@ export interface CaptureOptions {
|
|
|
210
315
|
* @default false
|
|
211
316
|
*/
|
|
212
317
|
xhr: boolean;
|
|
318
|
+
/**
|
|
319
|
+
* Record the `http.client.request.duration` histogram of each request that `fetch` or `xhr`
|
|
320
|
+
* capture sees. The histogram is in seconds.
|
|
321
|
+
* @default true
|
|
322
|
+
*/
|
|
323
|
+
httpMetrics: boolean;
|
|
213
324
|
/**
|
|
214
325
|
* Log clicks and other interactions as breadcrumbs.
|
|
215
326
|
* @default false
|
|
@@ -298,8 +409,15 @@ export interface ResolvedConsole {
|
|
|
298
409
|
/** CSS for the namespace and for each level. */
|
|
299
410
|
styles: Required<ConsoleStyles>;
|
|
300
411
|
}
|
|
412
|
+
/**
|
|
413
|
+
* Kind of a batch. A batch of metric records is "metrics" when `metricsEndpoint` is set. Its body
|
|
414
|
+
* is then an OTLP `ExportMetricsServiceRequest`.
|
|
415
|
+
*/
|
|
416
|
+
export type BatchKind = "logs" | "metrics";
|
|
301
417
|
/** One batch that the library gives to a custom transport. */
|
|
302
418
|
export interface TransportRequest {
|
|
419
|
+
/** Kind of the batch. Send a "metrics" body to your metrics endpoint. */
|
|
420
|
+
kind: BatchKind;
|
|
303
421
|
/** Serialized batch from the configured serializer. The library does not compress it. */
|
|
304
422
|
body: string;
|
|
305
423
|
/** Content type of `body`, from the serializer. */
|
|
@@ -350,6 +468,14 @@ export interface ObservabilityConfig {
|
|
|
350
468
|
* If the key is missing or `""`, the library reports `config.invalid`.
|
|
351
469
|
*/
|
|
352
470
|
endpoint?: string | null;
|
|
471
|
+
/**
|
|
472
|
+
* OTLP metrics endpoint URL, for example `"https://ingest.example/v1/metrics"`. With this key,
|
|
473
|
+
* the library sends each batch of metric records there as an OTLP `ExportMetricsServiceRequest`.
|
|
474
|
+
* Without it, metric records are log records on `endpoint`. The key needs `serializer: "otlp"`.
|
|
475
|
+
* Set `""` to turn it off.
|
|
476
|
+
* @default ""
|
|
477
|
+
*/
|
|
478
|
+
metricsEndpoint?: string;
|
|
353
479
|
/**
|
|
354
480
|
* The library reports this value as `service.name`.
|
|
355
481
|
* @default ""
|
|
@@ -422,6 +548,21 @@ export interface ObservabilityConfig {
|
|
|
422
548
|
* @see {@link JourneyOptions}
|
|
423
549
|
*/
|
|
424
550
|
journey?: Partial<JourneyOptions>;
|
|
551
|
+
/**
|
|
552
|
+
* Batch size and flush interval of each record stream.
|
|
553
|
+
* @see {@link BatchingOptions}
|
|
554
|
+
*/
|
|
555
|
+
batching?: Partial<BatchingOptions>;
|
|
556
|
+
/**
|
|
557
|
+
* Retention of undelivered batches.
|
|
558
|
+
* @see {@link RetentionOptions}
|
|
559
|
+
*/
|
|
560
|
+
retention?: Partial<RetentionOptions>;
|
|
561
|
+
/**
|
|
562
|
+
* Size limits for each record.
|
|
563
|
+
* @see {@link LimitOptions}
|
|
564
|
+
*/
|
|
565
|
+
limits?: Partial<LimitOptions>;
|
|
425
566
|
/**
|
|
426
567
|
* Automatic instrumentation.
|
|
427
568
|
* @see {@link CaptureOptions}
|
|
@@ -462,11 +603,22 @@ export interface ObservabilityConfig {
|
|
|
462
603
|
* @see {@link DiagnosticHandler}
|
|
463
604
|
*/
|
|
464
605
|
onDiagnostic?: DiagnosticHandler;
|
|
606
|
+
/**
|
|
607
|
+
* Receives a summary when the library loses records that it built. Sampling, `minLevel` and
|
|
608
|
+
* `redact` do not cause a loss. The library joins the losses of one reason in one task.
|
|
609
|
+
* Do not log through the library in the hook. A record from the hook can evict a stored batch.
|
|
610
|
+
* A batch that storage evicts during its send can still reach the server.
|
|
611
|
+
* @param summary Reason, record count, batch ids, journey ids and action names of the loss.
|
|
612
|
+
* @see {@link DropSummary}
|
|
613
|
+
*/
|
|
614
|
+
onDrop?: (summary: DropSummary) => void;
|
|
465
615
|
}
|
|
466
616
|
/** Fully resolved configuration that the runtime holds. */
|
|
467
617
|
export interface ResolvedConfig {
|
|
468
618
|
/** Ingest endpoint URL, or null in console-only mode. */
|
|
469
619
|
endpoint: string | null;
|
|
620
|
+
/** OTLP metrics endpoint URL. An empty string sends metric records as log records. */
|
|
621
|
+
metricsEndpoint: string;
|
|
470
622
|
/** The library reports this value as `service.name`. */
|
|
471
623
|
serviceName: string;
|
|
472
624
|
/** The library reports this value as `service.version`. */
|
|
@@ -500,6 +652,21 @@ export interface ResolvedConfig {
|
|
|
500
652
|
* @see {@link JourneyOptions}
|
|
501
653
|
*/
|
|
502
654
|
journey: JourneyOptions;
|
|
655
|
+
/**
|
|
656
|
+
* Batch size and flush interval of each record stream.
|
|
657
|
+
* @see {@link BatchingOptions}
|
|
658
|
+
*/
|
|
659
|
+
batching: BatchingOptions;
|
|
660
|
+
/**
|
|
661
|
+
* Retention of undelivered batches.
|
|
662
|
+
* @see {@link RetentionOptions}
|
|
663
|
+
*/
|
|
664
|
+
retention: RetentionOptions;
|
|
665
|
+
/**
|
|
666
|
+
* Size limits for each record.
|
|
667
|
+
* @see {@link LimitOptions}
|
|
668
|
+
*/
|
|
669
|
+
limits: LimitOptions;
|
|
503
670
|
/**
|
|
504
671
|
* Automatic instrumentation.
|
|
505
672
|
* @see {@link CaptureOptions}
|
|
@@ -528,4 +695,6 @@ export interface ResolvedConfig {
|
|
|
528
695
|
* @see {@link DiagnosticHandler}
|
|
529
696
|
*/
|
|
530
697
|
onDiagnostic?: DiagnosticHandler;
|
|
698
|
+
/** Receives a summary when the library loses records that it built. */
|
|
699
|
+
onDrop?: ObservabilityConfig["onDrop"];
|
|
531
700
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { LogRecord } from "./log-record";
|
|
2
|
+
/**
|
|
3
|
+
* Cause of a loss.
|
|
4
|
+
* - "buffer_full": a hold buffer before startup or before the sender loads is full.
|
|
5
|
+
* - "expired", "over_capacity", "quota": storage removed stored batches. The reasons are
|
|
6
|
+
* `retention.maxAgeMs`, `retention.maxBatches` and the storage quota of the browser.
|
|
7
|
+
* - "max_attempts": a stored batch reached `retention.maxAttempts`.
|
|
8
|
+
* - "rejected": the server refused the batch permanently, or one record is too large for it.
|
|
9
|
+
* - "unserializable": the serializer threw on the batch.
|
|
10
|
+
* - "exit_queue_full": the exit queue in localStorage is full. It drops its oldest batch.
|
|
11
|
+
* - "load_failed": the delivery code did not load, or shutdown() came first. The held records are
|
|
12
|
+
* lost.
|
|
13
|
+
* - "not_stored": storage did not keep a batch after a failed send. The cause is a write error or
|
|
14
|
+
* `storage: "none"`.
|
|
15
|
+
*/
|
|
16
|
+
export type LossReason = "buffer_full" | "expired" | "over_capacity" | "quota" | "max_attempts" | "rejected" | "unserializable" | "exit_queue_full" | "load_failed" | "not_stored";
|
|
17
|
+
/**
|
|
18
|
+
* One report of lost records. The library joins the losses of one reason in one task.
|
|
19
|
+
* Each list holds at most 20 different values.
|
|
20
|
+
*/
|
|
21
|
+
export interface DropSummary {
|
|
22
|
+
/** Cause of the loss. */
|
|
23
|
+
reason: LossReason;
|
|
24
|
+
/** Number of lost records. */
|
|
25
|
+
records: number;
|
|
26
|
+
/** Ids of the lost batches. A hold buffer loses records, not batches. Its list is empty. */
|
|
27
|
+
batchIds: string[];
|
|
28
|
+
/** Journey ids of the lost records. */
|
|
29
|
+
journeyIds: string[];
|
|
30
|
+
/** Names of the lost action records. An action is an audit fact. */
|
|
31
|
+
actions: string[];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Receives lost records. The runtime adds them to the onDrop report.
|
|
35
|
+
* @param reason Cause of the loss.
|
|
36
|
+
* @param records Lost records.
|
|
37
|
+
* @param batchIds Ids of the lost batches.
|
|
38
|
+
*/
|
|
39
|
+
export type LossReporter = (reason: LossReason, records: readonly LogRecord[], batchIds?: readonly string[]) => void;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Attribute set of a metric point. Keep it small. Each set is one series in the backend. */
|
|
2
|
+
export type MetricAttributes = Record<string, string | number | boolean>;
|
|
3
|
+
/** Options of an instrument. */
|
|
4
|
+
export interface InstrumentOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Unit of the values, for example "ms" or "By".
|
|
7
|
+
* @default "count"
|
|
8
|
+
*/
|
|
9
|
+
unit?: string;
|
|
10
|
+
}
|
|
11
|
+
/** Options of a histogram. */
|
|
12
|
+
export interface HistogramOptions extends InstrumentOptions {
|
|
13
|
+
/**
|
|
14
|
+
* Ascending bucket boundaries, at most 50. A value goes into the first bucket whose boundary
|
|
15
|
+
* is equal to or larger than the value.
|
|
16
|
+
* @default [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000]
|
|
17
|
+
*/
|
|
18
|
+
boundaries?: readonly number[];
|
|
19
|
+
}
|
|
20
|
+
/** Counter that sums its values in memory. The library sends one point at each interval. */
|
|
21
|
+
export interface Counter {
|
|
22
|
+
/**
|
|
23
|
+
* Adds a value to the sum of an attribute set.
|
|
24
|
+
* @param value Finite number, 0 or larger.
|
|
25
|
+
* @param attributes Attribute set of the point.
|
|
26
|
+
*/
|
|
27
|
+
add(value: number, attributes?: MetricAttributes): void;
|
|
28
|
+
}
|
|
29
|
+
/** Histogram that counts its values in buckets in memory. It sends one point at each interval. */
|
|
30
|
+
export interface Histogram {
|
|
31
|
+
/**
|
|
32
|
+
* Adds a value to the buckets of an attribute set.
|
|
33
|
+
* @param value Finite number.
|
|
34
|
+
* @param attributes Attribute set of the point.
|
|
35
|
+
*/
|
|
36
|
+
record(value: number, attributes?: MetricAttributes): void;
|
|
37
|
+
}
|
|
38
|
+
/** Kind of an instrument. */
|
|
39
|
+
export type InstrumentKind = "counter" | "histogram";
|
|
40
|
+
/** Definition of an instrument. A handle gives it to the meter at each call. */
|
|
41
|
+
export interface InstrumentDef {
|
|
42
|
+
/** Metric name. */
|
|
43
|
+
name: string;
|
|
44
|
+
/** Kind of the instrument. */
|
|
45
|
+
kind: InstrumentKind;
|
|
46
|
+
/** Unit of the values. */
|
|
47
|
+
unit: string;
|
|
48
|
+
/** Bucket boundaries of a histogram. A counter has none. */
|
|
49
|
+
boundaries: readonly number[];
|
|
50
|
+
}
|
package/dist/models/storage.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { LogBatch } from "./batch";
|
|
2
|
+
import type { RetentionOptions } from "./config";
|
|
2
3
|
/** Persistent batch storage interface. All methods must resolve and never throw. */
|
|
3
4
|
export interface StorageAdapter {
|
|
4
5
|
/** Adapter identifier name. */
|
|
@@ -46,17 +47,28 @@ export interface StorageLimits {
|
|
|
46
47
|
/** Maximum delivery attempts before dead-letter drop. */
|
|
47
48
|
maxAttempts: number;
|
|
48
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Gives the storage limits of a retention setting. "until-delivered" has no age limit and no
|
|
52
|
+
* attempt limit. The batch cap still applies.
|
|
53
|
+
* @param retention Retention setting from the config.
|
|
54
|
+
* @returns The limits for the storage adapters and the retry engine.
|
|
55
|
+
*/
|
|
56
|
+
export declare function storageLimits(retention: RetentionOptions): StorageLimits;
|
|
49
57
|
/** Metrics for batches and records dropped during storage pruning. */
|
|
50
58
|
export interface PruneResult {
|
|
51
59
|
/** Total batches dropped. */
|
|
52
60
|
batches: number;
|
|
53
61
|
/** Total records dropped within evicted batches. */
|
|
54
62
|
records: number;
|
|
55
|
-
/**
|
|
56
|
-
|
|
63
|
+
/**
|
|
64
|
+
* Cause of the drop. If more than one rule applies, this is the last rule. "not_stored" means
|
|
65
|
+
* that storage did not keep a batch after a failed send.
|
|
66
|
+
*/
|
|
67
|
+
reason: "expired" | "over_capacity" | "quota" | "not_stored";
|
|
57
68
|
}
|
|
58
69
|
/**
|
|
59
70
|
* Callback invoked when dropped records create a telemetry gap.
|
|
60
71
|
* @param result Summary of evicted data.
|
|
72
|
+
* @param dropped The dropped batches. A corrupt entry has no batch. The list then has none for it.
|
|
61
73
|
*/
|
|
62
|
-
export type GapReporter = (result: PruneResult) => void;
|
|
74
|
+
export type GapReporter = (result: PruneResult, dropped: readonly LogBatch[]) => void;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-DNOJjpOm.cjs"),n=require("./library-request-BIG3Xpx3.cjs"),r=require("./patch-BX8KrPCT.cjs");function i(e,t){return typeof e==`string`&&t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}var a=1e3,o={name:`http.client.request.duration`,kind:`histogram`,unit:`s`,boundaries:[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10]};function s(t,n,r,i){let a=typeof location<`u`?location.href:void 0,o={"http.request.method":t,"server.address":new URL(n,a).hostname};if(r===0){let t=e.r(i)?i.name:``;return o[`error.type`]=t===``?`_OTHER`:t,o}return o[`http.response.status_code`]=r,r>=400&&(o[`error.type`]=String(r)),o}function c(){return XMLHttpRequest.prototype}function l(e){if(typeof e==`string`)return e;if(e instanceof URL)return e.href;if(typeof e==`object`&&e){let{url:t}=e;if(typeof t==`string`)return t}return String(e)}function u(e,t){let n=t?.method;return n===void 0&&typeof e==`object`&&e&&(n=e.method),f(n??`GET`)}function d(e){return typeof e==`object`&&!(e instanceof URL)&&!(e instanceof Request)}function f(e){return typeof e==`string`?e.toUpperCase():String(e)}var p=class{ctx;name=`network`;installed=!1;restores=[];warnedTransport=!1;constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr())}uninstall(){if(this.installed){this.installed=!1;for(let e of this.restores.splice(0))e()}}ignored(e){return n.t()||i(e,this.ctx.config.capture.ignoreUrls)}propagates(e){let t=this.ctx.config.capture.propagateTraceHeaderTo;if(t.length===0)return!1;let n=this.ctx.diagnostics.guard(`capture.header_failed`,`The library could not read the origin of a request URL. Only a RegExp target can match it.`,()=>new URL(e,location.href).origin);return t.some(t=>typeof t==`string`?t===n:t.test(e))}installFetch(){if(typeof globalThis.fetch!=`function`)return;let e=!0,t=(e,t)=>this.prepareFetch(e,t),n=(e,t,n,r,i)=>{this.record(e,t,n,r,i)},i=r.t(globalThis,`fetch`,r=>{let i=r.bind(globalThis);return async function(r,a){let o=e?t(r,a):void 0;if(!o)return i(r,a);let s=performance.now();try{let e=await i(o.input,o.init);return n(o.method,o.url,e.status,performance.now()-s,void 0),e}catch(e){throw n(o.method,o.url,0,performance.now()-s,e),e}}});this.restores.push(()=>{e=!1,i()})}prepareFetch(e,t){let n=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read a fetch request. It sends the request unchanged.`,()=>{let n=l(e);if(!this.ignored(n))return{method:u(e,t),url:n,propagate:this.propagates(n)}});if(!n)return;let{method:r,url:i}=n,a={method:r,url:i,input:e,init:t};if(!n.propagate||d(e))return a;try{let n=Object.entries(this.ctx.tracing.headers());if(e instanceof Request){let t=new Headers(e.headers);for(let[e,r]of n)t.set(e,r);a.input=new Request(e,{headers:t})}else{let e=new Headers(t?.headers);for(let[t,r]of n)e.set(t,r);a.init={...t,headers:e}}}catch(n){a.input=e,a.init=t,this.ctx.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:i},n)}return a}installXhr(){if(typeof XMLHttpRequest>`u`)return;let e=!0,t=this.ctx,n=e=>this.ignored(e),i=e=>this.propagates(e),a=(e,t,n,r)=>{this.record(e,t,n,r,void 0)},o=c(),s=r.t(o,`open`,n=>function(r,i,...a){e&&t.diagnostics.guard(`capture.record_failed`,`The library could not read an XMLHttpRequest. It does not record the request.`,()=>{this.__uiobs={method:f(r),url:l(i),startedAt:0}}),n.apply(this,[r,i,...a])}),u=r.t(o,`send`,r=>function(...o){let s=e?this.__uiobs:void 0;s&&t.diagnostics.guard(`capture.record_failed`,`The library could not record ${s.method} ${s.url}.`,()=>{n(s.url)||(s.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{a(s.method,s.url,this.status,performance.now()-s.startedAt)}),i(s.url)&&m(this,s.url,t))}),r.apply(this,o)});this.restores.push(()=>{e=!1,s(),u()})}record(e,r,i,c,l){let u=this.ctx.config.capture.fullUrls?r:t.r(r);!this.warnedTransport&&n.n()&&(this.warnedTransport=!0,this.ctx.diagnostics.report(`capture.transport_request`,`Network capture saw ${e} ${u} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`)),this.ctx.config.capture.httpMetrics&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record the duration of ${e} ${u}.`,()=>{let t=s(e,r,i,l);this.ctx.recordMetric(o,c/a,t)}),this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${e} ${u}.`,()=>{let t=Math.round(c);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${e} ${u} ${i===0?`failed`:String(i)}`,data:{durationMs:t}});let n={"http.request.method":e,"url.full":u,"http.response.status_code":i,"http.duration_ms":t};i===0?this.ctx.logger.error(`${e} ${u} failed`,l,n):i>=400?this.ctx.logger.warn(`${e} ${u} returned ${String(i)}`,n):this.ctx.logger.debug(`${e} ${u}`,n)})}};function m(e,t,n){try{for(let[t,r]of Object.entries(n.tracing.headers()))e.setRequestHeader(t,r)}catch(e){n.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:t},e)}}exports.NetworkCapture=p;
|
|
2
|
+
//# sourceMappingURL=network-C6kJbW6K.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network-C6kJbW6K.cjs","names":["isErrorLike","isLibraryRequest","patch","stripUrlQuery","isTransportPending","require_error_like","require_platform","require_library_request","require_patch","matchesAny","url","patterns","pattern","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","durationMs","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","rounded","xhr"],"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 { InstrumentDef, MetricAttributes } from \"../models/metric\";\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 /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: 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 /** Adds a value to a counter or a histogram of the runtime. */\n recordMetric: (def: InstrumentDef, value: number, attributes?: MetricAttributes) => void;\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 * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\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 type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\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/** Milliseconds in one second. The histogram is in seconds, as the OpenTelemetry name gives. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram of the OpenTelemetry semantic conventions. Its boundaries\n * are the ones that the conventions advise.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Gives the low-cardinality attributes of one request. The path and the query stay out. Each\n * value of an attribute makes a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error Failure of a request without a response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request without a response has the type of its error, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\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/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\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 /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** True after the report of a request during a custom transport call. It reports one time. */\n private warnedTransport = false;\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.installed) {\n return;\n }\n this.installed = true;\n\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 /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if 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 // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\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 const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\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 const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.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 second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = 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 plan.init = { ...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 plan.input = input;\n plan.init = init;\n this.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 return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(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\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\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 you set fullUrls.\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 // A request of the transport after an await records a value. That value causes the next send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard. A URL that does not parse must not stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\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\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\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"],"mappings":"gKAmHA,SAAgBS,EAAW,EAAc,EAAwC,CAM/E,OAJI,OAAOC,GAAQ,UAIZC,EAAS,KAAM,GACpB,OAAOC,GAAY,SAAWF,EAAI,SAASE,CAAO,EAAIA,EAAQ,KAAKF,CAAG,CACxE,CACF,CC7GA,IAAMG,EAAgB,IAMhBC,EAA+B,CACnC,KAAM,+BACN,KAAM,YACN,KAAM,IACN,WAAY,CAAC,KAAO,IAAM,KAAO,IAAM,KAAO,GAAK,IAAM,GAAK,IAAM,EAAG,IAAK,EAAG,IAAK,EAAE,CACxF,EAWA,SAASC,EACP,EACA,EACA,EACA,EACkB,CAElB,IAAMC,EAAO,OAAO,SAAa,IAAc,SAAS,KAAO,IAAA,GACzDC,EAA+B,CACnC,sBAAuBC,EACvB,iBAAkB,IAAI,IAAIR,EAAKM,CAAI,CAAC,CAAC,QACvC,EAEA,GAAIG,IAAW,EAAG,CAEhB,IAAMC,EAAOpB,EAAAA,EAAYqB,CAAK,EAAIA,EAAM,KAAO,GAE/C,MADA,GAAW,cAAgBD,IAAS,GAAK,SAAWA,EAC7CH,CACT,CAOA,MALA,GAAW,6BAA+BE,EACtCA,GAAU,MACZ,EAAW,cAAgB,OAAOA,CAAM,GAGnCF,CACT,CAwBA,SAASK,GAAyB,CAChC,OAAO,eAAe,SACxB,CAqBA,SAASC,EAAQ,EAAwB,C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ACnE,KAAK,IAAI,aAAaP,EAAeyB,EAAa1B,EAAeI,CAAU,CAC7E,CACF,EAKF,KAAK,IAAI,YAAY,MACnB,wBACA,gCAAgCC,EAAO,GAAGR,EAAI,OACxC,CACJ,IAAMmD,EAAU,KAAK,MAAMtB,CAAU,EAErC,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,OACV,QAAS,GAAGrB,EAAO,GAAGR,EAAI,GAAGS,IAAW,EAAI,SAAW,OAAOA,CAAM,IACpE,KAAM,CAAE,WAAY0C,CAAQ,CAC9B,CAAC,EAED,IAAM5C,EAAa,CACjB,sBAAuBC,EACvB,WAAYR,EACZ,4BAA6BS,EAC7B,mBAAoB0C,CACtB,EAEI1C,IAAW,EACb,KAAK,IAAI,OAAO,MAAM,GAAGD,EAAO,GAAGR,EAAI,SAAUW,EAAOJ,CAAU,EAGhEE,GAAU,IACZ,KAAK,IAAI,OAAO,KAAK,GAAGD,EAAO,GAAGR,EAAI,YAAY,OAAOS,CAAM,IAAKF,CAAU,EAMhF,KAAK,IAAI,OAAO,MAAM,GAAGC,EAAO,GAAGR,IAAOO,CAAU,CACtD,CACF,CACF,CACF,EAQA,SAAS0C,EAAgB,EAAqB,EAAa,EAA2B,CACpF,GAAI,CACF,IAAK,GAAM,CAACX,EAAKC,KAAU,OAAO,QAAQlB,EAAI,QAAQ,QAAQ,CAAC,EAC7D+B,EAAI,iBAAiBd,EAAKC,CAAK,CAEnC,OAAS5B,EAAO,CACdU,EAAI,YAAY,OACd,wBACA,oFACA,CAAE,KAAI,EACNV,CACF,CACF,CACF"}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { r as e } from "./error-like-Ywo5uRHo.js";
|
|
2
|
+
import { r as t } from "./platform-j0uMPwHi.js";
|
|
3
|
+
import { n, t as r } from "./library-request-DX6ev9oG.js";
|
|
4
|
+
import { t as i } from "./patch-CCWfuEY7.js";
|
|
5
|
+
//#region src/capture/types.ts
|
|
6
|
+
function a(e, t) {
|
|
7
|
+
return typeof e == "string" && t.some((t) => typeof t == "string" ? e.includes(t) : t.test(e));
|
|
8
|
+
}
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/capture/network.ts
|
|
11
|
+
var o = 1e3, s = {
|
|
12
|
+
name: "http.client.request.duration",
|
|
13
|
+
kind: "histogram",
|
|
14
|
+
unit: "s",
|
|
15
|
+
boundaries: [
|
|
16
|
+
.005,
|
|
17
|
+
.01,
|
|
18
|
+
.025,
|
|
19
|
+
.05,
|
|
20
|
+
.075,
|
|
21
|
+
.1,
|
|
22
|
+
.25,
|
|
23
|
+
.5,
|
|
24
|
+
.75,
|
|
25
|
+
1,
|
|
26
|
+
2.5,
|
|
27
|
+
5,
|
|
28
|
+
7.5,
|
|
29
|
+
10
|
|
30
|
+
]
|
|
31
|
+
};
|
|
32
|
+
function c(t, n, r, i) {
|
|
33
|
+
let a = typeof location < "u" ? location.href : void 0, o = {
|
|
34
|
+
"http.request.method": t,
|
|
35
|
+
"server.address": new URL(n, a).hostname
|
|
36
|
+
};
|
|
37
|
+
if (r === 0) {
|
|
38
|
+
let t = e(i) ? i.name : "";
|
|
39
|
+
return o["error.type"] = t === "" ? "_OTHER" : t, o;
|
|
40
|
+
}
|
|
41
|
+
return o["http.response.status_code"] = r, r >= 400 && (o["error.type"] = String(r)), o;
|
|
42
|
+
}
|
|
43
|
+
function l() {
|
|
44
|
+
return XMLHttpRequest.prototype;
|
|
45
|
+
}
|
|
46
|
+
function u(e) {
|
|
47
|
+
if (typeof e == "string") return e;
|
|
48
|
+
if (e instanceof URL) return e.href;
|
|
49
|
+
if (typeof e == "object" && e) {
|
|
50
|
+
let { url: t } = e;
|
|
51
|
+
if (typeof t == "string") return t;
|
|
52
|
+
}
|
|
53
|
+
return String(e);
|
|
54
|
+
}
|
|
55
|
+
function d(e, t) {
|
|
56
|
+
let n = t?.method;
|
|
57
|
+
return n === void 0 && typeof e == "object" && e && (n = e.method), p(n ?? "GET");
|
|
58
|
+
}
|
|
59
|
+
function f(e) {
|
|
60
|
+
return typeof e == "object" && !(e instanceof URL) && !(e instanceof Request);
|
|
61
|
+
}
|
|
62
|
+
function p(e) {
|
|
63
|
+
return typeof e == "string" ? e.toUpperCase() : String(e);
|
|
64
|
+
}
|
|
65
|
+
var m = class {
|
|
66
|
+
ctx;
|
|
67
|
+
name = "network";
|
|
68
|
+
installed = !1;
|
|
69
|
+
restores = [];
|
|
70
|
+
warnedTransport = !1;
|
|
71
|
+
constructor(e) {
|
|
72
|
+
this.ctx = e;
|
|
73
|
+
}
|
|
74
|
+
install() {
|
|
75
|
+
this.installed || (this.installed = !0, this.ctx.config.capture.fetch && this.installFetch(), this.ctx.config.capture.xhr && this.installXhr());
|
|
76
|
+
}
|
|
77
|
+
uninstall() {
|
|
78
|
+
if (this.installed) {
|
|
79
|
+
this.installed = !1;
|
|
80
|
+
for (let e of this.restores.splice(0)) e();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
ignored(e) {
|
|
84
|
+
return r() || a(e, this.ctx.config.capture.ignoreUrls);
|
|
85
|
+
}
|
|
86
|
+
propagates(e) {
|
|
87
|
+
let t = this.ctx.config.capture.propagateTraceHeaderTo;
|
|
88
|
+
if (t.length === 0) return !1;
|
|
89
|
+
let n = this.ctx.diagnostics.guard("capture.header_failed", "The library could not read the origin of a request URL. Only a RegExp target can match it.", () => new URL(e, location.href).origin);
|
|
90
|
+
return t.some((t) => typeof t == "string" ? t === n : t.test(e));
|
|
91
|
+
}
|
|
92
|
+
installFetch() {
|
|
93
|
+
if (typeof globalThis.fetch != "function") return;
|
|
94
|
+
let e = !0, t = (e, t) => this.prepareFetch(e, t), n = (e, t, n, r, i) => {
|
|
95
|
+
this.record(e, t, n, r, i);
|
|
96
|
+
}, r = i(globalThis, "fetch", (r) => {
|
|
97
|
+
let i = r.bind(globalThis);
|
|
98
|
+
return async function(r, a) {
|
|
99
|
+
let o = e ? t(r, a) : void 0;
|
|
100
|
+
if (!o) return i(r, a);
|
|
101
|
+
let s = performance.now();
|
|
102
|
+
try {
|
|
103
|
+
let e = await i(o.input, o.init);
|
|
104
|
+
return n(o.method, o.url, e.status, performance.now() - s, void 0), e;
|
|
105
|
+
} catch (e) {
|
|
106
|
+
throw n(o.method, o.url, 0, performance.now() - s, e), e;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
this.restores.push(() => {
|
|
111
|
+
e = !1, r();
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
prepareFetch(e, t) {
|
|
115
|
+
let n = this.ctx.diagnostics.guard("capture.record_failed", "The library could not read a fetch request. It sends the request unchanged.", () => {
|
|
116
|
+
let n = u(e);
|
|
117
|
+
if (!this.ignored(n)) return {
|
|
118
|
+
method: d(e, t),
|
|
119
|
+
url: n,
|
|
120
|
+
propagate: this.propagates(n)
|
|
121
|
+
};
|
|
122
|
+
});
|
|
123
|
+
if (!n) return;
|
|
124
|
+
let { method: r, url: i } = n, a = {
|
|
125
|
+
method: r,
|
|
126
|
+
url: i,
|
|
127
|
+
input: e,
|
|
128
|
+
init: t
|
|
129
|
+
};
|
|
130
|
+
if (!n.propagate || f(e)) return a;
|
|
131
|
+
try {
|
|
132
|
+
let n = Object.entries(this.ctx.tracing.headers());
|
|
133
|
+
if (e instanceof Request) {
|
|
134
|
+
let t = new Headers(e.headers);
|
|
135
|
+
for (let [e, r] of n) t.set(e, r);
|
|
136
|
+
a.input = new Request(e, { headers: t });
|
|
137
|
+
} else {
|
|
138
|
+
let e = new Headers(t?.headers);
|
|
139
|
+
for (let [t, r] of n) e.set(t, r);
|
|
140
|
+
a.init = {
|
|
141
|
+
...t,
|
|
142
|
+
headers: e
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
} catch (n) {
|
|
146
|
+
a.input = e, a.init = t, this.ctx.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: i }, n);
|
|
147
|
+
}
|
|
148
|
+
return a;
|
|
149
|
+
}
|
|
150
|
+
installXhr() {
|
|
151
|
+
if (typeof XMLHttpRequest > "u") return;
|
|
152
|
+
let e = !0, t = this.ctx, n = (e) => this.ignored(e), r = (e) => this.propagates(e), a = (e, t, n, r) => {
|
|
153
|
+
this.record(e, t, n, r, void 0);
|
|
154
|
+
}, o = l(), s = i(o, "open", (n) => function(r, i, ...a) {
|
|
155
|
+
e && t.diagnostics.guard("capture.record_failed", "The library could not read an XMLHttpRequest. It does not record the request.", () => {
|
|
156
|
+
this.__uiobs = {
|
|
157
|
+
method: p(r),
|
|
158
|
+
url: u(i),
|
|
159
|
+
startedAt: 0
|
|
160
|
+
};
|
|
161
|
+
}), n.apply(this, [
|
|
162
|
+
r,
|
|
163
|
+
i,
|
|
164
|
+
...a
|
|
165
|
+
]);
|
|
166
|
+
}), c = i(o, "send", (i) => function(...o) {
|
|
167
|
+
let s = e ? this.__uiobs : void 0;
|
|
168
|
+
s && t.diagnostics.guard("capture.record_failed", `The library could not record ${s.method} ${s.url}.`, () => {
|
|
169
|
+
n(s.url) || (s.startedAt = performance.now(), this.addEventListener("loadend", () => {
|
|
170
|
+
a(s.method, s.url, this.status, performance.now() - s.startedAt);
|
|
171
|
+
}), r(s.url) && h(this, s.url, t));
|
|
172
|
+
}), i.apply(this, o);
|
|
173
|
+
});
|
|
174
|
+
this.restores.push(() => {
|
|
175
|
+
e = !1, s(), c();
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
record(e, r, i, a, l) {
|
|
179
|
+
let u = this.ctx.config.capture.fullUrls ? r : t(r);
|
|
180
|
+
!this.warnedTransport && n() && (this.warnedTransport = !0, this.ctx.diagnostics.report("capture.transport_request", `Network capture saw ${e} ${u} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`)), this.ctx.config.capture.httpMetrics && this.ctx.diagnostics.guard("capture.record_failed", `The library could not record the duration of ${e} ${u}.`, () => {
|
|
181
|
+
let t = c(e, r, i, l);
|
|
182
|
+
this.ctx.recordMetric(s, a / o, t);
|
|
183
|
+
}), this.ctx.diagnostics.guard("capture.record_failed", `The library could not record ${e} ${u}.`, () => {
|
|
184
|
+
let t = Math.round(a);
|
|
185
|
+
this.ctx.breadcrumbs.push({
|
|
186
|
+
t: Date.now(),
|
|
187
|
+
category: "http",
|
|
188
|
+
message: `${e} ${u} ${i === 0 ? "failed" : String(i)}`,
|
|
189
|
+
data: { durationMs: t }
|
|
190
|
+
});
|
|
191
|
+
let n = {
|
|
192
|
+
"http.request.method": e,
|
|
193
|
+
"url.full": u,
|
|
194
|
+
"http.response.status_code": i,
|
|
195
|
+
"http.duration_ms": t
|
|
196
|
+
};
|
|
197
|
+
i === 0 ? this.ctx.logger.error(`${e} ${u} failed`, l, n) : i >= 400 ? this.ctx.logger.warn(`${e} ${u} returned ${String(i)}`, n) : this.ctx.logger.debug(`${e} ${u}`, n);
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
function h(e, t, n) {
|
|
202
|
+
try {
|
|
203
|
+
for (let [t, r] of Object.entries(n.tracing.headers())) e.setRequestHeader(t, r);
|
|
204
|
+
} catch (e) {
|
|
205
|
+
n.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: t }, e);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
//#endregion
|
|
209
|
+
export { m as NetworkCapture };
|
|
210
|
+
|
|
211
|
+
//# sourceMappingURL=network-CMnEvGJB.js.map
|