@adsk-platform/httpclient 0.1.0 → 0.1.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.
@@ -1,3787 +0,0 @@
1
- (function(global2, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.AutodeskCommonHttpClient = {}));
3
- })(this, (function(exports2) {
4
- "use strict";
5
- class ParseNodeFactoryRegistry {
6
- constructor() {
7
- this.jsonContentType = "application/json";
8
- this.contentTypeAssociatedFactories = /* @__PURE__ */ new Map();
9
- }
10
- getValidContentType() {
11
- throw new Error("The registry supports multiple content types. Get the registered factory instead.");
12
- }
13
- /**
14
- * Creates a {@link ParseNode} from the given {@link ArrayBuffer} and content type.
15
- * @param contentType the content type of the {@link ArrayBuffer}.
16
- * @param content the {@link ArrayBuffer} to read from.
17
- * @returns a {@link ParseNode} that can deserialize the given {@link ArrayBuffer}.
18
- */
19
- getRootParseNode(contentType, content) {
20
- if (!contentType) {
21
- throw new Error("content type cannot be undefined or empty");
22
- }
23
- if (!content) {
24
- throw new Error("content cannot be undefined or empty");
25
- }
26
- const vendorSpecificContentType = contentType.split(";")[0];
27
- let factory = this.contentTypeAssociatedFactories.get(vendorSpecificContentType);
28
- if (factory) {
29
- return factory.getRootParseNode(vendorSpecificContentType, content);
30
- }
31
- const cleanedContentType = vendorSpecificContentType.replace(/[^/]+\+/gi, "");
32
- factory = this.contentTypeAssociatedFactories.get(cleanedContentType);
33
- if (factory) {
34
- return factory.getRootParseNode(cleanedContentType, content);
35
- }
36
- throw new Error(`Content type ${cleanedContentType} does not have a factory registered to be parsed`);
37
- }
38
- /**
39
- * Registers the default deserializer to the registry.
40
- * @param type the class of the factory to be registered.
41
- * @param backingStoreFactory The backing store factory to use.
42
- */
43
- registerDefaultDeserializer(type, backingStoreFactory) {
44
- if (!type)
45
- throw new Error("Type is required");
46
- const deserializer = new type(backingStoreFactory);
47
- this.contentTypeAssociatedFactories.set(deserializer.getValidContentType(), deserializer);
48
- }
49
- /**
50
- * Deserializes a buffer into a parsable object
51
- * @param bufferOrString the value to serialize
52
- * @param factory the factory for the model type
53
- * @returns the deserialized parsable object
54
- */
55
- deserializeFromJson(bufferOrString, factory) {
56
- return this.deserialize(this.jsonContentType, bufferOrString, factory);
57
- }
58
- /**
59
- * Deserializes a buffer into a collection of parsable object
60
- * @param bufferOrString the value to serialize
61
- * @param factory the factory for the model type
62
- * @returns the deserialized collection of parsable objects
63
- */
64
- deserializeCollectionFromJson(bufferOrString, factory) {
65
- return this.deserializeCollection(this.jsonContentType, bufferOrString, factory);
66
- }
67
- /**
68
- * Deserializes a buffer into a parsable object
69
- * @param contentType the content type to serialize to
70
- * @param bufferOrString the value to serialize
71
- * @param factory the factory for the model type
72
- * @returns the deserialized parsable object
73
- */
74
- deserialize(contentType, bufferOrString, factory) {
75
- if (typeof bufferOrString === "string") {
76
- bufferOrString = this.getBufferFromString(bufferOrString);
77
- }
78
- const reader = this.getParseNode(contentType, bufferOrString, factory);
79
- return reader.getObjectValue(factory);
80
- }
81
- /**
82
- * Deserializes a buffer into a parsable object
83
- * @param contentType the content type to serialize to
84
- * @param buffer the value to deserialize
85
- * @param factory the factory for the model type
86
- * @returns the deserialized parsable object
87
- */
88
- getParseNode(contentType, buffer, factory) {
89
- if (!contentType) {
90
- throw new Error("content type cannot be undefined or empty");
91
- }
92
- if (!buffer) {
93
- throw new Error("buffer cannot be undefined");
94
- }
95
- if (!factory) {
96
- throw new Error("factory cannot be undefined");
97
- }
98
- return this.getRootParseNode(contentType, buffer);
99
- }
100
- /**
101
- * Deserializes a buffer into a collection of parsable object
102
- * @param contentType the content type to serialize to
103
- * @param bufferOrString the value to serialize
104
- * @param factory the factory for the model type
105
- * @returns the deserialized collection of parsable objects
106
- */
107
- deserializeCollection(contentType, bufferOrString, factory) {
108
- if (typeof bufferOrString === "string") {
109
- bufferOrString = this.getBufferFromString(bufferOrString);
110
- }
111
- const reader = this.getParseNode(contentType, bufferOrString, factory);
112
- return reader.getCollectionOfObjectValues(factory);
113
- }
114
- /**
115
- * Deserializes a buffer into a a collection of parsable object
116
- * @param value the string to get a buffer from
117
- * @returns the ArrayBuffer representation of the string
118
- */
119
- getBufferFromString(value) {
120
- const encoder = new TextEncoder();
121
- return encoder.encode(value).buffer;
122
- }
123
- }
124
- class ParseNodeProxyFactory {
125
- getValidContentType() {
126
- return this._concrete.getValidContentType();
127
- }
128
- /**
129
- * Creates a new proxy factory that wraps the specified concrete factory while composing the before and after callbacks.
130
- * @param _concrete the concrete factory to wrap
131
- * @param _onBefore the callback to invoke before the deserialization of any model object.
132
- * @param _onAfter the callback to invoke after the deserialization of any model object.
133
- */
134
- constructor(_concrete, _onBefore, _onAfter) {
135
- this._concrete = _concrete;
136
- this._onBefore = _onBefore;
137
- this._onAfter = _onAfter;
138
- if (!_concrete) {
139
- throw new Error("_concrete cannot be undefined");
140
- }
141
- }
142
- getRootParseNode(contentType, content) {
143
- const node = this._concrete.getRootParseNode(contentType, content);
144
- const originalBefore = node.onBeforeAssignFieldValues;
145
- const originalAfter = node.onAfterAssignFieldValues;
146
- node.onBeforeAssignFieldValues = (value) => {
147
- if (this._onBefore)
148
- this._onBefore(value);
149
- if (originalBefore)
150
- originalBefore(value);
151
- };
152
- node.onAfterAssignFieldValues = (value) => {
153
- if (this._onAfter)
154
- this._onAfter(value);
155
- if (originalAfter)
156
- originalAfter(value);
157
- };
158
- return node;
159
- }
160
- }
161
- class SerializationWriterFactoryRegistry {
162
- constructor() {
163
- this.jsonContentType = "application/json";
164
- this.contentTypeAssociatedFactories = /* @__PURE__ */ new Map();
165
- }
166
- getValidContentType() {
167
- throw new Error("The registry supports multiple content types. Get the registered factory instead.");
168
- }
169
- getSerializationWriter(contentType) {
170
- if (!contentType) {
171
- throw new Error("content type cannot be undefined or empty");
172
- }
173
- const vendorSpecificContentType = contentType.split(";")[0];
174
- let factory = this.contentTypeAssociatedFactories.get(vendorSpecificContentType);
175
- if (factory) {
176
- return factory.getSerializationWriter(vendorSpecificContentType);
177
- }
178
- const cleanedContentType = vendorSpecificContentType.replace(/[^/]+\+/gi, "");
179
- factory = this.contentTypeAssociatedFactories.get(cleanedContentType);
180
- if (factory) {
181
- return factory.getSerializationWriter(cleanedContentType);
182
- }
183
- throw new Error(`Content type ${cleanedContentType} does not have a factory registered to be serialized`);
184
- }
185
- /**
186
- * Registers the default serializer to the registry.
187
- * @param type the class of the factory to be registered.
188
- */
189
- registerDefaultSerializer(type) {
190
- if (!type)
191
- throw new Error("Type is required");
192
- const serializer = new type();
193
- this.contentTypeAssociatedFactories.set(serializer.getValidContentType(), serializer);
194
- }
195
- /**
196
- * Serializes a parsable object into a buffer
197
- * @param value the value to serialize
198
- * @param serializationFunction the serialization function for the model type
199
- * @returns a buffer containing the serialized value
200
- */
201
- serializeToJson(value, serializationFunction) {
202
- return this.serialize(this.jsonContentType, value, serializationFunction);
203
- }
204
- /**
205
- * Serializes a parsable object into a string representation
206
- * @param value the value to serialize
207
- * @param serializationFunction the serialization function for the model type
208
- * @returns a string representing the serialized value
209
- */
210
- serializeToJsonAsString(value, serializationFunction) {
211
- return this.serializeToString(this.jsonContentType, value, serializationFunction);
212
- }
213
- /**
214
- * Serializes a collection of parsable objects into a buffer
215
- * @param values the value to serialize
216
- * @param serializationFunction the serialization function for the model type
217
- * @returns a string representing the serialized value
218
- */
219
- serializeCollectionToJson(values, serializationFunction) {
220
- return this.serializeCollection(this.jsonContentType, values, serializationFunction);
221
- }
222
- /**
223
- * Serializes a collection of parsable objects into a string representation
224
- * @param values the value to serialize
225
- * @param serializationFunction the serialization function for the model type
226
- * @returns a string representing the serialized value
227
- */
228
- serializeCollectionToJsonAsString(values, serializationFunction) {
229
- return this.serializeCollectionToString(this.jsonContentType, values, serializationFunction);
230
- }
231
- /**
232
- * Serializes a parsable object into a buffer
233
- * @param contentType the content type to serialize to
234
- * @param value the value to serialize
235
- * @param serializationFunction the serialization function for the model type
236
- * @returns a buffer containing the serialized value
237
- */
238
- serialize(contentType, value, serializationFunction) {
239
- const writer = this.getSerializationFactoryWriter(contentType, value, serializationFunction);
240
- writer.writeObjectValue(void 0, value, serializationFunction);
241
- return writer.getSerializedContent();
242
- }
243
- /**
244
- * Serializes a parsable object into a string representation
245
- * @param contentType the content type to serialize to
246
- * @param value the value to serialize
247
- * @param serializationFunction the serialization function for the model type
248
- * @returns a string representing the serialized value
249
- */
250
- serializeToString(contentType, value, serializationFunction) {
251
- const buffer = this.serialize(contentType, value, serializationFunction);
252
- return this.getStringValueFromBuffer(buffer);
253
- }
254
- /**
255
- * Serializes a collection of parsable objects into a buffer
256
- * @param contentType the content type to serialize to
257
- * @param values the value to serialize
258
- * @param serializationFunction the serialization function for the model type
259
- * @returns a string representing the serialized value
260
- */
261
- serializeCollection(contentType, values, serializationFunction) {
262
- const writer = this.getSerializationFactoryWriter(contentType, values, serializationFunction);
263
- writer.writeCollectionOfObjectValues(void 0, values, serializationFunction);
264
- return writer.getSerializedContent();
265
- }
266
- /**
267
- * Serializes a collection of parsable objects into a string representation
268
- * @param contentType the content type to serialize to
269
- * @param values the value to serialize
270
- * @param serializationFunction the serialization function for the model type
271
- * @returns a string representing the serialized value
272
- */
273
- serializeCollectionToString(contentType, values, serializationFunction) {
274
- const buffer = this.serializeCollection(contentType, values, serializationFunction);
275
- return this.getStringValueFromBuffer(buffer);
276
- }
277
- /**
278
- * Gets a serialization writer for a given content type
279
- * @param contentType the content type to serialize to
280
- * @param value the value to serialize
281
- * @param serializationFunction the serialization function for the model type
282
- * @returns the serialization writer for the given content type
283
- */
284
- getSerializationFactoryWriter(contentType, value, serializationFunction) {
285
- if (!contentType) {
286
- throw new Error("content type cannot be undefined or empty");
287
- }
288
- if (!value) {
289
- throw new Error("value cannot be undefined");
290
- }
291
- if (!serializationFunction) {
292
- throw new Error("serializationFunction cannot be undefined");
293
- }
294
- return this.getSerializationWriter(contentType);
295
- }
296
- /**
297
- * Gets a string value from a buffer
298
- * @param buffer the buffer to get a string from
299
- * @returns the string representation of the buffer
300
- */
301
- getStringValueFromBuffer(buffer) {
302
- const decoder = new TextDecoder();
303
- return decoder.decode(buffer);
304
- }
305
- }
306
- class SerializationWriterProxyFactory {
307
- getValidContentType() {
308
- return this._concrete.getValidContentType();
309
- }
310
- /**
311
- * Creates a new proxy factory that wraps the specified concrete factory while composing the before and after callbacks.
312
- * @param _concrete the concrete factory to wrap
313
- * @param _onBefore the callback to invoke before the serialization of any model object.
314
- * @param _onAfter the callback to invoke after the serialization of any model object.
315
- * @param _onStart the callback to invoke when the serialization of a model object starts
316
- */
317
- constructor(_concrete, _onBefore, _onAfter, _onStart) {
318
- this._concrete = _concrete;
319
- this._onBefore = _onBefore;
320
- this._onAfter = _onAfter;
321
- this._onStart = _onStart;
322
- if (!_concrete) {
323
- throw new Error("_concrete cannot be undefined");
324
- }
325
- }
326
- getSerializationWriter(contentType) {
327
- const writer = this._concrete.getSerializationWriter(contentType);
328
- const originalBefore = writer.onBeforeObjectSerialization;
329
- const originalAfter = writer.onAfterObjectSerialization;
330
- const originalStart = writer.onStartObjectSerialization;
331
- writer.onBeforeObjectSerialization = (value) => {
332
- if (this._onBefore)
333
- this._onBefore(value);
334
- if (originalBefore)
335
- originalBefore(value);
336
- };
337
- writer.onAfterObjectSerialization = (value) => {
338
- if (this._onAfter)
339
- this._onAfter(value);
340
- if (originalAfter)
341
- originalAfter(value);
342
- };
343
- writer.onStartObjectSerialization = (value, writer_) => {
344
- if (this._onStart)
345
- this._onStart(value, writer_);
346
- if (originalStart)
347
- originalStart(value, writer_);
348
- };
349
- return writer;
350
- }
351
- }
352
- class BackingStoreParseNodeFactory extends ParseNodeProxyFactory {
353
- /**
354
- * Initializes a new instance of the BackingStoreParseNodeFactory class given the concrete implementation.
355
- * @param concrete the concrete implementation of the ParseNodeFactory
356
- */
357
- constructor(concrete) {
358
- super(concrete, (value) => {
359
- const backedModel = value;
360
- if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) {
361
- backedModel.backingStore.initializationCompleted = false;
362
- }
363
- }, (value) => {
364
- const backedModel = value;
365
- if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) {
366
- backedModel.backingStore.initializationCompleted = true;
367
- }
368
- });
369
- }
370
- }
371
- class BackingStoreSerializationWriterProxyFactory extends SerializationWriterProxyFactory {
372
- /**
373
- * Initializes a new instance of the BackingStoreSerializationWriterProxyFactory class given a concrete implementation of SerializationWriterFactory.
374
- * @param concrete a concrete implementation of SerializationWriterFactory to wrap.
375
- */
376
- constructor(concrete) {
377
- super(concrete, (value) => {
378
- const backedModel = value;
379
- if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) {
380
- backedModel.backingStore.returnOnlyChangedValues = true;
381
- }
382
- }, (value) => {
383
- const backedModel = value;
384
- if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) {
385
- backedModel.backingStore.returnOnlyChangedValues = false;
386
- backedModel.backingStore.initializationCompleted = true;
387
- }
388
- }, (value, writer) => {
389
- const backedModel = value;
390
- if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) {
391
- const keys = backedModel.backingStore.enumerateKeysForValuesChangedToNull();
392
- for (const key of keys) {
393
- writer.writeNullValue(key);
394
- }
395
- }
396
- });
397
- }
398
- }
399
- const createGuid = () => [gen(2), gen(1), gen(1), gen(1), gen(3)].join("-");
400
- const gen = (count) => {
401
- let out = "";
402
- for (let i = 0; i < count; i++) {
403
- out += ((1 + Math.random()) * 65536 | 0).toString(16).substring(1);
404
- }
405
- return out;
406
- };
407
- const inNodeEnv = () => {
408
- try {
409
- return !!Buffer && !!process;
410
- } catch (err) {
411
- return !(err instanceof ReferenceError);
412
- }
413
- };
414
- class InMemoryBackingStore {
415
- constructor() {
416
- this.subscriptions = /* @__PURE__ */ new Map();
417
- this.store = /* @__PURE__ */ new Map();
418
- this.returnOnlyChangedValues = false;
419
- this._initializationCompleted = true;
420
- }
421
- get(key) {
422
- const wrapper = this.store.get(key);
423
- if (wrapper && (this.returnOnlyChangedValues && wrapper.changed || !this.returnOnlyChangedValues)) {
424
- return wrapper.value;
425
- }
426
- return void 0;
427
- }
428
- set(key, value) {
429
- const oldValueWrapper = this.store.get(key);
430
- const oldValue = oldValueWrapper === null || oldValueWrapper === void 0 ? void 0 : oldValueWrapper.value;
431
- if (oldValueWrapper) {
432
- oldValueWrapper.value = value;
433
- oldValueWrapper.changed = this.initializationCompleted;
434
- } else {
435
- this.store.set(key, {
436
- changed: this.initializationCompleted,
437
- value
438
- });
439
- }
440
- this.subscriptions.forEach((sub) => {
441
- sub(key, oldValue, value);
442
- });
443
- }
444
- enumerate() {
445
- let filterableArray = [...this.store.entries()];
446
- if (this.returnOnlyChangedValues) {
447
- filterableArray = filterableArray.filter(([_, v]) => v.changed);
448
- }
449
- return filterableArray.map(([key, value]) => {
450
- return { key, value };
451
- });
452
- }
453
- enumerateKeysForValuesChangedToNull() {
454
- const keys = [];
455
- for (const [key, entry] of this.store) {
456
- if (entry.changed && !entry.value) {
457
- keys.push(key);
458
- }
459
- }
460
- return keys;
461
- }
462
- subscribe(callback, subscriptionId) {
463
- if (!callback) {
464
- throw new Error("callback cannot be undefined");
465
- }
466
- subscriptionId = subscriptionId !== null && subscriptionId !== void 0 ? subscriptionId : createGuid();
467
- this.subscriptions.set(subscriptionId, callback);
468
- return subscriptionId;
469
- }
470
- unsubscribe(subscriptionId) {
471
- this.subscriptions.delete(subscriptionId);
472
- }
473
- clear() {
474
- this.store.clear();
475
- }
476
- set initializationCompleted(value) {
477
- this._initializationCompleted = value;
478
- this.store.forEach((v) => {
479
- v.changed = !value;
480
- });
481
- }
482
- get initializationCompleted() {
483
- return this._initializationCompleted;
484
- }
485
- }
486
- class InMemoryBackingStoreFactory {
487
- createBackingStore() {
488
- return new InMemoryBackingStore();
489
- }
490
- }
491
- function enableBackingStoreForSerializationWriterFactory(serializationWriterFactoryRegistry, parseNodeFactoryRegistry, original) {
492
- if (!original)
493
- throw new Error("Original must be specified");
494
- let result = original;
495
- if (original instanceof SerializationWriterFactoryRegistry) {
496
- enableBackingStoreForSerializationRegistry(original);
497
- } else {
498
- result = new BackingStoreSerializationWriterProxyFactory(original);
499
- }
500
- enableBackingStoreForSerializationRegistry(serializationWriterFactoryRegistry);
501
- enableBackingStoreForParseNodeRegistry(parseNodeFactoryRegistry);
502
- return result;
503
- }
504
- function enableBackingStoreForParseNodeFactory(parseNodeFactoryRegistry, original) {
505
- if (!original)
506
- throw new Error("Original must be specified");
507
- let result = original;
508
- if (original instanceof ParseNodeFactoryRegistry) {
509
- enableBackingStoreForParseNodeRegistry(original);
510
- } else {
511
- result = new BackingStoreParseNodeFactory(original);
512
- }
513
- enableBackingStoreForParseNodeRegistry(parseNodeFactoryRegistry);
514
- return result;
515
- }
516
- function enableBackingStoreForParseNodeRegistry(registry) {
517
- for (const [k, v] of registry.contentTypeAssociatedFactories) {
518
- if (!(v instanceof BackingStoreParseNodeFactory || v instanceof ParseNodeFactoryRegistry)) {
519
- registry.contentTypeAssociatedFactories.set(k, new BackingStoreParseNodeFactory(v));
520
- }
521
- }
522
- }
523
- function enableBackingStoreForSerializationRegistry(registry) {
524
- for (const [k, v] of registry.contentTypeAssociatedFactories) {
525
- if (!(v instanceof BackingStoreSerializationWriterProxyFactory || v instanceof SerializationWriterFactoryRegistry)) {
526
- registry.contentTypeAssociatedFactories.set(k, new BackingStoreSerializationWriterProxyFactory(v));
527
- }
528
- }
529
- }
530
- var _globalThis = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {};
531
- var VERSION = "1.9.0";
532
- var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
533
- function _makeCompatibilityCheck(ownVersion) {
534
- var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
535
- var rejectedVersions = /* @__PURE__ */ new Set();
536
- var myVersionMatch = ownVersion.match(re);
537
- if (!myVersionMatch) {
538
- return function() {
539
- return false;
540
- };
541
- }
542
- var ownVersionParsed = {
543
- major: +myVersionMatch[1],
544
- minor: +myVersionMatch[2],
545
- patch: +myVersionMatch[3],
546
- prerelease: myVersionMatch[4]
547
- };
548
- if (ownVersionParsed.prerelease != null) {
549
- return function isExactmatch(globalVersion) {
550
- return globalVersion === ownVersion;
551
- };
552
- }
553
- function _reject(v) {
554
- rejectedVersions.add(v);
555
- return false;
556
- }
557
- function _accept(v) {
558
- acceptedVersions.add(v);
559
- return true;
560
- }
561
- return function isCompatible2(globalVersion) {
562
- if (acceptedVersions.has(globalVersion)) {
563
- return true;
564
- }
565
- if (rejectedVersions.has(globalVersion)) {
566
- return false;
567
- }
568
- var globalVersionMatch = globalVersion.match(re);
569
- if (!globalVersionMatch) {
570
- return _reject(globalVersion);
571
- }
572
- var globalVersionParsed = {
573
- major: +globalVersionMatch[1],
574
- minor: +globalVersionMatch[2],
575
- patch: +globalVersionMatch[3],
576
- prerelease: globalVersionMatch[4]
577
- };
578
- if (globalVersionParsed.prerelease != null) {
579
- return _reject(globalVersion);
580
- }
581
- if (ownVersionParsed.major !== globalVersionParsed.major) {
582
- return _reject(globalVersion);
583
- }
584
- if (ownVersionParsed.major === 0) {
585
- if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
586
- return _accept(globalVersion);
587
- }
588
- return _reject(globalVersion);
589
- }
590
- if (ownVersionParsed.minor <= globalVersionParsed.minor) {
591
- return _accept(globalVersion);
592
- }
593
- return _reject(globalVersion);
594
- };
595
- }
596
- var isCompatible = _makeCompatibilityCheck(VERSION);
597
- var major = VERSION.split(".")[0];
598
- var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
599
- var _global = _globalThis;
600
- function registerGlobal(type, instance, diag, allowOverride) {
601
- var _a;
602
- if (allowOverride === void 0) {
603
- allowOverride = false;
604
- }
605
- var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
606
- version: VERSION
607
- };
608
- if (!allowOverride && api[type]) {
609
- var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
610
- diag.error(err.stack || err.message);
611
- return false;
612
- }
613
- if (api.version !== VERSION) {
614
- var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
615
- diag.error(err.stack || err.message);
616
- return false;
617
- }
618
- api[type] = instance;
619
- diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
620
- return true;
621
- }
622
- function getGlobal(type) {
623
- var _a, _b;
624
- var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
625
- if (!globalVersion || !isCompatible(globalVersion)) {
626
- return;
627
- }
628
- return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
629
- }
630
- function unregisterGlobal(type, diag) {
631
- diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
632
- var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
633
- if (api) {
634
- delete api[type];
635
- }
636
- }
637
- var __read$4 = function(o, n) {
638
- var m = typeof Symbol === "function" && o[Symbol.iterator];
639
- if (!m) return o;
640
- var i = m.call(o), r, ar = [], e;
641
- try {
642
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
643
- } catch (error) {
644
- e = { error };
645
- } finally {
646
- try {
647
- if (r && !r.done && (m = i["return"])) m.call(i);
648
- } finally {
649
- if (e) throw e.error;
650
- }
651
- }
652
- return ar;
653
- };
654
- var __spreadArray$3 = function(to, from, pack) {
655
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
656
- if (ar || !(i in from)) {
657
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
658
- ar[i] = from[i];
659
- }
660
- }
661
- return to.concat(ar || Array.prototype.slice.call(from));
662
- };
663
- var DiagComponentLogger = (
664
- /** @class */
665
- (function() {
666
- function DiagComponentLogger2(props) {
667
- this._namespace = props.namespace || "DiagComponentLogger";
668
- }
669
- DiagComponentLogger2.prototype.debug = function() {
670
- var args = [];
671
- for (var _i = 0; _i < arguments.length; _i++) {
672
- args[_i] = arguments[_i];
673
- }
674
- return logProxy("debug", this._namespace, args);
675
- };
676
- DiagComponentLogger2.prototype.error = function() {
677
- var args = [];
678
- for (var _i = 0; _i < arguments.length; _i++) {
679
- args[_i] = arguments[_i];
680
- }
681
- return logProxy("error", this._namespace, args);
682
- };
683
- DiagComponentLogger2.prototype.info = function() {
684
- var args = [];
685
- for (var _i = 0; _i < arguments.length; _i++) {
686
- args[_i] = arguments[_i];
687
- }
688
- return logProxy("info", this._namespace, args);
689
- };
690
- DiagComponentLogger2.prototype.warn = function() {
691
- var args = [];
692
- for (var _i = 0; _i < arguments.length; _i++) {
693
- args[_i] = arguments[_i];
694
- }
695
- return logProxy("warn", this._namespace, args);
696
- };
697
- DiagComponentLogger2.prototype.verbose = function() {
698
- var args = [];
699
- for (var _i = 0; _i < arguments.length; _i++) {
700
- args[_i] = arguments[_i];
701
- }
702
- return logProxy("verbose", this._namespace, args);
703
- };
704
- return DiagComponentLogger2;
705
- })()
706
- );
707
- function logProxy(funcName, namespace, args) {
708
- var logger = getGlobal("diag");
709
- if (!logger) {
710
- return;
711
- }
712
- args.unshift(namespace);
713
- return logger[funcName].apply(logger, __spreadArray$3([], __read$4(args), false));
714
- }
715
- var DiagLogLevel;
716
- (function(DiagLogLevel2) {
717
- DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
718
- DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
719
- DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
720
- DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
721
- DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
722
- DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
723
- DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
724
- })(DiagLogLevel || (DiagLogLevel = {}));
725
- function createLogLevelDiagLogger(maxLevel, logger) {
726
- if (maxLevel < DiagLogLevel.NONE) {
727
- maxLevel = DiagLogLevel.NONE;
728
- } else if (maxLevel > DiagLogLevel.ALL) {
729
- maxLevel = DiagLogLevel.ALL;
730
- }
731
- logger = logger || {};
732
- function _filterFunc(funcName, theLevel) {
733
- var theFunc = logger[funcName];
734
- if (typeof theFunc === "function" && maxLevel >= theLevel) {
735
- return theFunc.bind(logger);
736
- }
737
- return function() {
738
- };
739
- }
740
- return {
741
- error: _filterFunc("error", DiagLogLevel.ERROR),
742
- warn: _filterFunc("warn", DiagLogLevel.WARN),
743
- info: _filterFunc("info", DiagLogLevel.INFO),
744
- debug: _filterFunc("debug", DiagLogLevel.DEBUG),
745
- verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
746
- };
747
- }
748
- var __read$3 = function(o, n) {
749
- var m = typeof Symbol === "function" && o[Symbol.iterator];
750
- if (!m) return o;
751
- var i = m.call(o), r, ar = [], e;
752
- try {
753
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
754
- } catch (error) {
755
- e = { error };
756
- } finally {
757
- try {
758
- if (r && !r.done && (m = i["return"])) m.call(i);
759
- } finally {
760
- if (e) throw e.error;
761
- }
762
- }
763
- return ar;
764
- };
765
- var __spreadArray$2 = function(to, from, pack) {
766
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
767
- if (ar || !(i in from)) {
768
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
769
- ar[i] = from[i];
770
- }
771
- }
772
- return to.concat(ar || Array.prototype.slice.call(from));
773
- };
774
- var API_NAME$4 = "diag";
775
- var DiagAPI = (
776
- /** @class */
777
- (function() {
778
- function DiagAPI2() {
779
- function _logProxy(funcName) {
780
- return function() {
781
- var args = [];
782
- for (var _i = 0; _i < arguments.length; _i++) {
783
- args[_i] = arguments[_i];
784
- }
785
- var logger = getGlobal("diag");
786
- if (!logger)
787
- return;
788
- return logger[funcName].apply(logger, __spreadArray$2([], __read$3(args), false));
789
- };
790
- }
791
- var self2 = this;
792
- var setLogger = function(logger, optionsOrLogLevel) {
793
- var _a, _b, _c;
794
- if (optionsOrLogLevel === void 0) {
795
- optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
796
- }
797
- if (logger === self2) {
798
- var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
799
- self2.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
800
- return false;
801
- }
802
- if (typeof optionsOrLogLevel === "number") {
803
- optionsOrLogLevel = {
804
- logLevel: optionsOrLogLevel
805
- };
806
- }
807
- var oldLogger = getGlobal("diag");
808
- var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
809
- if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
810
- var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
811
- oldLogger.warn("Current logger will be overwritten from " + stack);
812
- newLogger.warn("Current logger will overwrite one already registered from " + stack);
813
- }
814
- return registerGlobal("diag", newLogger, self2, true);
815
- };
816
- self2.setLogger = setLogger;
817
- self2.disable = function() {
818
- unregisterGlobal(API_NAME$4, self2);
819
- };
820
- self2.createComponentLogger = function(options) {
821
- return new DiagComponentLogger(options);
822
- };
823
- self2.verbose = _logProxy("verbose");
824
- self2.debug = _logProxy("debug");
825
- self2.info = _logProxy("info");
826
- self2.warn = _logProxy("warn");
827
- self2.error = _logProxy("error");
828
- }
829
- DiagAPI2.instance = function() {
830
- if (!this._instance) {
831
- this._instance = new DiagAPI2();
832
- }
833
- return this._instance;
834
- };
835
- return DiagAPI2;
836
- })()
837
- );
838
- var __read$2 = function(o, n) {
839
- var m = typeof Symbol === "function" && o[Symbol.iterator];
840
- if (!m) return o;
841
- var i = m.call(o), r, ar = [], e;
842
- try {
843
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
844
- } catch (error) {
845
- e = { error };
846
- } finally {
847
- try {
848
- if (r && !r.done && (m = i["return"])) m.call(i);
849
- } finally {
850
- if (e) throw e.error;
851
- }
852
- }
853
- return ar;
854
- };
855
- var __values = function(o) {
856
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
857
- if (m) return m.call(o);
858
- if (o && typeof o.length === "number") return {
859
- next: function() {
860
- if (o && i >= o.length) o = void 0;
861
- return { value: o && o[i++], done: !o };
862
- }
863
- };
864
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
865
- };
866
- var BaggageImpl = (
867
- /** @class */
868
- (function() {
869
- function BaggageImpl2(entries) {
870
- this._entries = entries ? new Map(entries) : /* @__PURE__ */ new Map();
871
- }
872
- BaggageImpl2.prototype.getEntry = function(key) {
873
- var entry = this._entries.get(key);
874
- if (!entry) {
875
- return void 0;
876
- }
877
- return Object.assign({}, entry);
878
- };
879
- BaggageImpl2.prototype.getAllEntries = function() {
880
- return Array.from(this._entries.entries()).map(function(_a) {
881
- var _b = __read$2(_a, 2), k = _b[0], v = _b[1];
882
- return [k, v];
883
- });
884
- };
885
- BaggageImpl2.prototype.setEntry = function(key, entry) {
886
- var newBaggage = new BaggageImpl2(this._entries);
887
- newBaggage._entries.set(key, entry);
888
- return newBaggage;
889
- };
890
- BaggageImpl2.prototype.removeEntry = function(key) {
891
- var newBaggage = new BaggageImpl2(this._entries);
892
- newBaggage._entries.delete(key);
893
- return newBaggage;
894
- };
895
- BaggageImpl2.prototype.removeEntries = function() {
896
- var e_1, _a;
897
- var keys = [];
898
- for (var _i = 0; _i < arguments.length; _i++) {
899
- keys[_i] = arguments[_i];
900
- }
901
- var newBaggage = new BaggageImpl2(this._entries);
902
- try {
903
- for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
904
- var key = keys_1_1.value;
905
- newBaggage._entries.delete(key);
906
- }
907
- } catch (e_1_1) {
908
- e_1 = { error: e_1_1 };
909
- } finally {
910
- try {
911
- if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1);
912
- } finally {
913
- if (e_1) throw e_1.error;
914
- }
915
- }
916
- return newBaggage;
917
- };
918
- BaggageImpl2.prototype.clear = function() {
919
- return new BaggageImpl2();
920
- };
921
- return BaggageImpl2;
922
- })()
923
- );
924
- DiagAPI.instance();
925
- function createBaggage(entries) {
926
- if (entries === void 0) {
927
- entries = {};
928
- }
929
- return new BaggageImpl(new Map(Object.entries(entries)));
930
- }
931
- function createContextKey(description) {
932
- return Symbol.for(description);
933
- }
934
- var BaseContext = (
935
- /** @class */
936
- /* @__PURE__ */ (function() {
937
- function BaseContext2(parentContext) {
938
- var self2 = this;
939
- self2._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
940
- self2.getValue = function(key) {
941
- return self2._currentContext.get(key);
942
- };
943
- self2.setValue = function(key, value) {
944
- var context = new BaseContext2(self2._currentContext);
945
- context._currentContext.set(key, value);
946
- return context;
947
- };
948
- self2.deleteValue = function(key) {
949
- var context = new BaseContext2(self2._currentContext);
950
- context._currentContext.delete(key);
951
- return context;
952
- };
953
- }
954
- return BaseContext2;
955
- })()
956
- );
957
- var ROOT_CONTEXT = new BaseContext();
958
- var __extends = /* @__PURE__ */ (function() {
959
- var extendStatics = function(d, b) {
960
- extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
961
- d2.__proto__ = b2;
962
- } || function(d2, b2) {
963
- for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
964
- };
965
- return extendStatics(d, b);
966
- };
967
- return function(d, b) {
968
- if (typeof b !== "function" && b !== null)
969
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
970
- extendStatics(d, b);
971
- function __() {
972
- this.constructor = d;
973
- }
974
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
975
- };
976
- })();
977
- var NoopMeter = (
978
- /** @class */
979
- (function() {
980
- function NoopMeter2() {
981
- }
982
- NoopMeter2.prototype.createGauge = function(_name, _options) {
983
- return NOOP_GAUGE_METRIC;
984
- };
985
- NoopMeter2.prototype.createHistogram = function(_name, _options) {
986
- return NOOP_HISTOGRAM_METRIC;
987
- };
988
- NoopMeter2.prototype.createCounter = function(_name, _options) {
989
- return NOOP_COUNTER_METRIC;
990
- };
991
- NoopMeter2.prototype.createUpDownCounter = function(_name, _options) {
992
- return NOOP_UP_DOWN_COUNTER_METRIC;
993
- };
994
- NoopMeter2.prototype.createObservableGauge = function(_name, _options) {
995
- return NOOP_OBSERVABLE_GAUGE_METRIC;
996
- };
997
- NoopMeter2.prototype.createObservableCounter = function(_name, _options) {
998
- return NOOP_OBSERVABLE_COUNTER_METRIC;
999
- };
1000
- NoopMeter2.prototype.createObservableUpDownCounter = function(_name, _options) {
1001
- return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
1002
- };
1003
- NoopMeter2.prototype.addBatchObservableCallback = function(_callback, _observables) {
1004
- };
1005
- NoopMeter2.prototype.removeBatchObservableCallback = function(_callback) {
1006
- };
1007
- return NoopMeter2;
1008
- })()
1009
- );
1010
- var NoopMetric = (
1011
- /** @class */
1012
- /* @__PURE__ */ (function() {
1013
- function NoopMetric2() {
1014
- }
1015
- return NoopMetric2;
1016
- })()
1017
- );
1018
- var NoopCounterMetric = (
1019
- /** @class */
1020
- (function(_super) {
1021
- __extends(NoopCounterMetric2, _super);
1022
- function NoopCounterMetric2() {
1023
- return _super !== null && _super.apply(this, arguments) || this;
1024
- }
1025
- NoopCounterMetric2.prototype.add = function(_value, _attributes) {
1026
- };
1027
- return NoopCounterMetric2;
1028
- })(NoopMetric)
1029
- );
1030
- var NoopUpDownCounterMetric = (
1031
- /** @class */
1032
- (function(_super) {
1033
- __extends(NoopUpDownCounterMetric2, _super);
1034
- function NoopUpDownCounterMetric2() {
1035
- return _super !== null && _super.apply(this, arguments) || this;
1036
- }
1037
- NoopUpDownCounterMetric2.prototype.add = function(_value, _attributes) {
1038
- };
1039
- return NoopUpDownCounterMetric2;
1040
- })(NoopMetric)
1041
- );
1042
- var NoopGaugeMetric = (
1043
- /** @class */
1044
- (function(_super) {
1045
- __extends(NoopGaugeMetric2, _super);
1046
- function NoopGaugeMetric2() {
1047
- return _super !== null && _super.apply(this, arguments) || this;
1048
- }
1049
- NoopGaugeMetric2.prototype.record = function(_value, _attributes) {
1050
- };
1051
- return NoopGaugeMetric2;
1052
- })(NoopMetric)
1053
- );
1054
- var NoopHistogramMetric = (
1055
- /** @class */
1056
- (function(_super) {
1057
- __extends(NoopHistogramMetric2, _super);
1058
- function NoopHistogramMetric2() {
1059
- return _super !== null && _super.apply(this, arguments) || this;
1060
- }
1061
- NoopHistogramMetric2.prototype.record = function(_value, _attributes) {
1062
- };
1063
- return NoopHistogramMetric2;
1064
- })(NoopMetric)
1065
- );
1066
- var NoopObservableMetric = (
1067
- /** @class */
1068
- (function() {
1069
- function NoopObservableMetric2() {
1070
- }
1071
- NoopObservableMetric2.prototype.addCallback = function(_callback) {
1072
- };
1073
- NoopObservableMetric2.prototype.removeCallback = function(_callback) {
1074
- };
1075
- return NoopObservableMetric2;
1076
- })()
1077
- );
1078
- var NoopObservableCounterMetric = (
1079
- /** @class */
1080
- (function(_super) {
1081
- __extends(NoopObservableCounterMetric2, _super);
1082
- function NoopObservableCounterMetric2() {
1083
- return _super !== null && _super.apply(this, arguments) || this;
1084
- }
1085
- return NoopObservableCounterMetric2;
1086
- })(NoopObservableMetric)
1087
- );
1088
- var NoopObservableGaugeMetric = (
1089
- /** @class */
1090
- (function(_super) {
1091
- __extends(NoopObservableGaugeMetric2, _super);
1092
- function NoopObservableGaugeMetric2() {
1093
- return _super !== null && _super.apply(this, arguments) || this;
1094
- }
1095
- return NoopObservableGaugeMetric2;
1096
- })(NoopObservableMetric)
1097
- );
1098
- var NoopObservableUpDownCounterMetric = (
1099
- /** @class */
1100
- (function(_super) {
1101
- __extends(NoopObservableUpDownCounterMetric2, _super);
1102
- function NoopObservableUpDownCounterMetric2() {
1103
- return _super !== null && _super.apply(this, arguments) || this;
1104
- }
1105
- return NoopObservableUpDownCounterMetric2;
1106
- })(NoopObservableMetric)
1107
- );
1108
- var NOOP_METER = new NoopMeter();
1109
- var NOOP_COUNTER_METRIC = new NoopCounterMetric();
1110
- var NOOP_GAUGE_METRIC = new NoopGaugeMetric();
1111
- var NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();
1112
- var NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();
1113
- var NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();
1114
- var NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();
1115
- var NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric();
1116
- var defaultTextMapGetter = {
1117
- get: function(carrier, key) {
1118
- if (carrier == null) {
1119
- return void 0;
1120
- }
1121
- return carrier[key];
1122
- },
1123
- keys: function(carrier) {
1124
- if (carrier == null) {
1125
- return [];
1126
- }
1127
- return Object.keys(carrier);
1128
- }
1129
- };
1130
- var defaultTextMapSetter = {
1131
- set: function(carrier, key, value) {
1132
- if (carrier == null) {
1133
- return;
1134
- }
1135
- carrier[key] = value;
1136
- }
1137
- };
1138
- var __read$1 = function(o, n) {
1139
- var m = typeof Symbol === "function" && o[Symbol.iterator];
1140
- if (!m) return o;
1141
- var i = m.call(o), r, ar = [], e;
1142
- try {
1143
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
1144
- } catch (error) {
1145
- e = { error };
1146
- } finally {
1147
- try {
1148
- if (r && !r.done && (m = i["return"])) m.call(i);
1149
- } finally {
1150
- if (e) throw e.error;
1151
- }
1152
- }
1153
- return ar;
1154
- };
1155
- var __spreadArray$1 = function(to, from, pack) {
1156
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1157
- if (ar || !(i in from)) {
1158
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1159
- ar[i] = from[i];
1160
- }
1161
- }
1162
- return to.concat(ar || Array.prototype.slice.call(from));
1163
- };
1164
- var NoopContextManager = (
1165
- /** @class */
1166
- (function() {
1167
- function NoopContextManager2() {
1168
- }
1169
- NoopContextManager2.prototype.active = function() {
1170
- return ROOT_CONTEXT;
1171
- };
1172
- NoopContextManager2.prototype.with = function(_context, fn, thisArg) {
1173
- var args = [];
1174
- for (var _i = 3; _i < arguments.length; _i++) {
1175
- args[_i - 3] = arguments[_i];
1176
- }
1177
- return fn.call.apply(fn, __spreadArray$1([thisArg], __read$1(args), false));
1178
- };
1179
- NoopContextManager2.prototype.bind = function(_context, target) {
1180
- return target;
1181
- };
1182
- NoopContextManager2.prototype.enable = function() {
1183
- return this;
1184
- };
1185
- NoopContextManager2.prototype.disable = function() {
1186
- return this;
1187
- };
1188
- return NoopContextManager2;
1189
- })()
1190
- );
1191
- var __read = function(o, n) {
1192
- var m = typeof Symbol === "function" && o[Symbol.iterator];
1193
- if (!m) return o;
1194
- var i = m.call(o), r, ar = [], e;
1195
- try {
1196
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
1197
- } catch (error) {
1198
- e = { error };
1199
- } finally {
1200
- try {
1201
- if (r && !r.done && (m = i["return"])) m.call(i);
1202
- } finally {
1203
- if (e) throw e.error;
1204
- }
1205
- }
1206
- return ar;
1207
- };
1208
- var __spreadArray = function(to, from, pack) {
1209
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1210
- if (ar || !(i in from)) {
1211
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1212
- ar[i] = from[i];
1213
- }
1214
- }
1215
- return to.concat(ar || Array.prototype.slice.call(from));
1216
- };
1217
- var API_NAME$3 = "context";
1218
- var NOOP_CONTEXT_MANAGER = new NoopContextManager();
1219
- var ContextAPI = (
1220
- /** @class */
1221
- (function() {
1222
- function ContextAPI2() {
1223
- }
1224
- ContextAPI2.getInstance = function() {
1225
- if (!this._instance) {
1226
- this._instance = new ContextAPI2();
1227
- }
1228
- return this._instance;
1229
- };
1230
- ContextAPI2.prototype.setGlobalContextManager = function(contextManager) {
1231
- return registerGlobal(API_NAME$3, contextManager, DiagAPI.instance());
1232
- };
1233
- ContextAPI2.prototype.active = function() {
1234
- return this._getContextManager().active();
1235
- };
1236
- ContextAPI2.prototype.with = function(context, fn, thisArg) {
1237
- var _a;
1238
- var args = [];
1239
- for (var _i = 3; _i < arguments.length; _i++) {
1240
- args[_i - 3] = arguments[_i];
1241
- }
1242
- return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], __read(args), false));
1243
- };
1244
- ContextAPI2.prototype.bind = function(context, target) {
1245
- return this._getContextManager().bind(context, target);
1246
- };
1247
- ContextAPI2.prototype._getContextManager = function() {
1248
- return getGlobal(API_NAME$3) || NOOP_CONTEXT_MANAGER;
1249
- };
1250
- ContextAPI2.prototype.disable = function() {
1251
- this._getContextManager().disable();
1252
- unregisterGlobal(API_NAME$3, DiagAPI.instance());
1253
- };
1254
- return ContextAPI2;
1255
- })()
1256
- );
1257
- var TraceFlags;
1258
- (function(TraceFlags2) {
1259
- TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
1260
- TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
1261
- })(TraceFlags || (TraceFlags = {}));
1262
- var INVALID_SPANID = "0000000000000000";
1263
- var INVALID_TRACEID = "00000000000000000000000000000000";
1264
- var INVALID_SPAN_CONTEXT = {
1265
- traceId: INVALID_TRACEID,
1266
- spanId: INVALID_SPANID,
1267
- traceFlags: TraceFlags.NONE
1268
- };
1269
- var NonRecordingSpan = (
1270
- /** @class */
1271
- (function() {
1272
- function NonRecordingSpan2(_spanContext) {
1273
- if (_spanContext === void 0) {
1274
- _spanContext = INVALID_SPAN_CONTEXT;
1275
- }
1276
- this._spanContext = _spanContext;
1277
- }
1278
- NonRecordingSpan2.prototype.spanContext = function() {
1279
- return this._spanContext;
1280
- };
1281
- NonRecordingSpan2.prototype.setAttribute = function(_key, _value) {
1282
- return this;
1283
- };
1284
- NonRecordingSpan2.prototype.setAttributes = function(_attributes) {
1285
- return this;
1286
- };
1287
- NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) {
1288
- return this;
1289
- };
1290
- NonRecordingSpan2.prototype.addLink = function(_link) {
1291
- return this;
1292
- };
1293
- NonRecordingSpan2.prototype.addLinks = function(_links) {
1294
- return this;
1295
- };
1296
- NonRecordingSpan2.prototype.setStatus = function(_status) {
1297
- return this;
1298
- };
1299
- NonRecordingSpan2.prototype.updateName = function(_name) {
1300
- return this;
1301
- };
1302
- NonRecordingSpan2.prototype.end = function(_endTime) {
1303
- };
1304
- NonRecordingSpan2.prototype.isRecording = function() {
1305
- return false;
1306
- };
1307
- NonRecordingSpan2.prototype.recordException = function(_exception, _time) {
1308
- };
1309
- return NonRecordingSpan2;
1310
- })()
1311
- );
1312
- var SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
1313
- function getSpan(context) {
1314
- return context.getValue(SPAN_KEY) || void 0;
1315
- }
1316
- function getActiveSpan() {
1317
- return getSpan(ContextAPI.getInstance().active());
1318
- }
1319
- function setSpan(context, span) {
1320
- return context.setValue(SPAN_KEY, span);
1321
- }
1322
- function deleteSpan(context) {
1323
- return context.deleteValue(SPAN_KEY);
1324
- }
1325
- function setSpanContext(context, spanContext) {
1326
- return setSpan(context, new NonRecordingSpan(spanContext));
1327
- }
1328
- function getSpanContext(context) {
1329
- var _a;
1330
- return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();
1331
- }
1332
- var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
1333
- var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
1334
- function isValidTraceId(traceId) {
1335
- return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;
1336
- }
1337
- function isValidSpanId(spanId) {
1338
- return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;
1339
- }
1340
- function isSpanContextValid(spanContext) {
1341
- return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
1342
- }
1343
- function wrapSpanContext(spanContext) {
1344
- return new NonRecordingSpan(spanContext);
1345
- }
1346
- var contextApi = ContextAPI.getInstance();
1347
- var NoopTracer = (
1348
- /** @class */
1349
- (function() {
1350
- function NoopTracer2() {
1351
- }
1352
- NoopTracer2.prototype.startSpan = function(name, options, context) {
1353
- if (context === void 0) {
1354
- context = contextApi.active();
1355
- }
1356
- var root = Boolean(options === null || options === void 0 ? void 0 : options.root);
1357
- if (root) {
1358
- return new NonRecordingSpan();
1359
- }
1360
- var parentFromContext = context && getSpanContext(context);
1361
- if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
1362
- return new NonRecordingSpan(parentFromContext);
1363
- } else {
1364
- return new NonRecordingSpan();
1365
- }
1366
- };
1367
- NoopTracer2.prototype.startActiveSpan = function(name, arg2, arg3, arg4) {
1368
- var opts;
1369
- var ctx;
1370
- var fn;
1371
- if (arguments.length < 2) {
1372
- return;
1373
- } else if (arguments.length === 2) {
1374
- fn = arg2;
1375
- } else if (arguments.length === 3) {
1376
- opts = arg2;
1377
- fn = arg3;
1378
- } else {
1379
- opts = arg2;
1380
- ctx = arg3;
1381
- fn = arg4;
1382
- }
1383
- var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
1384
- var span = this.startSpan(name, opts, parentContext);
1385
- var contextWithSpanSet = setSpan(parentContext, span);
1386
- return contextApi.with(contextWithSpanSet, fn, void 0, span);
1387
- };
1388
- return NoopTracer2;
1389
- })()
1390
- );
1391
- function isSpanContext(spanContext) {
1392
- return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
1393
- }
1394
- var NOOP_TRACER = new NoopTracer();
1395
- var ProxyTracer = (
1396
- /** @class */
1397
- (function() {
1398
- function ProxyTracer2(_provider, name, version, options) {
1399
- this._provider = _provider;
1400
- this.name = name;
1401
- this.version = version;
1402
- this.options = options;
1403
- }
1404
- ProxyTracer2.prototype.startSpan = function(name, options, context) {
1405
- return this._getTracer().startSpan(name, options, context);
1406
- };
1407
- ProxyTracer2.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
1408
- var tracer = this._getTracer();
1409
- return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
1410
- };
1411
- ProxyTracer2.prototype._getTracer = function() {
1412
- if (this._delegate) {
1413
- return this._delegate;
1414
- }
1415
- var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
1416
- if (!tracer) {
1417
- return NOOP_TRACER;
1418
- }
1419
- this._delegate = tracer;
1420
- return this._delegate;
1421
- };
1422
- return ProxyTracer2;
1423
- })()
1424
- );
1425
- var NoopTracerProvider = (
1426
- /** @class */
1427
- (function() {
1428
- function NoopTracerProvider2() {
1429
- }
1430
- NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options) {
1431
- return new NoopTracer();
1432
- };
1433
- return NoopTracerProvider2;
1434
- })()
1435
- );
1436
- var NOOP_TRACER_PROVIDER = new NoopTracerProvider();
1437
- var ProxyTracerProvider = (
1438
- /** @class */
1439
- (function() {
1440
- function ProxyTracerProvider2() {
1441
- }
1442
- ProxyTracerProvider2.prototype.getTracer = function(name, version, options) {
1443
- var _a;
1444
- return (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options);
1445
- };
1446
- ProxyTracerProvider2.prototype.getDelegate = function() {
1447
- var _a;
1448
- return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
1449
- };
1450
- ProxyTracerProvider2.prototype.setDelegate = function(delegate) {
1451
- this._delegate = delegate;
1452
- };
1453
- ProxyTracerProvider2.prototype.getDelegateTracer = function(name, version, options) {
1454
- var _a;
1455
- return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);
1456
- };
1457
- return ProxyTracerProvider2;
1458
- })()
1459
- );
1460
- var SpanStatusCode;
1461
- (function(SpanStatusCode2) {
1462
- SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
1463
- SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
1464
- SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
1465
- })(SpanStatusCode || (SpanStatusCode = {}));
1466
- ContextAPI.getInstance();
1467
- DiagAPI.instance();
1468
- var NoopMeterProvider = (
1469
- /** @class */
1470
- (function() {
1471
- function NoopMeterProvider2() {
1472
- }
1473
- NoopMeterProvider2.prototype.getMeter = function(_name, _version, _options) {
1474
- return NOOP_METER;
1475
- };
1476
- return NoopMeterProvider2;
1477
- })()
1478
- );
1479
- var NOOP_METER_PROVIDER = new NoopMeterProvider();
1480
- var API_NAME$2 = "metrics";
1481
- var MetricsAPI = (
1482
- /** @class */
1483
- (function() {
1484
- function MetricsAPI2() {
1485
- }
1486
- MetricsAPI2.getInstance = function() {
1487
- if (!this._instance) {
1488
- this._instance = new MetricsAPI2();
1489
- }
1490
- return this._instance;
1491
- };
1492
- MetricsAPI2.prototype.setGlobalMeterProvider = function(provider) {
1493
- return registerGlobal(API_NAME$2, provider, DiagAPI.instance());
1494
- };
1495
- MetricsAPI2.prototype.getMeterProvider = function() {
1496
- return getGlobal(API_NAME$2) || NOOP_METER_PROVIDER;
1497
- };
1498
- MetricsAPI2.prototype.getMeter = function(name, version, options) {
1499
- return this.getMeterProvider().getMeter(name, version, options);
1500
- };
1501
- MetricsAPI2.prototype.disable = function() {
1502
- unregisterGlobal(API_NAME$2, DiagAPI.instance());
1503
- };
1504
- return MetricsAPI2;
1505
- })()
1506
- );
1507
- MetricsAPI.getInstance();
1508
- var NoopTextMapPropagator = (
1509
- /** @class */
1510
- (function() {
1511
- function NoopTextMapPropagator2() {
1512
- }
1513
- NoopTextMapPropagator2.prototype.inject = function(_context, _carrier) {
1514
- };
1515
- NoopTextMapPropagator2.prototype.extract = function(context, _carrier) {
1516
- return context;
1517
- };
1518
- NoopTextMapPropagator2.prototype.fields = function() {
1519
- return [];
1520
- };
1521
- return NoopTextMapPropagator2;
1522
- })()
1523
- );
1524
- var BAGGAGE_KEY = createContextKey("OpenTelemetry Baggage Key");
1525
- function getBaggage(context) {
1526
- return context.getValue(BAGGAGE_KEY) || void 0;
1527
- }
1528
- function getActiveBaggage() {
1529
- return getBaggage(ContextAPI.getInstance().active());
1530
- }
1531
- function setBaggage(context, baggage) {
1532
- return context.setValue(BAGGAGE_KEY, baggage);
1533
- }
1534
- function deleteBaggage(context) {
1535
- return context.deleteValue(BAGGAGE_KEY);
1536
- }
1537
- var API_NAME$1 = "propagation";
1538
- var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator();
1539
- var PropagationAPI = (
1540
- /** @class */
1541
- (function() {
1542
- function PropagationAPI2() {
1543
- this.createBaggage = createBaggage;
1544
- this.getBaggage = getBaggage;
1545
- this.getActiveBaggage = getActiveBaggage;
1546
- this.setBaggage = setBaggage;
1547
- this.deleteBaggage = deleteBaggage;
1548
- }
1549
- PropagationAPI2.getInstance = function() {
1550
- if (!this._instance) {
1551
- this._instance = new PropagationAPI2();
1552
- }
1553
- return this._instance;
1554
- };
1555
- PropagationAPI2.prototype.setGlobalPropagator = function(propagator) {
1556
- return registerGlobal(API_NAME$1, propagator, DiagAPI.instance());
1557
- };
1558
- PropagationAPI2.prototype.inject = function(context, carrier, setter) {
1559
- if (setter === void 0) {
1560
- setter = defaultTextMapSetter;
1561
- }
1562
- return this._getGlobalPropagator().inject(context, carrier, setter);
1563
- };
1564
- PropagationAPI2.prototype.extract = function(context, carrier, getter) {
1565
- if (getter === void 0) {
1566
- getter = defaultTextMapGetter;
1567
- }
1568
- return this._getGlobalPropagator().extract(context, carrier, getter);
1569
- };
1570
- PropagationAPI2.prototype.fields = function() {
1571
- return this._getGlobalPropagator().fields();
1572
- };
1573
- PropagationAPI2.prototype.disable = function() {
1574
- unregisterGlobal(API_NAME$1, DiagAPI.instance());
1575
- };
1576
- PropagationAPI2.prototype._getGlobalPropagator = function() {
1577
- return getGlobal(API_NAME$1) || NOOP_TEXT_MAP_PROPAGATOR;
1578
- };
1579
- return PropagationAPI2;
1580
- })()
1581
- );
1582
- PropagationAPI.getInstance();
1583
- var API_NAME = "trace";
1584
- var TraceAPI = (
1585
- /** @class */
1586
- (function() {
1587
- function TraceAPI2() {
1588
- this._proxyTracerProvider = new ProxyTracerProvider();
1589
- this.wrapSpanContext = wrapSpanContext;
1590
- this.isSpanContextValid = isSpanContextValid;
1591
- this.deleteSpan = deleteSpan;
1592
- this.getSpan = getSpan;
1593
- this.getActiveSpan = getActiveSpan;
1594
- this.getSpanContext = getSpanContext;
1595
- this.setSpan = setSpan;
1596
- this.setSpanContext = setSpanContext;
1597
- }
1598
- TraceAPI2.getInstance = function() {
1599
- if (!this._instance) {
1600
- this._instance = new TraceAPI2();
1601
- }
1602
- return this._instance;
1603
- };
1604
- TraceAPI2.prototype.setGlobalTracerProvider = function(provider) {
1605
- var success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance());
1606
- if (success) {
1607
- this._proxyTracerProvider.setDelegate(provider);
1608
- }
1609
- return success;
1610
- };
1611
- TraceAPI2.prototype.getTracerProvider = function() {
1612
- return getGlobal(API_NAME) || this._proxyTracerProvider;
1613
- };
1614
- TraceAPI2.prototype.getTracer = function(name, version) {
1615
- return this.getTracerProvider().getTracer(name, version);
1616
- };
1617
- TraceAPI2.prototype.disable = function() {
1618
- unregisterGlobal(API_NAME, DiagAPI.instance());
1619
- this._proxyTracerProvider = new ProxyTracerProvider();
1620
- };
1621
- return TraceAPI2;
1622
- })()
1623
- );
1624
- var trace = TraceAPI.getInstance();
1625
- var dist = {};
1626
- var hasRequiredDist;
1627
- function requireDist() {
1628
- if (hasRequiredDist) return dist;
1629
- hasRequiredDist = 1;
1630
- (function(exports3) {
1631
- Object.defineProperty(exports3, "__esModule", { value: true });
1632
- exports3.serialize = exports3.parse = exports3.MultipleFractionsError = exports3.InvalidDurationError = void 0;
1633
- const DEFAULT_PARSE_CONFIG = {
1634
- allowMultipleFractions: true
1635
- };
1636
- const units = [
1637
- { unit: "years", symbol: "Y" },
1638
- { unit: "months", symbol: "M" },
1639
- { unit: "weeks", symbol: "W" },
1640
- { unit: "days", symbol: "D" },
1641
- { unit: "hours", symbol: "H" },
1642
- { unit: "minutes", symbol: "M" },
1643
- { unit: "seconds", symbol: "S" }
1644
- ];
1645
- const r = (name, unit) => `((?<${name}>-?\\d*[\\.,]?\\d+)${unit})?`;
1646
- const durationRegex = new RegExp([
1647
- "(?<negative>-)?P",
1648
- r("years", "Y"),
1649
- r("months", "M"),
1650
- r("weeks", "W"),
1651
- r("days", "D"),
1652
- "(T",
1653
- r("hours", "H"),
1654
- r("minutes", "M"),
1655
- r("seconds", "S"),
1656
- ")?"
1657
- // end optional time
1658
- ].join(""));
1659
- function parseNum(s2) {
1660
- if (s2 === "" || s2 === void 0 || s2 === null) {
1661
- return void 0;
1662
- }
1663
- return parseFloat(s2.replace(",", "."));
1664
- }
1665
- exports3.InvalidDurationError = new Error("Invalid duration");
1666
- exports3.MultipleFractionsError = new Error("Multiple fractions specified");
1667
- function parse(durationStr, config = DEFAULT_PARSE_CONFIG) {
1668
- const match = durationRegex.exec(durationStr);
1669
- if (!match || !match.groups) {
1670
- throw exports3.InvalidDurationError;
1671
- }
1672
- let empty = true;
1673
- let decimalFractionCount = 0;
1674
- const values = {};
1675
- for (const { unit } of units) {
1676
- if (match.groups[unit]) {
1677
- empty = false;
1678
- values[unit] = parseNum(match.groups[unit]);
1679
- if (!config.allowMultipleFractions && !Number.isInteger(values[unit])) {
1680
- decimalFractionCount++;
1681
- if (decimalFractionCount > 1) {
1682
- throw exports3.MultipleFractionsError;
1683
- }
1684
- }
1685
- }
1686
- }
1687
- if (empty) {
1688
- throw exports3.InvalidDurationError;
1689
- }
1690
- const duration = values;
1691
- if (match.groups.negative) {
1692
- duration.negative = true;
1693
- }
1694
- return duration;
1695
- }
1696
- exports3.parse = parse;
1697
- const s = (number, component) => {
1698
- if (!number) {
1699
- return void 0;
1700
- }
1701
- let numberAsString = number.toString();
1702
- const exponentIndex = numberAsString.indexOf("e");
1703
- if (exponentIndex > -1) {
1704
- const magnitude = parseInt(numberAsString.slice(exponentIndex + 2), 10);
1705
- numberAsString = number.toFixed(magnitude + exponentIndex - 2);
1706
- }
1707
- return numberAsString + component;
1708
- };
1709
- function serialize(duration) {
1710
- if (!duration.years && !duration.months && !duration.weeks && !duration.days && !duration.hours && !duration.minutes && !duration.seconds) {
1711
- return "PT0S";
1712
- }
1713
- return [
1714
- duration.negative && "-",
1715
- "P",
1716
- s(duration.years, "Y"),
1717
- s(duration.months, "M"),
1718
- s(duration.weeks, "W"),
1719
- s(duration.days, "D"),
1720
- (duration.hours || duration.minutes || duration.seconds) && "T",
1721
- s(duration.hours, "H"),
1722
- s(duration.minutes, "M"),
1723
- s(duration.seconds, "S")
1724
- ].filter(Boolean).join("");
1725
- }
1726
- exports3.serialize = serialize;
1727
- })(dist);
1728
- return dist;
1729
- }
1730
- requireDist();
1731
- function dictionaryWithCanonicalKeys(canon) {
1732
- const keysNormalizationMap = /* @__PURE__ */ new Map();
1733
- return new Proxy({}, {
1734
- /**
1735
- * Intercept the get operation on the dictionary object and forward it to the target object using Reflect.get.
1736
- * @param target The target object.
1737
- * @param prop The property to get.
1738
- * @returns The value of the property.
1739
- */
1740
- get(target, prop) {
1741
- const normalKey = canon(prop);
1742
- return Reflect.get(target, normalKey);
1743
- },
1744
- /**
1745
- * Intercept the set operation on the dictionary object and forward it to the target object using Reflect.set.
1746
- * @param target The target object.
1747
- * @param prop The property to set.
1748
- * @param value The value to set.
1749
- * @returns A boolean indicating whether the property was set.
1750
- */
1751
- set(target, prop, value) {
1752
- const nonNormalKey = prop.toString();
1753
- const normalKey = canon(prop);
1754
- keysNormalizationMap.set(normalKey, nonNormalKey);
1755
- return Reflect.set(target, normalKey, value);
1756
- },
1757
- /**
1758
- * Intercept the has operation on the dictionary object and forward it to the target object using Reflect.has.
1759
- * @param _ the target object.
1760
- * @param prop The property to check.
1761
- * @returns A boolean indicating whether the property exists.
1762
- */
1763
- has(_, prop) {
1764
- const normalKey = canon(prop);
1765
- return keysNormalizationMap.has(normalKey);
1766
- },
1767
- /**
1768
- * Intercept the defineProperty operation on the dictionary object and forward it to the target object using Reflect.defineProperty.
1769
- * @param target The target object.
1770
- * @param prop The property to define.
1771
- * @param attribs The attributes of the property.
1772
- * @returns A boolean indicating whether the property was defined.
1773
- */
1774
- defineProperty(target, prop, attribs) {
1775
- const nonNormalKey = prop.toString();
1776
- const normalKey = canon(prop);
1777
- keysNormalizationMap.set(normalKey, nonNormalKey);
1778
- return Reflect.defineProperty(target, normalKey, attribs);
1779
- },
1780
- /**
1781
- * Intercept the deleteProperty operation on the dictionary object and forward it to the target object using Reflect.deleteProperty.
1782
- * @param target The target object.
1783
- * @param prop The property to delete.
1784
- * @returns A boolean indicating whether the property was deleted.
1785
- */
1786
- deleteProperty(target, prop) {
1787
- const normalKey = canon(prop);
1788
- keysNormalizationMap.delete(normalKey);
1789
- return Reflect.deleteProperty(target, normalKey);
1790
- },
1791
- /**
1792
- * Intercept the getOwnPropertyDescriptor operation on the dictionary object and forward it to the target object using Reflect.getOwnPropertyDescriptor.
1793
- * @param target The target object.
1794
- * @param prop The property to gets its descriptor.
1795
- * @returns The property descriptor.
1796
- */
1797
- getOwnPropertyDescriptor(target, prop) {
1798
- return Reflect.getOwnPropertyDescriptor(target, canon(prop));
1799
- },
1800
- ownKeys() {
1801
- return [...keysNormalizationMap.values()];
1802
- }
1803
- });
1804
- }
1805
- function createRecordWithCaseInsensitiveKeys() {
1806
- const record = dictionaryWithCanonicalKeys((p) => typeof p === "string" ? p.toLowerCase() : p.toString().toLowerCase());
1807
- return record;
1808
- }
1809
- class Headers extends Map {
1810
- /**
1811
- * Creates a new Headers object.
1812
- * @param entries An iterable object that contains key-value pairs. Each key-value pair must be an array with two elements: the key of the header, and the value of the header.
1813
- * @example
1814
- * ```typescript
1815
- * const entries: [string, Set<string>][] = [
1816
- * ['header1', new Set(['value1'])],
1817
- * ['header2', new Set(['value2', 'value3'])]
1818
- * ];
1819
- * const headers = new Headers(entries);
1820
- * ```
1821
- */
1822
- constructor(entries) {
1823
- super();
1824
- this.headers = createRecordWithCaseInsensitiveKeys();
1825
- this.singleValueHeaders = /* @__PURE__ */ new Set(["Content-Type", "Content-Encoding", "Content-Length"]);
1826
- if (entries) {
1827
- entries.forEach(([key, value]) => {
1828
- this.headers[key] = value;
1829
- });
1830
- }
1831
- }
1832
- /**
1833
- * Sets a header with the specified name and value. If a header with the same name already exists, its value is appended with the specified value.
1834
- * @param headerName the name of the header to set
1835
- * @param headerValue the value of the header to set
1836
- * @returns Headers object
1837
- */
1838
- set(headerName, headerValue) {
1839
- this.add(headerName, ...headerValue);
1840
- return this;
1841
- }
1842
- /**
1843
- * Gets the values for the header with the specified name.
1844
- * @param headerName The name of the header to get the values for.
1845
- * @returns The values for the header with the specified name.
1846
- * @throws Error if headerName is null or empty
1847
- */
1848
- get(headerName) {
1849
- if (!headerName) {
1850
- throw new Error("headerName cannot be null or empty");
1851
- }
1852
- return this.headers[headerName];
1853
- }
1854
- /**
1855
- * Checks if a header exists.
1856
- * @param key The name of the header to check for.
1857
- * @returns whether or not a header with the given name/key exists.
1858
- */
1859
- has(key) {
1860
- return !!key && !!this.headers[key];
1861
- }
1862
- /**
1863
- * Delete the header with the specified name.
1864
- * @param headerName The name of the header to delete.
1865
- * @returns Whether or not the header existed and was deleted.
1866
- * @throws Error if headerName is null or empty
1867
- */
1868
- delete(headerName) {
1869
- if (!headerName) {
1870
- throw new Error("headerName cannot be null or empty");
1871
- }
1872
- if (this.headers[headerName]) {
1873
- delete this.headers[headerName];
1874
- return true;
1875
- }
1876
- return false;
1877
- }
1878
- /**
1879
- * clear the headers collection
1880
- */
1881
- clear() {
1882
- for (const header in this.headers) {
1883
- if (Object.prototype.hasOwnProperty.call(this.headers, header)) {
1884
- delete this.headers[header];
1885
- }
1886
- }
1887
- }
1888
- /**
1889
- * execute a provided function once per each header
1890
- * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each header in the dictionary.
1891
- * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
1892
- */
1893
- forEach(callbackfn, thisArg) {
1894
- for (const header in this.headers) {
1895
- if (Object.prototype.hasOwnProperty.call(this.headers, header)) {
1896
- callbackfn.call(thisArg, this.headers[header], header, this);
1897
- }
1898
- }
1899
- }
1900
- /**
1901
- * Adds values to the header with the specified name.
1902
- * @param headerName The name of the header to add values to.
1903
- * @param headerValues The values to add to the header.
1904
- * @returns Whether or not the values were added to the header.
1905
- */
1906
- add(headerName, ...headerValues) {
1907
- if (!headerName) {
1908
- console.error("headerName cannot be null or empty");
1909
- return false;
1910
- }
1911
- if (!headerValues) {
1912
- console.error("headerValues cannot be null");
1913
- return false;
1914
- }
1915
- if (headerValues.length === 0) {
1916
- return false;
1917
- }
1918
- if (this.singleValueHeaders.has(headerName)) {
1919
- this.headers[headerName] = /* @__PURE__ */ new Set([headerValues[0]]);
1920
- } else if (this.headers[headerName]) {
1921
- headerValues.forEach((headerValue) => this.headers[headerName].add(headerValue));
1922
- } else {
1923
- this.headers[headerName] = new Set(headerValues);
1924
- }
1925
- return true;
1926
- }
1927
- /**
1928
- * Adds values to the header with the specified name if it's not already present
1929
- * @param headerName The name of the header to add values to.
1930
- * @param headerValue The values to add to the header.
1931
- * @returns If the headerValue have been added to the Dictionary.
1932
- */
1933
- tryAdd(headerName, headerValue) {
1934
- if (!headerName) {
1935
- throw new Error("headerName cannot be null or empty");
1936
- }
1937
- if (!headerValue) {
1938
- throw new Error("headerValue cannot be null");
1939
- }
1940
- if (!this.headers[headerName]) {
1941
- this.headers[headerName] = /* @__PURE__ */ new Set([headerValue]);
1942
- return true;
1943
- }
1944
- return false;
1945
- }
1946
- /**
1947
- * Removes the specified value from the header with the specified name.
1948
- * @param headerName The name of the header to remove the value from.
1949
- * @param headerValue The value to remove from the header.
1950
- * @returns Whether or not the header existed and was removed.
1951
- * @throws Error if headerName is null or empty
1952
- * @throws Error if headerValue is null
1953
- */
1954
- remove(headerName, headerValue) {
1955
- if (!headerName) {
1956
- throw new Error("headerName cannot be null or empty");
1957
- }
1958
- if (!headerValue) {
1959
- throw new Error("headerValue cannot be null");
1960
- }
1961
- if (this.headers[headerName]) {
1962
- const result = this.headers[headerName].delete(headerValue);
1963
- if (this.headers[headerName].size === 0) {
1964
- delete this.headers[headerName];
1965
- }
1966
- return result;
1967
- }
1968
- return false;
1969
- }
1970
- /**
1971
- * Adds all the headers values from the specified headers collection.
1972
- * @param headers The headers to update the current headers with.
1973
- * @throws Error if headers is null
1974
- */
1975
- addAll(headers) {
1976
- if (!headers) {
1977
- throw new Error("headers cannot be null");
1978
- }
1979
- for (const header in headers.headers) {
1980
- if (Object.prototype.hasOwnProperty.call(headers.headers, header)) {
1981
- headers.headers[header].forEach((value) => this.add(header, value));
1982
- }
1983
- }
1984
- }
1985
- /**
1986
- * Adds all headers from the request configuration value to the current headers collection.
1987
- * Replaces any existing headers with the same key.
1988
- * @param headers The headers to update the current headers with.
1989
- * @throws Error if headers is null
1990
- */
1991
- addAllRaw(headers) {
1992
- if (!headers) {
1993
- throw new Error("headers cannot be null");
1994
- }
1995
- for (const header in headers) {
1996
- if (Object.prototype.hasOwnProperty.call(headers, header)) {
1997
- const headerValues = headers[header];
1998
- if (Array.isArray(headerValues)) {
1999
- this.add(header, ...headerValues);
2000
- } else {
2001
- this.add(header, headerValues);
2002
- }
2003
- }
2004
- }
2005
- }
2006
- /**
2007
- * Gets the values for the header with the specified name.
2008
- * @param key The name of the header to get the values for.
2009
- * @returns The values for the header with the specified name.
2010
- * @throws Error if key is null or empty
2011
- */
2012
- tryGetValue(key) {
2013
- if (!key) {
2014
- throw new Error("key cannot be null or empty");
2015
- }
2016
- return this.headers[key] ? Array.from(this.headers[key]) : null;
2017
- }
2018
- /**
2019
- * Override toString method for the headers collection
2020
- * @returns a string representation of the headers collection
2021
- */
2022
- toString() {
2023
- return JSON.stringify(this.headers, (_key, value) => value instanceof Set ? [...value] : value);
2024
- }
2025
- /**
2026
- * check if the headers collection is empty
2027
- * @returns a boolean indicating if the headers collection is empty
2028
- */
2029
- isEmpty() {
2030
- return Object.keys(this.headers).length === 0;
2031
- }
2032
- /**
2033
- * get keys of the headers collection
2034
- * @returns an iterator of keys
2035
- */
2036
- keys() {
2037
- return Object.keys(this.headers)[Symbol.iterator]();
2038
- }
2039
- /**
2040
- * get entries
2041
- * @returns an iterator of entries
2042
- */
2043
- entries() {
2044
- return Object.entries(this.headers)[Symbol.iterator]();
2045
- }
2046
- }
2047
- var HttpMethod;
2048
- (function(HttpMethod2) {
2049
- HttpMethod2["GET"] = "GET";
2050
- HttpMethod2["POST"] = "POST";
2051
- HttpMethod2["PATCH"] = "PATCH";
2052
- HttpMethod2["DELETE"] = "DELETE";
2053
- HttpMethod2["OPTIONS"] = "OPTIONS";
2054
- HttpMethod2["CONNECT"] = "CONNECT";
2055
- HttpMethod2["TRACE"] = "TRACE";
2056
- HttpMethod2["HEAD"] = "HEAD";
2057
- HttpMethod2["PUT"] = "PUT";
2058
- })(HttpMethod || (HttpMethod = {}));
2059
- class DefaultApiError extends Error {
2060
- constructor(message) {
2061
- super(message);
2062
- this.responseHeaders = {};
2063
- }
2064
- }
2065
- var ApiKeyLocation;
2066
- (function(ApiKeyLocation2) {
2067
- ApiKeyLocation2[ApiKeyLocation2["QueryParameter"] = 0] = "QueryParameter";
2068
- ApiKeyLocation2[ApiKeyLocation2["Header"] = 1] = "Header";
2069
- })(ApiKeyLocation || (ApiKeyLocation = {}));
2070
- class BaseBearerTokenAuthenticationProvider {
2071
- /**
2072
- * The constructor for the BaseBearerTokenAuthenticationProvider
2073
- * @param accessTokenProvider The AccessTokenProvider instance that this provider will use to authenticate requests.
2074
- */
2075
- constructor(accessTokenProvider) {
2076
- this.accessTokenProvider = accessTokenProvider;
2077
- this.authenticateRequest = async (request, additionalAuthenticationContext) => {
2078
- var _a;
2079
- if (!request) {
2080
- throw new Error("request info cannot be null");
2081
- }
2082
- if ((additionalAuthenticationContext === null || additionalAuthenticationContext === void 0 ? void 0 : additionalAuthenticationContext.claims) && request.headers.has(BaseBearerTokenAuthenticationProvider.authorizationHeaderKey)) {
2083
- request.headers.delete(BaseBearerTokenAuthenticationProvider.authorizationHeaderKey);
2084
- }
2085
- if (!((_a = request.headers) === null || _a === void 0 ? void 0 : _a.has(BaseBearerTokenAuthenticationProvider.authorizationHeaderKey))) {
2086
- const token = await this.accessTokenProvider.getAuthorizationToken(request.URL, additionalAuthenticationContext);
2087
- if (!request.headers) {
2088
- request.headers = new Headers();
2089
- }
2090
- if (token) {
2091
- request.headers.add(BaseBearerTokenAuthenticationProvider.authorizationHeaderKey, `Bearer ${token}`);
2092
- }
2093
- }
2094
- };
2095
- }
2096
- }
2097
- BaseBearerTokenAuthenticationProvider.authorizationHeaderKey = "Authorization";
2098
- class NativeResponseHandler {
2099
- handleResponse(response, errorMappings) {
2100
- this.value = response;
2101
- this.errorMappings = errorMappings;
2102
- return Promise.resolve(void 0);
2103
- }
2104
- }
2105
- class NativeResponseWrapper {
2106
- }
2107
- NativeResponseWrapper.CallAndGetNative = async (originalCall, q, h, o) => {
2108
- const responseHandler = new NativeResponseHandler();
2109
- await originalCall(q, h, o, responseHandler);
2110
- return responseHandler.value;
2111
- };
2112
- NativeResponseWrapper.CallAndGetNativeWithBody = async (originalCall, requestBody, q, h, o) => {
2113
- const responseHandler = new NativeResponseHandler();
2114
- await originalCall(requestBody, q, h, o, responseHandler);
2115
- return responseHandler.value;
2116
- };
2117
- const ResponseHandlerOptionKey = "ResponseHandlerOptionKey";
2118
- class CustomFetchHandler {
2119
- constructor(customFetch) {
2120
- this.customFetch = customFetch;
2121
- }
2122
- /**
2123
- * @inheritdoc
2124
- */
2125
- async execute(url, requestInit) {
2126
- return await this.customFetch(url, requestInit);
2127
- }
2128
- }
2129
- class HttpClient {
2130
- /**
2131
- *
2132
- * Creates an instance of a HttpClient which contains the middlewares and fetch implementation for request execution.
2133
- * @param customFetch - custom fetch function - a Fetch API implementation
2134
- * @param middlewares - an array of Middleware handlers
2135
- */
2136
- constructor(customFetch, ...middlewares) {
2137
- this.customFetch = customFetch;
2138
- middlewares = (middlewares === null || middlewares === void 0 ? void 0 : middlewares.length) && middlewares[0] ? middlewares : MiddlewareFactory.getDefaultMiddlewares(customFetch);
2139
- if (this.customFetch) {
2140
- middlewares.push(new CustomFetchHandler(customFetch));
2141
- }
2142
- this.setMiddleware(...middlewares);
2143
- }
2144
- /**
2145
- * Processes the middleware parameter passed to set this.middleware property
2146
- * The calling function should validate if middleware is not undefined or not empty.
2147
- * @param middleware - The middleware passed
2148
- */
2149
- setMiddleware(...middleware) {
2150
- for (let i = 0; i < middleware.length - 1; i++) {
2151
- middleware[i].next = middleware[i + 1];
2152
- }
2153
- this.middleware = middleware[0];
2154
- }
2155
- /**
2156
- * Executes a request and returns a promise resolving the response.
2157
- * @param url the request url.
2158
- * @param requestInit the RequestInit object.
2159
- * @param requestOptions the request options.
2160
- * @returns the promise resolving the response.
2161
- */
2162
- async executeFetch(url, requestInit, requestOptions) {
2163
- if (this.middleware) {
2164
- return await this.middleware.execute(url, requestInit, requestOptions);
2165
- } else if (this.customFetch) {
2166
- return this.customFetch(url, requestInit);
2167
- }
2168
- throw new Error("Please provide middlewares or a custom fetch function to execute the request");
2169
- }
2170
- }
2171
- const ObservabilityOptionKey = "ObservabilityOptionKey";
2172
- class ObservabilityOptionsImpl {
2173
- constructor(originalOptions) {
2174
- this._originalOptions = originalOptions !== null && originalOptions !== void 0 ? originalOptions : {};
2175
- }
2176
- getKey() {
2177
- return ObservabilityOptionKey;
2178
- }
2179
- get includeEUIIAttributes() {
2180
- return this._originalOptions.includeEUIIAttributes;
2181
- }
2182
- set includeEUIIAttributes(value) {
2183
- this._originalOptions.includeEUIIAttributes = value;
2184
- }
2185
- getTracerInstrumentationName() {
2186
- return "@microsoft/kiota-http-fetchlibrary";
2187
- }
2188
- }
2189
- function getObservabilityOptionsFromRequest(requestOptions) {
2190
- if (requestOptions) {
2191
- const observabilityOptions = requestOptions[ObservabilityOptionKey];
2192
- if (observabilityOptions instanceof ObservabilityOptionsImpl) {
2193
- return observabilityOptions;
2194
- }
2195
- }
2196
- return void 0;
2197
- }
2198
- class FetchRequestAdapter {
2199
- getSerializationWriterFactory() {
2200
- return this.serializationWriterFactory;
2201
- }
2202
- getParseNodeFactory() {
2203
- return this.parseNodeFactory;
2204
- }
2205
- getBackingStoreFactory() {
2206
- return this.backingStoreFactory;
2207
- }
2208
- /**
2209
- * Instantiates a new request adapter.
2210
- * @param authenticationProvider the authentication provider to use.
2211
- * @param parseNodeFactory the parse node factory to deserialize responses.
2212
- * @param serializationWriterFactory the serialization writer factory to use to serialize request bodies.
2213
- * @param httpClient the http client to use to execute requests.
2214
- * @param observabilityOptions the observability options to use.
2215
- * @param backingStoreFactory the backing store factory to use.
2216
- */
2217
- constructor(authenticationProvider, parseNodeFactory = new ParseNodeFactoryRegistry(), serializationWriterFactory = new SerializationWriterFactoryRegistry(), httpClient = new HttpClient(), observabilityOptions = new ObservabilityOptionsImpl(), backingStoreFactory = new InMemoryBackingStoreFactory()) {
2218
- this.authenticationProvider = authenticationProvider;
2219
- this.parseNodeFactory = parseNodeFactory;
2220
- this.serializationWriterFactory = serializationWriterFactory;
2221
- this.httpClient = httpClient;
2222
- this.backingStoreFactory = backingStoreFactory;
2223
- this.baseUrl = "";
2224
- this.getResponseContentType = (response) => {
2225
- var _a;
2226
- const header = (_a = response.headers.get("content-type")) === null || _a === void 0 ? void 0 : _a.toLowerCase();
2227
- if (!header)
2228
- return void 0;
2229
- const segments = header.split(";");
2230
- if (segments.length === 0)
2231
- return void 0;
2232
- else
2233
- return segments[0];
2234
- };
2235
- this.getResponseHandler = (response) => {
2236
- const options = response.getRequestOptions();
2237
- const responseHandlerOption = options[ResponseHandlerOptionKey];
2238
- return responseHandlerOption === null || responseHandlerOption === void 0 ? void 0 : responseHandlerOption.responseHandler;
2239
- };
2240
- this.sendCollectionOfPrimitive = (requestInfo, responseType, errorMappings) => {
2241
- if (!requestInfo) {
2242
- throw new Error("requestInfo cannot be null");
2243
- }
2244
- return this.startTracingSpan(requestInfo, "sendCollectionOfPrimitive", async (span) => {
2245
- const response = await this.getHttpResponseMessage(requestInfo, span);
2246
- const responseHandler = this.getResponseHandler(requestInfo);
2247
- if (responseHandler) {
2248
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
2249
- return await responseHandler.handleResponse(response, errorMappings);
2250
- } else {
2251
- try {
2252
- await this.throwIfFailedResponse(response, errorMappings, span);
2253
- if (this.shouldReturnUndefined(response))
2254
- return void 0;
2255
- switch (responseType) {
2256
- case "string":
2257
- case "number":
2258
- case "boolean":
2259
- case "Date":
2260
- const rootNode = await this.getRootParseNode(response);
2261
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan(`getCollectionOf${responseType}Value`, (deserializeSpan) => {
2262
- try {
2263
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, responseType);
2264
- if (responseType === "string") {
2265
- return rootNode.getCollectionOfPrimitiveValues();
2266
- } else if (responseType === "number") {
2267
- return rootNode.getCollectionOfPrimitiveValues();
2268
- } else if (responseType === "boolean") {
2269
- return rootNode.getCollectionOfPrimitiveValues();
2270
- } else if (responseType === "Date") {
2271
- return rootNode.getCollectionOfPrimitiveValues();
2272
- } else if (responseType === "Duration") {
2273
- return rootNode.getCollectionOfPrimitiveValues();
2274
- } else if (responseType === "DateOnly") {
2275
- return rootNode.getCollectionOfPrimitiveValues();
2276
- } else if (responseType === "TimeOnly") {
2277
- return rootNode.getCollectionOfPrimitiveValues();
2278
- } else {
2279
- throw new Error("unexpected type to deserialize");
2280
- }
2281
- } finally {
2282
- deserializeSpan.end();
2283
- }
2284
- });
2285
- }
2286
- } finally {
2287
- await this.purgeResponseBody(response);
2288
- }
2289
- }
2290
- });
2291
- };
2292
- this.sendCollection = (requestInfo, deserialization, errorMappings) => {
2293
- if (!requestInfo) {
2294
- throw new Error("requestInfo cannot be null");
2295
- }
2296
- return this.startTracingSpan(requestInfo, "sendCollection", async (span) => {
2297
- const response = await this.getHttpResponseMessage(requestInfo, span);
2298
- const responseHandler = this.getResponseHandler(requestInfo);
2299
- if (responseHandler) {
2300
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
2301
- return await responseHandler.handleResponse(response, errorMappings);
2302
- } else {
2303
- try {
2304
- await this.throwIfFailedResponse(response, errorMappings, span);
2305
- if (this.shouldReturnUndefined(response))
2306
- return void 0;
2307
- const rootNode = await this.getRootParseNode(response);
2308
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getCollectionOfObjectValues", (deserializeSpan) => {
2309
- try {
2310
- const result = rootNode.getCollectionOfObjectValues(deserialization);
2311
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, "object[]");
2312
- return result;
2313
- } finally {
2314
- deserializeSpan.end();
2315
- }
2316
- });
2317
- } finally {
2318
- await this.purgeResponseBody(response);
2319
- }
2320
- }
2321
- });
2322
- };
2323
- this.startTracingSpan = (requestInfo, methodName, callback) => {
2324
- var _a;
2325
- const urlTemplate = decodeURIComponent((_a = requestInfo.urlTemplate) !== null && _a !== void 0 ? _a : "");
2326
- const telemetryPathValue = urlTemplate.replace(/\{\?[^}]+\}/gi, "");
2327
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan(`${methodName} - ${telemetryPathValue}`, async (span) => {
2328
- try {
2329
- span.setAttribute("url.uri_template", urlTemplate);
2330
- return await callback(span);
2331
- } finally {
2332
- span.end();
2333
- }
2334
- });
2335
- };
2336
- this.send = (requestInfo, deserializer, errorMappings) => {
2337
- if (!requestInfo) {
2338
- throw new Error("requestInfo cannot be null");
2339
- }
2340
- return this.startTracingSpan(requestInfo, "send", async (span) => {
2341
- const response = await this.getHttpResponseMessage(requestInfo, span);
2342
- const responseHandler = this.getResponseHandler(requestInfo);
2343
- if (responseHandler) {
2344
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
2345
- return await responseHandler.handleResponse(response, errorMappings);
2346
- } else {
2347
- try {
2348
- await this.throwIfFailedResponse(response, errorMappings, span);
2349
- if (this.shouldReturnUndefined(response))
2350
- return void 0;
2351
- const rootNode = await this.getRootParseNode(response);
2352
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getObjectValue", (deserializeSpan) => {
2353
- try {
2354
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, "object");
2355
- const result = rootNode.getObjectValue(deserializer);
2356
- return result;
2357
- } finally {
2358
- deserializeSpan.end();
2359
- }
2360
- });
2361
- } finally {
2362
- await this.purgeResponseBody(response);
2363
- }
2364
- }
2365
- });
2366
- };
2367
- this.sendPrimitive = (requestInfo, responseType, errorMappings) => {
2368
- if (!requestInfo) {
2369
- throw new Error("requestInfo cannot be null");
2370
- }
2371
- return this.startTracingSpan(requestInfo, "sendPrimitive", async (span) => {
2372
- const response = await this.getHttpResponseMessage(requestInfo, span);
2373
- const responseHandler = this.getResponseHandler(requestInfo);
2374
- if (responseHandler) {
2375
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
2376
- return await responseHandler.handleResponse(response, errorMappings);
2377
- } else {
2378
- try {
2379
- await this.throwIfFailedResponse(response, errorMappings, span);
2380
- if (this.shouldReturnUndefined(response))
2381
- return void 0;
2382
- switch (responseType) {
2383
- case "ArrayBuffer":
2384
- if (!response.body) {
2385
- return void 0;
2386
- }
2387
- return await response.arrayBuffer();
2388
- case "string":
2389
- case "number":
2390
- case "boolean":
2391
- case "Date":
2392
- const rootNode = await this.getRootParseNode(response);
2393
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, responseType);
2394
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan(`get${responseType}Value`, (deserializeSpan) => {
2395
- try {
2396
- if (responseType === "string") {
2397
- return rootNode.getStringValue();
2398
- } else if (responseType === "number") {
2399
- return rootNode.getNumberValue();
2400
- } else if (responseType === "boolean") {
2401
- return rootNode.getBooleanValue();
2402
- } else if (responseType === "Date") {
2403
- return rootNode.getDateValue();
2404
- } else if (responseType === "Duration") {
2405
- return rootNode.getDurationValue();
2406
- } else if (responseType === "DateOnly") {
2407
- return rootNode.getDateOnlyValue();
2408
- } else if (responseType === "TimeOnly") {
2409
- return rootNode.getTimeOnlyValue();
2410
- } else {
2411
- throw new Error("unexpected type to deserialize");
2412
- }
2413
- } finally {
2414
- deserializeSpan.end();
2415
- }
2416
- });
2417
- }
2418
- } finally {
2419
- await this.purgeResponseBody(response);
2420
- }
2421
- }
2422
- });
2423
- };
2424
- this.sendNoResponseContent = (requestInfo, errorMappings) => {
2425
- if (!requestInfo) {
2426
- throw new Error("requestInfo cannot be null");
2427
- }
2428
- return this.startTracingSpan(requestInfo, "sendNoResponseContent", async (span) => {
2429
- const response = await this.getHttpResponseMessage(requestInfo, span);
2430
- const responseHandler = this.getResponseHandler(requestInfo);
2431
- if (responseHandler) {
2432
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
2433
- return await responseHandler.handleResponse(response, errorMappings);
2434
- }
2435
- try {
2436
- await this.throwIfFailedResponse(response, errorMappings, span);
2437
- } finally {
2438
- await this.purgeResponseBody(response);
2439
- }
2440
- });
2441
- };
2442
- this.sendEnum = (requestInfo, enumObject, errorMappings) => {
2443
- if (!requestInfo) {
2444
- throw new Error("requestInfo cannot be null");
2445
- }
2446
- return this.startTracingSpan(requestInfo, "sendEnum", async (span) => {
2447
- const response = await this.getHttpResponseMessage(requestInfo, span);
2448
- const responseHandler = this.getResponseHandler(requestInfo);
2449
- if (responseHandler) {
2450
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
2451
- return await responseHandler.handleResponse(response, errorMappings);
2452
- } else {
2453
- try {
2454
- await this.throwIfFailedResponse(response, errorMappings, span);
2455
- if (this.shouldReturnUndefined(response))
2456
- return void 0;
2457
- const rootNode = await this.getRootParseNode(response);
2458
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getEnumValue", (deserializeSpan) => {
2459
- try {
2460
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, "enum");
2461
- const result = rootNode.getEnumValue(enumObject);
2462
- return result;
2463
- } finally {
2464
- deserializeSpan.end();
2465
- }
2466
- });
2467
- } finally {
2468
- await this.purgeResponseBody(response);
2469
- }
2470
- }
2471
- });
2472
- };
2473
- this.sendCollectionOfEnum = (requestInfo, enumObject, errorMappings) => {
2474
- if (!requestInfo) {
2475
- throw new Error("requestInfo cannot be null");
2476
- }
2477
- return this.startTracingSpan(requestInfo, "sendCollectionOfEnum", async (span) => {
2478
- const response = await this.getHttpResponseMessage(requestInfo, span);
2479
- const responseHandler = this.getResponseHandler(requestInfo);
2480
- if (responseHandler) {
2481
- span.addEvent(FetchRequestAdapter.eventResponseHandlerInvokedKey);
2482
- return await responseHandler.handleResponse(response, errorMappings);
2483
- } else {
2484
- try {
2485
- await this.throwIfFailedResponse(response, errorMappings, span);
2486
- if (this.shouldReturnUndefined(response))
2487
- return void 0;
2488
- const rootNode = await this.getRootParseNode(response);
2489
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getCollectionOfEnumValues", (deserializeSpan) => {
2490
- try {
2491
- const result = rootNode.getCollectionOfEnumValues(enumObject);
2492
- span.setAttribute(FetchRequestAdapter.responseTypeAttributeKey, "enum[]");
2493
- return result;
2494
- } finally {
2495
- deserializeSpan.end();
2496
- }
2497
- });
2498
- } finally {
2499
- await this.purgeResponseBody(response);
2500
- }
2501
- }
2502
- });
2503
- };
2504
- this.enableBackingStore = (backingStoreFactory2) => {
2505
- if (this.parseNodeFactory instanceof ParseNodeFactoryRegistry) {
2506
- this.parseNodeFactory = enableBackingStoreForParseNodeFactory(this.parseNodeFactory, this.parseNodeFactory);
2507
- } else {
2508
- throw new Error("parseNodeFactory is not a ParseNodeFactoryRegistry");
2509
- }
2510
- if (this.serializationWriterFactory instanceof SerializationWriterFactoryRegistry && this.parseNodeFactory instanceof ParseNodeFactoryRegistry) {
2511
- this.serializationWriterFactory = enableBackingStoreForSerializationWriterFactory(this.serializationWriterFactory, this.parseNodeFactory, this.serializationWriterFactory);
2512
- } else {
2513
- throw new Error("serializationWriterFactory is not a SerializationWriterFactoryRegistry or parseNodeFactory is not a ParseNodeFactoryRegistry");
2514
- }
2515
- if (!this.serializationWriterFactory || !this.parseNodeFactory)
2516
- throw new Error("unable to enable backing store");
2517
- if (backingStoreFactory2) {
2518
- this.backingStoreFactory = backingStoreFactory2;
2519
- }
2520
- };
2521
- this.getRootParseNode = (response) => {
2522
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getRootParseNode", async (span) => {
2523
- try {
2524
- const payload = await response.arrayBuffer();
2525
- const responseContentType = this.getResponseContentType(response);
2526
- if (!responseContentType)
2527
- throw new Error("no response content type found for deserialization");
2528
- return this.parseNodeFactory.getRootParseNode(responseContentType, payload);
2529
- } finally {
2530
- span.end();
2531
- }
2532
- });
2533
- };
2534
- this.shouldReturnUndefined = (response) => {
2535
- return response.status === 204 || response.status === 304 || !response.body;
2536
- };
2537
- this.purgeResponseBody = async (response) => {
2538
- if (!response.bodyUsed && response.body) {
2539
- await response.arrayBuffer();
2540
- }
2541
- };
2542
- this.throwIfFailedResponse = (response, errorMappings, spanForAttributes) => {
2543
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("throwIfFailedResponse", async (span) => {
2544
- var _a, _b, _c;
2545
- try {
2546
- if (response.ok || response.status >= 300 && response.status < 400 && !response.headers.has(FetchRequestAdapter.locationHeaderName))
2547
- return;
2548
- spanForAttributes.setStatus({
2549
- code: SpanStatusCode.ERROR,
2550
- message: "received_error_response"
2551
- });
2552
- const statusCode = response.status;
2553
- const responseHeaders = {};
2554
- response.headers.forEach((value, key) => {
2555
- responseHeaders[key] = value.split(",");
2556
- });
2557
- const factory = errorMappings ? (_c = (_b = (_a = errorMappings[statusCode]) !== null && _a !== void 0 ? _a : statusCode >= 400 && statusCode < 500 ? errorMappings._4XX : void 0) !== null && _b !== void 0 ? _b : statusCode >= 500 && statusCode < 600 ? errorMappings._5XX : void 0) !== null && _c !== void 0 ? _c : errorMappings.XXX : void 0;
2558
- if (!factory) {
2559
- spanForAttributes.setAttribute(FetchRequestAdapter.errorMappingFoundAttributeName, false);
2560
- const error = new DefaultApiError("the server returned an unexpected status code and no error class is registered for this code " + statusCode);
2561
- error.responseStatusCode = statusCode;
2562
- error.responseHeaders = responseHeaders;
2563
- spanForAttributes.recordException(error);
2564
- throw error;
2565
- }
2566
- spanForAttributes.setAttribute(FetchRequestAdapter.errorMappingFoundAttributeName, true);
2567
- const rootNode = await this.getRootParseNode(response);
2568
- let deserializedError = trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getObjectValue", (deserializeSpan) => {
2569
- try {
2570
- return rootNode.getObjectValue(factory);
2571
- } finally {
2572
- deserializeSpan.end();
2573
- }
2574
- });
2575
- spanForAttributes.setAttribute(FetchRequestAdapter.errorBodyFoundAttributeName, !!deserializedError);
2576
- if (!deserializedError)
2577
- deserializedError = new DefaultApiError("unexpected error type" + typeof deserializedError);
2578
- const errorObject = deserializedError;
2579
- errorObject.responseStatusCode = statusCode;
2580
- errorObject.responseHeaders = responseHeaders;
2581
- spanForAttributes.recordException(errorObject);
2582
- throw errorObject;
2583
- } finally {
2584
- span.end();
2585
- }
2586
- });
2587
- };
2588
- this.getHttpResponseMessage = (requestInfo, spanForAttributes, claims) => {
2589
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getHttpResponseMessage", async (span) => {
2590
- try {
2591
- if (!requestInfo) {
2592
- throw new Error("requestInfo cannot be null");
2593
- }
2594
- this.setBaseUrlForRequestInformation(requestInfo);
2595
- const additionalContext = {};
2596
- if (claims) {
2597
- additionalContext.claims = claims;
2598
- }
2599
- await this.authenticationProvider.authenticateRequest(requestInfo, additionalContext);
2600
- const request = await this.getRequestFromRequestInformation(requestInfo, spanForAttributes);
2601
- if (this.observabilityOptions) {
2602
- requestInfo.addRequestOptions([this.observabilityOptions]);
2603
- }
2604
- let response = await this.httpClient.executeFetch(requestInfo.URL, request, requestInfo.getRequestOptions());
2605
- response = await this.retryCAEResponseIfRequired(requestInfo, response, spanForAttributes, claims);
2606
- if (response) {
2607
- const responseContentLength = response.headers.get("Content-Length");
2608
- if (responseContentLength) {
2609
- spanForAttributes.setAttribute("http.response.body.size", parseInt(responseContentLength, 10));
2610
- }
2611
- const responseContentType = response.headers.get("Content-Type");
2612
- if (responseContentType) {
2613
- spanForAttributes.setAttribute("http.response.header.content-type", responseContentType);
2614
- }
2615
- spanForAttributes.setAttribute("http.response.status_code", response.status);
2616
- }
2617
- return response;
2618
- } finally {
2619
- span.end();
2620
- }
2621
- });
2622
- };
2623
- this.retryCAEResponseIfRequired = async (requestInfo, response, spanForAttributes, claims) => {
2624
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("retryCAEResponseIfRequired", async (span) => {
2625
- try {
2626
- const responseClaims = this.getClaimsFromResponse(response, claims);
2627
- if (responseClaims) {
2628
- span.addEvent(FetchRequestAdapter.authenticateChallengedEventKey);
2629
- spanForAttributes.setAttribute("http.request.resend_count", 1);
2630
- await this.purgeResponseBody(response);
2631
- return await this.getHttpResponseMessage(requestInfo, spanForAttributes, responseClaims);
2632
- }
2633
- return response;
2634
- } finally {
2635
- span.end();
2636
- }
2637
- });
2638
- };
2639
- this.getClaimsFromResponse = (response, claims) => {
2640
- if (response.status === 401 && !claims) {
2641
- const rawAuthenticateHeader = response.headers.get("WWW-Authenticate");
2642
- if (rawAuthenticateHeader && /^Bearer /gi.test(rawAuthenticateHeader)) {
2643
- const rawParameters = rawAuthenticateHeader.replace(/^Bearer /gi, "").split(",");
2644
- for (const rawParameter of rawParameters) {
2645
- const trimmedParameter = rawParameter.trim();
2646
- if (/claims="[^"]+"/gi.test(trimmedParameter)) {
2647
- return trimmedParameter.replace(/claims="([^"]+)"/gi, "$1");
2648
- }
2649
- }
2650
- }
2651
- }
2652
- return void 0;
2653
- };
2654
- this.setBaseUrlForRequestInformation = (requestInfo) => {
2655
- requestInfo.pathParameters.baseurl = this.baseUrl;
2656
- };
2657
- this.getRequestFromRequestInformation = (requestInfo, spanForAttributes) => {
2658
- return trace.getTracer(this.observabilityOptions.getTracerInstrumentationName()).startActiveSpan("getRequestFromRequestInformation", async (span) => {
2659
- var _a, _b;
2660
- try {
2661
- const method = (_a = requestInfo.httpMethod) === null || _a === void 0 ? void 0 : _a.toString();
2662
- const uri = requestInfo.URL;
2663
- spanForAttributes.setAttribute("http.request.method", method !== null && method !== void 0 ? method : "");
2664
- const uriContainsScheme = uri.includes("://");
2665
- const schemeSplatUri = uri.split("://");
2666
- if (uriContainsScheme) {
2667
- spanForAttributes.setAttribute("server.address", schemeSplatUri[0]);
2668
- }
2669
- const uriWithoutScheme = uriContainsScheme ? schemeSplatUri[1] : uri;
2670
- spanForAttributes.setAttribute("url.scheme", uriWithoutScheme.split("/")[0]);
2671
- if (this.observabilityOptions.includeEUIIAttributes) {
2672
- spanForAttributes.setAttribute("url.full", decodeURIComponent(uri));
2673
- }
2674
- const requestContentLength = requestInfo.headers.tryGetValue("Content-Length");
2675
- if (requestContentLength) {
2676
- spanForAttributes.setAttribute("http.response.body.size", parseInt(requestContentLength[0], 10));
2677
- }
2678
- const requestContentType = requestInfo.headers.tryGetValue("Content-Type");
2679
- if (requestContentType) {
2680
- spanForAttributes.setAttribute("http.request.header.content-type", requestContentType);
2681
- }
2682
- const headers = {};
2683
- (_b = requestInfo.headers) === null || _b === void 0 ? void 0 : _b.forEach((_, key) => {
2684
- headers[key.toString().toLocaleLowerCase()] = this.foldHeaderValue(requestInfo.headers.tryGetValue(key));
2685
- });
2686
- const request = {
2687
- method,
2688
- headers,
2689
- body: requestInfo.content
2690
- };
2691
- return request;
2692
- } finally {
2693
- span.end();
2694
- }
2695
- });
2696
- };
2697
- this.foldHeaderValue = (value) => {
2698
- if (!value || value.length < 1) {
2699
- return "";
2700
- } else if (value.length === 1) {
2701
- return value[0];
2702
- } else {
2703
- return value.reduce((acc, val) => acc + val, ",");
2704
- }
2705
- };
2706
- this.convertToNativeRequest = async (requestInfo) => {
2707
- if (!requestInfo) {
2708
- throw new Error("requestInfo cannot be null");
2709
- }
2710
- await this.authenticationProvider.authenticateRequest(requestInfo, void 0);
2711
- return this.startTracingSpan(requestInfo, "convertToNativeRequest", async (span) => {
2712
- const request = await this.getRequestFromRequestInformation(requestInfo, span);
2713
- return request;
2714
- });
2715
- };
2716
- if (!authenticationProvider) {
2717
- throw new Error("authentication provider cannot be null");
2718
- }
2719
- if (!parseNodeFactory) {
2720
- throw new Error("parse node factory cannot be null");
2721
- }
2722
- if (!serializationWriterFactory) {
2723
- throw new Error("serialization writer factory cannot be null");
2724
- }
2725
- if (!httpClient) {
2726
- throw new Error("http client cannot be null");
2727
- }
2728
- if (!observabilityOptions) {
2729
- throw new Error("observability options cannot be null");
2730
- } else {
2731
- this.observabilityOptions = new ObservabilityOptionsImpl(observabilityOptions);
2732
- }
2733
- }
2734
- }
2735
- FetchRequestAdapter.responseTypeAttributeKey = "com.microsoft.kiota.response.type";
2736
- FetchRequestAdapter.eventResponseHandlerInvokedKey = "com.microsoft.kiota.response_handler_invoked";
2737
- FetchRequestAdapter.errorMappingFoundAttributeName = "com.microsoft.kiota.error.mapping_found";
2738
- FetchRequestAdapter.errorBodyFoundAttributeName = "com.microsoft.kiota.error.body_found";
2739
- FetchRequestAdapter.locationHeaderName = "Location";
2740
- FetchRequestAdapter.authenticateChallengedEventKey = "com.microsoft.kiota.authenticate_challenge_received";
2741
- const getRequestHeader = (options, key) => {
2742
- if (options && options.headers) {
2743
- return options.headers[key];
2744
- }
2745
- return void 0;
2746
- };
2747
- const setRequestHeader = (options, key, value) => {
2748
- if (options) {
2749
- if (!options.headers) {
2750
- options.headers = {};
2751
- }
2752
- options.headers[key] = value;
2753
- }
2754
- };
2755
- const deleteRequestHeader = (options, key) => {
2756
- if (options) {
2757
- if (!options.headers) {
2758
- options.headers = {};
2759
- }
2760
- delete options.headers[key];
2761
- }
2762
- };
2763
- const appendRequestHeader = (options, key, value, separator = ", ") => {
2764
- if (options) {
2765
- if (!options.headers) {
2766
- options.headers = {};
2767
- }
2768
- if (!options.headers[key]) {
2769
- options.headers[key] = value;
2770
- } else {
2771
- options.headers[key] += `${separator}${value}`;
2772
- }
2773
- }
2774
- };
2775
- var ChaosStrategy;
2776
- (function(ChaosStrategy2) {
2777
- ChaosStrategy2[ChaosStrategy2["MANUAL"] = 0] = "MANUAL";
2778
- ChaosStrategy2[ChaosStrategy2["RANDOM"] = 1] = "RANDOM";
2779
- })(ChaosStrategy || (ChaosStrategy = {}));
2780
- const CompressionHandlerOptionsKey = "CompressionHandlerOptionsKey";
2781
- class CompressionHandlerOptions {
2782
- /**
2783
- * Create a new instance of the CompressionHandlerOptions class
2784
- * @param config the configuration to apply to the compression handler options.
2785
- */
2786
- constructor(config) {
2787
- var _a;
2788
- this._enableCompression = (_a = config === null || config === void 0 ? void 0 : config.enableCompression) !== null && _a !== void 0 ? _a : true;
2789
- }
2790
- /**
2791
- * @inheritdoc
2792
- */
2793
- getKey() {
2794
- return CompressionHandlerOptionsKey;
2795
- }
2796
- /**
2797
- * Returns whether the compression handler is enabled or not.
2798
- * @returns whether the compression handler is enabled or not.
2799
- */
2800
- get ShouldCompress() {
2801
- return this._enableCompression;
2802
- }
2803
- }
2804
- class CompressionHandler {
2805
- /**
2806
- * Creates a new instance of the CompressionHandler class
2807
- * @param handlerOptions The options for the compression handler.
2808
- * @returns An instance of the CompressionHandler class
2809
- */
2810
- constructor(handlerOptions = new CompressionHandlerOptions()) {
2811
- this.handlerOptions = handlerOptions;
2812
- if (!handlerOptions) {
2813
- throw new Error("handlerOptions cannot be undefined");
2814
- }
2815
- }
2816
- /**
2817
- * @inheritdoc
2818
- */
2819
- execute(url, requestInit, requestOptions) {
2820
- let currentOptions = this.handlerOptions;
2821
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[CompressionHandlerOptionsKey]) {
2822
- currentOptions = requestOptions[CompressionHandlerOptionsKey];
2823
- }
2824
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
2825
- if (obsOptions) {
2826
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("compressionHandler - execute", (span) => {
2827
- try {
2828
- span.setAttribute("com.microsoft.kiota.handler.compression.enable", currentOptions.ShouldCompress);
2829
- return this.executeInternal(currentOptions, url, requestInit, requestOptions, span);
2830
- } finally {
2831
- span.end();
2832
- }
2833
- });
2834
- }
2835
- return this.executeInternal(currentOptions, url, requestInit, requestOptions);
2836
- }
2837
- async executeInternal(options, url, requestInit, requestOptions, span) {
2838
- var _a, _b, _c, _d;
2839
- if (!options.ShouldCompress || this.contentRangeBytesIsPresent(requestInit.headers) || this.contentEncodingIsPresent(requestInit.headers) || requestInit.body === null || requestInit.body === void 0) {
2840
- return (_b = (_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(url, requestInit, requestOptions)) !== null && _b !== void 0 ? _b : Promise.reject(new Error("Response is undefined"));
2841
- }
2842
- span === null || span === void 0 ? void 0 : span.setAttribute("http.request.body.compressed", true);
2843
- const unCompressedBody = requestInit.body;
2844
- const unCompressedBodySize = this.getRequestBodySize(unCompressedBody);
2845
- const compressedBody = await this.compressRequestBody(unCompressedBody);
2846
- setRequestHeader(requestInit, CompressionHandler.CONTENT_ENCODING_HEADER, "gzip");
2847
- requestInit.body = compressedBody.compressedBody;
2848
- span === null || span === void 0 ? void 0 : span.setAttribute("http.request.body.size", compressedBody.size);
2849
- let response = await ((_c = this.next) === null || _c === void 0 ? void 0 : _c.execute(url, requestInit, requestOptions));
2850
- if (!response) {
2851
- throw new Error("Response is undefined");
2852
- }
2853
- if (response.status === 415) {
2854
- deleteRequestHeader(requestInit, CompressionHandler.CONTENT_ENCODING_HEADER);
2855
- requestInit.body = unCompressedBody;
2856
- span === null || span === void 0 ? void 0 : span.setAttribute("http.request.body.compressed", false);
2857
- span === null || span === void 0 ? void 0 : span.setAttribute("http.request.body.size", unCompressedBodySize);
2858
- response = await ((_d = this.next) === null || _d === void 0 ? void 0 : _d.execute(url, requestInit, requestOptions));
2859
- }
2860
- return response !== void 0 && response !== null ? Promise.resolve(response) : Promise.reject(new Error("Response is undefined"));
2861
- }
2862
- contentRangeBytesIsPresent(header) {
2863
- var _a;
2864
- if (!header) {
2865
- return false;
2866
- }
2867
- const contentRange = getRequestHeader(header, CompressionHandler.CONTENT_RANGE_HEADER);
2868
- return (_a = contentRange === null || contentRange === void 0 ? void 0 : contentRange.toLowerCase().includes("bytes")) !== null && _a !== void 0 ? _a : false;
2869
- }
2870
- contentEncodingIsPresent(header) {
2871
- if (!header) {
2872
- return false;
2873
- }
2874
- return getRequestHeader(header, CompressionHandler.CONTENT_ENCODING_HEADER) !== void 0;
2875
- }
2876
- getRequestBodySize(body) {
2877
- if (!body) {
2878
- return 0;
2879
- }
2880
- if (typeof body === "string") {
2881
- return body.length;
2882
- }
2883
- if (body instanceof Blob) {
2884
- return body.size;
2885
- }
2886
- if (body instanceof ArrayBuffer) {
2887
- return body.byteLength;
2888
- }
2889
- if (ArrayBuffer.isView(body)) {
2890
- return body.byteLength;
2891
- }
2892
- if (inNodeEnv() && Buffer.isBuffer(body)) {
2893
- return body.byteLength;
2894
- }
2895
- throw new Error("Unsupported body type");
2896
- }
2897
- readBodyAsBytes(body) {
2898
- if (!body) {
2899
- return { stream: new ReadableStream(), size: 0 };
2900
- }
2901
- const uint8ArrayToStream = (uint8Array) => {
2902
- return new ReadableStream({
2903
- start(controller) {
2904
- controller.enqueue(uint8Array);
2905
- controller.close();
2906
- }
2907
- });
2908
- };
2909
- if (typeof body === "string") {
2910
- return { stream: uint8ArrayToStream(new TextEncoder().encode(body)), size: body.length };
2911
- }
2912
- if (body instanceof Blob) {
2913
- return { stream: body.stream(), size: body.size };
2914
- }
2915
- if (body instanceof ArrayBuffer) {
2916
- return { stream: uint8ArrayToStream(new Uint8Array(body)), size: body.byteLength };
2917
- }
2918
- if (ArrayBuffer.isView(body)) {
2919
- return { stream: uint8ArrayToStream(new Uint8Array(body.buffer, body.byteOffset, body.byteLength)), size: body.byteLength };
2920
- }
2921
- throw new Error("Unsupported body type");
2922
- }
2923
- async compressRequestBody(body) {
2924
- const compressionData = this.readBodyAsBytes(body);
2925
- const compressedBody = await this.compressUsingCompressionStream(compressionData.stream);
2926
- return {
2927
- compressedBody: compressedBody.body,
2928
- size: compressedBody.size
2929
- };
2930
- }
2931
- async compressUsingCompressionStream(uint8ArrayStream) {
2932
- const compressionStream = new CompressionStream("gzip");
2933
- const compressedStream = uint8ArrayStream.pipeThrough(compressionStream);
2934
- const reader = compressedStream.getReader();
2935
- const compressedChunks = [];
2936
- let totalLength = 0;
2937
- let result = await reader.read();
2938
- while (!result.done) {
2939
- const chunk = result.value;
2940
- compressedChunks.push(chunk);
2941
- totalLength += chunk.length;
2942
- result = await reader.read();
2943
- }
2944
- const compressedArray = new Uint8Array(totalLength);
2945
- let offset = 0;
2946
- for (const chunk of compressedChunks) {
2947
- compressedArray.set(chunk, offset);
2948
- offset += chunk.length;
2949
- }
2950
- return {
2951
- body: compressedArray.buffer,
2952
- size: compressedArray.length
2953
- };
2954
- }
2955
- }
2956
- CompressionHandler.CONTENT_RANGE_HEADER = "Content-Range";
2957
- CompressionHandler.CONTENT_ENCODING_HEADER = "Content-Encoding";
2958
- const HeadersInspectionOptionsKey = "HeadersInspectionOptionsKey";
2959
- class HeadersInspectionOptions {
2960
- /**
2961
- * Gets the request headers
2962
- * @returns the request headers
2963
- */
2964
- getRequestHeaders() {
2965
- return this.requestHeaders;
2966
- }
2967
- /**
2968
- * Gets the response headers
2969
- * @returns the response headers
2970
- */
2971
- getResponseHeaders() {
2972
- return this.responseHeaders;
2973
- }
2974
- /**
2975
- *
2976
- * To create an instance of HeadersInspectionOptions
2977
- * @param [options] - The headers inspection options value
2978
- * @returns An instance of HeadersInspectionOptions
2979
- * @example const options = new HeadersInspectionOptions({ inspectRequestHeaders: true, inspectResponseHeaders: true });
2980
- */
2981
- constructor(options = {}) {
2982
- var _a, _b;
2983
- this.requestHeaders = new Headers();
2984
- this.responseHeaders = new Headers();
2985
- this.inspectRequestHeaders = (_a = options.inspectRequestHeaders) !== null && _a !== void 0 ? _a : false;
2986
- this.inspectResponseHeaders = (_b = options.inspectResponseHeaders) !== null && _b !== void 0 ? _b : false;
2987
- }
2988
- getKey() {
2989
- return HeadersInspectionOptionsKey;
2990
- }
2991
- }
2992
- class HeadersInspectionHandler {
2993
- /**
2994
- *
2995
- * Creates new instance of HeadersInspectionHandler
2996
- * @param _options The options for inspecting the headers
2997
- */
2998
- constructor(_options = new HeadersInspectionOptions()) {
2999
- this._options = _options;
3000
- }
3001
- execute(url, requestInit, requestOptions) {
3002
- let currentOptions = this._options;
3003
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[HeadersInspectionOptionsKey]) {
3004
- currentOptions = requestOptions[HeadersInspectionOptionsKey];
3005
- }
3006
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
3007
- if (obsOptions) {
3008
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("retryHandler - execute", (span) => {
3009
- try {
3010
- span.setAttribute("com.microsoft.kiota.handler.headersInspection.enable", true);
3011
- return this.executeInternal(url, requestInit, requestOptions, currentOptions);
3012
- } finally {
3013
- span.end();
3014
- }
3015
- });
3016
- }
3017
- return this.executeInternal(url, requestInit, requestOptions, currentOptions);
3018
- }
3019
- async executeInternal(url, requestInit, requestOptions, currentOptions) {
3020
- if (!this.next) {
3021
- throw new Error("next middleware is undefined.");
3022
- }
3023
- if (currentOptions.inspectRequestHeaders && requestInit.headers) {
3024
- for (const [key, value] of requestInit.headers) {
3025
- currentOptions.getRequestHeaders().add(key, value);
3026
- }
3027
- }
3028
- const response = await this.next.execute(url, requestInit, requestOptions);
3029
- if (currentOptions.inspectResponseHeaders && response.headers) {
3030
- for (const [key, value] of response.headers.entries()) {
3031
- currentOptions.getResponseHeaders().add(key, value);
3032
- }
3033
- }
3034
- return response;
3035
- }
3036
- }
3037
- const ParametersNameDecodingHandlerOptionsKey = "RetryHandlerOptionKey";
3038
- class ParametersNameDecodingHandlerOptions {
3039
- getKey() {
3040
- return ParametersNameDecodingHandlerOptionsKey;
3041
- }
3042
- /**
3043
- *
3044
- * To create an instance of ParametersNameDecodingHandlerOptions
3045
- * @param [options] - The optional parameters
3046
- * @returns An instance of ParametersNameDecodingHandlerOptions
3047
- * @example ParametersNameDecodingHandlerOptions({ enable: true, charactersToDecode: [".", "-", "~", "$"] });
3048
- */
3049
- constructor(options = {}) {
3050
- var _a, _b;
3051
- this.enable = (_a = options.enable) !== null && _a !== void 0 ? _a : true;
3052
- this.charactersToDecode = (_b = options.charactersToDecode) !== null && _b !== void 0 ? _b : [".", "-", "~", "$"];
3053
- }
3054
- }
3055
- class ParametersNameDecodingHandler {
3056
- /**
3057
- *
3058
- * To create an instance of ParametersNameDecodingHandler
3059
- * @param [options] - The parameters name decoding handler options value
3060
- */
3061
- constructor(options = new ParametersNameDecodingHandlerOptions()) {
3062
- this.options = options;
3063
- if (!options) {
3064
- throw new Error("The options parameter is required.");
3065
- }
3066
- }
3067
- /**
3068
- * To execute the current middleware
3069
- * @param url - The url to be fetched
3070
- * @param requestInit - The request init object
3071
- * @param requestOptions - The request options
3072
- * @returns A Promise that resolves to nothing
3073
- */
3074
- execute(url, requestInit, requestOptions) {
3075
- let currentOptions = this.options;
3076
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[ParametersNameDecodingHandlerOptionsKey]) {
3077
- currentOptions = requestOptions[ParametersNameDecodingHandlerOptionsKey];
3078
- }
3079
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
3080
- if (obsOptions) {
3081
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("parametersNameDecodingHandler - execute", (span) => {
3082
- try {
3083
- span.setAttribute("com.microsoft.kiota.handler.parameters_name_decoding.enable", currentOptions.enable);
3084
- return this.decodeParameters(url, requestInit, currentOptions, requestOptions);
3085
- } finally {
3086
- span.end();
3087
- }
3088
- });
3089
- }
3090
- return this.decodeParameters(url, requestInit, currentOptions, requestOptions);
3091
- }
3092
- decodeParameters(url, requestInit, currentOptions, requestOptions) {
3093
- var _a, _b;
3094
- let updatedUrl = url;
3095
- if (currentOptions && currentOptions.enable && url.includes("%") && currentOptions.charactersToDecode && currentOptions.charactersToDecode.length > 0) {
3096
- currentOptions.charactersToDecode.forEach((character) => {
3097
- updatedUrl = updatedUrl.replace(new RegExp(`%${character.charCodeAt(0).toString(16)}`, "gi"), character);
3098
- });
3099
- }
3100
- return (_b = (_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(updatedUrl, requestInit, requestOptions)) !== null && _b !== void 0 ? _b : Promise.reject(new Error("The next middleware is not set."));
3101
- }
3102
- }
3103
- const RedirectHandlerOptionKey = "RedirectHandlerOption";
3104
- class RedirectHandlerOptions {
3105
- /**
3106
- *
3107
- * To create an instance of RedirectHandlerOptions
3108
- * @param [options] - The redirect handler options instance
3109
- * @returns An instance of RedirectHandlerOptions
3110
- * @throws Error if maxRedirects is more than 20 or less than 0
3111
- * @example const options = new RedirectHandlerOptions({ maxRedirects: 5 });
3112
- */
3113
- constructor(options = {}) {
3114
- var _a, _b;
3115
- if (options.maxRedirects && options.maxRedirects > RedirectHandlerOptions.MAX_MAX_REDIRECTS) {
3116
- const error = new Error(`MaxRedirects should not be more than ${RedirectHandlerOptions.MAX_MAX_REDIRECTS}`);
3117
- error.name = "MaxLimitExceeded";
3118
- throw error;
3119
- }
3120
- if (options.maxRedirects !== void 0 && options.maxRedirects < 0) {
3121
- const error = new Error(`MaxRedirects should not be negative`);
3122
- error.name = "MinExpectationNotMet";
3123
- throw error;
3124
- }
3125
- this.maxRedirects = (_a = options.maxRedirects) !== null && _a !== void 0 ? _a : RedirectHandlerOptions.DEFAULT_MAX_REDIRECTS;
3126
- this.shouldRedirect = (_b = options.shouldRedirect) !== null && _b !== void 0 ? _b : RedirectHandlerOptions.defaultShouldRetry;
3127
- }
3128
- getKey() {
3129
- return RedirectHandlerOptionKey;
3130
- }
3131
- }
3132
- RedirectHandlerOptions.DEFAULT_MAX_REDIRECTS = 5;
3133
- RedirectHandlerOptions.MAX_MAX_REDIRECTS = 20;
3134
- RedirectHandlerOptions.defaultShouldRetry = () => true;
3135
- class RedirectHandler {
3136
- /**
3137
- *
3138
- *
3139
- * To create an instance of RedirectHandler
3140
- * @param [options] - The redirect handler options instance
3141
- * @returns An instance of RedirectHandler
3142
- */
3143
- constructor(options = new RedirectHandlerOptions()) {
3144
- this.options = options;
3145
- if (!options) {
3146
- throw new Error("The options parameter is required.");
3147
- }
3148
- }
3149
- /**
3150
- *
3151
- * To check whether the response has the redirect status code or not
3152
- * @param response - The response object
3153
- * @returns A boolean representing whether the response contains the redirect status code or not
3154
- */
3155
- isRedirect(response) {
3156
- return RedirectHandler.REDIRECT_STATUS_CODES.has(response.status);
3157
- }
3158
- /**
3159
- *
3160
- * To check whether the response has location header or not
3161
- * @param response - The response object
3162
- * @returns A boolean representing the whether the response has location header or not
3163
- */
3164
- hasLocationHeader(response) {
3165
- return response.headers.has(RedirectHandler.LOCATION_HEADER);
3166
- }
3167
- /**
3168
- *
3169
- * To get the redirect url from location header in response object
3170
- * @param response - The response object
3171
- * @returns A redirect url from location header
3172
- */
3173
- getLocationHeader(response) {
3174
- return response.headers.get(RedirectHandler.LOCATION_HEADER);
3175
- }
3176
- /**
3177
- *
3178
- * To check whether the given url is a relative url or not
3179
- * @param url - The url string value
3180
- * @returns A boolean representing whether the given url is a relative url or not
3181
- */
3182
- isRelativeURL(url) {
3183
- return !url.includes("://");
3184
- }
3185
- /**
3186
- *
3187
- * To check whether the authorization header in the request should be dropped for consequent redirected requests
3188
- * @param requestUrl - The request url value
3189
- * @param redirectUrl - The redirect url value
3190
- * @returns A boolean representing whether the authorization header in the request should be dropped for consequent redirected requests
3191
- */
3192
- shouldDropAuthorizationHeader(requestUrl, redirectUrl) {
3193
- const schemeHostRegex = /^[A-Za-z].+?:\/\/.+?(?=\/|$)/;
3194
- const requestMatches = schemeHostRegex.exec(requestUrl);
3195
- let requestAuthority;
3196
- let redirectAuthority;
3197
- if (requestMatches !== null) {
3198
- requestAuthority = requestMatches[0];
3199
- }
3200
- const redirectMatches = schemeHostRegex.exec(redirectUrl);
3201
- if (redirectMatches !== null) {
3202
- redirectAuthority = redirectMatches[0];
3203
- }
3204
- return typeof requestAuthority !== "undefined" && typeof redirectAuthority !== "undefined" && requestAuthority !== redirectAuthority;
3205
- }
3206
- /**
3207
- * To execute the next middleware and to handle in case of redirect response returned by the server
3208
- * @param url - The url string value
3209
- * @param fetchRequestInit - The Fetch RequestInit object
3210
- * @param redirectCount - The redirect count value
3211
- * @param currentOptions - The redirect handler options instance
3212
- * @param requestOptions - The request options
3213
- * @param tracerName - The name to use for the tracer
3214
- * @returns A promise that resolves to nothing
3215
- */
3216
- async executeWithRedirect(url, fetchRequestInit, redirectCount, currentOptions, requestOptions, tracerName) {
3217
- var _a;
3218
- const response = await ((_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(url, fetchRequestInit, requestOptions));
3219
- if (!response) {
3220
- throw new Error("Response is undefined");
3221
- }
3222
- if (redirectCount < currentOptions.maxRedirects && this.isRedirect(response) && this.hasLocationHeader(response) && currentOptions.shouldRedirect(response)) {
3223
- ++redirectCount;
3224
- if (response.status === RedirectHandler.STATUS_CODE_SEE_OTHER) {
3225
- fetchRequestInit.method = HttpMethod.GET;
3226
- delete fetchRequestInit.body;
3227
- } else {
3228
- const redirectUrl = this.getLocationHeader(response);
3229
- if (redirectUrl) {
3230
- if (fetchRequestInit.headers && !this.isRelativeURL(redirectUrl) && this.shouldDropAuthorizationHeader(url, redirectUrl)) {
3231
- delete fetchRequestInit.headers[RedirectHandler.AUTHORIZATION_HEADER];
3232
- }
3233
- url = redirectUrl;
3234
- }
3235
- }
3236
- if (tracerName) {
3237
- return trace.getTracer(tracerName).startActiveSpan(`redirectHandler - redirect ${redirectCount}`, (span) => {
3238
- try {
3239
- span.setAttribute("com.microsoft.kiota.handler.redirect.count", redirectCount);
3240
- span.setAttribute("http.response.status_code", response.status);
3241
- return this.executeWithRedirect(url, fetchRequestInit, redirectCount, currentOptions, requestOptions);
3242
- } finally {
3243
- span.end();
3244
- }
3245
- });
3246
- }
3247
- return await this.executeWithRedirect(url, fetchRequestInit, redirectCount, currentOptions, requestOptions);
3248
- } else {
3249
- return response;
3250
- }
3251
- }
3252
- /**
3253
- * Executes the request and returns a promise resolving the response.
3254
- * @param url - The url for the request
3255
- * @param requestInit - The Fetch RequestInit object.
3256
- * @param requestOptions - The request options.
3257
- * @returns A Promise that resolves to the response.
3258
- */
3259
- execute(url, requestInit, requestOptions) {
3260
- const redirectCount = 0;
3261
- let currentOptions = this.options;
3262
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[RedirectHandlerOptionKey]) {
3263
- currentOptions = requestOptions[RedirectHandlerOptionKey];
3264
- }
3265
- requestInit.redirect = RedirectHandler.MANUAL_REDIRECT;
3266
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
3267
- if (obsOptions) {
3268
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("redirectHandler - execute", (span) => {
3269
- try {
3270
- span.setAttribute("com.microsoft.kiota.handler.redirect.enable", true);
3271
- return this.executeWithRedirect(url, requestInit, redirectCount, currentOptions, requestOptions, obsOptions.getTracerInstrumentationName());
3272
- } finally {
3273
- span.end();
3274
- }
3275
- });
3276
- }
3277
- return this.executeWithRedirect(url, requestInit, redirectCount, currentOptions, requestOptions);
3278
- }
3279
- }
3280
- RedirectHandler.REDIRECT_STATUS_CODES = /* @__PURE__ */ new Set([
3281
- 301,
3282
- // Moved Permanently
3283
- 302,
3284
- // Found
3285
- 303,
3286
- // See Other
3287
- 307,
3288
- // Temporary Permanently
3289
- 308
3290
- // Moved Permanently
3291
- ]);
3292
- RedirectHandler.STATUS_CODE_SEE_OTHER = 303;
3293
- RedirectHandler.LOCATION_HEADER = "Location";
3294
- RedirectHandler.AUTHORIZATION_HEADER = "Authorization";
3295
- RedirectHandler.MANUAL_REDIRECT = "manual";
3296
- const RetryHandlerOptionKey = "RetryHandlerOptionKey";
3297
- class RetryHandlerOptions {
3298
- /**
3299
- *
3300
- * To create an instance of RetryHandlerOptions
3301
- * @param options - The RetryHandlerOptionsParams object
3302
- * @returns An instance of RetryHandlerOptions
3303
- * @example const options = new RetryHandlerOptions({ maxRetries: 4 });
3304
- */
3305
- constructor(options = {}) {
3306
- var _a, _b, _c;
3307
- if (options.delay !== void 0 && options.delay > RetryHandlerOptions.MAX_DELAY) {
3308
- throw this.createError(`Delay should not be more than ${RetryHandlerOptions.MAX_DELAY}`, "MaxLimitExceeded");
3309
- }
3310
- if (options.maxRetries !== void 0 && options.maxRetries > RetryHandlerOptions.MAX_MAX_RETRIES) {
3311
- throw this.createError(`MaxRetries should not be more than ${RetryHandlerOptions.MAX_MAX_RETRIES}`, "MaxLimitExceeded");
3312
- }
3313
- if (options.delay !== void 0 && options.delay < 0) {
3314
- throw this.createError(`Delay should not be negative`, "MinExpectationNotMet");
3315
- }
3316
- if (options.maxRetries !== void 0 && options.maxRetries < 0) {
3317
- throw this.createError(`MaxRetries should not be negative`, "MinExpectationNotMet");
3318
- }
3319
- this.delay = Math.min((_a = options.delay) !== null && _a !== void 0 ? _a : RetryHandlerOptions.DEFAULT_DELAY, RetryHandlerOptions.MAX_DELAY);
3320
- this.maxRetries = Math.min((_b = options.maxRetries) !== null && _b !== void 0 ? _b : RetryHandlerOptions.DEFAULT_MAX_RETRIES, RetryHandlerOptions.MAX_MAX_RETRIES);
3321
- this.shouldRetry = (_c = options.shouldRetry) !== null && _c !== void 0 ? _c : RetryHandlerOptions.defaultShouldRetry;
3322
- }
3323
- /**
3324
- *
3325
- * Creates an error object with a message and name
3326
- * @param message - The error message
3327
- * @param name - The error name
3328
- * @returns An error object
3329
- */
3330
- createError(message, name) {
3331
- const error = new Error(message);
3332
- error.name = name;
3333
- return error;
3334
- }
3335
- /**
3336
- *
3337
- * To get the maximum delay
3338
- * @returns A maximum delay
3339
- */
3340
- getMaxDelay() {
3341
- return RetryHandlerOptions.MAX_DELAY;
3342
- }
3343
- getKey() {
3344
- return RetryHandlerOptionKey;
3345
- }
3346
- }
3347
- RetryHandlerOptions.DEFAULT_DELAY = 3;
3348
- RetryHandlerOptions.DEFAULT_MAX_RETRIES = 3;
3349
- RetryHandlerOptions.MAX_DELAY = 180;
3350
- RetryHandlerOptions.MAX_MAX_RETRIES = 10;
3351
- RetryHandlerOptions.defaultShouldRetry = () => true;
3352
- class RetryHandler {
3353
- /**
3354
- *
3355
- * To create an instance of RetryHandler
3356
- * @param [options] - The retry handler options value
3357
- * @returns An instance of RetryHandler
3358
- */
3359
- constructor(options = new RetryHandlerOptions()) {
3360
- this.options = options;
3361
- if (!options) {
3362
- throw new Error("The options parameter is required.");
3363
- }
3364
- }
3365
- /**
3366
- *
3367
- *
3368
- * To check whether the response has the retry status code
3369
- * @param response - The response object
3370
- * @returns Whether the response has retry status code or not
3371
- */
3372
- isRetry(response) {
3373
- return RetryHandler.RETRY_STATUS_CODES.has(response.status);
3374
- }
3375
- /**
3376
- *
3377
- * To check whether the payload is buffered or not
3378
- * @param options - The options of a request
3379
- * @returns Whether the payload is buffered or not
3380
- */
3381
- isBuffered(options) {
3382
- var _a;
3383
- const method = options.method;
3384
- const isPutPatchOrPost = method === HttpMethod.PUT || method === HttpMethod.PATCH || method === HttpMethod.POST;
3385
- if (isPutPatchOrPost) {
3386
- const isStream = ((_a = getRequestHeader(options, "content-type")) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === "application/octet-stream";
3387
- if (isStream) {
3388
- return false;
3389
- }
3390
- }
3391
- return true;
3392
- }
3393
- /**
3394
- *
3395
- * To get the delay for a retry
3396
- * @param response - The response object
3397
- * @param retryAttempts - The current attempt count
3398
- * @param delay - The delay value in seconds
3399
- * @returns A delay for a retry
3400
- */
3401
- getDelay(response, retryAttempts, delay) {
3402
- const getRandomness = () => Number(Math.random().toFixed(3));
3403
- const retryAfter = response.headers !== void 0 ? response.headers.get(RetryHandler.RETRY_AFTER_HEADER) : null;
3404
- let newDelay;
3405
- if (retryAfter !== null) {
3406
- if (Number.isNaN(Number(retryAfter))) {
3407
- newDelay = Math.round((new Date(retryAfter).getTime() - Date.now()) / 1e3);
3408
- } else {
3409
- newDelay = Number(retryAfter);
3410
- }
3411
- } else {
3412
- newDelay = retryAttempts >= 2 ? this.getExponentialBackOffTime(retryAttempts) + delay + getRandomness() : delay + getRandomness();
3413
- }
3414
- return Math.min(newDelay, this.options.getMaxDelay() + getRandomness());
3415
- }
3416
- /**
3417
- *
3418
- * To get an exponential back off value
3419
- * @param attempts - The current attempt count
3420
- * @returns An exponential back off value
3421
- */
3422
- getExponentialBackOffTime(attempts) {
3423
- return Math.round(1 / 2 * (2 ** attempts - 1));
3424
- }
3425
- /**
3426
- * To add delay for the execution
3427
- * @param delaySeconds - The delay value in seconds
3428
- * @returns A Promise that resolves to nothing
3429
- */
3430
- async sleep(delaySeconds) {
3431
- const delayMilliseconds = delaySeconds * 1e3;
3432
- return new Promise((resolve) => setTimeout(resolve, delayMilliseconds));
3433
- }
3434
- /**
3435
- * To execute the middleware with retries
3436
- * @param url - The request url
3437
- * @param fetchRequestInit - The request options
3438
- * @param retryAttempts - The current attempt count
3439
- * @param currentOptions - The current request options for the retry handler.
3440
- * @param requestOptions - The retry middleware options instance
3441
- * @param tracerName - The name to use for the tracer
3442
- * @returns A Promise that resolves to nothing
3443
- */
3444
- async executeWithRetry(url, fetchRequestInit, retryAttempts, currentOptions, requestOptions, tracerName) {
3445
- var _a;
3446
- const response = await ((_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(url, fetchRequestInit, requestOptions));
3447
- if (!response) {
3448
- throw new Error("Response is undefined");
3449
- }
3450
- if (retryAttempts < currentOptions.maxRetries && this.isRetry(response) && this.isBuffered(fetchRequestInit) && currentOptions.shouldRetry(currentOptions.delay, retryAttempts, url, fetchRequestInit, response)) {
3451
- ++retryAttempts;
3452
- setRequestHeader(fetchRequestInit, RetryHandler.RETRY_ATTEMPT_HEADER, retryAttempts.toString());
3453
- let delay = null;
3454
- if (response) {
3455
- delay = this.getDelay(response, retryAttempts, currentOptions.delay);
3456
- await this.sleep(delay);
3457
- }
3458
- if (tracerName) {
3459
- return await trace.getTracer(tracerName).startActiveSpan(`retryHandler - attempt ${retryAttempts}`, (span) => {
3460
- try {
3461
- span.setAttribute("http.request.resend_count", retryAttempts);
3462
- if (delay) {
3463
- span.setAttribute("http.request.resend_delay", delay);
3464
- }
3465
- span.setAttribute("http.response.status_code", response.status);
3466
- return this.executeWithRetry(url, fetchRequestInit, retryAttempts, currentOptions, requestOptions);
3467
- } finally {
3468
- span.end();
3469
- }
3470
- });
3471
- }
3472
- return await this.executeWithRetry(url, fetchRequestInit, retryAttempts, currentOptions, requestOptions);
3473
- } else {
3474
- return response;
3475
- }
3476
- }
3477
- /**
3478
- * To execute the current middleware
3479
- * @param url - The request url
3480
- * @param requestInit - The request options
3481
- * @param requestOptions - The request options
3482
- * @returns A Promise that resolves to nothing
3483
- */
3484
- execute(url, requestInit, requestOptions) {
3485
- const retryAttempts = 0;
3486
- let currentOptions = this.options;
3487
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[RetryHandlerOptionKey]) {
3488
- currentOptions = requestOptions[RetryHandlerOptionKey];
3489
- }
3490
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
3491
- if (obsOptions) {
3492
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("retryHandler - execute", (span) => {
3493
- try {
3494
- span.setAttribute("com.microsoft.kiota.handler.retry.enable", true);
3495
- return this.executeWithRetry(url, requestInit, retryAttempts, currentOptions, requestOptions, obsOptions.getTracerInstrumentationName());
3496
- } finally {
3497
- span.end();
3498
- }
3499
- });
3500
- }
3501
- return this.executeWithRetry(url, requestInit, retryAttempts, currentOptions, requestOptions);
3502
- }
3503
- }
3504
- RetryHandler.RETRY_STATUS_CODES = /* @__PURE__ */ new Set([
3505
- 429,
3506
- // Too many requests
3507
- 503,
3508
- // Service unavailable
3509
- 504
3510
- // Gateway timeout
3511
- ]);
3512
- RetryHandler.RETRY_ATTEMPT_HEADER = "Retry-Attempt";
3513
- RetryHandler.RETRY_AFTER_HEADER = "Retry-After";
3514
- const libraryVersion = "1.0.0-preview.24";
3515
- const UserAgentHandlerOptionsKey = "UserAgentHandlerOptionKey";
3516
- class UserAgentHandlerOptions {
3517
- getKey() {
3518
- return UserAgentHandlerOptionsKey;
3519
- }
3520
- /**
3521
- *
3522
- * To create an instance of UserAgentHandlerOptions
3523
- * @param [options] - The options for the UserAgentHandler
3524
- * @example const options = new UserAgentHandlerOptions({ enable: false });
3525
- */
3526
- constructor(options = {}) {
3527
- var _a, _b, _c;
3528
- this.enable = (_a = options.enable) !== null && _a !== void 0 ? _a : true;
3529
- this.productName = (_b = options.productName) !== null && _b !== void 0 ? _b : "kiota-typescript";
3530
- this.productVersion = (_c = options.productVersion) !== null && _c !== void 0 ? _c : libraryVersion;
3531
- }
3532
- }
3533
- const USER_AGENT_HEADER_KEY = "User-Agent";
3534
- class UserAgentHandler {
3535
- /**
3536
- * To create an instance of UserAgentHandler
3537
- * @param _options - The options for the middleware
3538
- */
3539
- constructor(_options = new UserAgentHandlerOptions()) {
3540
- this._options = _options;
3541
- }
3542
- /** @inheritdoc */
3543
- execute(url, requestInit, requestOptions) {
3544
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
3545
- if (obsOptions) {
3546
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("userAgentHandler - execute", (span) => {
3547
- try {
3548
- span.setAttribute("com.microsoft.kiota.handler.useragent.enable", true);
3549
- return this.addValue(url, requestInit, requestOptions);
3550
- } finally {
3551
- span.end();
3552
- }
3553
- });
3554
- } else {
3555
- return this.addValue(url, requestInit, requestOptions);
3556
- }
3557
- }
3558
- async addValue(url, requestInit, requestOptions) {
3559
- var _a;
3560
- let currentOptions = this._options;
3561
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[UserAgentHandlerOptionsKey]) {
3562
- currentOptions = requestOptions[UserAgentHandlerOptionsKey];
3563
- }
3564
- if (currentOptions.enable) {
3565
- const additionalValue = `${currentOptions.productName}/${currentOptions.productVersion}`;
3566
- const currentValue = getRequestHeader(requestInit, USER_AGENT_HEADER_KEY);
3567
- if (!(currentValue === null || currentValue === void 0 ? void 0 : currentValue.includes(additionalValue))) {
3568
- appendRequestHeader(requestInit, USER_AGENT_HEADER_KEY, additionalValue, " ");
3569
- }
3570
- }
3571
- const response = await ((_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(url, requestInit, requestOptions));
3572
- if (!response)
3573
- throw new Error("No response returned by the next middleware");
3574
- return response;
3575
- }
3576
- }
3577
- const UrlReplaceHandlerOptionsKey = "UrlReplaceHandlerOptionsKey";
3578
- class UrlReplaceHandlerOptions {
3579
- /**
3580
- * Create a new instance of the UrlReplaceHandlerOptions class
3581
- * @param config the configuration to apply to the url replace handler options.
3582
- */
3583
- constructor(config) {
3584
- var _a, _b;
3585
- if (config) {
3586
- this._urlReplacements = (_a = config.urlReplacements) !== null && _a !== void 0 ? _a : {};
3587
- this._enabled = (_b = config.enabled) !== null && _b !== void 0 ? _b : true;
3588
- } else {
3589
- this._urlReplacements = {};
3590
- this._enabled = true;
3591
- }
3592
- }
3593
- /**
3594
- * @inheritdoc
3595
- */
3596
- getKey() {
3597
- return UrlReplaceHandlerOptionsKey;
3598
- }
3599
- /**
3600
- * Returns whether the url replace handler is enabled or not.
3601
- * @returns whether the url replace handler is enabled or not.
3602
- */
3603
- get enabled() {
3604
- return this._enabled;
3605
- }
3606
- /**
3607
- * Returns the url replacements combinations.
3608
- * @returns the url replacements combinations.
3609
- */
3610
- get urlReplacements() {
3611
- return this._urlReplacements;
3612
- }
3613
- }
3614
- class UrlReplaceHandler {
3615
- /**
3616
- *
3617
- * Creates a new instance of the UrlReplaceHandler class
3618
- * @param handlerOptions The options for the url replace handler.
3619
- * @returns An instance of the UrlReplaceHandler class
3620
- */
3621
- constructor(handlerOptions = new UrlReplaceHandlerOptions()) {
3622
- this.handlerOptions = handlerOptions;
3623
- if (!handlerOptions) {
3624
- throw new Error("handlerOptions cannot be undefined");
3625
- }
3626
- }
3627
- /**
3628
- * @inheritdoc
3629
- */
3630
- execute(url, requestInit, requestOptions) {
3631
- let currentOptions = this.handlerOptions;
3632
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions[UrlReplaceHandlerOptionsKey]) {
3633
- currentOptions = requestOptions[UrlReplaceHandlerOptionsKey];
3634
- }
3635
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
3636
- if (obsOptions) {
3637
- return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("urlReplaceHandler - execute", (span) => {
3638
- try {
3639
- span.setAttribute("com.microsoft.kiota.handler.urlReplace.enable", currentOptions.enabled);
3640
- return this.replaceTokensInUrl(currentOptions, url, requestInit, requestOptions);
3641
- } finally {
3642
- span.end();
3643
- }
3644
- });
3645
- }
3646
- return this.replaceTokensInUrl(currentOptions, url, requestInit, requestOptions);
3647
- }
3648
- replaceTokensInUrl(options, url, requestInit, requestOptions) {
3649
- var _a;
3650
- if (options.enabled) {
3651
- Object.keys(options.urlReplacements).forEach((replacementKey) => {
3652
- url = url.replace(replacementKey, options.urlReplacements[replacementKey]);
3653
- });
3654
- }
3655
- const response = (_a = this.next) === null || _a === void 0 ? void 0 : _a.execute(url, requestInit, requestOptions);
3656
- if (!response) {
3657
- throw new Error("Response is undefined");
3658
- }
3659
- return response;
3660
- }
3661
- }
3662
- class MiddlewareFactory {
3663
- /**
3664
- * @param customFetch - The custom fetch implementation
3665
- * Returns the default middleware chain an array with the middleware handlers
3666
- * @returns an array of the middleware handlers of the default middleware chain
3667
- */
3668
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
3669
- static getDefaultMiddlewares(customFetch = (...args) => fetch(...args)) {
3670
- return [new RetryHandler(), new RedirectHandler(), new ParametersNameDecodingHandler(), new UserAgentHandler(), new HeadersInspectionHandler(), new UrlReplaceHandler(), new CustomFetchHandler(customFetch)];
3671
- }
3672
- /**
3673
- * @param customFetch - The custom fetch implementation
3674
- * Returns the default middleware chain + performance middleware
3675
- * @returns an array of the middleware handlers of the default + performance middleware chain
3676
- */
3677
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
3678
- static getPerformanceMiddlewares(customFetch = (...args) => fetch(...args)) {
3679
- const middlewares = MiddlewareFactory.getDefaultMiddlewares(customFetch);
3680
- middlewares.splice(middlewares.length - 3, 0, new CompressionHandler());
3681
- return middlewares;
3682
- }
3683
- }
3684
- const ErrorHandlerOptionKey = "ErrorHandlerOptionKey";
3685
- class ErrorHandlerOptions {
3686
- constructor(enabled = true) {
3687
- this.enabled = enabled;
3688
- }
3689
- getKey() {
3690
- return ErrorHandlerOptionKey;
3691
- }
3692
- }
3693
- class ErrorHandler {
3694
- /**
3695
- *
3696
- * To create an instance of ErrorHandler
3697
- * @param [options] - The error handler options value
3698
- * @returns An instance of ErrorHandler
3699
- */
3700
- constructor(options = new ErrorHandlerOptions()) {
3701
- this.options = options;
3702
- }
3703
- /**
3704
- *
3705
- * The next middleware in the middleware chain
3706
- */
3707
- next;
3708
- /**
3709
- * To execute the current middleware
3710
- * @param url - The request url
3711
- * @param requestInit - The request options
3712
- * @param requestOptions - The request options
3713
- * @returns A Promise that resolves to nothing
3714
- */
3715
- async execute(url, requestInit, requestOptions) {
3716
- const response = await this.next?.execute(url, requestInit, requestOptions);
3717
- if (!response) {
3718
- throw new Error("Response is undefined");
3719
- }
3720
- let currentOptions = this.options;
3721
- if (requestOptions?.[ErrorHandlerOptionKey]) {
3722
- currentOptions = requestOptions[ErrorHandlerOptionKey];
3723
- }
3724
- if (currentOptions.enabled === false || this.isSuccessStatusCode(response)) {
3725
- return response;
3726
- }
3727
- const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
3728
- if (obsOptions) {
3729
- trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("retryHandler - execute", (span) => {
3730
- span.setAttribute("com.microsoft.kiota.handler.error.enable", true);
3731
- span.setAttribute("http.response.status_code", response.status);
3732
- span.setAttribute("http.response.status_text", response.statusText);
3733
- span.setAttribute("http.response.url", response.url);
3734
- span.end();
3735
- });
3736
- }
3737
- const err = new HttpRequestError(
3738
- `Request to ${url} failed with status code ${response.status}`,
3739
- response.status,
3740
- { url, request: requestInit, response }
3741
- );
3742
- throw err;
3743
- }
3744
- isSuccessStatusCode(response) {
3745
- return response.status >= 200 && response.status < 300;
3746
- }
3747
- }
3748
- class HttpRequestError extends Error {
3749
- constructor(message, statusCode, context) {
3750
- super(message);
3751
- this.statusCode = statusCode;
3752
- this.name = "HttpRequestError";
3753
- if (Error.captureStackTrace) {
3754
- Error.captureStackTrace(this, HttpRequestError);
3755
- }
3756
- }
3757
- }
3758
- class AccessTokenProvider {
3759
- constructor(getAccessToken) {
3760
- this.getAccessToken = getAccessToken;
3761
- }
3762
- async getAuthorizationToken(url, additionalAuthenticationContext) {
3763
- return await this.getAccessToken();
3764
- }
3765
- getAllowedHostsValidator() {
3766
- throw new Error("Method not implemented.");
3767
- }
3768
- }
3769
- class HttpClientFactory {
3770
- static create(customFetch) {
3771
- const middlewares = [new ErrorHandler(), ...MiddlewareFactory.getDefaultMiddlewares(customFetch)];
3772
- return new HttpClient(customFetch, ...middlewares);
3773
- }
3774
- static createFetchRequestAdapter(getAccessToken, httpClient) {
3775
- const auth = new BaseBearerTokenAuthenticationProvider(new AccessTokenProvider(getAccessToken));
3776
- return new FetchRequestAdapter(
3777
- auth,
3778
- void 0,
3779
- void 0,
3780
- httpClient
3781
- );
3782
- }
3783
- }
3784
- exports2.HttpClientFactory = HttpClientFactory;
3785
- Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
3786
- }));
3787
- //# sourceMappingURL=index.umd.js.map