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