@d1g1tal/transportr 1.4.4 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2695 +1,3 @@
1
- // node_modules/.pnpm/@d1g1tal+collections@0.2.5/node_modules/@d1g1tal/collections/src/set-multi-map.js
2
- var SetMultiMap = class extends Map {
3
- /**
4
- * Adds a new element with a specified key and value to the SetMultiMap.
5
- * If an element with the same key already exists, the value will be added to the underlying {@link Set}.
6
- * If the value already exists in the {@link Set}, it will not be added again.
7
- *
8
- * @param {K} key The key to set.
9
- * @param {V} value The value to add to the SetMultiMap
10
- * @returns {SetMultiMap<K, V>} The SetMultiMap with the updated key and value.
11
- */
12
- set(key, value) {
13
- super.set(key, (super.get(key) ?? /* @__PURE__ */ new Set()).add(value));
14
- return this;
15
- }
16
- /**
17
- * Checks if a specific key has a specific value.
18
- *
19
- * @param {K} key The key to check.
20
- * @param {V} value The value to check.
21
- * @returns {boolean} True if the key has the value, false otherwise.
22
- */
23
- hasValue(key, value) {
24
- const values = super.get(key);
25
- return values ? values.has(value) : false;
26
- }
27
- /**
28
- * Removes a specific value from a specific key.
29
- *
30
- * @param {K} key The key to remove the value from.
31
- * @param {V} value The value to remove.
32
- * @returns {boolean} True if the value was removed, false otherwise.
33
- */
34
- deleteValue(key, value) {
35
- const values = super.get(key);
36
- if (values) {
37
- return values.delete(value);
38
- }
39
- return false;
40
- }
41
- get [Symbol.toStringTag]() {
42
- return "SetMultiMap";
43
- }
44
- };
45
-
46
- // node_modules/.pnpm/@d1g1tal+subscribr@3.0.3/node_modules/@d1g1tal/subscribr/src/context-event-handler.js
47
- var ContextEventHandler = class {
48
- #context;
49
- #eventHandler;
50
- /**
51
- * @param {*} context The context to bind to the event handler.
52
- * @param {function(*): void} eventHandler The event handler to call when the event is published.
53
- */
54
- constructor(context, eventHandler) {
55
- this.#context = context;
56
- this.#eventHandler = eventHandler;
57
- }
58
- /**
59
- * Call the event handler for the provided event.
60
- *
61
- * @param {Event} event The event to handle
62
- * @param {*} [data] The value to be passed to the event handler as a parameter.
63
- */
64
- handle(event, data) {
65
- this.#eventHandler.call(this.#context, event, data);
66
- }
67
- get [Symbol.toStringTag]() {
68
- return "ContextEventHandler";
69
- }
70
- };
71
-
72
- // node_modules/.pnpm/@d1g1tal+subscribr@3.0.3/node_modules/@d1g1tal/subscribr/src/subscription.js
73
- var Subscription = class {
74
- #eventName;
75
- #contextEventHandler;
76
- /**
77
- * @param {string} eventName The event name.
78
- * @param {ContextEventHandler} contextEventHandler Then context event handler.
79
- */
80
- constructor(eventName, contextEventHandler) {
81
- this.#eventName = eventName;
82
- this.#contextEventHandler = contextEventHandler;
83
- }
84
- /**
85
- * Gets the event name for the subscription.
86
- *
87
- * @returns {string} The event name.
88
- */
89
- get eventName() {
90
- return this.#eventName;
91
- }
92
- /**
93
- * Gets the context event handler.
94
- *
95
- * @returns {ContextEventHandler} The context event handler
96
- */
97
- get contextEventHandler() {
98
- return this.#contextEventHandler;
99
- }
100
- get [Symbol.toStringTag]() {
101
- return "Subscription";
102
- }
103
- };
104
-
105
- // node_modules/.pnpm/@d1g1tal+subscribr@3.0.3/node_modules/@d1g1tal/subscribr/src/subscribr.js
106
- var Subscribr = class {
107
- /** @type {SetMultiMap<string, ContextEventHandler>} */
108
- #subscribers;
109
- constructor() {
110
- this.#subscribers = new SetMultiMap();
111
- }
112
- /**
113
- * Subscribe to an event
114
- *
115
- * @param {string} eventName The event name to subscribe to.
116
- * @param {function(Event, *): void} eventHandler The event handler to call when the event is published.
117
- * @param {*} [context] The context to bind to the event handler.
118
- * @returns {Subscription} An object used to check if the subscription still exists and to unsubscribe from the event.
119
- */
120
- subscribe(eventName, eventHandler, context = eventHandler) {
121
- const contextEventHandler = new ContextEventHandler(context, eventHandler);
122
- this.#subscribers.set(eventName, contextEventHandler);
123
- return new Subscription(eventName, contextEventHandler);
124
- }
125
- /**
126
- * Unsubscribe from the event
127
- *
128
- * @param {Subscription} subscription The subscription to unsubscribe.
129
- * @param {string} subscription.eventName The event name to subscribe to.
130
- * @param {ContextEventHandler} subscription.contextEventHandler The event handler to call when the event is published.
131
- * @returns {boolean} true if eventListener has been removed successfully. false if the value is not found or if the value is not an object.
132
- */
133
- unsubscribe({ eventName, contextEventHandler }) {
134
- const contextEventHandlers = this.#subscribers.get(eventName);
135
- const removed = contextEventHandlers?.delete(contextEventHandler);
136
- if (removed && contextEventHandlers.size == 0) {
137
- this.#subscribers.delete(eventName);
138
- }
139
- return removed;
140
- }
141
- /**
142
- * Publish an event
143
- *
144
- * @param {string} eventName The name of the event.
145
- * @param {Event} [event=new CustomEvent(eventName)] The event to be handled.
146
- * @param {*} [data] The value to be passed to the event handler as a parameter.
147
- */
148
- publish(eventName, event = new CustomEvent(eventName), data) {
149
- if (data == null && !(event instanceof Event)) {
150
- [data, event] = [event, new CustomEvent(eventName)];
151
- }
152
- this.#subscribers.get(eventName)?.forEach((contextEventHandler) => contextEventHandler.handle(event, data));
153
- }
154
- /**
155
- * Check if the event and handler are subscribed.
156
- *
157
- * @param {Subscription} subscription The subscription object.
158
- * @param {string} subscription.eventName The name of the event to check.
159
- * @param {ContextEventHandler} subscription.contextEventHandler The event handler to check.
160
- * @returns {boolean} true if the event name and handler are subscribed, false otherwise.
161
- */
162
- isSubscribed({ eventName, contextEventHandler }) {
163
- return this.#subscribers.get(eventName)?.has(contextEventHandler);
164
- }
165
- get [Symbol.toStringTag]() {
166
- return "Subscribr";
167
- }
168
- };
169
-
170
- // src/http-request-methods.js
171
- var HttpRequestMethod = {
172
- /**
173
- * The OPTIONS method represents a request for information about the communication options available on the
174
- * request/response chain identified by the Request-URI. This method allows the client to determine the options and/or
175
- * requirements associated with a resource, or the capabilities of a server, without implying a resource action or
176
- * initiating a resource retrieval.
177
- *
178
- * Responses to this method are not cacheable.
179
- *
180
- * If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or
181
- * Transfer-Encoding), then the media type MUST be indicated by a Content-Type field. Although this specification does
182
- * not define any use for such a body, future extensions to HTTP might use the OPTIONS body to make more detailed
183
- * queries on the server. A server that does not support such an extension MAY discard the request body.
184
- *
185
- * If the Request-URI is an asterisk ("*"), the OPTIONS request is intended to apply to the server in general rather
186
- * than to a specific resource. Since a server's communication options typically depend on the resource, the "*"
187
- * request is only useful as a "ping" or "no-op" type of method, it does nothing beyond allowing the client to test the
188
- * capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 compliance (or lack thereof).
189
- *
190
- * If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when
191
- * communicating with that resource.
192
- *
193
- * A 200 response SHOULD include any header fields that indicate optional features implemented by the server and
194
- * applicable to that resource (e.g., Allow), possibly including extensions not defined by this specification. The
195
- * response body, if any, SHOULD also include information about the communication options. The format for such a body
196
- * is not defined by this specification, but might be defined by future extensions to HTTP. Content negotiation MAY be
197
- * used to select the appropriate response format. If no response body is included, the response MUST include a
198
- * Content-Length field with a field-value of "0".
199
- *
200
- * The Max-Forwards request-header field MAY be used to target a specific proxy in the request chain. When a proxy
201
- * receives an OPTIONS request on an absoluteURI for which request forwarding is permitted, the proxy MUST check for a
202
- * Max-Forwards field. If the Max-Forwards field-value is zero ("0"), the proxy MUST NOT forward the message, instead,
203
- * the proxy SHOULD respond with its own communication options. If the Max-Forwards field-value is an integer greater
204
- * than zero, the proxy MUST decrement the field-value when it forwards the request. If no Max-Forwards field is
205
- * present in the request, then the forwarded request MUST NOT include a Max-Forwards field.
206
- */
207
- OPTIONS: "OPTIONS",
208
- /**
209
- * The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If
210
- * the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in
211
- * the response and not the source text of the process, unless that text happens to be the output of the process.
212
- *
213
- * The semantics of the GET method change to a "conditional GET" if the request message includes an If-Modified-Since;
214
- * If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the
215
- * entity be transferred only under the circumstances described by the conditional header field(s). The conditional GET
216
- * method is intended to reduce unnecessary network usage by allowing cached entities to be refreshed without requiring
217
- * multiple requests or transferring data already held by the client.
218
- *
219
- * The semantics of the GET method change to a "partial GET" if the request message includes a Range header field. A
220
- * partial GET requests that only part of the entity be transferred, as described in section 14.35. The partial GET
221
- * method is intended to reduce unnecessary network usage by allowing partially-retrieved entities to be completed
222
- * without transferring data already held by the client.
223
- *
224
- * The response to a GET request is cacheable if and only if it meets the requirements for HTTP caching described in
225
- * section 13.
226
- *
227
- * See section 15.1.3 for security considerations when used for forms.
228
- */
229
- GET: "GET",
230
- /**
231
- * The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The
232
- * meta information contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information
233
- * sent in response to a GET request. This method can be used for obtaining meta information about the entity implied by
234
- * the request without transferring the entity-body itself. This method is often used for testing hypertext links for
235
- * validity, accessibility, and recent modification.
236
- *
237
- * The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be
238
- * used to update a previously cached entity from that resource. If the new field values indicate that the cached
239
- * entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or
240
- * Last-Modified), then the cache MUST treat the cache entry as stale.
241
- */
242
- HEAD: "HEAD",
243
- /**
244
- * The POST method is used to request that the origin server accept the entity enclosed in the request as a new
245
- * subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform
246
- * method to cover the following functions:
247
- * <ul>
248
- * <li>Annotation of existing resources,</li>
249
- * <li>Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles,</li>
250
- * <li>Providing a block of data, such as the result of submitting a form, to a data-handling process,</li>
251
- * <li>Extending a database through an append operation.</li>
252
- * </ul>
253
- *
254
- * The actual function performed by the POST method is determined by the server and is usually dependent on the
255
- * Request-URI. The posted entity is subordinate to that URI in the same way that a file is subordinate to a directory
256
- * containing it, a news article is subordinate to a newsgroup to which it is posted, or a record is subordinate to a
257
- * database.
258
- *
259
- * The action performed by the POST method might not result in a resource that can be identified by a URI. In this
260
- * case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the
261
- * response includes an entity that describes the result.
262
- *
263
- * If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity
264
- * which describes the status of the request and refers to the new resource, and a Location header (see section 14.30).
265
- *
266
- * Responses to this method are not cacheable, unless the response includes appropriate Cache-Control or Expires header
267
- * fields. However, the 303 (See Other) response can be used to direct the user agent to retrieve a cacheable resource.
268
- *
269
- * POST requests MUST obey the message transmission requirements set out in section 8.2.
270
- *
271
- * See section 15.1.3 for security considerations.
272
- */
273
- POST: "POST",
274
- /**
275
- * The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers
276
- * to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing
277
- * on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being
278
- * defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. If
279
- * a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. If an
280
- * existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate
281
- * successful completion of the request. If the resource could not be created or modified with the Request-URI, an
282
- * appropriate error response SHOULD be given that reflects the nature of the problem. The recipient of the entity MUST
283
- * \NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return a
284
- * 501 (Not Implemented) response in such cases.
285
- *
286
- * If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those
287
- * entries SHOULD be treated as stale. Responses to this method are not cacheable.
288
- *
289
- * The fundamental difference between the POST and PUT requests is reflected in the different meaning of the
290
- * Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource
291
- * might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations.
292
- * In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what
293
- * URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires
294
- * that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response, the user agent MAY
295
- * then make its own decision regarding whether or not to redirect the request.
296
- *
297
- * A single resource MAY be identified by many different URIs. For example, an article might have a URI for identifying
298
- * "the current version" which is separate from the URI identifying each particular version. In this case, a PUT
299
- * request on a general URI might result in several other URIs being defined by the origin server.
300
- *
301
- * HTTP/1.1 does not define how a PUT method affects the state of an origin server.
302
- *
303
- * PUT requests MUST obey the message transmission requirements set out in section 8.2.
304
- *
305
- * Unless otherwise specified for a particular entity-header, the entity-headers in the PUT request SHOULD be applied
306
- * to the resource created or modified by the PUT.
307
- */
308
- PUT: "PUT",
309
- /**
310
- * The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY
311
- * be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the
312
- * operation has been carried out, even if the status code returned from the origin server indicates that the action
313
- * has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response
314
- * is given, it intends to delete the resource or move it to an inaccessible location.
315
- *
316
- * A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if
317
- * the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not
318
- * include an entity.
319
- *
320
- * If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those
321
- * entries SHOULD be treated as stale. Responses to this method are not cacheable.
322
- */
323
- DELETE: "DELETE",
324
- /**
325
- * The TRACE method is used to invoke a remote, application-layer loop- back of the request message. The final
326
- * recipient of the request SHOULD reflect the message received back to the client as the entity-body of a 200 (OK)
327
- * response. The final recipient is either the origin server or the first proxy or gateway to receive a Max-Forwards
328
- * value of zero (0) in the request (see section 14.31). A TRACE request MUST NOT include an entity.
329
- *
330
- * TRACE allows the client to see what is being received at the other end of the request chain and use that data for
331
- * testing or diagnostic information. The value of the Via header field (section 14.45) is of particular interest,
332
- * since it acts as a trace of the request chain. Use of the Max-Forwards header field allows the client to limit the
333
- * length of the request chain, which is useful for testing a chain of proxies forwarding messages in an infinite loop.
334
- *
335
- * If the request is valid, the response SHOULD contain the entire request message in the entity-body, with a
336
- * Content-Type of "message/http". Responses to this method MUST NOT be cached.
337
- */
338
- TRACE: "TRACE",
339
- /**
340
- * This specification reserves the method name CONNECT for use with a proxy that can dynamically switch to being a
341
- * tunnel (e.g. SSL tunneling [44]).
342
- */
343
- CONNECT: "CONNECT",
344
- /**
345
- * The PATCH method requests that a set of changes described in the
346
- * request entity be applied to the resource identified by the Request-
347
- * URI. The set of changes is represented in a format called a "patch
348
- * document" identified by a media type. If the Request-URI does not
349
- * point to an existing resource, the server MAY create a new resource,
350
- * depending on the patch document type (whether it can logically modify
351
- * a null resource) and permissions, etc.
352
- *
353
- * The difference between the PUT and PATCH requests is reflected in the
354
- * way the server processes the enclosed entity to modify the resource
355
- * identified by the Request-URI. In a PUT request, the enclosed entity
356
- * is considered to be a modified version of the resource stored on the
357
- * origin server, and the client is requesting that the stored version
358
- * be replaced. With PATCH, however, the enclosed entity contains a set
359
- * of instructions describing how a resource currently residing on the
360
- * origin server should be modified to produce a new version. The PATCH
361
- * method affects the resource identified by the Request-URI, and it
362
- * also MAY have side effects on other resources; i.e., new resources
363
- * may be created, or existing ones modified, by the application of a
364
- * PATCH.
365
- *
366
- * PATCH is neither safe nor idempotent as defined by [RFC2616], Section
367
- * 9.1.
368
- *
369
- * A PATCH request can be issued in such a way as to be idempotent,
370
- * which also helps prevent bad outcomes from collisions between two
371
- * PATCH requests on the same resource in a similar time frame.
372
- * Collisions from multiple PATCH requests may be more dangerous than
373
- * PUT collisions because some patch formats need to operate from a
374
- * known base-point or else they will corrupt the resource. Clients
375
- * using this kind of patch application SHOULD use a conditional request
376
- * such that the request will fail if the resource has been updated
377
- * since the client last accessed the resource. For example, the client
378
- * can use a strong ETag [RFC2616] in an If-Match header on the PATCH
379
- * request.
380
- *
381
- * There are also cases where patch formats do not need to operate from
382
- * a known base-point (e.g., appending text lines to log files, or non-
383
- * colliding rows to database tables), in which case the same care in
384
- * client requests is not needed.
385
- *
386
- * The server MUST apply the entire set of changes atomically and never
387
- * provide (e.g., in response to a GET during this operation) a
388
- * partially modified representation. If the entire patch document
389
- * cannot be successfully applied, then the server MUST NOT apply any of
390
- * the changes. The determination of what constitutes a successful
391
- * PATCH can vary depending on the patch document and the type of
392
- * resource(s) being modified. For example, the common 'diff' utility
393
- * can generate a patch document that applies to multiple files in a
394
- * directory hierarchy. The atomicity requirement holds for all
395
- * directly affected files. See "Error Handling", Section 2.2, for
396
- * details on status codes and possible error conditions.
397
- *
398
- * If the request passes through a cache and the Request-URI identifies
399
- * one or more currently cached entities, those entries SHOULD be
400
- * treated as stale. A response to this method is only cacheable if it
401
- * contains explicit freshness information (such as an Expires header or
402
- * "Cache-Control: max-age" directive) as well as the Content-Location
403
- * header matching the Request-URI, indicating that the PATCH response
404
- * body is a resource representation. A cached PATCH response can only
405
- * be used to respond to subsequent GET and HEAD requests; it MUST NOT
406
- * be used to respond to other methods (in particular, PATCH).
407
- *
408
- * Note that entity-headers contained in the request apply only to the
409
- * contained patch document and MUST NOT be applied to the resource
410
- * being modified. Thus, a Content-Language header could be present on
411
- * the request, but it would only mean (for whatever that's worth) that
412
- * the patch document had a language. Servers SHOULD NOT store such
413
- * headers except as trace information, and SHOULD NOT use such header
414
- * values the same way they might be used on PUT requests. Therefore,
415
- * this document does not specify a way to modify a document's Content-
416
- * Type or Content-Language value through headers, though a mechanism
417
- * could well be designed to achieve this goal through a patch document.
418
- *
419
- * There is no guarantee that a resource can be modified with PATCH.
420
- * Further, it is expected that different patch document formats will be
421
- * appropriate for different types of resources and that no single
422
- * format will be appropriate for all types of resources. Therefore,
423
- * there is no single default patch document format that implementations
424
- * are required to support. Servers MUST ensure that a received patch
425
- * document is appropriate for the type of resource identified by the
426
- * Request-URI.
427
- *
428
- * Clients need to choose when to use PATCH rather than PUT. For
429
- * example, if the patch document size is larger than the size of the
430
- * new resource data that would be used in a PUT, then it might make
431
- * sense to use PUT instead of PATCH. A comparison to POST is even more
432
- * difficult, because POST is used in widely varying ways and can
433
- * encompass PUT and PATCH-like operations if the server chooses. If
434
- * the operation does not modify the resource identified by the Request-
435
- * URI in a predictable way, POST should be considered instead of PATCH
436
- * or PUT.
437
- */
438
- PATCH: "PATCH"
439
- };
440
- var http_request_methods_default = HttpRequestMethod;
441
-
442
- // src/response-status.js
443
- var ResponseStatus = class {
444
- /** @type {number} */
445
- #code;
446
- /** @type {string} */
447
- #text;
448
- /**
449
- *
450
- * @param {number} code The status code from the {@link Response}
451
- * @param {string} text The status text from the {@link Response}
452
- */
453
- constructor(code, text) {
454
- this.#code = code;
455
- this.#text = text;
456
- }
457
- /**
458
- * Returns the status code from the {@link Response}
459
- *
460
- * @returns {number} The status code.
461
- */
462
- get code() {
463
- return this.#code;
464
- }
465
- /**
466
- * Returns the status text from the {@link Response}.
467
- *
468
- * @returns {string} The status text.
469
- */
470
- get text() {
471
- return this.#text;
472
- }
473
- /**
474
- * A String value that is used in the creation of the default string
475
- * description of an object. Called by the built-in method {@link Object.prototype.toString}.
476
- *
477
- * @override
478
- * @returns {string} The default string description of this object.
479
- */
480
- get [Symbol.toStringTag]() {
481
- return "ResponseStatus";
482
- }
483
- /**
484
- * tostring method for the class.
485
- *
486
- * @override
487
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString|Object.prototype.toString}
488
- * @returns {string} The status code and status text.
489
- */
490
- toString() {
491
- return `${this.#code} ${this.#text}`;
492
- }
493
- };
494
-
495
- // node_modules/.pnpm/@d1g1tal+chrysalis@2.2.1/node_modules/@d1g1tal/chrysalis/src/esm/object-type.js
496
- var _type = (object) => object?.constructor ?? object?.prototype?.constructor ?? globalThis[Object.prototype.toString.call(object).slice(8, -1)] ?? object;
497
- var object_type_default = _type;
498
-
499
- // node_modules/.pnpm/@d1g1tal+chrysalis@2.2.1/node_modules/@d1g1tal/chrysalis/src/esm/object-merge.js
500
- var _objectMerge = (...objects) => {
501
- const target = {};
502
- for (const source of objects) {
503
- if (object_type_default(source) != Object)
504
- return void 0;
505
- let descriptor, sourceType;
506
- for (const property of Object.getOwnPropertyNames(source)) {
507
- descriptor = Object.getOwnPropertyDescriptor(source, property);
508
- if (descriptor.enumerable) {
509
- sourceType = object_type_default(source[property]);
510
- if (sourceType == Object) {
511
- descriptor.value = object_type_default(target[property]) == Object ? _objectMerge(target[property], source[property]) : { ...source[property] };
512
- } else if (sourceType == Array) {
513
- descriptor.value = Array.isArray(target[property]) ? [.../* @__PURE__ */ new Set([...source[property], ...target[property]])] : [...source[property]];
514
- }
515
- target[property] = descriptor.value;
516
- }
517
- }
518
- }
519
- return target;
520
- };
521
- var object_merge_default = _objectMerge;
522
-
523
- // node_modules/.pnpm/@d1g1tal+media-type@5.0.0/node_modules/@d1g1tal/media-type/src/utils.js
524
- var httpTokenCodePoints = /^[-!#$%&'*+.^_`|~A-Za-z0-9]*$/u;
525
- var utils_default = httpTokenCodePoints;
526
-
527
- // node_modules/.pnpm/@d1g1tal+media-type@5.0.0/node_modules/@d1g1tal/media-type/src/media-type-parameters.js
528
- var matcher = /(["\\])/ug;
529
- var httpQuotedStringTokenCodePoints = /^[\t\u0020-\u007E\u0080-\u00FF]*$/u;
530
- var MediaTypeParameters = class _MediaTypeParameters extends Map {
531
- /**
532
- * Create a new MediaTypeParameters instance.
533
- *
534
- * @param {Array<[string, string]>} entries An array of [name, value] tuples.
535
- */
536
- constructor(entries = []) {
537
- super(entries);
538
- }
539
- /**
540
- * Indicates whether the supplied name and value are valid media type parameters.
541
- *
542
- * @static
543
- * @param {string} name The name of the media type parameter to validate.
544
- * @param {string} value The media type parameter value to validate.
545
- * @returns {boolean} true if the media type parameter is valid, false otherwise.
546
- */
547
- static isValid(name, value) {
548
- return utils_default.test(name) && httpQuotedStringTokenCodePoints.test(value);
549
- }
550
- /**
551
- * Gets the media type parameter value for the supplied name.
552
- *
553
- * @param {string} name The name of the media type parameter to retrieve.
554
- * @returns {string} The media type parameter value.
555
- */
556
- get(name) {
557
- return super.get(name.toLowerCase());
558
- }
559
- /**
560
- * Indicates whether the media type parameter with the specified name exists or not.
561
- *
562
- * @param {string} name The name of the media type parameter to check.
563
- * @returns {boolean} true if the media type parameter exists, false otherwise.
564
- */
565
- has(name) {
566
- return super.has(name.toLowerCase());
567
- }
568
- /**
569
- * Adds a new media type parameter using the specified name and value to the MediaTypeParameters.
570
- * If an parameter with the same name already exists, the parameter will be updated.
571
- *
572
- * @param {string} name The name of the media type parameter to set.
573
- * @param {string} value The media type parameter value.
574
- * @returns {MediaTypeParameters} This instance.
575
- */
576
- set(name, value) {
577
- if (!_MediaTypeParameters.isValid(name, value)) {
578
- throw new Error(`Invalid media type parameter name/value: ${name}/${value}`);
579
- }
580
- super.set(name.toLowerCase(), value);
581
- return this;
582
- }
583
- /**
584
- * Removes the media type parameter using the specified name.
585
- *
586
- * @param {string} name The name of the media type parameter to delete.
587
- * @returns {boolean} true if the parameter existed and has been removed, or false if the parameter does not exist.
588
- */
589
- delete(name) {
590
- return super.delete(name.toLowerCase());
591
- }
592
- /**
593
- * Returns a string representation of the media type parameters.
594
- *
595
- * @override
596
- * @returns {string} The string representation of the media type parameters.
597
- */
598
- toString() {
599
- return Array.from(this).map(([name, value]) => `;${name}=${!value || !utils_default.test(value) ? `"${value.replace(matcher, "\\$1")}"` : value}`).join("");
600
- }
601
- /**
602
- * Returns the name of this class.
603
- *
604
- * @override
605
- * @returns {string} The name of this class.
606
- */
607
- [Symbol.toStringTag]() {
608
- return "MediaTypeParameters";
609
- }
610
- };
611
-
612
- // node_modules/.pnpm/@d1g1tal+media-type@5.0.0/node_modules/@d1g1tal/media-type/src/media-type-parser.js
613
- var whitespaceCharacters = [" ", " ", "\n", "\r"];
614
- var trailingWhitespace = /[ \t\n\r]+$/u;
615
- var leadingAndTrailingWhitespace = /^[ \t\n\r]+|[ \t\n\r]+$/ug;
616
- var MediaTypeParser = class _MediaTypeParser {
617
- /**
618
- * Function to parse a media type.
619
- *
620
- * @static
621
- * @param {string} input The media type to parse
622
- * @returns {{ type: string, subtype: string, parameters: MediaTypeParameters }} An object populated with the parsed media type properties and any parameters.
623
- */
624
- static parse(input) {
625
- input = input.replace(leadingAndTrailingWhitespace, "");
626
- const length = input.length, trim = true, lowerCase = false;
627
- let { position, result: type, subtype = "" } = _MediaTypeParser.#filterComponent({ input }, "/");
628
- if (!type.length || position >= length || !utils_default.test(type)) {
629
- throw new TypeError(_MediaTypeParser.#generateErrorMessage("type", type));
630
- }
631
- ({ position, result: subtype } = _MediaTypeParser.#filterComponent({ position: ++position, input, trim }, ";"));
632
- if (!subtype.length || !utils_default.test(subtype)) {
633
- throw new TypeError(_MediaTypeParser.#generateErrorMessage("subtype", subtype));
634
- }
635
- let parameterName = "", parameterValue = null;
636
- const parameters = new MediaTypeParameters();
637
- while (position++ < length) {
638
- while (whitespaceCharacters.includes(input[position])) {
639
- ++position;
640
- }
641
- ({ position, result: parameterName } = _MediaTypeParser.#filterComponent({ position, input, lowerCase }, ";", "="));
642
- if (position < length) {
643
- if (input[position] == ";") {
644
- continue;
645
- }
646
- ++position;
647
- }
648
- if (input[position] == '"') {
649
- [parameterValue, position] = _MediaTypeParser.#collectHttpQuotedString(input, position);
650
- while (position < length && input[position] != ";") {
651
- ++position;
652
- }
653
- } else {
654
- ({ position, result: parameterValue } = _MediaTypeParser.#filterComponent({ position, input, lowerCase, trim }, ";"));
655
- if (!parameterValue) {
656
- continue;
657
- }
658
- }
659
- if (parameterName && MediaTypeParameters.isValid(parameterName, parameterValue) && !parameters.has(parameterName)) {
660
- parameters.set(parameterName, parameterValue);
661
- }
662
- }
663
- return { type, subtype, parameters };
664
- }
665
- /**
666
- * Filters a component from the input string.
667
- *
668
- * @private
669
- * @static
670
- * @param {Object} options The options.
671
- * @param {number} [options.position] The starting position.
672
- * @param {string} options.input The input string.
673
- * @param {boolean} [options.lowerCase] Indicates whether the result should be lowercased.
674
- * @param {boolean} [options.trim] Indicates whether the result should be trimmed.
675
- * @param {string[]} charactersToFilter The characters to filter.
676
- * @returns {{ position: number, result: string }} An object that includes the resulting string and updated position.
677
- */
678
- static #filterComponent({ position = 0, input, lowerCase = true, trim = false }, ...charactersToFilter) {
679
- let result = "";
680
- for (const length = input.length; position < length && !charactersToFilter.includes(input[position]); position++) {
681
- result += input[position];
682
- }
683
- if (lowerCase) {
684
- result = result.toLowerCase();
685
- }
686
- if (trim) {
687
- result = result.replace(trailingWhitespace, "");
688
- }
689
- return { position, result };
690
- }
691
- /**
692
- * Collects all the HTTP quoted strings.
693
- * This variant only implements it with the extract-value flag set.
694
- *
695
- * @private
696
- * @static
697
- * @param {string} input The string to process.
698
- * @param {number} position The starting position.
699
- * @returns {Array<string|number>} An array that includes the resulting string and updated position.
700
- */
701
- static #collectHttpQuotedString(input, position) {
702
- let value = "";
703
- for (let length = input.length, char; ++position < length; ) {
704
- if ((char = input[position]) == '"') {
705
- break;
706
- }
707
- value += char == "\\" && ++position < length ? input[position] : char;
708
- }
709
- return [value, position];
710
- }
711
- /**
712
- * Generates an error message.
713
- *
714
- * @private
715
- * @static
716
- * @param {string} component The component name.
717
- * @param {string} value The component value.
718
- * @returns {string} The error message.
719
- */
720
- static #generateErrorMessage(component, value) {
721
- return `Invalid ${component} "${value}": only HTTP token code points are valid.`;
722
- }
723
- };
724
-
725
- // node_modules/.pnpm/@d1g1tal+media-type@5.0.0/node_modules/@d1g1tal/media-type/src/media-type.js
726
- var MediaType = class _MediaType {
727
- /** @type {string} */
728
- #type;
729
- /** @type {string} */
730
- #subtype;
731
- /** @type {MediaTypeParameters} */
732
- #parameters;
733
- /**
734
- * Create a new MediaType instance from a string representation.
735
- *
736
- * @param {string} mediaType The media type to parse.
737
- * @param {Object} [parameters] Optional parameters.
738
- */
739
- constructor(mediaType, parameters = {}) {
740
- if (object_type_default(parameters) != Object) {
741
- throw new TypeError("The parameters argument must be an object");
742
- }
743
- ({ type: this.#type, subtype: this.#subtype, parameters: this.#parameters } = MediaTypeParser.parse(mediaType));
744
- for (const [name, value] of Object.entries(parameters)) {
745
- this.#parameters.set(name, value);
746
- }
747
- }
748
- static parse(mediaType) {
749
- try {
750
- return new _MediaType(mediaType);
751
- } catch (e) {
752
- }
753
- return null;
754
- }
755
- /**
756
- * Gets the type.
757
- *
758
- * @returns {string} The type.
759
- */
760
- get type() {
761
- return this.#type;
762
- }
763
- /**
764
- * Gets the subtype.
765
- *
766
- * @returns {string} The subtype.
767
- */
768
- get subtype() {
769
- return this.#subtype;
770
- }
771
- /**
772
- * Gets the media type essence (type/subtype).
773
- *
774
- * @returns {string} The media type without any parameters
775
- */
776
- get essence() {
777
- return `${this.#type}/${this.#subtype}`;
778
- }
779
- /**
780
- * Gets the parameters.
781
- *
782
- * @returns {MediaTypeParameters} The media type parameters.
783
- */
784
- get parameters() {
785
- return this.#parameters;
786
- }
787
- /**
788
- * Checks if the media type matches the specified type.
789
- *
790
- * @todo Fix string handling to parse the type and subtype from the string.
791
- * @param {MediaType|string} type The media type to check.
792
- * @returns {boolean} true if the media type matches the specified type, false otherwise.
793
- */
794
- matches(type) {
795
- return this.#type == type?.type && this.#subtype == type?.subtype || this.essence.includes(type);
796
- }
797
- /**
798
- * Gets the serialized version of the media type.
799
- *
800
- * @returns {string} The serialized media type.
801
- */
802
- toString() {
803
- return `${this.essence}${this.#parameters.toString()}`;
804
- }
805
- /**
806
- * Gets the name of the class.
807
- *
808
- * @returns {string} The class name
809
- */
810
- get [Symbol.toStringTag]() {
811
- return "MediaType";
812
- }
813
- };
814
-
815
- // src/http-media-type.js
816
- var HttpMediaType = {
817
- /** Advanced Audio Coding (AAC) */
818
- AAC: "audio/aac",
819
- /** AbiWord */
820
- ABW: "application/x-abiword",
821
- /** Archive document (multiple files embedded) */
822
- ARC: "application/x-freearc",
823
- /** AVIF image */
824
- AVIF: "image/avif",
825
- /** Audio Video Interleave (AVI) */
826
- AVI: "video/x-msvideo",
827
- /** Amazon Kindle eBook format */
828
- AZW: "application/vnd.amazon.ebook",
829
- /** Binary Data */
830
- BIN: "application/octet-stream",
831
- /** Windows OS/2 Bitmap Graphics */
832
- BMP: "image/bmp",
833
- /** Bzip Archive */
834
- BZIP: "application/x-bzip",
835
- /** Bzip2 Archive */
836
- BZIP2: "application/x-bzip2",
837
- /** CD audio */
838
- CDA: "application/x-cdf",
839
- /** C Shell Script */
840
- CSH: "application/x-csh",
841
- /** Cascading Style Sheets (CSS) */
842
- CSS: "text/css",
843
- /** Comma-Separated Values */
844
- CSV: "text/csv",
845
- /** Microsoft Office Word Document */
846
- DOC: "application/msword",
847
- /** Microsoft Office Word Document (OpenXML) */
848
- DOCX: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
849
- /** Microsoft Embedded OpenType */
850
- EOT: "application/vnd.ms-fontobject",
851
- /** Electronic Publication (EPUB) */
852
- EPUB: "application/epub+zip",
853
- /** GZip Compressed Archive */
854
- GZIP: "application/gzip",
855
- /** Graphics Interchange Format */
856
- GIF: "image/gif",
857
- /** HyperText Markup Language (HTML) */
858
- HTML: "text/html",
859
- /** Icon Format */
860
- ICO: "image/vnd.microsoft.icon",
861
- /** iCalendar Format */
862
- ICS: "text/calendar",
863
- /** Java Archive (JAR) */
864
- JAR: "application/java-archive",
865
- /** JPEG Image */
866
- JPEG: "image/jpeg",
867
- /** JavaScript */
868
- JAVA_SCRIPT: "text/javascript",
869
- /** JavaScript Object Notation Format (JSON) */
870
- JSON: "application/json",
871
- /** JavaScript Object Notation LD Format */
872
- JSON_LD: "application/ld+json",
873
- /** JavaScript Object Notation (JSON) Merge Patch */
874
- JSON_MERGE_PATCH: "application/merge-patch+json",
875
- /** Musical Instrument Digital Interface (MIDI) */
876
- MID: "audio/midi",
877
- /** Musical Instrument Digital Interface (MIDI) */
878
- X_MID: "audio/x-midi",
879
- /** MP3 Audio */
880
- MP3: "audio/mpeg",
881
- /** MPEG-4 Audio */
882
- MP4A: "audio/mp4",
883
- /** MPEG-4 Video */
884
- MP4: "video/mp4",
885
- /** MPEG Video */
886
- MPEG: "video/mpeg",
887
- /** Apple Installer Package */
888
- MPKG: "application/vnd.apple.installer+xml",
889
- /** OpenDocument Presentation Document */
890
- ODP: "application/vnd.oasis.opendocument.presentation",
891
- /** OpenDocument Spreadsheet Document */
892
- ODS: "application/vnd.oasis.opendocument.spreadsheet",
893
- /** OpenDocument Text Document */
894
- ODT: "application/vnd.oasis.opendocument.text",
895
- /** Ogg Audio */
896
- OGA: "audio/ogg",
897
- /** Ogg Video */
898
- OGV: "video/ogg",
899
- /** Ogg */
900
- OGX: "application/ogg",
901
- /** Opus audio */
902
- OPUS: "audio/opus",
903
- /** OpenType Font File */
904
- OTF: "font/otf",
905
- /** Portable Network Graphics (PNG) */
906
- PNG: "image/png",
907
- /** Adobe Portable Document Format */
908
- PDF: "application/pdf",
909
- /** Hypertext Preprocessor (Personal Home Page) */
910
- PHP: "application/x-httpd-php",
911
- /** Microsoft PowerPoint */
912
- PPT: "application/vnd.ms-powerpoint",
913
- /** Microsoft Office Presentation (OpenXML) */
914
- PPTX: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
915
- /** RAR Archive */
916
- RAR: "application/vnd.rar",
917
- /** Rich Text Format */
918
- RTF: "application/rtf",
919
- /** Bourne Shell Script */
920
- SH: "application/x-sh",
921
- /** Scalable Vector Graphics (SVG) */
922
- SVG: "image/svg+xml",
923
- /** Tape Archive (TAR) */
924
- TAR: "application/x-tar",
925
- /** Tagged Image File Format (TIFF) */
926
- TIFF: "image/tiff",
927
- /** MPEG transport stream */
928
- TRANSPORT_STREAM: "video/mp2t",
929
- /** TrueType Font */
930
- TTF: "font/ttf",
931
- /** Text, (generally ASCII or ISO 8859-n) */
932
- TEXT: "text/plain",
933
- /** Microsoft Visio */
934
- VSD: "application/vnd.visio",
935
- /** Waveform Audio Format (WAV) */
936
- WAV: "audio/wav",
937
- /** Open Web Media Project - Audio */
938
- WEBA: "audio/webm",
939
- /** Open Web Media Project - Video */
940
- WEBM: "video/webm",
941
- /** WebP Image */
942
- WEBP: "image/webp",
943
- /** Web Open Font Format */
944
- WOFF: "font/woff",
945
- /** Web Open Font Format */
946
- WOFF2: "font/woff2",
947
- /** Form - Encoded */
948
- FORM: "application/x-www-form-urlencoded",
949
- /** Multipart FormData */
950
- MULTIPART_FORM_DATA: "multipart/form-data",
951
- /** XHTML - The Extensible HyperText Markup Language */
952
- XHTML: "application/xhtml+xml",
953
- /** Microsoft Excel Document */
954
- XLS: "application/vnd.ms-excel",
955
- /** Microsoft Office Spreadsheet Document (OpenXML) */
956
- XLSX: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
957
- /** Extensible Markup Language (XML) */
958
- XML: "application/xml",
959
- /** XML User Interface Language (XUL) */
960
- XUL: "application/vnd.mozilla.xul+xml",
961
- /** Zip Archive */
962
- ZIP: "application/zip",
963
- /** 3GPP audio/video container */
964
- "3GP": "video/3gpp",
965
- /** 3GPP2 audio/video container */
966
- "3G2": "video/3gpp2",
967
- /** 7-Zip Archive */
968
- "7Z": "application/x-7z-compressed"
969
- };
970
- var http_media_type_default = HttpMediaType;
971
-
972
- // src/constants.js
973
- var defaultCharset = "utf-8";
974
- var endsWithSlashRegEx = /\/$/;
975
- var mediaTypes = /* @__PURE__ */ new Map([
976
- [http_media_type_default.PNG, new MediaType(http_media_type_default.PNG)],
977
- [http_media_type_default.TEXT, new MediaType(http_media_type_default.TEXT, { defaultCharset })],
978
- [http_media_type_default.JSON, new MediaType(http_media_type_default.JSON, { defaultCharset })],
979
- [http_media_type_default.HTML, new MediaType(http_media_type_default.HTML, { defaultCharset })],
980
- [http_media_type_default.JAVA_SCRIPT, new MediaType(http_media_type_default.JAVA_SCRIPT, { defaultCharset })],
981
- [http_media_type_default.CSS, new MediaType(http_media_type_default.CSS, { defaultCharset })],
982
- [http_media_type_default.XML, new MediaType(http_media_type_default.XML, { defaultCharset })],
983
- [http_media_type_default.BIN, new MediaType(http_media_type_default.BIN)]
984
- ]);
985
- var RequestEvents = Object.freeze({
986
- CONFIGURED: "configured",
987
- SUCCESS: "success",
988
- ERROR: "error",
989
- ABORTED: "aborted",
990
- TIMEOUT: "timeout",
991
- COMPLETE: "complete",
992
- ALL_COMPLETE: "all-complete"
993
- });
994
- var SignalEvents = Object.freeze({
995
- ABORT: "abort",
996
- TIMEOUT: "timeout"
997
- });
998
- var _abortEvent = new CustomEvent(SignalEvents.ABORT, { detail: { cause: new DOMException("The request was aborted", "AbortError") } });
999
- var requestBodyMethods = [http_request_methods_default.POST, http_request_methods_default.PUT, http_request_methods_default.PATCH];
1000
- var internalServerError = new ResponseStatus(500, "Internal Server Error");
1001
- var eventResponseStatuses = Object.freeze({
1002
- [RequestEvents.ABORTED]: new ResponseStatus(499, "Aborted"),
1003
- [RequestEvents.TIMEOUT]: new ResponseStatus(504, "Request Timeout")
1004
- });
1005
- var abortSignalProxyHandler = { get: (target, property) => property == "signal" ? target.signal.timeout(target.timeout) : Reflect.get(target, property) };
1006
-
1007
- // src/abort-signal.js
1008
- var AbortSignal = class {
1009
- /** @type {AbortController} */
1010
- #abortController;
1011
- /** @type {number} */
1012
- #timeoutId;
1013
- /**
1014
- * @param {NativeAbortSignal} signal The signal to chain.
1015
- * This signal will be able to abort the request, but will not be notified if the request is aborted by the timeout.
1016
- */
1017
- constructor(signal) {
1018
- this.#abortController = new AbortController();
1019
- signal?.addEventListener(SignalEvents.ABORT, (event) => this.#abort(event));
1020
- }
1021
- /**
1022
- * The aborted property is a Boolean that indicates whether the request has been aborted (true) or not (false).
1023
- *
1024
- * @returns {boolean} Whether the signal was aborted or not
1025
- */
1026
- get aborted() {
1027
- return this.#abortController.signal.aborted;
1028
- }
1029
- /**
1030
- * The reason property returns a DOMException object indicating the reason the operation was aborted, or null if the operation is not aborted.
1031
- *
1032
- * @returns {DOMException} The reason the signal was aborted
1033
- */
1034
- get reason() {
1035
- return this.#abortController.signal.reason;
1036
- }
1037
- /**
1038
- * Returns an AbortSignal instance that will be aborted when the provided amount of milliseconds have passed.
1039
- * A value of {@link Infinity} means there is no timeout.
1040
- * Note: You can't set this property to a value less than 0.
1041
- *
1042
- * @param {number} timeout The timeout in milliseconds
1043
- * @returns {AbortSignal} The abort signal
1044
- */
1045
- timeout(timeout) {
1046
- if (timeout < 0) {
1047
- throw new RangeError("The timeout cannot be negative");
1048
- }
1049
- if (timeout != Infinity) {
1050
- this.#timeoutId ??= setTimeout(() => this.#abort(new CustomEvent(SignalEvents.TIMEOUT, { detail: { timeout, cause: new DOMException(`The request timed-out after ${timeout / 1e3} seconds`, "TimeoutError") } }), true), timeout);
1051
- }
1052
- return this.#abortController.signal;
1053
- }
1054
- /**
1055
- * Clears the timeout.
1056
- * Note: This does not abort the signal, dispatch the timeout event, or reset the timeout.
1057
- *
1058
- * @returns {void}
1059
- */
1060
- clearTimeout() {
1061
- clearTimeout(this.#timeoutId);
1062
- }
1063
- /**
1064
- * Adds an event listener for the 'abort' event.
1065
- *
1066
- * @param {EventListener} listener The listener to add
1067
- * @returns {AbortSignal} The AbortSignal
1068
- */
1069
- onAbort(listener) {
1070
- this.#abortController.signal.addEventListener(SignalEvents.ABORT, listener);
1071
- return this;
1072
- }
1073
- /**
1074
- * Adds an event listener for the 'timeout' event.
1075
- *
1076
- * @param {EventListener} listener The listener to add
1077
- * @returns {AbortSignal} The AbortSignal
1078
- */
1079
- onTimeout(listener) {
1080
- this.#abortController.signal.addEventListener(SignalEvents.TIMEOUT, listener);
1081
- return this;
1082
- }
1083
- /**
1084
- * Aborts the signal. This is so naughty. ¯\_(ツ)_/¯
1085
- *
1086
- * @param {Event} event The event to abort with
1087
- * @returns {void}
1088
- */
1089
- abort(event) {
1090
- this.#abort(event);
1091
- }
1092
- /**
1093
- * Aborts the signal.
1094
- *
1095
- * @private
1096
- * @param {Event} event The event to abort with
1097
- * @param {boolean} [dispatchEvent = false] Whether to dispatch the event or not
1098
- * @returns {void}
1099
- * @fires SignalEvents.ABORT When the signal is aborted
1100
- * @fires SignalEvents.TIMEOUT When the signal times out
1101
- */
1102
- #abort(event = _abortEvent, dispatchEvent = false) {
1103
- clearTimeout(this.#timeoutId);
1104
- this.#abortController.abort(event.detail?.cause);
1105
- if (dispatchEvent) {
1106
- this.#abortController.signal.dispatchEvent(event);
1107
- }
1108
- }
1109
- };
1110
-
1111
- // src/http-error.js
1112
- var HttpError = class extends Error {
1113
- /** @type {ResponseBody} */
1114
- #entity;
1115
- /** @type {ResponseStatus} */
1116
- #responseStatus;
1117
- /**
1118
- * @param {string} [message] The error message.
1119
- * @param {HttpErrorOptions} [httpErrorOptions] The http error options.
1120
- * @param {any} [httpErrorOptions.cause] The cause of the error.
1121
- * @param {ResponseStatus} [httpErrorOptions.status] The response status.
1122
- * @param {ResponseBody} [httpErrorOptions.entity] The error entity from the server, if any.
1123
- */
1124
- constructor(message, { cause, status, entity }) {
1125
- super(message, { cause });
1126
- this.#entity = entity;
1127
- this.#responseStatus = status;
1128
- }
1129
- /**
1130
- * It returns the value of the private variable #entity.
1131
- *
1132
- * @returns {ResponseBody} The entity property of the class.
1133
- */
1134
- get entity() {
1135
- return this.#entity;
1136
- }
1137
- /**
1138
- * It returns the status code of the {@link Response}.
1139
- *
1140
- * @returns {number} The status code of the {@link Response}.
1141
- */
1142
- get statusCode() {
1143
- return this.#responseStatus?.code;
1144
- }
1145
- /**
1146
- * It returns the status text of the {@link Response}.
1147
- *
1148
- * @returns {string} The status code and status text of the {@link Response}.
1149
- */
1150
- get statusText() {
1151
- return this.#responseStatus?.text;
1152
- }
1153
- get name() {
1154
- return "HttpError";
1155
- }
1156
- /**
1157
- * A String value that is used in the creation of the default string
1158
- * description of an object. Called by the built-in method {@link Object.prototype.toString}.
1159
- *
1160
- * @returns {string} The default string description of this object.
1161
- */
1162
- get [Symbol.toStringTag]() {
1163
- return "HttpError";
1164
- }
1165
- };
1166
-
1167
- // src/http-request-headers.js
1168
- var HttpRequestHeader = {
1169
- /**
1170
- * Content-Types that are acceptable for the response. See Content negotiation. Permanent.
1171
- *
1172
- * @example
1173
- * <code>Accept: text/plain</code>
1174
- */
1175
- ACCEPT: "accept",
1176
- /**
1177
- * Character sets that are acceptable. Permanent.
1178
- *
1179
- * @example
1180
- * <code>Accept-Charset: utf-8</code>
1181
- */
1182
- ACCEPT_CHARSET: "accept-charset",
1183
- /**
1184
- * List of acceptable encodings. See HTTP compression. Permanent.
1185
- *
1186
- * @example
1187
- * <code>Accept-Encoding: gzip, deflate</code>
1188
- */
1189
- ACCEPT_ENCODING: "accept-encoding",
1190
- /**
1191
- * List of acceptable human languages for response. See Content negotiation. Permanent.
1192
- *
1193
- * @example
1194
- * <code>Accept-Language: en-US</code>
1195
- */
1196
- ACCEPT_LANGUAGE: "accept-language",
1197
- /**
1198
- * Authentication credentials for HTTP authentication. Permanent.
1199
- *
1200
- * @example
1201
- * <code>Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==</code>
1202
- */
1203
- AUTHORIZATION: "authorization",
1204
- /**
1205
- * Used to specify directives that must be obeyed by all caching mechanisms along the request-response chain.
1206
- * Permanent.
1207
- *
1208
- * @example
1209
- * <code>Cache-Control: no-cache</code>
1210
- */
1211
- CACHE_CONTROL: "cache-control",
1212
- /**
1213
- * Control options for the current connection and list of hop-by-hop request fields. Permanent.
1214
- *
1215
- * @example
1216
- * <code>Connection: keep-alive</code>
1217
- * <code>Connection: Upgrade</code>
1218
- */
1219
- CONNECTION: "connection",
1220
- /**
1221
- * An HTTP cookie previously sent by the server with Set-Cookie (below). Permanent: standard.
1222
- *
1223
- * @example
1224
- * <code>Cookie: $Version=1, Skin=new,</code>
1225
- */
1226
- COOKIE: "cookie",
1227
- /**
1228
- * The length of the request body in octets (8-bit bytes). Permanent.
1229
- *
1230
- * @example
1231
- * <code>Content-Length: 348</code>
1232
- */
1233
- CONTENT_LENGTH: "content-length",
1234
- /**
1235
- * A Base64-encoded binary MD5 sum of the content of the request body. Obsolete.
1236
- *
1237
- * @example
1238
- * <code>Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==</code>
1239
- */
1240
- CONTENT_MD5: "content-md5",
1241
- /**
1242
- * The MIME type of the body of the request (used with POST and PUT requests). Permanent.
1243
- * <code>Content-Type: application/x-www-form-urlencoded</code>
1244
- */
1245
- CONTENT_TYPE: "content-type",
1246
- /**
1247
- * The date and time that the message was sent (in "HTTP-date" format as defined by RFC 7231 Date/Time Formats).
1248
- * Permanent.
1249
- *
1250
- * @example
1251
- * <code>Date: Tue, 15 Nov 1994 08:12:31 GMT</code>
1252
- */
1253
- DATE: "date",
1254
- /**
1255
- * Indicates that particular server behaviors are required by the client. Permanent.
1256
- *
1257
- * @example
1258
- * <code>Expect: 100-continue</code>
1259
- */
1260
- EXPECT: "expect",
1261
- /**
1262
- * The email address of the user making the request. Permanent.
1263
- *
1264
- * @example
1265
- * <code>From: user@example.com</code>
1266
- */
1267
- FROM: "from",
1268
- /**
1269
- * The domain name of the server (for virtual hosting), and the TCP port number on which the server is listening. The
1270
- * port number may be omitted if the port is the standard port for the service requested. Permanent. Mandatory since
1271
- * HTTP/1.1.
1272
- *
1273
- * @example
1274
- * <code>Host: en.wikipedia.org:80</code>
1275
- * <code>Host: en.wikipedia.org</code>
1276
- */
1277
- HOST: "host",
1278
- /**
1279
- * Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for
1280
- * methods like PUT to only update a resource if it has not been modified since the user last updated it. Permanent.
1281
- *
1282
- * @example
1283
- * <code>If-Match: "737060cd8c284d8af7ad3082f209582d"</code>
1284
- */
1285
- IF_MATCH: "if-match",
1286
- /**
1287
- * Allows a 304 Not Modified to be returned if content is unchanged. Permanent.
1288
- *
1289
- * @example
1290
- * <code>If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT</code>
1291
- */
1292
- IF_MODIFIED_SINCE: "if-modified-since",
1293
- /**
1294
- * Allows a 304 Not Modified to be returned if content is unchanged, see HTTP ETag. Permanent.
1295
- *
1296
- * @example
1297
- * <code>If-None-Match: "737060cd8c284d8af7ad3082f209582d"</code>
1298
- */
1299
- IF_NONE_MATCH: "if-none-match",
1300
- /**
1301
- * If the entity is unchanged, send me the part(s) that I am missing, otherwise, send me the entire new entity.
1302
- * Permanent.
1303
- *
1304
- * @example
1305
- * <code>If-Range: "737060cd8c284d8af7ad3082f209582d"</code>
1306
- */
1307
- IF_RANGE: "if-range",
1308
- /**
1309
- * Only send the response if the entity has not been modified since a specific time. Permanent.
1310
- *
1311
- * @example
1312
- * <code>If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT</code>
1313
- */
1314
- IF_UNMODIFIED_SINCE: "if-unmodified-since",
1315
- /**
1316
- * Limit the number of times the message can be forwarded through proxies or gateways. Permanent.
1317
- *
1318
- * @example
1319
- * <code>Max-Forwards: 10</code>
1320
- */
1321
- MAX_FORWARDS: "max-forwards",
1322
- /**
1323
- * Initiates a request for cross-origin resource sharing (asks server for an 'Access-Control-Allow-Origin' response
1324
- * field). Permanent: standard.
1325
- *
1326
- * @example
1327
- * <code>Origin: http://www.example-social-network.com</code>
1328
- */
1329
- ORIGIN: "origin",
1330
- /**
1331
- * Implementation-specific fields that may have various effects anywhere along the request-response chain. Permanent.
1332
- *
1333
- * @example
1334
- * <code>Pragma: no-cache</code>
1335
- */
1336
- PRAGMA: "pragma",
1337
- /**
1338
- * Authorization credentials for connecting to a proxy. Permanent.
1339
- *
1340
- * @example
1341
- * <code>Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==</code>
1342
- */
1343
- PROXY_AUTHORIZATION: "proxy-authorization",
1344
- /**
1345
- * Request only part of an entity. Bytes are numbered from 0. See Byte serving. Permanent.
1346
- *
1347
- * @example
1348
- * <code>Range: bytes=500-999</code>
1349
- */
1350
- RANGE: "range",
1351
- /**
1352
- * This is the address of the previous web page from which a link to the currently requested page was followed. (The
1353
- * word "referrer" has been misspelled in the RFC as well as in most implementations to the point that it has become
1354
- * standard usage and is considered correct terminology). Permanent.
1355
- *
1356
- * @example
1357
- * <code>Referer: http://en.wikipedia.org/wiki/Main_Page</code>
1358
- */
1359
- REFERER: "referer",
1360
- /**
1361
- * The transfer encodings the user agent is willing to accept: the same values as for the response header field
1362
- * Transfer-Encoding can be used, plus the "trailers" value (related to the "chunked" transfer method) to notify the
1363
- * server it expects to receive additional fields in the trailer after the last, zero-sized, chunk. Permanent.
1364
- *
1365
- * @example
1366
- * <code>TE: trailers, deflate</code>
1367
- */
1368
- TE: "te",
1369
- /**
1370
- * The user agent string of the user agent. Permanent.
1371
- *
1372
- * @example
1373
- * <code>User-Agent: Mozilla/5.0 (X11, Linux x86_64, rv:12.0) Gecko/20100101 Firefox/21.0</code>
1374
- */
1375
- USER_AGENT: "user-agent",
1376
- /**
1377
- * Ask the server to upgrade to another protocol. Permanent.
1378
- *
1379
- * @example
1380
- * <code>Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11</code>
1381
- */
1382
- UPGRADE: "upgrade",
1383
- /**
1384
- * Informs the server of proxies through which the request was sent. Permanent.
1385
- *
1386
- * @example
1387
- * <code>Via: 1.0 fred, 1.1 example.com (Apache/1.1)</code>
1388
- */
1389
- VIA: "via",
1390
- /**
1391
- * A general warning about possible problems with the entity body. Permanent.
1392
- *
1393
- * @example
1394
- * <code>Warning: 199 Miscellaneous warning</code>
1395
- */
1396
- WARNING: "warning",
1397
- /**
1398
- * mainly used to identify Ajax requests. Most JavaScript frameworks send this field with value of XMLHttpRequest.
1399
- *
1400
- * @example
1401
- * <code>X-Requested-With: XMLHttpRequest</code>
1402
- */
1403
- X_REQUESTED_WITH: "x-requested-with",
1404
- /**
1405
- * Requests a web application to disable their tracking of a user. This is Mozilla's version of the X-Do-Not-Track
1406
- * header field (since Firefox 4.0 Beta 11). Safari and IE9 also have support for this field. On March 7, 2011, a
1407
- * draft proposal was submitted to IETF. The W3C Tracking Protection Working Group is producing a specification.
1408
- *
1409
- * @example
1410
- * <code>DNT: 1 (Do Not Track Enabled)</code>
1411
- * <code>DNT: 0 (Do Not Track Disabled)</code>
1412
- */
1413
- DNT: "dnt",
1414
- /**
1415
- * A de facto standard for identifying the originating IP address of a client connecting to a web server through an
1416
- * HTTP proxy or load balancer.
1417
- *
1418
- * @example
1419
- * <code>X-Forwarded-For: client1, proxy1, proxy2</code>
1420
- * <code>X-Forwarded-For: 129.78.138.66, 129.78.64.103</code>
1421
- */
1422
- X_FORWARDED_FOR: "x-forwarded-for",
1423
- /**
1424
- * A de facto standard for identifying the original host requested by the client in the Host HTTP request header, since
1425
- * the host name and/or port of the reverse proxy (load balancer) may differ from the origin server handling the
1426
- * request.
1427
- *
1428
- * @example
1429
- * <code>X-Forwarded-Host: en.wikipedia.org:80</code>
1430
- * <code>X-Forwarded-Host: en.wikipedia.org</code>
1431
- */
1432
- X_FORWARDED_HOST: "x-forwarded-host",
1433
- /**
1434
- * A de facto standard for identifying the originating protocol of an HTTP request, since a reverse proxy (load
1435
- * balancer) may communicate with a web server using HTTP even if the request to the reverse proxy is HTTPS. An
1436
- * alternative form of the header (X-ProxyUser-Ip) is used by Google clients talking to Google servers.
1437
- *
1438
- * @example
1439
- * <code>X-Forwarded-Proto: https</code>
1440
- */
1441
- X_FORWARDED_PROTO: "x-forwarded-proto",
1442
- /**
1443
- * Non-standard header field used by Microsoft applications and load-balancers.
1444
- *
1445
- * @example
1446
- * <code>Front-End-Https: on</code>
1447
- */
1448
- FRONT_END_HTTPS: "front-end-https",
1449
- /**
1450
- * Requests a web application override the method specified in the request (typically POST) with the method given in
1451
- * the header field (typically PUT or DELETE). Can be used when a user agent or firewall prevents PUT or DELETE methods
1452
- * from being sent directly (note that this either a bug in the software component, which ought to be fixed, or an
1453
- * intentional configuration, in which case bypassing it may be the wrong thing to do).
1454
- *
1455
- * @example
1456
- * <code>X-HTTP-Method-Override: DELETE</code>
1457
- */
1458
- X_HTTP_METHOD_OVERRIDE: "x-http-method-override",
1459
- /**
1460
- * Allows easier parsing of the MakeModel/Firmware that is usually found in the User-Agent String of AT&T Devices.
1461
- *
1462
- * @example
1463
- * <code>X-Att-Deviceid: GT-P7320/P7320XXLPG</code>
1464
- */
1465
- X_ATT_DEVICE_ID: "x-att-deviceid",
1466
- /**
1467
- * Links to an XML file on the Internet with a full description and details about the device currently connecting. In the example to the right is an XML file for an AT&T Samsung Galaxy S2.
1468
- * x-wap-profile: http://wap.samsungmobile.com/uaprof/SGH-I777.xml
1469
- */
1470
- X_WAP_PROFILE: "x-wap-profile"
1471
- };
1472
- var http_request_headers_default = HttpRequestHeader;
1473
-
1474
- // src/http-response-headers.js
1475
- var HttpResponseHeader = {
1476
- /**
1477
- * Implemented as a misunderstanding of the HTTP specifications. Common because of mistakes in implementations of early HTTP versions. Has exactly the same functionality as standard Connection field.
1478
- *
1479
- * @example
1480
- * proxy-connection: keep-alive
1481
- */
1482
- PROXY_CONNECTION: "proxy-connection",
1483
- /**
1484
- * Server-side deep packet insertion of a unique ID identifying customers of Verizon Wireless, also known as "perma-cookie" or "supercookie"
1485
- *
1486
- * @example
1487
- * x-uidh: ...
1488
- */
1489
- X_UIDH: "x-uidh",
1490
- /**
1491
- * Used to prevent cross-site request forgery. Alternative header names are: X-CSRFToken and X-XSRF-TOKEN
1492
- *
1493
- * @example
1494
- * x-csrf-token: i8XNjC4b8KVok4uw5RftR38Wgp2BFwql
1495
- */
1496
- X_CSRF_TOKEN: "x-csrf-token",
1497
- /**
1498
- * Specifying which web sites can participate in cross-origin resource sharing
1499
- *
1500
- * @example
1501
- * access-control-allow-origin: *
1502
- * Provisional
1503
- */
1504
- ACCESS_CONTROL_ALLOW_ORIGIN: "access-control-allow-origin",
1505
- /**
1506
- * Specifies which patch document formats this server supports
1507
- *
1508
- * @example
1509
- * accept-patch: text/example,charset=utf-8
1510
- * Permanent
1511
- */
1512
- ACCEPT_PATCH: "accept-patch",
1513
- /**
1514
- * What partial content range types this server supports via byte serving
1515
- *
1516
- * @example
1517
- * accept-ranges: bytes
1518
- * Permanent
1519
- */
1520
- ACCEPT_RANGES: "accept-ranges",
1521
- /**
1522
- * The age the object has been in a proxy cache in seconds
1523
- *
1524
- * @example
1525
- * age: 12
1526
- * Permanent
1527
- */
1528
- AGE: "age",
1529
- /**
1530
- * Valid actions for a specified resource. To be used for a 405 Method not allowed
1531
- *
1532
- * @example
1533
- * allow: GET, HEAD
1534
- * Permanent
1535
- */
1536
- ALLOW: "allow",
1537
- /**
1538
- * Tells all caching mechanisms from server to client whether they may cache this object. It is measured in seconds
1539
- *
1540
- * @example
1541
- * cache-control: max-age=3600
1542
- * Permanent
1543
- */
1544
- CACHE_CONTROL: "cache-control",
1545
- /**
1546
- * Control options for the current connection and list of hop-by-hop response fields
1547
- *
1548
- * @example
1549
- * connection: close
1550
- * Permanent
1551
- */
1552
- CONNECTION: "connection",
1553
- /**
1554
- * An opportunity to raise a "File Download" dialogue box for a known MIME type with binary format or suggest a filename for dynamic content. Quotes are necessary with special characters.
1555
- *
1556
- * @example
1557
- * content-disposition: attachment, filename="fname.ext"
1558
- * Permanent
1559
- */
1560
- CONTENT_DISPOSITION: "content-disposition",
1561
- /**
1562
- * The type of encoding used on the data. See HTTP compression.
1563
- *
1564
- * @example
1565
- * content-encoding: gzip
1566
- * Permanent
1567
- */
1568
- CONTENT_ENCODING: "content-encoding",
1569
- /**
1570
- * The natural language or languages of the intended audience for the enclosed content
1571
- *
1572
- * @example
1573
- * content-language: da
1574
- * Permanent
1575
- */
1576
- CONTENT_LANGUAGE: "content-language",
1577
- /**
1578
- * The length of the response body in octets (8-bit bytes)
1579
- *
1580
- * @example
1581
- * content-length: 348
1582
- * Permanent
1583
- */
1584
- CONTENT_LENGTH: "content-length",
1585
- /**
1586
- * An alternate location for the returned data
1587
- *
1588
- * @example
1589
- * content-location: /index.htm
1590
- * Permanent
1591
- */
1592
- CONTENT_LOCATION: "content-location",
1593
- /**
1594
- * Where in a full body message this partial message belongs
1595
- *
1596
- * @example
1597
- * content-range: bytes 21010-47021/47022
1598
- * Permanent
1599
- */
1600
- CONTENT_RANGE: "content-range",
1601
- /**
1602
- * The MIME type of this content
1603
- *
1604
- * @example
1605
- * content-type: text/html, charset=utf-8
1606
- * Permanent
1607
- */
1608
- CONTENT_TYPE: "content-type",
1609
- /**
1610
- * The date and time that the message was sent (in "HTTP-date" format as defined by RFC 7231)
1611
- *
1612
- * @example
1613
- * date: Tue, 15 Nov 1994 08:12:31 GMT
1614
- * Permanent
1615
- */
1616
- DATE: "date",
1617
- /**
1618
- * An identifier for a specific version of a resource, often a message digest
1619
- *
1620
- * @example
1621
- * etag: "737060cd8c284d8af7ad3082f209582d"
1622
- * Permanent
1623
- */
1624
- ETAG: "etag",
1625
- /**
1626
- * Gives the date/time after which the response is considered stale (in "HTTP-date" format as defined by RFC 7231)
1627
- *
1628
- * @example
1629
- * expires: Thu, 01 Dec 1994 16:00:00 GMT
1630
- * Permanent
1631
- */
1632
- EXPIRES: "expires",
1633
- /**
1634
- * The last modified date for the requested object (in "HTTP-date" format as defined by RFC 7231)
1635
- *
1636
- * @example
1637
- * last-modified: Tue, 15 Nov 1994 12:45:26 GMT
1638
- * Permanent
1639
- */
1640
- LAST_MODIFIED: "last-modified",
1641
- /**
1642
- * Used to express a typed relationship with another resource, where the relation type is defined by RFC 5988
1643
- *
1644
- * @example
1645
- * link: </feed>, rel="alternate"
1646
- * Permanent
1647
- */
1648
- LINK: "link",
1649
- /**
1650
- * Used in redirection, or when a new resource has been created.
1651
- *
1652
- * @example
1653
- * location: http://www.w3.org/pub/WWW/People.html
1654
- * Permanent
1655
- */
1656
- LOCATION: "location",
1657
- /**
1658
- * This field is supposed to set P3P policy, in the form of P3P:CP="your_compact_policy". However, P3P did not take off, most browsers have never fully
1659
- * implemented it, a lot of websites set this field with fake policy text, that was enough to fool browsers the existence of P3P policy and grant permissions for third party cookies.
1660
- *
1661
- * @example
1662
- * p3p: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
1663
- * Permanent
1664
- */
1665
- P3P: "p3p",
1666
- /**
1667
- * Implementation-specific fields that may have various effects anywhere along the request-response chain.
1668
- *
1669
- * @example
1670
- * pragma: no-cache
1671
- * Permanent
1672
- */
1673
- PRAGMA: "pragma",
1674
- /**
1675
- * Request authentication to access the proxy.
1676
- *
1677
- * @example
1678
- * proxy-authenticate: Basic
1679
- * Permanent
1680
- */
1681
- PROXY_AUTHENTICATION: "proxy-authenticate",
1682
- /**
1683
- * HTTP Public Key Pinning, announces hash of website's authentic TLS certificate
1684
- *
1685
- * @example
1686
- * public-key-pins: max-age=2592000, pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=",
1687
- * Permanent
1688
- */
1689
- PUBLIC_KEY_PINS: "public-key-pins",
1690
- /**
1691
- * If an entity is temporarily unavailable, this instructs the client to try again later. Value could be a specified period of time (in seconds) or a HTTP-date.
1692
- *
1693
- * @example
1694
- * retry-after: 120
1695
- * retry-after: Fri, 07 Nov 2014 23:59:59 GMT
1696
- * Permanent
1697
- */
1698
- RETRY_AFTER: "retry-after",
1699
- /**
1700
- * A name for the server
1701
- *
1702
- * @example
1703
- * server: Apache/2.4.1 (Unix)
1704
- * Permanent
1705
- */
1706
- SERVER: "server",
1707
- /**
1708
- * An HTTP cookie
1709
- *
1710
- * @example
1711
- * set-cookie: UserID=JohnDoe, Max-Age=3600, Version=1
1712
- * Permanent
1713
- */
1714
- SET_COOKIE: "set-cookie",
1715
- /**
1716
- * CGI header field specifying the status of the HTTP response. Normal HTTP responses use a separate "Status-Line" instead, defined by RFC 7230.
1717
- *
1718
- * @example
1719
- * status: 200 OK
1720
- */
1721
- STATUS: "status",
1722
- /**
1723
- * A HSTS Policy informing the HTTP client how long to cache the HTTPS only policy and whether this applies to subdomains.
1724
- *
1725
- * @example
1726
- * strict-transport-security: max-age=16070400, includeSubDomains
1727
- * Permanent
1728
- */
1729
- STRICT_TRANSPORT_SECURITY: "strict-transport-security",
1730
- /**
1731
- * The Trailer general field value indicates that the given set of header fields is present in the trailer of a message encoded with chunked transfer coding.
1732
- *
1733
- * @example
1734
- * trailer: Max-Forwards
1735
- * Permanent
1736
- */
1737
- TRAILER: "trailer",
1738
- /**
1739
- * The form of encoding used to safely transfer the entity to the user. Currently defined methods are: chunked, compress, deflate, gzip, identity.
1740
- *
1741
- * @example
1742
- * transfer-encoding: chunked
1743
- * Permanent
1744
- */
1745
- TRANSFER_ENCODING: "transfer-encoding",
1746
- /**
1747
- * Ask the client to upgrade to another protocol.
1748
- *
1749
- * @example
1750
- * upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
1751
- * Permanent
1752
- */
1753
- UPGRADE: "upgrade",
1754
- /**
1755
- * Tells downstream proxies how to match future request headers to decide whether the cached response can be used rather than requesting a fresh one from the origin server.
1756
- *
1757
- * @example
1758
- * vary: *
1759
- * Permanent
1760
- */
1761
- VARY: "vary",
1762
- /**
1763
- * Informs the client of proxies through which the response was sent.
1764
- *
1765
- * @example
1766
- * via: 1.0 fred, 1.1 example.com (Apache/1.1)
1767
- * Permanent
1768
- */
1769
- VIA: "via",
1770
- /**
1771
- * A general warning about possible problems with the entity body.
1772
- *
1773
- * @example
1774
- * warning: 199 Miscellaneous warning
1775
- * Permanent
1776
- */
1777
- WARNING: "warning",
1778
- /**
1779
- * Indicates the authentication scheme that should be used to access the requested entity.
1780
- *
1781
- * @example
1782
- * www-authenticate: Basic
1783
- * Permanent
1784
- */
1785
- WWW_AUTHENTICATE: "www-authenticate",
1786
- /**
1787
- * Cross-site scripting (XSS) filter
1788
- *
1789
- * @example
1790
- * x-xss-protection: 1, mode=block
1791
- */
1792
- X_XSS_PROTECTION: "x-xss-protection",
1793
- /**
1794
- * The HTTP Content-Security-Policy response header allows web site administrators to control resources the user agent is allowed
1795
- * to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints.
1796
- * This helps guard against cross-site scripting attacks (Cross-site_scripting).
1797
- *
1798
- * @example
1799
- * content-security-policy: default-src
1800
- */
1801
- CONTENT_SECURITY_POLICY: "content-security-policy",
1802
- /**
1803
- * The only defined value, "nosniff", prevents Internet Explorer from MIME-sniffing a response away from the declared content-type. This also applies to Google Chrome, when downloading extensions.
1804
- *
1805
- * @example
1806
- * x-content-type-options: nosniff
1807
- */
1808
- X_CONTENT_TYPE_OPTIONS: "x-content-type-options",
1809
- /**
1810
- * specifies the technology (e.g. ASP.NET, PHP, JBoss) supporting the web application (version details are often in X-Runtime, X-Version, or X-AspNet-Version)
1811
- *
1812
- * @example
1813
- * x-powered-by: PHP/5.4.0
1814
- */
1815
- X_POWERED_BY: "x-powered-by"
1816
- };
1817
- var http_response_headers_default = HttpResponseHeader;
1818
-
1819
- // src/parameter-map.js
1820
- var ParameterMap = class _ParameterMap extends Map {
1821
- /**
1822
- * @param {Iterable<[string, *]>|Object} parameters The initial parameters to set.
1823
- * @returns {ParameterMap<string, *>} The ParameterMap with the updated key and value.
1824
- */
1825
- constructor(parameters = {}) {
1826
- super();
1827
- for (const [key, value] of _ParameterMap.#entries(parameters)) {
1828
- this.append(key, value);
1829
- }
1830
- }
1831
- /**
1832
- * Adds a new element with a specified key and value to the ParameterMap.
1833
- * If an element with the same key already exists, the value will be replaced in the underlying {@link Set}.
1834
- *
1835
- * @override
1836
- * @param {string} key The key to set.
1837
- * @param {*} value The value to add to the ParameterMap
1838
- * @returns {ParameterMap<string, *>} The ParameterMap with the updated key and value.
1839
- */
1840
- set(key, value) {
1841
- const array = super.get(key);
1842
- if (array?.length > 0) {
1843
- array.length = 0;
1844
- array[0] = value;
1845
- } else {
1846
- super.set(key, [value]);
1847
- }
1848
- return this;
1849
- }
1850
- /**
1851
- * Adds all key-value pairs from an iterable or object to the ParameterMap.
1852
- * If a key already exists, the value will be replaced in the underlying {@link Array}.
1853
- *
1854
- * @param {Iterable<[string, *]>|Object} parameters The parameters to set.
1855
- * @returns {ParameterMap<string, *>} The ParameterMap with the updated key and value.
1856
- */
1857
- setAll(parameters) {
1858
- for (const [key, value] of _ParameterMap.#entries(parameters)) {
1859
- this.set(key, value);
1860
- }
1861
- return this;
1862
- }
1863
- /**
1864
- * Returns the value associated to the key, or undefined if there is none.
1865
- * If the key has multiple values, the first value will be returned.
1866
- * If the key has no values, undefined will be returned.
1867
- *
1868
- * @override
1869
- * @param {string} key The key to get.
1870
- * @returns {*} The value associated to the key, or undefined if there is none.
1871
- */
1872
- get(key) {
1873
- return super.get(key)?.[0];
1874
- }
1875
- /**
1876
- * Returns an array of all values associated to the key, or undefined if there are none.
1877
- *
1878
- * @param {string} key The key to get.
1879
- * @returns {Array<*>} An array of all values associated to the key, or undefined if there are none.
1880
- */
1881
- getAll(key) {
1882
- return super.get(key);
1883
- }
1884
- /**
1885
- * Appends a new value to an existing key inside a ParameterMap, or adds the new key if it does not exist.
1886
- *
1887
- * @param {string} key The key to append.
1888
- * @param {*} value The value to append.
1889
- * @returns {ParameterMap<string, *>} The ParameterMap with the updated key and value to allow chaining.
1890
- */
1891
- append(key, value) {
1892
- const array = super.get(key);
1893
- if (array?.length > 0) {
1894
- array.push(value);
1895
- } else {
1896
- super.set(key, [value]);
1897
- }
1898
- return this;
1899
- }
1900
- /**
1901
- * Appends all key-value pairs from an iterable or object to the ParameterMap.
1902
- * If a key already exists, the value will be appended to the underlying {@link Array}.
1903
- * If a key does not exist, the key and value will be added to the ParameterMap.
1904
- *
1905
- * @param {Iterable<[string, *]>|Object} parameters The parameters to append.
1906
- * @returns {ParameterMap<string, *>} The ParameterMap with the updated key and value.
1907
- */
1908
- appendAll(parameters) {
1909
- for (const [key, value] of _ParameterMap.#entries(parameters)) {
1910
- this.append(key, value);
1911
- }
1912
- return this;
1913
- }
1914
- /**
1915
- * Checks if a specific key has a specific value.
1916
- *
1917
- * @param {*} value The value to check.
1918
- * @returns {boolean} True if the key has the value, false otherwise.
1919
- */
1920
- hasValue(value) {
1921
- for (const array of super.values()) {
1922
- if (array.includes(value)) {
1923
- return true;
1924
- }
1925
- }
1926
- return false;
1927
- }
1928
- /**
1929
- * Removes a specific value from a specific key.
1930
- *
1931
- * @param {*} value The value to remove.
1932
- * @returns {boolean} True if the value was removed, false otherwise.
1933
- */
1934
- deleteValue(value) {
1935
- for (const array of this.values()) {
1936
- if (array.includes(value)) {
1937
- return array.splice(array.indexOf(value), 1).length > 0;
1938
- }
1939
- }
1940
- return false;
1941
- }
1942
- /**
1943
- * Determines whether the ParameterMap contains anything.
1944
- *
1945
- * @returns {boolean} True if the ParameterMap size is greater than 0, false otherwise.
1946
- */
1947
- isEmpty() {
1948
- return this.size === 0;
1949
- }
1950
- /**
1951
- * Returns an Object that can be serialized to JSON.
1952
- * If a key has only one value, the value will be a single value.
1953
- * If a key has multiple values, the value will be an array of values.
1954
- * If a key has no values, the value will be undefined.
1955
- *
1956
- * @override
1957
- * @returns {Object} The Object to be serialized to JSON.
1958
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior}
1959
- */
1960
- toJSON() {
1961
- const obj = /* @__PURE__ */ Object.create(null);
1962
- for (const [key, values] of super.entries()) {
1963
- obj[key] = values.length === 1 ? values[0] : values;
1964
- }
1965
- return obj;
1966
- }
1967
- /**
1968
- * Returns an iterator that yields all key-value pairs in the map as arrays in their insertion order.
1969
- *
1970
- * @override
1971
- * @yields {[string, *]} An iterator for the key-value pairs in the map.
1972
- */
1973
- *entries() {
1974
- for (const [key, array] of super.entries()) {
1975
- for (const value of array) {
1976
- yield [key, value];
1977
- }
1978
- }
1979
- }
1980
- /**
1981
- * Returns an iterator that yields all key-value pairs in the map as arrays in their insertion order.
1982
- *
1983
- * @override
1984
- * @yields {[string, *]} An iterator for the key-value pairs in the map.
1985
- */
1986
- *[Symbol.iterator]() {
1987
- yield* this.entries();
1988
- }
1989
- /**
1990
- * Returns an iterable of key, value pairs for every entry in the parameters object.
1991
- *
1992
- * @private
1993
- * @static
1994
- * @param {Iterable<[string, *]>|Object} parameters The parameters to set.
1995
- * @returns {Iterable<[string, *]>} An iterable of key, value pairs for every entry in the parameters object.
1996
- */
1997
- static #entries(parameters) {
1998
- return parameters[Symbol.iterator] ? parameters : Object.entries(parameters);
1999
- }
2000
- /**
2001
- * A String value that is used in the creation of the default string description of an object.
2002
- * Called by the built-in method {@link Object.prototype.toString}.
2003
- *
2004
- * @override
2005
- * @returns {string} The default string description of this object.
2006
- */
2007
- get [Symbol.toStringTag]() {
2008
- return "ParameterMap";
2009
- }
2010
- };
2011
-
2012
- // src/transportr.js
2013
- var _handleText = async (response) => await response.text();
2014
- var _handleScript = async (response) => {
2015
- const objectURL = URL.createObjectURL(await response.blob());
2016
- document.head.removeChild(document.head.appendChild(Object.assign(document.createElement("script"), { src: objectURL, type: http_media_type_default.JAVA_SCRIPT, async: true })));
2017
- URL.revokeObjectURL(objectURL);
2018
- return Promise.resolve();
2019
- };
2020
- var _handleCss = async (response) => {
2021
- const objectURL = URL.createObjectURL(await response.blob());
2022
- document.head.appendChild(Object.assign(document.createElement("link"), { href: objectURL, type: http_media_type_default.CSS, rel: "stylesheet" }));
2023
- URL.revokeObjectURL(objectURL);
2024
- return Promise.resolve();
2025
- };
2026
- var _handleJson = async (response) => await response.json();
2027
- var _handleBlob = async (response) => await response.blob();
2028
- var _handleImage = async (response) => URL.createObjectURL(await response.blob());
2029
- var _handleBuffer = async (response) => await response.arrayBuffer();
2030
- var _handleReadableStream = async (response) => response.body;
2031
- var _handleXml = async (response) => new DOMParser().parseFromString(await response.text(), http_media_type_default.XML);
2032
- var _handleHtml = async (response) => new DOMParser().parseFromString(await response.text(), http_media_type_default.HTML);
2033
- var _handleHtmlFragment = async (response) => document.createRange().createContextualFragment(await response.text());
2034
- var Transportr = class _Transportr {
2035
- /** @type {URL} */
2036
- #baseUrl;
2037
- /** @type {RequestOptions} */
2038
- #options;
2039
- /** @type {Subscribr} */
2040
- #subscribr;
2041
- /** @type {Subscribr} */
2042
- static #globalSubscribr = new Subscribr();
2043
- /** @type {Set<AbortSignal>} */
2044
- static #activeRequests = /* @__PURE__ */ new Set();
2045
- /** @type {Map<ResponseHandler<ResponseBody>, string>} */
2046
- static #contentTypeHandlers = /* @__PURE__ */ new Map([
2047
- [_handleImage, mediaTypes.get(http_media_type_default.PNG).type],
2048
- [_handleText, mediaTypes.get(http_media_type_default.TEXT).type],
2049
- [_handleJson, mediaTypes.get(http_media_type_default.JSON).subtype],
2050
- [_handleHtml, mediaTypes.get(http_media_type_default.HTML).subtype],
2051
- [_handleScript, mediaTypes.get(http_media_type_default.JAVA_SCRIPT).subtype],
2052
- [_handleCss, mediaTypes.get(http_media_type_default.CSS).subtype],
2053
- [_handleXml, mediaTypes.get(http_media_type_default.XML).subtype],
2054
- [_handleReadableStream, mediaTypes.get(http_media_type_default.BIN).subtype]
2055
- ]);
2056
- /**
2057
- * Create a new Transportr instance with the provided location or origin and context path.
2058
- *
2059
- * @param {URL|string|RequestOptions} [url=location.origin] The URL for {@link fetch} requests.
2060
- * @param {RequestOptions} [options={}] The default {@link RequestOptions} for this instance.
2061
- */
2062
- constructor(url = globalThis.location.origin, options = {}) {
2063
- if (object_type_default(url) == Object) {
2064
- [url, options] = [globalThis.location.origin, url];
2065
- }
2066
- this.#baseUrl = _Transportr.#getBaseUrl(url);
2067
- this.#options = _Transportr.#createOptions(options, _Transportr.#defaultRequestOptions);
2068
- this.#subscribr = new Subscribr();
2069
- }
2070
- /**
2071
- * @static
2072
- * @constant {Object<string, HttpRequestMethod>}
2073
- */
2074
- static Method = Object.freeze(http_request_methods_default);
2075
- /**
2076
- * @static
2077
- * @constant {Object<string, HttpMediaType>}
2078
- */
2079
- static MediaType = Object.freeze(http_media_type_default);
2080
- /**
2081
- * @static
2082
- * @see {@link HttpRequestHeader}
2083
- * @constant {Object<string, HttpRequestHeader>}
2084
- */
2085
- static RequestHeader = Object.freeze(http_request_headers_default);
2086
- /**
2087
- * @static
2088
- * @constant {Object<string, HttpResponseHeader>}
2089
- */
2090
- static ResponseHeader = Object.freeze(http_response_headers_default);
2091
- /**
2092
- * @static
2093
- * @constant {Object<string, RequestCache>}
2094
- */
2095
- static CachingPolicy = Object.freeze({
2096
- DEFAULT: "default",
2097
- FORCE_CACHE: "force-cache",
2098
- NO_CACHE: "no-cache",
2099
- NO_STORE: "no-store",
2100
- ONLY_IF_CACHED: "only-if-cached",
2101
- RELOAD: "reload"
2102
- });
2103
- /**
2104
- * @static
2105
- * @constant {Object<string, RequestCredentials>}
2106
- */
2107
- static CredentialsPolicy = Object.freeze({
2108
- INCLUDE: "include",
2109
- OMIT: "omit",
2110
- SAME_ORIGIN: "same-origin"
2111
- });
2112
- /**
2113
- * @static
2114
- * @constant {Object<string, RequestMode>}
2115
- */
2116
- static RequestMode = Object.freeze({
2117
- CORS: "cors",
2118
- NAVIGATE: "navigate",
2119
- NO_CORS: "no-cors",
2120
- SAME_ORIGIN: "same-origin"
2121
- });
2122
- /**
2123
- * @static
2124
- * @constant {Object<string, RequestRedirect>}
2125
- */
2126
- static RedirectPolicy = Object.freeze({
2127
- ERROR: "error",
2128
- FOLLOW: "follow",
2129
- MANUAL: "manual"
2130
- });
2131
- /**
2132
- * @static
2133
- * @constant {Object<string, ReferrerPolicy>}
2134
- */
2135
- static ReferrerPolicy = Object.freeze({
2136
- NO_REFERRER: "no-referrer",
2137
- NO_REFERRER_WHEN_DOWNGRADE: "no-referrer-when-downgrade",
2138
- ORIGIN: "origin",
2139
- ORIGIN_WHEN_CROSS_ORIGIN: "origin-when-cross-origin",
2140
- SAME_ORIGIN: "same-origin",
2141
- STRICT_ORIGIN: "strict-origin",
2142
- STRICT_ORIGIN_WHEN_CROSS_ORIGIN: "strict-origin-when-cross-origin",
2143
- UNSAFE_URL: "unsafe-url"
2144
- });
2145
- /**
2146
- * @static
2147
- * @constant {Object<string, TransportrEvent>}
2148
- */
2149
- static Events = RequestEvents;
2150
- /**
2151
- * @private
2152
- * @static
2153
- * @type {RequestOptions}
2154
- */
2155
- static #defaultRequestOptions = Object.freeze({
2156
- body: null,
2157
- cache: _Transportr.CachingPolicy.NO_STORE,
2158
- credentials: _Transportr.CredentialsPolicy.SAME_ORIGIN,
2159
- headers: { [http_request_headers_default.CONTENT_TYPE]: `${mediaTypes.get(http_media_type_default.JSON)}`, [http_request_headers_default.ACCEPT]: `${mediaTypes.get(http_media_type_default.JSON)}` },
2160
- searchParams: {},
2161
- integrity: void 0,
2162
- keepalive: void 0,
2163
- method: http_request_methods_default.GET,
2164
- mode: _Transportr.RequestMode.CORS,
2165
- redirect: _Transportr.RedirectPolicy.FOLLOW,
2166
- referrer: "about:client",
2167
- referrerPolicy: _Transportr.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN,
2168
- signal: void 0,
2169
- timeout: 3e4,
2170
- global: true,
2171
- window: null
2172
- });
2173
- /**
2174
- * Returns a {@link EventRegistration} used for subscribing to global events.
2175
- *
2176
- * @static
2177
- * @param {TransportrEvent} event The event to subscribe to.
2178
- * @param {function(Event, *): void} handler The event handler.
2179
- * @param {*} context The context to bind the handler to.
2180
- * @returns {EventRegistration} A new {@link EventRegistration} instance.
2181
- */
2182
- static register(event, handler, context) {
2183
- return _Transportr.#globalSubscribr.subscribe(event, handler, context);
2184
- }
2185
- /**
2186
- * Removes a {@link EventRegistration} from the global event handler.
2187
- *
2188
- * @static
2189
- * @param {EventRegistration} eventRegistration The {@link EventRegistration} to remove.
2190
- * @returns {boolean} True if the {@link EventRegistration} was removed, false otherwise.
2191
- */
2192
- static unregister(eventRegistration) {
2193
- return _Transportr.#globalSubscribr.unsubscribe(eventRegistration);
2194
- }
2195
- /**
2196
- * Aborts all active requests.
2197
- * This is useful for when the user navigates away from the current page.
2198
- * This will also clear the {@link Transportr#activeRequests} set.
2199
- *
2200
- * @static
2201
- * @returns {void}
2202
- */
2203
- static abortAll() {
2204
- for (const abortSignal of this.#activeRequests) {
2205
- abortSignal.abort(_abortEvent);
2206
- }
2207
- this.#activeRequests.clear();
2208
- }
2209
- /**
2210
- * It returns the base {@link URL} for the API.
2211
- *
2212
- * @returns {URL} The baseUrl property.
2213
- */
2214
- get baseUrl() {
2215
- return this.#baseUrl;
2216
- }
2217
- /**
2218
- * Registers an event handler with a {@link Transportr} instance.
2219
- *
2220
- * @param {TransportrEvent} event The name of the event to listen for.
2221
- * @param {function(Event, *): void} handler The function to call when the event is triggered.
2222
- * @param {*} [context] The context to bind to the handler.
2223
- * @returns {EventRegistration} An object that can be used to remove the event handler.
2224
- */
2225
- register(event, handler, context) {
2226
- return this.#subscribr.subscribe(event, handler, context);
2227
- }
2228
- /**
2229
- * Unregisters an event handler from a {@link Transportr} instance.
2230
- *
2231
- * @param {EventRegistration} eventRegistration The event registration to remove.
2232
- * @returns {void}
2233
- */
2234
- unregister(eventRegistration) {
2235
- this.#subscribr.unsubscribe(eventRegistration);
2236
- }
2237
- /**
2238
- * This function returns a promise that resolves to the result of a request to the specified path with
2239
- * the specified options, where the method is GET.
2240
- *
2241
- * @async
2242
- * @param {string} [path] The path to the resource you want to get.
2243
- * @param {RequestOptions} [options] The options for the request.
2244
- * @returns {Promise<ResponseBody>} A promise that resolves to the response of the request.
2245
- */
2246
- async get(path, options) {
2247
- return this.#get(path, options);
2248
- }
2249
- /**
2250
- * This function makes a POST request to the given path with the given body and options.
2251
- *
2252
- * @async
2253
- * @param {string} [path] The path to the endpoint you want to call.
2254
- * @param {RequestBody} body The body of the request.
2255
- * @param {RequestOptions} [options] The options for the request.
2256
- * @returns {Promise<ResponseBody>} A promise that resolves to the response body.
2257
- */
2258
- async post(path, body = {}, options = {}) {
2259
- if (object_type_default(path) != String) {
2260
- [path, body, options] = [void 0, path, body];
2261
- }
2262
- return this.#request(path, Object.assign(options, { body }), { method: http_request_methods_default.POST });
2263
- }
2264
- /**
2265
- * This function returns a promise that resolves to the result of a request to the specified path with
2266
- * the specified options, where the method is PUT.
2267
- *
2268
- * @async
2269
- * @param {string} [path] The path to the endpoint you want to call.
2270
- * @param {RequestOptions} [options] The options for the request.
2271
- * @returns {Promise<ResponseBody>} The return value of the #request method.
2272
- */
2273
- async put(path, options) {
2274
- return this.#request(path, options, { method: http_request_methods_default.PUT });
2275
- }
2276
- /**
2277
- * It takes a path and options, and returns a request with the method set to PATCH.
2278
- *
2279
- * @async
2280
- * @param {string} [path] The path to the endpoint you want to hit.
2281
- * @param {RequestOptions} [options] The options for the request.
2282
- * @returns {Promise<ResponseBody>} A promise that resolves to the response of the request.
2283
- */
2284
- async patch(path, options) {
2285
- return this.#request(path, options, { method: http_request_methods_default.PATCH });
2286
- }
2287
- /**
2288
- * It takes a path and options, and returns a request with the method set to DELETE.
2289
- *
2290
- * @async
2291
- * @param {string} [path] The path to the resource you want to access.
2292
- * @param {RequestOptions} [options] The options for the request.
2293
- * @returns {Promise<ResponseBody>} The result of the request.
2294
- */
2295
- async delete(path, options) {
2296
- return this.#request(path, options, { method: http_request_methods_default.DELETE });
2297
- }
2298
- /**
2299
- * Returns the response headers of a request to the given path.
2300
- *
2301
- * @async
2302
- * @param {string} [path] The path to the resource you want to access.
2303
- * @param {RequestOptions} [options] The options for the request.
2304
- * @returns {Promise<ResponseBody>} A promise that resolves to the response object.
2305
- */
2306
- async head(path, options) {
2307
- return this.#request(path, options, { method: http_request_methods_default.HEAD });
2308
- }
2309
- /**
2310
- * It returns a promise that resolves to the allowed request methods for the given resource path.
2311
- *
2312
- * @async
2313
- * @param {string} [path] The path to the resource.
2314
- * @param {RequestOptions} [options] The options for the request.
2315
- * @returns {Promise<string[]>} A promise that resolves to an array of allowed request methods for this resource.
2316
- */
2317
- async options(path, options) {
2318
- const response = await this.#request(path, options, { method: http_request_methods_default.OPTIONS });
2319
- return response.headers.get("allow").split(",").map((method) => method.trim());
2320
- }
2321
- /**
2322
- * It takes a path and options, and makes a request to the server.
2323
- *
2324
- * @async
2325
- * @param {string} [path] The path to the endpoint you want to hit.
2326
- * @param {RequestOptions} [userOptions] The options for the request.
2327
- * @returns {Promise<ResponseBody>} The return value of the function is the return value of the function that is passed to the `then` method of the promise returned by the `fetch` method.
2328
- */
2329
- async request(path, userOptions) {
2330
- return this.#request(path, userOptions, {}, (response) => response);
2331
- }
2332
- /**
2333
- * It gets a JSON resource from the server.
2334
- *
2335
- * @async
2336
- * @param {string} [path] The path to the resource.
2337
- * @param {RequestOptions} [options] The options object to pass to the request.
2338
- * @returns {Promise<JsonObject>} A promise that resolves to the response body as a JSON object.
2339
- */
2340
- async getJson(path, options) {
2341
- return this.#get(path, options, { headers: { [http_request_headers_default.ACCEPT]: `${mediaTypes.get(http_media_type_default.JSON)}` } }, _handleJson);
2342
- }
2343
- /**
2344
- * It gets the XML representation of the resource at the given path.
2345
- *
2346
- * @async
2347
- * @param {string} [path] The path to the resource you want to get.
2348
- * @param {RequestOptions} [options] The options for the request.
2349
- * @returns {Promise<Document>} The result of the function call to #get.
2350
- */
2351
- async getXml(path, options) {
2352
- return this.#get(path, options, { headers: { [http_request_headers_default.ACCEPT]: `${mediaTypes.get(http_media_type_default.XML)}` } }, _handleXml);
2353
- }
2354
- /**
2355
- * Get the HTML content of the specified path.
2356
- *
2357
- * @todo Add way to return portion of the retrieved HTML using a selector. Like jQuery.
2358
- * @async
2359
- * @param {string} [path] The path to the resource.
2360
- * @param {RequestOptions} [options] The options for the request.
2361
- * @returns {Promise<Document>} The return value of the function is the return value of the function passed to the `then`
2362
- * method of the promise returned by the `#get` method.
2363
- */
2364
- async getHtml(path, options) {
2365
- return this.#get(path, options, { headers: { [http_request_headers_default.ACCEPT]: `${mediaTypes.get(http_media_type_default.HTML)}` } }, _handleHtml);
2366
- }
2367
- /**
2368
- * It returns a promise that resolves to the HTML fragment at the given path.
2369
- *
2370
- * @todo Add way to return portion of the retrieved HTML using a selector. Like jQuery.
2371
- * @async
2372
- * @param {string} [path] The path to the resource.
2373
- * @param {RequestOptions} [options] The options for the request.
2374
- * @returns {Promise<DocumentFragment>} A promise that resolves to an HTML fragment.
2375
- */
2376
- async getHtmlFragment(path, options) {
2377
- return this.#get(path, options, { headers: { [http_request_headers_default.ACCEPT]: `${mediaTypes.get(http_media_type_default.HTML)}` } }, _handleHtmlFragment);
2378
- }
2379
- /**
2380
- * It gets a script from the server, and appends the script to the {@link Document} {@link HTMLHeadElement}
2381
- * CORS is enabled by default.
2382
- *
2383
- * @async
2384
- * @param {string} [path] The path to the script.
2385
- * @param {RequestOptions} [options] The options for the request.
2386
- * @returns {Promise<void>} A promise that has been resolved.
2387
- */
2388
- async getScript(path, options) {
2389
- return this.#get(path, options, { headers: { [http_request_headers_default.ACCEPT]: `${mediaTypes.get(http_media_type_default.JAVA_SCRIPT)}` } }, _handleScript);
2390
- }
2391
- /**
2392
- * Gets a stylesheet from the server, and adds it as a {@link Blob} {@link URL}.
2393
- *
2394
- * @async
2395
- * @param {string} [path] The path to the stylesheet.
2396
- * @param {RequestOptions} [options] The options for the request.
2397
- * @returns {Promise<void>} A promise that has been resolved.
2398
- */
2399
- async getStylesheet(path, options) {
2400
- return this.#get(path, options, { headers: { [http_request_headers_default.ACCEPT]: `${mediaTypes.get(http_media_type_default.CSS)}` } }, _handleCss);
2401
- }
2402
- /**
2403
- * It returns a blob from the specified path.
2404
- *
2405
- * @async
2406
- * @param {string} [path] The path to the resource.
2407
- * @param {RequestOptions} [options] The options for the request.
2408
- * @returns {Promise<Blob>} A promise that resolves to a blob.
2409
- */
2410
- async getBlob(path, options) {
2411
- return this.#get(path, options, { headers: { [http_request_headers_default.ACCEPT]: http_media_type_default.BIN } }, _handleBlob);
2412
- }
2413
- /**
2414
- * It returns a promise that resolves to an object URL.
2415
- *
2416
- * @async
2417
- * @param {string|RequestOptions} [path] The path to the resource.
2418
- * @param {RequestOptions} [options] The options for the request.
2419
- * @returns {Promise<string>} A promise that resolves to an object URL.
2420
- */
2421
- async getImage(path, options) {
2422
- return this.#get(path, options, { headers: { [http_request_headers_default.ACCEPT]: "image/*" } }, _handleImage);
2423
- }
2424
- /**
2425
- * It gets a buffer from the specified path
2426
- *
2427
- * @async
2428
- * @param {string} [path] The path to the resource.
2429
- * @param {RequestOptions} [options] The options for the request.
2430
- * @returns {Promise<ArrayBuffer>} A promise that resolves to a buffer.
2431
- */
2432
- async getBuffer(path, options) {
2433
- return this.#get(path, options, { headers: { [http_request_headers_default.ACCEPT]: http_media_type_default.BIN } }, _handleBuffer);
2434
- }
2435
- /**
2436
- * It returns a readable stream of the response body from the specified path.
2437
- *
2438
- * @async
2439
- * @param {string} [path] The path to the resource.
2440
- * @param {RequestOptions} [options] The options for the request.
2441
- * @returns {Promise<ReadableStream<Uint8Array>>} A readable stream.
2442
- */
2443
- async getStream(path, options) {
2444
- return this.#get(path, options, { headers: { [http_request_headers_default.ACCEPT]: http_media_type_default.BIN } }, _handleReadableStream);
2445
- }
2446
- /**
2447
- * Makes a GET request to the given path, using the given options, and then calls the
2448
- * given response handler with the response.
2449
- *
2450
- * @private
2451
- * @async
2452
- * @param {string} [path] The path to the endpoint you want to call.
2453
- * @param {RequestOptions} [userOptions] The options passed to the public function to use for the request.
2454
- * @param {RequestOptions} [options={}] The options for the request.
2455
- * @param {ResponseHandler<ResponseBody>} [responseHandler] A function that will be called with the response object.
2456
- * @returns {Promise<ResponseBody>} The result of the #request method.
2457
- */
2458
- async #get(path, userOptions, options = {}, responseHandler) {
2459
- return this.#request(path, userOptions, Object.assign(options, { method: http_request_methods_default.GET }), responseHandler);
2460
- }
2461
- /**
2462
- * It takes a path, options, and a response handler, and returns a promise that resolves to the
2463
- * response entity.
2464
- *
2465
- * @private
2466
- * @async
2467
- * @param {string} [path] The path to the resource you want to access.
2468
- * @param {RequestOptions} [userOptions={}] The options passed to the public function to use for the request.
2469
- * @param {RequestOptions} [options={}] The options to use for the request.
2470
- * @param {ResponseHandler<ResponseBody>} [responseHandler] A function that will be called with the response body as a parameter. This
2471
- * is useful if you want to do something with the response body before returning it.
2472
- * @returns {Promise<ResponseBody>} The response from the API call.
2473
- */
2474
- async #request(path, userOptions = {}, options = {}, responseHandler) {
2475
- if (object_type_default(path) == Object) {
2476
- [path, userOptions] = [void 0, path];
2477
- }
2478
- options = this.#processRequestOptions(userOptions, options);
2479
- let response;
2480
- const url = _Transportr.#createUrl(this.#baseUrl, path, options.searchParams);
2481
- try {
2482
- _Transportr.#activeRequests.add(options.signal);
2483
- response = await fetch(url, new Proxy(options, abortSignalProxyHandler));
2484
- if (!responseHandler && response.status != 204) {
2485
- responseHandler = this.#getResponseHandler(response.headers.get(http_response_headers_default.CONTENT_TYPE));
2486
- }
2487
- const result = await responseHandler?.(response) ?? response;
2488
- if (!response.ok) {
2489
- return Promise.reject(this.#handleError(url, { status: _Transportr.#generateResponseStatusFromError("ResponseError", response), entity: result }));
2490
- }
2491
- this.#publish({ name: RequestEvents.SUCCESS, data: result, global: options.global });
2492
- return result;
2493
- } catch (cause) {
2494
- return Promise.reject(this.#handleError(url, { cause, status: _Transportr.#generateResponseStatusFromError(cause.name, response) }));
2495
- } finally {
2496
- options.signal.clearTimeout();
2497
- if (!options.signal.aborted) {
2498
- this.#publish({ name: RequestEvents.COMPLETE, data: response, global: options.global });
2499
- _Transportr.#activeRequests.delete(options.signal);
2500
- if (_Transportr.#activeRequests.size == 0) {
2501
- this.#publish({ name: RequestEvents.ALL_COMPLETE, global: options.global });
2502
- }
2503
- }
2504
- }
2505
- }
2506
- /**
2507
- * Creates the options for a {@link Transportr} instance.
2508
- *
2509
- * @private
2510
- * @static
2511
- * @param {RequestOptions} userOptions The {@link RequestOptions} to convert.
2512
- * @param {RequestOptions} options The default {@link RequestOptions}.
2513
- * @returns {RequestOptions} The converted {@link RequestOptions}.
2514
- */
2515
- static #createOptions({ body, headers: userHeaders, searchParams: userSearchParams, ...userOptions }, { headers, searchParams, ...options }) {
2516
- return object_merge_default(options, userOptions, {
2517
- body: [FormData, URLSearchParams, Object].includes(object_type_default(body)) ? new ParameterMap(body) : body,
2518
- headers: _Transportr.#mergeOptions(new Headers(), userHeaders, headers),
2519
- searchParams: _Transportr.#mergeOptions(new URLSearchParams(), userSearchParams, searchParams)
2520
- });
2521
- }
2522
- /**
2523
- * Merge the user options and request options into the target.
2524
- *
2525
- * @private
2526
- * @static
2527
- * @param {Headers|URLSearchParams|FormData} target The target to merge the options into.
2528
- * @param {Headers|URLSearchParams|FormData|Object} userOption The user options to merge into the target.
2529
- * @param {Headers|URLSearchParams|FormData|Object} requestOption The request options to merge into the target.
2530
- * @returns {Headers|URLSearchParams} The target.
2531
- */
2532
- static #mergeOptions(target, userOption = {}, requestOption = {}) {
2533
- for (const option of [userOption, requestOption]) {
2534
- for (const [name, value] of option.entries?.() ?? Object.entries(option)) {
2535
- target.set(name, value);
2536
- }
2537
- }
2538
- return target;
2539
- }
2540
- /**
2541
- * Merges the user options and request options with the instance options into a new object that is used for the request.
2542
- *
2543
- * @private
2544
- * @param {RequestOptions} userOptions The user options to merge into the request options.
2545
- * @param {RequestOptions} options The request options to merge into the user options.
2546
- * @returns {RequestOptions} The merged options.
2547
- */
2548
- #processRequestOptions({ body: userBody, headers: userHeaders, searchParams: userSearchParams, ...userOptions }, { headers, searchParams, ...options }) {
2549
- const requestOptions = object_merge_default(this.#options, userOptions, options, {
2550
- headers: _Transportr.#mergeOptions(new Headers(this.#options.headers), userHeaders, headers),
2551
- searchParams: _Transportr.#mergeOptions(new URLSearchParams(this.#options.searchParams), userSearchParams, searchParams)
2552
- });
2553
- if (requestBodyMethods.includes(requestOptions.method)) {
2554
- if ([ParameterMap, FormData, URLSearchParams, Object].includes(object_type_default(userBody))) {
2555
- const contentType = requestOptions.headers.get(http_request_headers_default.CONTENT_TYPE);
2556
- const mediaType = (mediaTypes.get(contentType) ?? MediaType.parse(contentType))?.subtype;
2557
- if (mediaType == http_media_type_default.MULTIPART_FORM_DATA) {
2558
- requestOptions.body = _Transportr.#mergeOptions(new FormData(requestOptions.body), userBody);
2559
- } else if (mediaType == http_media_type_default.FORM) {
2560
- requestOptions.body = _Transportr.#mergeOptions(new URLSearchParams(requestOptions.body), userBody);
2561
- } else if (mediaType.includes("json")) {
2562
- requestOptions.body = JSON.stringify(_Transportr.#mergeOptions(new ParameterMap(requestOptions.body), userBody));
2563
- } else {
2564
- requestOptions.body = _Transportr.#mergeOptions(new ParameterMap(requestOptions.body), userBody);
2565
- }
2566
- } else {
2567
- requestOptions.body = userBody;
2568
- }
2569
- } else {
2570
- requestOptions.headers.delete(http_request_headers_default.CONTENT_TYPE);
2571
- if (requestOptions.body) {
2572
- _Transportr.#mergeOptions(requestOptions.searchParams, requestOptions.body);
2573
- }
2574
- requestOptions.body = void 0;
2575
- }
2576
- requestOptions.signal = new AbortSignal(requestOptions.signal).onAbort((event) => this.#publish({ name: RequestEvents.ABORTED, event, global: requestOptions.global })).onTimeout((event) => this.#publish({ name: RequestEvents.TIMEOUT, event, global: requestOptions.global }));
2577
- this.#publish({ name: RequestEvents.CONFIGURED, data: requestOptions, global: requestOptions.global });
2578
- return requestOptions;
2579
- }
2580
- /**
2581
- * It takes a url or a string, and returns a {@link URL} instance.
2582
- * If the url is a string and starts with a slash, then the origin of the current page is used as the base url.
2583
- *
2584
- * @private
2585
- * @static
2586
- * @param {URL|string} url The URL to convert to a {@link URL} instance.
2587
- * @returns {URL} A {@link URL} instance.
2588
- * @throws {TypeError} If the url is not a string or {@link URL} instance.
2589
- */
2590
- static #getBaseUrl(url) {
2591
- switch (object_type_default(url)) {
2592
- case URL:
2593
- return url;
2594
- case String:
2595
- return new URL(url, url.startsWith("/") ? globalThis.location.origin : void 0);
2596
- default:
2597
- throw new TypeError("Invalid URL");
2598
- }
2599
- }
2600
- /**
2601
- * It takes a URL, a path, and a set of search parameters, and returns a new URL with the path and
2602
- * search parameters applied.
2603
- *
2604
- * @private
2605
- * @static
2606
- * @param {URL} url The URL to use as a base.
2607
- * @param {string} [path] The optional, relative path to the resource. This MUST be a relative path, otherwise, you should create a new {@link Transportr} instance.
2608
- * @param {URLSearchParams} [searchParams] The optional search parameters to append to the URL.
2609
- * @returns {URL} A new URL object with the pathname and origin of the url parameter, and the path parameter appended to the end of the pathname.
2610
- */
2611
- static #createUrl(url, path, searchParams) {
2612
- const requestUrl = path ? new URL(`${url.pathname.replace(endsWithSlashRegEx, "")}${path}`, url.origin) : new URL(url);
2613
- searchParams?.forEach((value, name) => requestUrl.searchParams.append(name, value));
2614
- return requestUrl;
2615
- }
2616
- /**
2617
- * Generates a ResponseStatus object based on the error name and the response.
2618
- *
2619
- * @private
2620
- * @static
2621
- * @param {string} errorName The name of the error.
2622
- * @param {Response} response The response object returned by the fetch API.
2623
- * @returns {ResponseStatus} The response status object.
2624
- */
2625
- static #generateResponseStatusFromError(errorName, response) {
2626
- switch (errorName) {
2627
- case "AbortError":
2628
- return eventResponseStatuses[RequestEvents.ABORTED];
2629
- case "TimeoutError":
2630
- return eventResponseStatuses[RequestEvents.TIMEOUT];
2631
- default:
2632
- return response ? new ResponseStatus(response.status, response.statusText) : internalServerError;
2633
- }
2634
- }
2635
- /**
2636
- * Handles an error by logging it and throwing it.
2637
- *
2638
- * @private
2639
- * @param {URL} url The path to the resource you want to access.
2640
- * @param {import('./http-error.js').HttpErrorOptions} options The options for the HttpError.
2641
- * @returns {HttpError} The HttpError.
2642
- */
2643
- #handleError(url, options) {
2644
- const error = new HttpError(`An error has occurred with your request to: '${url}'`, options);
2645
- this.#publish({ name: RequestEvents.ERROR, data: error });
2646
- return error;
2647
- }
2648
- /**
2649
- * Publishes an event to the global and instance subscribers.
2650
- *
2651
- * @private
2652
- * @param {Object} options The options for the event.
2653
- * @param {string} options.name The name of the event.
2654
- * @param {Event} [options.event] The event object.
2655
- * @param {*} [options.data] The data to pass to the subscribers.
2656
- * @param {boolean} [options.global=true] Whether or not to publish the event to the global subscribers.
2657
- * @returns {void}
2658
- */
2659
- #publish({ name, event = new CustomEvent(name), data, global = true } = {}) {
2660
- if (global) {
2661
- _Transportr.#globalSubscribr.publish(name, event, data);
2662
- }
2663
- this.#subscribr.publish(name, event, data);
2664
- }
2665
- /**
2666
- * Returns a response handler for the given content type.
2667
- *
2668
- * @private
2669
- * @param {string} contentType The content type of the response.
2670
- * @returns {ResponseHandler<ResponseBody>} The response handler.
2671
- */
2672
- #getResponseHandler(contentType) {
2673
- const mediaType = MediaType.parse(contentType);
2674
- if (mediaType) {
2675
- for (const [responseHandler, contentType2] of _Transportr.#contentTypeHandlers) {
2676
- if (mediaType.matches(contentType2)) {
2677
- return responseHandler;
2678
- }
2679
- }
2680
- }
2681
- return void 0;
2682
- }
2683
- /**
2684
- * A String value that is used in the creation of the default string
2685
- * description of an object. Called by the built-in method {@link Object.prototype.toString}.
2686
- *
2687
- * @returns {string} The default string description of this object.
2688
- */
2689
- get [Symbol.toStringTag]() {
2690
- return "Transportr";
2691
- }
2692
- };
2693
- export {
2694
- Transportr as default
2695
- };
1
+ var P=/^[-!#$%&'*+.^_`|~A-Za-z0-9]*$/u,me=/(["\\])/ug,ye=/^[\t\u0020-\u007E\u0080-\u00FF]*$/u,W=class K extends Map{constructor(e=[]){super(e)}static isValid(e,t){return P.test(e)&&ye.test(t)}get(e){return super.get(e.toLowerCase())}has(e){return super.has(e.toLowerCase())}set(e,t){if(!K.isValid(e,t))throw new Error(`Invalid media type parameter name/value: ${e}/${t}`);return super.set(e.toLowerCase(),t),this}delete(e){return super.delete(e.toLowerCase())}toString(){return Array.from(this).map(([e,t])=>`;${e}=${!t||!P.test(t)?`"${t.replace(me,"\\$1")}"`:t}`).join("")}get[Symbol.toStringTag](){return"MediaTypeParameters"}},be=new Set([" "," ",`
2
+ `,"\r"]),Ee=/[ \t\n\r]+$/u,Te=/^[ \t\n\r]+|[ \t\n\r]+$/ug,Oe=class E{static parse(e){e=e.replace(Te,"");let t=0,[r,n]=E.collect(e,t,["/"]);if(t=n,!r.length||t>=e.length||!P.test(r))throw new TypeError(E.generateErrorMessage("type",r));++t;let[o,i]=E.collect(e,t,[";"],!0,!0);if(t=i,!o.length||!P.test(o))throw new TypeError(E.generateErrorMessage("subtype",o));let u=new W;for(;t<e.length;){for(++t;be.has(e[t]);)++t;let a;if([a,t]=E.collect(e,t,[";","="],!1),t>=e.length||e[t]===";")continue;++t;let l;if(e[t]==='"')for([l,t]=E.collectHttpQuotedString(e,t);t<e.length&&e[t]!==";";)++t;else if([l,t]=E.collect(e,t,[";"],!1,!0),!l)continue;a&&W.isValid(a,l)&&!u.has(a)&&u.set(a,l)}return{type:r,subtype:o,parameters:u}}get[Symbol.toStringTag](){return"MediaTypeParser"}static collect(e,t,r,n=!0,o=!1){let i="";for(let{length:u}=e;t<u&&!r.includes(e[t]);t++)i+=e[t];return n&&(i=i.toLowerCase()),o&&(i=i.replace(Ee,"")),[i,t]}static collectHttpQuotedString(e,t){let r="";for(let n=e.length,o;++t<n&&(o=e[t])!=='"';)r+=o=="\\"&&++t<n?e[t]:o;return[r,t]}static generateErrorMessage(e,t){return`Invalid ${e} "${t}": only HTTP token code points are valid.`}},y=class Y{_type;_subtype;_parameters;constructor(e,t={}){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("The parameters argument must be an object");({type:this._type,subtype:this._subtype,parameters:this._parameters}=Oe.parse(e));for(let[r,n]of Object.entries(t))this._parameters.set(r,n)}static parse(e){try{return new Y(e)}catch{}return null}get type(){return this._type}get subtype(){return this._subtype}get essence(){return`${this._type}/${this._subtype}`}get parameters(){return this._parameters}matches(e){return typeof e=="string"?this.essence.includes(e):this._type===e._type&&this._subtype===e._subtype}toString(){return`${this.essence}${this._parameters.toString()}`}get[Symbol.toStringTag](){return"MediaType"}};var Se=class extends Map{set(s,e){return super.set(s,e instanceof Set?e:(super.get(s)??new Set).add(e)),this}find(s,e){let t=this.get(s);if(t!==void 0)return Array.from(t).find(e)}hasValue(s,e){let t=super.get(s);return t?t.has(e):!1}deleteValue(s,e){if(e===void 0)return this.delete(s);let t=super.get(s);if(t){let r=t.delete(e);return t.size===0&&super.delete(s),r}return!1}get[Symbol.toStringTag](){return"SetMultiMap"}},ve=class{context;eventHandler;constructor(s,e){this.context=s,this.eventHandler=e}handle(s,e){this.eventHandler.call(this.context,s,e)}get[Symbol.toStringTag](){return"ContextEventHandler"}},we=class{_eventName;_contextEventHandler;constructor(s,e){this._eventName=s,this._contextEventHandler=e}get eventName(){return this._eventName}get contextEventHandler(){return this._contextEventHandler}get[Symbol.toStringTag](){return"Subscription"}},C=class{subscribers=new Se;errorHandler;setErrorHandler(s){this.errorHandler=s}subscribe(s,e,t=e,r){if(this.validateEventName(s),r?.once){let i=e;e=(u,a)=>{i.call(t,u,a),this.unsubscribe(o)}}let n=new ve(t,e);this.subscribers.set(s,n);let o=new we(s,n);return o}unsubscribe({eventName:s,contextEventHandler:e}){let t=this.subscribers.get(s)??new Set,r=t.delete(e);return r&&t.size===0&&this.subscribers.delete(s),r}publish(s,e=new CustomEvent(s),t){this.validateEventName(s),this.subscribers.get(s)?.forEach(r=>{try{r.handle(e,t)}catch(n){this.errorHandler?this.errorHandler(n,s,e,t):console.error(`Error in event handler for '${s}':`,n)}})}isSubscribed({eventName:s,contextEventHandler:e}){return this.subscribers.get(s)?.has(e)??!1}validateEventName(s){if(!s||typeof s!="string")throw new TypeError("Event name must be a non-empty string");if(s.trim()!==s)throw new Error("Event name cannot have leading or trailing whitespace")}destroy(){this.subscribers.clear()}get[Symbol.toStringTag](){return"Subscribr"}};var v=class extends Error{_entity;responseStatus;_url;_method;_timing;constructor(e,{message:t,cause:r,entity:n,url:o,method:i,timing:u}={}){super(t,{cause:r}),this._entity=n,this.responseStatus=e,this._url=o,this._method=i,this._timing=u}get entity(){return this._entity}get statusCode(){return this.responseStatus.code}get statusText(){return this.responseStatus?.text}get url(){return this._url}get method(){return this._method}get timing(){return this._timing}get name(){return"HttpError"}get[Symbol.toStringTag](){return this.name}};var T=class{_code;_text;constructor(e,t){this._code=e,this._text=t}get code(){return this._code}get text(){return this._text}get[Symbol.toStringTag](){return"ResponseStatus"}toString(){return`${this._code} ${this._text}`}};var w={charset:"utf-8"},Q=/\/$/,Z="XSRF-TOKEN",ee="X-XSRF-TOKEN",R={PNG:new y("image/png"),TEXT:new y("text/plain",w),JSON:new y("application/json",w),HTML:new y("text/html",w),JAVA_SCRIPT:new y("text/javascript",w),CSS:new y("text/css",w),XML:new y("application/xml",w),BIN:new y("application/octet-stream")},x=R.JSON.toString(),te={DEFAULT:"default",FORCE_CACHE:"force-cache",NO_CACHE:"no-cache",NO_STORE:"no-store",ONLY_IF_CACHED:"only-if-cached",RELOAD:"reload"},m={CONFIGURED:"configured",SUCCESS:"success",ERROR:"error",ABORTED:"aborted",TIMEOUT:"timeout",RETRY:"retry",COMPLETE:"complete",ALL_COMPLETE:"all-complete"},O={ABORT:"abort",TIMEOUT:"timeout"},S={ABORT:"AbortError",TIMEOUT:"TimeoutError"},H={once:!0,passive:!0},L=()=>new CustomEvent(O.ABORT,{detail:{cause:S.ABORT}}),se=()=>new CustomEvent(O.TIMEOUT,{detail:{cause:S.TIMEOUT}}),re=["POST","PUT","PATCH","DELETE"],ne=new T(500,"Internal Server Error"),oe=new T(499,"Aborted"),ie=new T(504,"Request Timeout"),I=[408,413,429,500,502,503,504],B=["GET","PUT","HEAD","DELETE","OPTIONS"],k=300,A=2;var M=class{abortSignal;abortController=new AbortController;events=new Map;constructor({signal:e,timeout:t=1/0}={}){if(t<0)throw new RangeError("The timeout cannot be negative");let r=[this.abortController.signal];e!=null&&r.push(e),t!==1/0&&r.push(AbortSignal.timeout(t)),(this.abortSignal=AbortSignal.any(r)).addEventListener(O.ABORT,this,H)}handleEvent({target:{reason:e}}){this.abortController.signal.aborted||e instanceof DOMException&&e.name===S.TIMEOUT&&this.abortSignal.dispatchEvent(se())}get signal(){return this.abortSignal}onAbort(e){return this.addEventListener(O.ABORT,e)}onTimeout(e){return this.addEventListener(O.TIMEOUT,e)}abort(e=L()){this.abortController.abort(e.detail?.cause)}destroy(){this.abortSignal.removeEventListener(O.ABORT,this,H);for(let[e,t]of this.events)this.abortSignal.removeEventListener(t,e,H);return this.events.clear(),this}addEventListener(e,t){return this.abortSignal.addEventListener(e,t,H),this.events.set(t,e),this}get[Symbol.toStringTag](){return"SignalController"}};var ae,qe,N=()=>qe??=import("./OP3JQ447.js").then(({default:s})=>e=>s.sanitize(e)),q=async()=>typeof document<"u"&&typeof DOMParser<"u"&&typeof DocumentFragment<"u"?Promise.resolve():ae??=import("jsdom").then(({JSDOM:s})=>{let{window:e}=new s("<!DOCTYPE html><html><head></head><body></body></html>",{url:"http://localhost"});globalThis.window=e,Object.assign(globalThis,{document:e.document,DOMParser:e.DOMParser,DocumentFragment:e.DocumentFragment})}).catch(()=>{throw ae=void 0,new Error("jsdom is required for HTML/XML/DOM features in Node.js environments. Install it with: npm install jsdom")}),ce=async s=>await s.text(),_=async s=>{await q();let e=URL.createObjectURL(await s.blob());return new Promise((t,r)=>{let n=document.createElement("script");Object.assign(n,{src:e,type:"text/javascript",async:!0}),n.onload=()=>{URL.revokeObjectURL(e),document.head.removeChild(n),t()},n.onerror=()=>{URL.revokeObjectURL(e),document.head.removeChild(n),r(new Error("Script failed to load"))},document.head.appendChild(n)})},D=async s=>{await q();let e=URL.createObjectURL(await s.blob());return new Promise((t,r)=>{let n=document.createElement("link");Object.assign(n,{href:e,type:"text/css",rel:"stylesheet"}),n.onload=()=>t(URL.revokeObjectURL(e)),n.onerror=()=>{URL.revokeObjectURL(e),document.head.removeChild(n),r(new Error("Stylesheet load failed"))},document.head.appendChild(n)})},j=async s=>await s.json(),ue=async s=>await s.blob(),F=async s=>{await q();let e=URL.createObjectURL(await s.blob());return new Promise((t,r)=>{let n=new Image;n.onload=()=>{URL.revokeObjectURL(e),t(n)},n.onerror=()=>{URL.revokeObjectURL(e),r(new Error("Image failed to load"))},n.src=e})},le=async s=>await s.arrayBuffer(),$=async s=>Promise.resolve(s.body),G=async s=>{await q();let e=await N();return new DOMParser().parseFromString(e(await s.text()),"application/xml")},J=async s=>{await q();let e=await N();return new DOMParser().parseFromString(e(await s.text()),"text/html")},de=async s=>{await q();let e=await N();return document.createRange().createContextualFragment(e(await s.text()))};var pe=s=>s!==void 0&&re.includes(s),fe=s=>s instanceof FormData||s instanceof Blob||s instanceof ArrayBuffer||s instanceof ReadableStream||s instanceof URLSearchParams||ArrayBuffer.isView(s),he=s=>{if(typeof document>"u"||!document.cookie)return;let e=`${s}=`,t=document.cookie.split(";");for(let r=0,n=t.length;r<n;r++){let o=t[r].trim();if(o.startsWith(e))return decodeURIComponent(o.slice(e.length))}},ge=s=>JSON.stringify(s),z=s=>s!==null&&typeof s=="string",b=s=>s!==null&&typeof s=="object"&&!Array.isArray(s)&&Object.getPrototypeOf(s)===Object.prototype,V=(...s)=>{let e=s.length;if(e===0)return;if(e===1){let[r]=s;return b(r)?X(r):r}let t={};for(let r of s){if(!b(r))return;for(let[n,o]of Object.entries(r)){let i=t[n];Array.isArray(o)?t[n]=[...o,...Array.isArray(i)?i.filter(u=>!o.includes(u)):[]]:b(o)?t[n]=b(i)?V(i,o):X(o):t[n]=o}}return t};function X(s){if(b(s)){let e={},t=Object.keys(s);for(let r=0,n=t.length,o;r<n;r++)o=t[r],e[o]=X(s[o]);return e}return s}var Re=class s{_baseUrl;_options;subscribr;hooks={beforeRequest:[],afterResponse:[],beforeError:[]};static globalSubscribr=new C;static globalHooks={beforeRequest:[],afterResponse:[],beforeError:[]};static signalControllers=new Set;static inflightRequests=new Map;static mediaTypeCache=new Map(Object.values(R).map(e=>[e.toString(),e]));static contentTypeHandlers=[[R.TEXT.type,ce],[R.JSON.subtype,j],[R.BIN.subtype,$],[R.HTML.subtype,J],[R.XML.subtype,G],[R.PNG.type,F],[R.JAVA_SCRIPT.subtype,_],[R.CSS.subtype,D]];constructor(e=globalThis.location?.origin??"http://localhost",t={}){b(e)&&([e,t]=[globalThis.location?.origin??"http://localhost",e]),this._baseUrl=s.getBaseUrl(e),this._options=s.createOptions(t,s.defaultRequestOptions),this.subscribr=new C}static CredentialsPolicy={INCLUDE:"include",OMIT:"omit",SAME_ORIGIN:"same-origin"};static RequestModes={CORS:"cors",NAVIGATE:"navigate",NO_CORS:"no-cors",SAME_ORIGIN:"same-origin"};static RequestPriorities={HIGH:"high",LOW:"low",AUTO:"auto"};static RedirectPolicies={ERROR:"error",FOLLOW:"follow",MANUAL:"manual"};static ReferrerPolicy={NO_REFERRER:"no-referrer",NO_REFERRER_WHEN_DOWNGRADE:"no-referrer-when-downgrade",ORIGIN:"origin",ORIGIN_WHEN_CROSS_ORIGIN:"origin-when-cross-origin",SAME_ORIGIN:"same-origin",STRICT_ORIGIN:"strict-origin",STRICT_ORIGIN_WHEN_CROSS_ORIGIN:"strict-origin-when-cross-origin",UNSAFE_URL:"unsafe-url"};static RequestEvents=m;static defaultRequestOptions={body:void 0,cache:te.NO_STORE,credentials:s.CredentialsPolicy.SAME_ORIGIN,headers:new Headers({"content-type":x,accept:x}),searchParams:void 0,integrity:void 0,keepalive:void 0,method:"GET",mode:s.RequestModes.CORS,priority:s.RequestPriorities.AUTO,redirect:s.RedirectPolicies.FOLLOW,referrer:"about:client",referrerPolicy:s.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN,signal:void 0,timeout:3e4,global:!0};static register(e,t,r){return s.globalSubscribr.subscribe(e,t,r)}static unregister(e){return s.globalSubscribr.unsubscribe(e)}static abortAll(){for(let e of this.signalControllers)e.abort(L());this.signalControllers.clear()}static registerContentTypeHandler(e,t){s.contentTypeHandlers.unshift([e,t])}static unregisterContentTypeHandler(e){let t=s.contentTypeHandlers.findIndex(([r])=>r===e);return t===-1?!1:(s.contentTypeHandlers.splice(t,1),!0)}static addHooks(e){e.beforeRequest&&s.globalHooks.beforeRequest.push(...e.beforeRequest),e.afterResponse&&s.globalHooks.afterResponse.push(...e.afterResponse),e.beforeError&&s.globalHooks.beforeError.push(...e.beforeError)}static clearHooks(){s.globalHooks={beforeRequest:[],afterResponse:[],beforeError:[]}}static unregisterAll(){s.abortAll(),s.globalSubscribr=new C,s.clearHooks(),s.inflightRequests.clear()}get baseUrl(){return this._baseUrl}register(e,t,r){return this.subscribr.subscribe(e,t,r)}unregister(e){return this.subscribr.unsubscribe(e)}addHooks(e){return e.beforeRequest&&this.hooks.beforeRequest.push(...e.beforeRequest),e.afterResponse&&this.hooks.afterResponse.push(...e.afterResponse),e.beforeError&&this.hooks.beforeError.push(...e.beforeError),this}clearHooks(){return this.hooks.beforeRequest.length=0,this.hooks.afterResponse.length=0,this.hooks.beforeError.length=0,this}destroy(){this.clearHooks(),this.subscribr.destroy()}async get(e,t){return this._get(e,t)}async post(e,t){return typeof e!="string"&&([e,t]=[void 0,e]),this.execute(e,t,{method:"POST"})}async put(e,t){return this.execute(e,t,{method:"PUT"})}async patch(e,t){return this.execute(e,t,{method:"PATCH"})}async delete(e,t){return this.execute(e,t,{method:"DELETE"})}async head(e,t){return this.execute(e,t,{method:"HEAD"})}async options(e,t={}){b(e)&&([e,t]=[void 0,e]);let r=this.processRequestOptions(t,{method:"OPTIONS"}),{requestOptions:n}=r,o=n.hooks,i=s.createUrl(this._baseUrl,e,n.searchParams),u=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,o?.beforeRequest];for(let d of u)if(d)for(let c of d){let g=await c(n,i);g&&(Object.assign(n,g),g.searchParams!==void 0&&(i=s.createUrl(this._baseUrl,e,n.searchParams)))}let a=await this._request(e,r),l=[s.globalHooks.afterResponse,this.hooks.afterResponse,o?.afterResponse];for(let d of l)if(d)for(let c of d){let g=await c(a,n);g&&(a=g)}let h=a.headers.get("allow")?.split(",").map(d=>d.trim());return this.publish({name:m.SUCCESS,data:h,global:t.global}),h}async request(e,t={}){b(e)&&([e,t]=[void 0,e]);let r=await this._request(e,this.processRequestOptions(t,{}));return this.publish({name:m.SUCCESS,data:r,global:t.global}),r}async getJson(e,t){return this._get(e,t,{headers:{accept:`${R.JSON}`}},j)}async getXml(e,t){return this._get(e,t,{headers:{accept:`${R.XML}`}},G)}async getHtml(e,t,r){let n=await this._get(e,t,{headers:{accept:`${R.HTML}`}},J);return r&&n?n.querySelector(r):n}async getHtmlFragment(e,t,r){let n=await this._get(e,t,{headers:{accept:`${R.HTML}`}},de);return r&&n?n.querySelector(r):n}async getScript(e,t){return this._get(e,t,{headers:{accept:`${R.JAVA_SCRIPT}`}},_)}async getStylesheet(e,t){return this._get(e,t,{headers:{accept:`${R.CSS}`}},D)}async getBlob(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},ue)}async getImage(e,t){return this._get(e,t,{headers:{accept:"image/*"}},F)}async getBuffer(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},le)}async getStream(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},$)}async _get(e,t,r={},n){return this.execute(e,t,{...r,method:"GET",body:void 0},n)}async _request(e,{signalController:t,requestOptions:r,global:n}){s.signalControllers.add(t);let o=s.normalizeRetryOptions(r.retry),i=r.method??"GET",u=o.limit>0&&o.methods.includes(i),a=r.dedupe===!0&&(i==="GET"||i==="HEAD"),l=0,h=performance.now(),d=()=>{let c=performance.now();return{start:h,end:c,duration:c-h}};try{let c=s.createUrl(this._baseUrl,e,r.searchParams),g=a?`${i}:${c.href}`:"";if(a){let f=s.inflightRequests.get(g);if(f)return(await f).clone()}let p=async()=>{for(;;)try{let f=await fetch(c,r);if(!f.ok){if(u&&l<o.limit&&o.statusCodes.includes(f.status)){l++,this.publish({name:m.RETRY,data:{attempt:l,status:f.status,method:i,path:e,timing:d()},global:n}),await s.retryDelay(o,l);continue}let U;try{U=await f.text()}catch{}throw await this.handleError(e,f,{entity:U,url:c,method:i,timing:d()},r)}return f}catch(f){if(f instanceof v)throw f;if(u&&l<o.limit){l++,this.publish({name:m.RETRY,data:{attempt:l,error:f.message,method:i,path:e,timing:d()},global:n}),await s.retryDelay(o,l);continue}throw await this.handleError(e,void 0,{cause:f,url:c,method:i,timing:d()},r)}};if(a){let f=p();s.inflightRequests.set(g,f);try{return await f}finally{s.inflightRequests.delete(g)}}return await p()}finally{if(s.signalControllers.delete(t.destroy()),!r.signal?.aborted){let c=d();this.publish({name:m.COMPLETE,data:{timing:c},global:n}),s.signalControllers.size===0&&this.publish({name:m.ALL_COMPLETE,global:n})}}}static normalizeRetryOptions(e){return e===void 0?{limit:0,statusCodes:[],methods:[],delay:k,backoffFactor:A}:typeof e=="number"?{limit:e,statusCodes:[...I],methods:[...B],delay:k,backoffFactor:A}:{limit:e.limit??0,statusCodes:e.statusCodes??[...I],methods:e.methods??[...B],delay:e.delay??k,backoffFactor:e.backoffFactor??A}}static retryDelay(e,t){let r=typeof e.delay=="function"?e.delay(t):e.delay*e.backoffFactor**(t-1);return new Promise(n=>setTimeout(n,r))}async execute(e,t={},r={},n){b(e)&&([e,t]=[void 0,e]);let o=this.processRequestOptions(t,r),{requestOptions:i}=o,u=i.hooks,a=s.createUrl(this._baseUrl,e,i.searchParams),l=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,u?.beforeRequest];for(let c of l)if(c)for(let g of c){let p=await g(i,a);p&&(Object.assign(i,p),p.searchParams!==void 0&&(a=s.createUrl(this._baseUrl,e,i.searchParams)))}let h=await this._request(e,o),d=[s.globalHooks.afterResponse,this.hooks.afterResponse,u?.afterResponse];for(let c of d)if(c)for(let g of c){let p=await g(h,i);p&&(h=p)}try{!n&&h.status!==204&&(n=this.getResponseHandler(h.headers.get("content-type")));let c=await n?.(h);return this.publish({name:m.SUCCESS,data:c,global:o.global}),c}catch(c){throw await this.handleError(e,h,{cause:c},i)}}static createOptions({headers:e,searchParams:t,...r},{headers:n,searchParams:o,...i}){return n=s.mergeHeaders(new Headers,e,n),o=s.mergeSearchParams(new URLSearchParams,t,o),{...V(i,r)??{},headers:n,searchParams:o}}static mergeHeaders(e,...t){for(let r of t)if(r!==void 0)if(r instanceof Headers)r.forEach((n,o)=>e.set(o,n));else if(Array.isArray(r))for(let[n,o]of r)e.set(n,o);else{let n=r,o=Object.keys(n);for(let i=0;i<o.length;i++){let u=o[i],a=n[u];a!==void 0&&e.set(u,String(a))}}return e}static mergeSearchParams(e,...t){for(let r of t)if(r!==void 0)if(r instanceof URLSearchParams)r.forEach((n,o)=>e.set(o,n));else if(z(r)||Array.isArray(r))for(let[n,o]of new URLSearchParams(r))e.set(n,o);else{let n=Object.keys(r);for(let o=0;o<n.length;o++){let i=n[o],u=r[i];u!==void 0&&e.set(i,String(u))}}return e}processRequestOptions({body:e,headers:t,searchParams:r,...n},{headers:o,searchParams:i,...u}){let a={...this._options,...n,...u,headers:s.mergeHeaders(new Headers,this._options.headers,t,o),searchParams:s.mergeSearchParams(new URLSearchParams,this._options.searchParams,r,i)};if(pe(a.method))if(fe(e))a.body=e,a.headers.delete("content-type");else{let p=a.headers.get("content-type")?.includes("json")??!1;a.body=p&&b(e)?ge(e):e}else a.headers.delete("content-type"),a.body instanceof URLSearchParams&&s.mergeSearchParams(a.searchParams,a.body),a.body=void 0;let{signal:l,timeout:h,global:d=!1,xsrf:c}=a;if(c){let p=typeof c=="object"?c:{},f=he(p.cookieName??Z);f&&a.headers.set(p.headerName??ee,f)}let g=new M({signal:l,timeout:h}).onAbort(p=>this.publish({name:m.ABORTED,event:p,global:d})).onTimeout(p=>this.publish({name:m.TIMEOUT,event:p,global:d}));return a.signal=g.signal,this.publish({name:m.CONFIGURED,data:a,global:d}),{signalController:g,requestOptions:a,global:d}}static getBaseUrl(e){if(e instanceof URL)return e;if(!z(e))throw new TypeError("Invalid URL");return new URL(e,e.startsWith("/")?globalThis.location.origin:void 0)}static getOrParseMediaType(e){if(e===null)return;let t=s.mediaTypeCache.get(e);if(t!==void 0)return t;if(t=y.parse(e)??void 0,t!==void 0){if(s.mediaTypeCache.size>=100){let r=s.mediaTypeCache.keys().next().value;r!==void 0&&s.mediaTypeCache.delete(r)}s.mediaTypeCache.set(e,t)}return t}static createUrl(e,t,r){let n=t?new URL(`${e.pathname.replace(Q,"")}${t}`,e.origin):new URL(e);return r&&s.mergeSearchParams(n.searchParams,r),n}static generateResponseStatusFromError(e,{status:t,statusText:r}=new Response){switch(e){case S.ABORT:return oe;case S.TIMEOUT:return ie;default:return t>=400?new T(t,r):ne}}async handleError(e,t,{cause:r,entity:n,url:o,method:i,timing:u}={},a){let l=i&&o?`${i} ${o.href} failed${t?` with status ${t.status}`:""}`:`An error has occurred with your request to: '${e}'`,h=new v(s.generateResponseStatusFromError(r?.name,t),{message:l,cause:r,entity:n,url:o,method:i,timing:u}),d=[s.globalHooks.beforeError,this.hooks.beforeError,a?.hooks?.beforeError];for(let c of d)if(c)for(let g of c){let p=await g(h);p instanceof v&&(h=p)}return this.publish({name:m.ERROR,data:h}),h}publish({name:e,event:t=new CustomEvent(e),data:r,global:n=!0}){n&&s.globalSubscribr.publish(e,t,r),this.subscribr.publish(e,t,r)}getResponseHandler(e){if(!e)return;let t=s.getOrParseMediaType(e);if(t){for(let[r,n]of s.contentTypeHandlers)if(t.matches(r))return n}}get[Symbol.toStringTag](){return"Transportr"}};export{Re as Transportr};
3
+ //# sourceMappingURL=transportr.js.map