@gjsify/fetch 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +9 -0
  2. package/lib/cjs/body.js +284 -0
  3. package/lib/cjs/errors/abort-error.js +28 -0
  4. package/lib/cjs/errors/base.js +36 -0
  5. package/lib/cjs/errors/fetch-error.js +40 -0
  6. package/lib/cjs/headers.js +231 -0
  7. package/lib/cjs/index.js +246 -0
  8. package/lib/cjs/request.js +306 -0
  9. package/lib/cjs/response.js +162 -0
  10. package/lib/cjs/types/index.js +17 -0
  11. package/lib/cjs/types/system-error.js +16 -0
  12. package/lib/cjs/utils/blob-from.js +124 -0
  13. package/lib/cjs/utils/get-search.js +30 -0
  14. package/lib/cjs/utils/is-redirect.js +26 -0
  15. package/lib/cjs/utils/is.js +47 -0
  16. package/lib/cjs/utils/multipart-parser.js +372 -0
  17. package/lib/cjs/utils/referrer.js +172 -0
  18. package/lib/esm/body.js +255 -0
  19. package/lib/esm/errors/abort-error.js +9 -0
  20. package/lib/esm/errors/base.js +17 -0
  21. package/lib/esm/errors/fetch-error.js +21 -0
  22. package/lib/esm/headers.js +202 -0
  23. package/lib/esm/index.js +224 -0
  24. package/lib/esm/request.js +281 -0
  25. package/lib/esm/response.js +133 -0
  26. package/lib/esm/types/index.js +1 -0
  27. package/lib/esm/types/system-error.js +1 -0
  28. package/lib/esm/utils/blob-from.js +101 -0
  29. package/lib/esm/utils/get-search.js +11 -0
  30. package/lib/esm/utils/is-redirect.js +7 -0
  31. package/lib/esm/utils/is.js +28 -0
  32. package/lib/esm/utils/multipart-parser.js +353 -0
  33. package/lib/esm/utils/referrer.js +153 -0
  34. package/package.json +53 -0
  35. package/src/body.ts +415 -0
  36. package/src/errors/abort-error.ts +10 -0
  37. package/src/errors/base.ts +20 -0
  38. package/src/errors/fetch-error.ts +26 -0
  39. package/src/headers.ts +279 -0
  40. package/src/index.spec.ts +13 -0
  41. package/src/index.ts +367 -0
  42. package/src/request.ts +396 -0
  43. package/src/response.ts +197 -0
  44. package/src/test.mts +6 -0
  45. package/src/types/index.ts +1 -0
  46. package/src/types/system-error.ts +11 -0
  47. package/src/utils/blob-from.ts +168 -0
  48. package/src/utils/get-search.ts +9 -0
  49. package/src/utils/is-redirect.ts +11 -0
  50. package/src/utils/is.ts +88 -0
  51. package/src/utils/multipart-parser.ts +448 -0
  52. package/src/utils/referrer.ts +350 -0
  53. package/test.gjs.js +34758 -0
  54. package/test.gjs.mjs +53177 -0
  55. package/test.node.js +1226 -0
  56. package/test.node.mjs +6294 -0
  57. package/tsconfig.json +19 -0
  58. package/tsconfig.types.json +8 -0
@@ -0,0 +1,101 @@
1
+ import { DOMException } from "@gjsify/deno-runtime/ext/web/01_dom_exception";
2
+ import { Blob, File } from "@gjsify/deno-runtime/ext/web/09_file";
3
+ import {
4
+ realpathSync,
5
+ statSync,
6
+ rmdirSync,
7
+ createReadStream,
8
+ promises as fs
9
+ } from "node:fs";
10
+ import { basename, sep, join } from "node:path";
11
+ import { tmpdir } from "node:os";
12
+ import process from "node:process";
13
+ const { stat, mkdtemp } = fs;
14
+ let i = 0, tempDir, registry;
15
+ const blobFromSync = (path, type) => fromBlob(statSync(path), path, type);
16
+ const blobFrom = (path, type) => stat(path).then((stat2) => fromBlob(stat2, path, type));
17
+ const fileFrom = (path, type) => stat(path).then((stat2) => fromFile(stat2, path, type));
18
+ const fileFromSync = (path, type) => fromFile(statSync(path), path, type);
19
+ const fromBlob = (stat2, path, type = "") => new Blob([new BlobDataItem({
20
+ path,
21
+ size: stat2.size,
22
+ lastModified: stat2.mtimeMs,
23
+ start: 0
24
+ })], { type });
25
+ const fromFile = (stat2, path, type = "") => new File([new BlobDataItem({
26
+ path,
27
+ size: stat2.size,
28
+ lastModified: stat2.mtimeMs,
29
+ start: 0
30
+ })], basename(path), { type, lastModified: stat2.mtimeMs });
31
+ const createTemporaryBlob = async (data, { signal, type } = {}) => {
32
+ registry = registry || new FinalizationRegistry(fs.unlink);
33
+ tempDir = tempDir || await mkdtemp(realpathSync(tmpdir()) + sep);
34
+ const id = `${i++}`;
35
+ const destination = join(tempDir, id);
36
+ if (data instanceof ArrayBuffer)
37
+ data = new Uint8Array(data);
38
+ await fs.writeFile(destination, data, { signal });
39
+ const blob = await blobFrom(destination, type);
40
+ registry.register(blob, destination);
41
+ return blob;
42
+ };
43
+ const createTemporaryFile = async (data, name, opts) => {
44
+ const blob = await createTemporaryBlob(data);
45
+ return new File([blob], name, opts);
46
+ };
47
+ class BlobDataItem {
48
+ #path;
49
+ #start;
50
+ size;
51
+ lastModified;
52
+ originalSize;
53
+ constructor(options) {
54
+ this.#path = options.path;
55
+ this.#start = options.start;
56
+ this.size = options.size;
57
+ this.lastModified = options.lastModified;
58
+ this.originalSize = options.originalSize === void 0 ? options.size : options.originalSize;
59
+ }
60
+ /**
61
+ * Slicing arguments is first validated and formatted
62
+ * to not be out of range by Blob.prototype.slice
63
+ */
64
+ slice(start, end) {
65
+ return new BlobDataItem({
66
+ path: this.#path,
67
+ lastModified: this.lastModified,
68
+ originalSize: this.originalSize,
69
+ size: end - start,
70
+ start: this.#start + start
71
+ });
72
+ }
73
+ async *stream() {
74
+ const { mtimeMs, size } = await stat(this.#path);
75
+ if (mtimeMs > this.lastModified || this.originalSize !== size) {
76
+ throw new DOMException("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", "NotReadableError");
77
+ }
78
+ yield* createReadStream(this.#path, {
79
+ start: this.#start,
80
+ end: this.#start + this.size - 1
81
+ });
82
+ }
83
+ get [Symbol.toStringTag]() {
84
+ return "Blob";
85
+ }
86
+ }
87
+ process.once("exit", () => {
88
+ tempDir && rmdirSync(tempDir, { recursive: true });
89
+ });
90
+ var blob_from_default = blobFromSync;
91
+ export {
92
+ Blob,
93
+ File,
94
+ blobFrom,
95
+ blobFromSync,
96
+ createTemporaryBlob,
97
+ createTemporaryFile,
98
+ blob_from_default as default,
99
+ fileFrom,
100
+ fileFromSync
101
+ };
@@ -0,0 +1,11 @@
1
+ const getSearch = (parsedURL) => {
2
+ if (parsedURL.search) {
3
+ return parsedURL.search;
4
+ }
5
+ const lastOffset = parsedURL.href.length - 1;
6
+ const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : "");
7
+ return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : "";
8
+ };
9
+ export {
10
+ getSearch
11
+ };
@@ -0,0 +1,7 @@
1
+ const redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
2
+ const isRedirect = (code) => {
3
+ return redirectStatus.has(code);
4
+ };
5
+ export {
6
+ isRedirect
7
+ };
@@ -0,0 +1,28 @@
1
+ import { URL } from "@gjsify/deno-runtime/ext/url/00_url";
2
+ const NAME = Symbol.toStringTag;
3
+ const isURLSearchParameters = (object) => {
4
+ return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams";
5
+ };
6
+ const isBlob = (value) => {
7
+ return value && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && typeof value.constructor === "function" && /^(Blob|File)$/.test(value[NAME]);
8
+ };
9
+ const isAbortSignal = (object) => {
10
+ return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget");
11
+ };
12
+ const isDomainOrSubdomain = (destination, original) => {
13
+ const orig = new URL(original).hostname;
14
+ const dest = new URL(destination).hostname;
15
+ return orig === dest || orig.endsWith(`.${dest}`);
16
+ };
17
+ const isSameProtocol = (destination, original) => {
18
+ const orig = new URL(original).protocol;
19
+ const dest = new URL(destination).protocol;
20
+ return orig === dest;
21
+ };
22
+ export {
23
+ isAbortSignal,
24
+ isBlob,
25
+ isDomainOrSubdomain,
26
+ isSameProtocol,
27
+ isURLSearchParameters
28
+ };
@@ -0,0 +1,353 @@
1
+ import { File } from "./blob-from.js";
2
+ import { FormData } from "formdata-polyfill/esm.min.js";
3
+ var S = /* @__PURE__ */ ((S2) => {
4
+ S2[S2["START_BOUNDARY"] = 0] = "START_BOUNDARY";
5
+ S2[S2["HEADER_FIELD_START"] = 1] = "HEADER_FIELD_START";
6
+ S2[S2["HEADER_FIELD"] = 2] = "HEADER_FIELD";
7
+ S2[S2["HEADER_VALUE_START"] = 3] = "HEADER_VALUE_START";
8
+ S2[S2["HEADER_VALUE"] = 4] = "HEADER_VALUE";
9
+ S2[S2["HEADER_VALUE_ALMOST_DONE"] = 5] = "HEADER_VALUE_ALMOST_DONE";
10
+ S2[S2["HEADERS_ALMOST_DONE"] = 6] = "HEADERS_ALMOST_DONE";
11
+ S2[S2["PART_DATA_START"] = 7] = "PART_DATA_START";
12
+ S2[S2["PART_DATA"] = 8] = "PART_DATA";
13
+ S2[S2["END"] = 9] = "END";
14
+ return S2;
15
+ })(S || {});
16
+ let f = 1;
17
+ const F = {
18
+ PART_BOUNDARY: f,
19
+ LAST_BOUNDARY: f *= 2
20
+ };
21
+ const LF = 10;
22
+ const CR = 13;
23
+ const SPACE = 32;
24
+ const HYPHEN = 45;
25
+ const COLON = 58;
26
+ const A = 97;
27
+ const Z = 122;
28
+ const lower = (c) => c | 32;
29
+ const noop = (...args) => {
30
+ };
31
+ class MultipartParser {
32
+ index = 0;
33
+ flags = 0;
34
+ boundary;
35
+ lookbehind;
36
+ state = 0 /* START_BOUNDARY */;
37
+ onHeaderEnd = noop;
38
+ onHeaderField = noop;
39
+ onHeadersEnd = noop;
40
+ onHeaderValue = noop;
41
+ onPartBegin = noop;
42
+ onPartData = noop;
43
+ onPartEnd = noop;
44
+ boundaryChars = {};
45
+ /**
46
+ * @param boundary
47
+ */
48
+ constructor(boundary) {
49
+ boundary = "\r\n--" + boundary;
50
+ const ui8a = new Uint8Array(boundary.length);
51
+ for (let i = 0; i < boundary.length; i++) {
52
+ ui8a[i] = boundary.charCodeAt(i);
53
+ this.boundaryChars[ui8a[i]] = true;
54
+ }
55
+ this.boundary = ui8a;
56
+ this.lookbehind = new Uint8Array(this.boundary.length + 8);
57
+ }
58
+ /**
59
+ * @param data
60
+ */
61
+ write(data) {
62
+ let i = 0;
63
+ const length_ = data.length;
64
+ let previousIndex = this.index;
65
+ let { lookbehind, boundary, boundaryChars, index, state, flags } = this;
66
+ const boundaryLength = this.boundary.length;
67
+ const boundaryEnd = boundaryLength - 1;
68
+ const bufferLength = data.length;
69
+ let c;
70
+ let cl;
71
+ const mark = (name) => {
72
+ this[name + "Mark"] = i;
73
+ };
74
+ const clear = (name) => {
75
+ delete this[name + "Mark"];
76
+ };
77
+ const callback = (callbackSymbol, start, end, ui8a) => {
78
+ if (start === void 0 || start !== end) {
79
+ this[callbackSymbol](ui8a && ui8a.subarray(start, end));
80
+ }
81
+ };
82
+ const dataCallback = (name, clear2 = false) => {
83
+ const markSymbol = name + "Mark";
84
+ if (!(markSymbol in this)) {
85
+ return;
86
+ }
87
+ if (clear2) {
88
+ callback(name, this[markSymbol], i, data);
89
+ delete this[markSymbol];
90
+ } else {
91
+ callback(name, this[markSymbol], data.length, data);
92
+ this[markSymbol] = 0;
93
+ }
94
+ };
95
+ for (i = 0; i < length_; i++) {
96
+ c = data[i];
97
+ switch (state) {
98
+ case 0 /* START_BOUNDARY */:
99
+ if (index === boundary.length - 2) {
100
+ if (c === HYPHEN) {
101
+ flags |= F.LAST_BOUNDARY;
102
+ } else if (c !== CR) {
103
+ return;
104
+ }
105
+ index++;
106
+ break;
107
+ } else if (index - 1 === boundary.length - 2) {
108
+ if (flags & F.LAST_BOUNDARY && c === HYPHEN) {
109
+ state = 9 /* END */;
110
+ flags = 0;
111
+ } else if (!(flags & F.LAST_BOUNDARY) && c === LF) {
112
+ index = 0;
113
+ callback("onPartBegin");
114
+ state = 1 /* HEADER_FIELD_START */;
115
+ } else {
116
+ return;
117
+ }
118
+ break;
119
+ }
120
+ if (c !== boundary[index + 2]) {
121
+ index = -2;
122
+ }
123
+ if (c === boundary[index + 2]) {
124
+ index++;
125
+ }
126
+ break;
127
+ case 1 /* HEADER_FIELD_START */:
128
+ state = 2 /* HEADER_FIELD */;
129
+ mark("onHeaderField");
130
+ index = 0;
131
+ case 2 /* HEADER_FIELD */:
132
+ if (c === CR) {
133
+ clear("onHeaderField");
134
+ state = 6 /* HEADERS_ALMOST_DONE */;
135
+ break;
136
+ }
137
+ index++;
138
+ if (c === HYPHEN) {
139
+ break;
140
+ }
141
+ if (c === COLON) {
142
+ if (index === 1) {
143
+ return;
144
+ }
145
+ dataCallback("onHeaderField", true);
146
+ state = 3 /* HEADER_VALUE_START */;
147
+ break;
148
+ }
149
+ cl = lower(c);
150
+ if (cl < A || cl > Z) {
151
+ return;
152
+ }
153
+ break;
154
+ case 3 /* HEADER_VALUE_START */:
155
+ if (c === SPACE) {
156
+ break;
157
+ }
158
+ mark("onHeaderValue");
159
+ state = 4 /* HEADER_VALUE */;
160
+ case 4 /* HEADER_VALUE */:
161
+ if (c === CR) {
162
+ dataCallback("onHeaderValue", true);
163
+ callback("onHeaderEnd");
164
+ state = 5 /* HEADER_VALUE_ALMOST_DONE */;
165
+ }
166
+ break;
167
+ case 5 /* HEADER_VALUE_ALMOST_DONE */:
168
+ if (c !== LF) {
169
+ return;
170
+ }
171
+ state = 1 /* HEADER_FIELD_START */;
172
+ break;
173
+ case 6 /* HEADERS_ALMOST_DONE */:
174
+ if (c !== LF) {
175
+ return;
176
+ }
177
+ callback("onHeadersEnd");
178
+ state = 7 /* PART_DATA_START */;
179
+ break;
180
+ case 7 /* PART_DATA_START */:
181
+ state = 8 /* PART_DATA */;
182
+ mark("onPartData");
183
+ case 8 /* PART_DATA */:
184
+ previousIndex = index;
185
+ if (index === 0) {
186
+ i += boundaryEnd;
187
+ while (i < bufferLength && !(data[i] in boundaryChars)) {
188
+ i += boundaryLength;
189
+ }
190
+ i -= boundaryEnd;
191
+ c = data[i];
192
+ }
193
+ if (index < boundary.length) {
194
+ if (boundary[index] === c) {
195
+ if (index === 0) {
196
+ dataCallback("onPartData", true);
197
+ }
198
+ index++;
199
+ } else {
200
+ index = 0;
201
+ }
202
+ } else if (index === boundary.length) {
203
+ index++;
204
+ if (c === CR) {
205
+ flags |= F.PART_BOUNDARY;
206
+ } else if (c === HYPHEN) {
207
+ flags |= F.LAST_BOUNDARY;
208
+ } else {
209
+ index = 0;
210
+ }
211
+ } else if (index - 1 === boundary.length) {
212
+ if (flags & F.PART_BOUNDARY) {
213
+ index = 0;
214
+ if (c === LF) {
215
+ flags &= ~F.PART_BOUNDARY;
216
+ callback("onPartEnd");
217
+ callback("onPartBegin");
218
+ state = 1 /* HEADER_FIELD_START */;
219
+ break;
220
+ }
221
+ } else if (flags & F.LAST_BOUNDARY) {
222
+ if (c === HYPHEN) {
223
+ callback("onPartEnd");
224
+ state = 9 /* END */;
225
+ flags = 0;
226
+ } else {
227
+ index = 0;
228
+ }
229
+ } else {
230
+ index = 0;
231
+ }
232
+ }
233
+ if (index > 0) {
234
+ lookbehind[index - 1] = c;
235
+ } else if (previousIndex > 0) {
236
+ const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);
237
+ callback("onPartData", 0, previousIndex, _lookbehind);
238
+ previousIndex = 0;
239
+ mark("onPartData");
240
+ i--;
241
+ }
242
+ break;
243
+ case 9 /* END */:
244
+ break;
245
+ default:
246
+ throw new Error(`Unexpected state entered: ${state}`);
247
+ }
248
+ }
249
+ dataCallback("onHeaderField");
250
+ dataCallback("onHeaderValue");
251
+ dataCallback("onPartData");
252
+ this.index = index;
253
+ this.state = state;
254
+ this.flags = flags;
255
+ }
256
+ end() {
257
+ if (this.state === 1 /* HEADER_FIELD_START */ && this.index === 0 || this.state === 8 /* PART_DATA */ && this.index === this.boundary.length) {
258
+ this.onPartEnd();
259
+ } else if (this.state !== 9 /* END */) {
260
+ throw new Error("MultipartParser.end(): stream ended unexpectedly");
261
+ }
262
+ }
263
+ }
264
+ function _fileName(headerValue) {
265
+ const m = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
266
+ if (!m) {
267
+ return;
268
+ }
269
+ const match = m[2] || m[3] || "";
270
+ let filename = match.slice(match.lastIndexOf("\\") + 1);
271
+ filename = filename.replace(/%22/g, '"');
272
+ filename = filename.replace(/&#(\d{4});/g, (m2, code) => {
273
+ return String.fromCharCode(code);
274
+ });
275
+ return filename;
276
+ }
277
+ async function toFormData(Body, ct) {
278
+ if (!/multipart/i.test(ct)) {
279
+ throw new TypeError("Failed to fetch");
280
+ }
281
+ const m = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
282
+ if (!m) {
283
+ throw new TypeError("no or bad content-type header, no multipart boundary");
284
+ }
285
+ const parser = new MultipartParser(m[1] || m[2]);
286
+ let headerField;
287
+ let headerValue;
288
+ let entryValue;
289
+ let entryName;
290
+ let contentType;
291
+ let filename;
292
+ const entryChunks = [];
293
+ const formData = new FormData();
294
+ const onPartData = (ui8a) => {
295
+ entryValue += decoder.decode(ui8a, { stream: true });
296
+ };
297
+ const appendToFile = (ui8a) => {
298
+ entryChunks.push(ui8a);
299
+ };
300
+ const appendFileToFormData = () => {
301
+ const file = new File(entryChunks, filename, { type: contentType });
302
+ formData.append(entryName, file);
303
+ };
304
+ const appendEntryToFormData = () => {
305
+ formData.append(entryName, entryValue);
306
+ };
307
+ const decoder = new TextDecoder("utf-8");
308
+ decoder.decode();
309
+ parser.onPartBegin = function() {
310
+ parser.onPartData = onPartData;
311
+ parser.onPartEnd = appendEntryToFormData;
312
+ headerField = "";
313
+ headerValue = "";
314
+ entryValue = "";
315
+ entryName = "";
316
+ contentType = "";
317
+ filename = null;
318
+ entryChunks.length = 0;
319
+ };
320
+ parser.onHeaderField = function(ui8a) {
321
+ headerField += decoder.decode(ui8a, { stream: true });
322
+ };
323
+ parser.onHeaderValue = function(ui8a) {
324
+ headerValue += decoder.decode(ui8a, { stream: true });
325
+ };
326
+ parser.onHeaderEnd = function() {
327
+ headerValue += decoder.decode();
328
+ headerField = headerField.toLowerCase();
329
+ if (headerField === "content-disposition") {
330
+ const m2 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);
331
+ if (m2) {
332
+ entryName = m2[2] || m2[3] || "";
333
+ }
334
+ filename = _fileName(headerValue);
335
+ if (filename) {
336
+ parser.onPartData = appendToFile;
337
+ parser.onPartEnd = appendFileToFormData;
338
+ }
339
+ } else if (headerField === "content-type") {
340
+ contentType = headerValue;
341
+ }
342
+ headerValue = "";
343
+ headerField = "";
344
+ };
345
+ for await (const chunk of Body) {
346
+ parser.write(chunk);
347
+ }
348
+ parser.end();
349
+ return formData;
350
+ }
351
+ export {
352
+ toFormData
353
+ };
@@ -0,0 +1,153 @@
1
+ import { URL } from "@gjsify/deno-runtime/ext/url/00_url";
2
+ import { isIP } from "net";
3
+ function stripURLForUseAsAReferrer(url, originOnly = false) {
4
+ if (url == null || url === "no-referrer") {
5
+ return "no-referrer";
6
+ }
7
+ url = new URL(url);
8
+ if (/^(about|blob|data):$/.test(url.protocol)) {
9
+ return "no-referrer";
10
+ }
11
+ url.username = "";
12
+ url.password = "";
13
+ url.hash = "";
14
+ if (originOnly) {
15
+ url.pathname = "";
16
+ url.search = "";
17
+ }
18
+ return url;
19
+ }
20
+ const ReferrerPolicy = /* @__PURE__ */ new Set([
21
+ "",
22
+ "no-referrer",
23
+ "no-referrer-when-downgrade",
24
+ "same-origin",
25
+ "origin",
26
+ "strict-origin",
27
+ "origin-when-cross-origin",
28
+ "strict-origin-when-cross-origin",
29
+ "unsafe-url"
30
+ ]);
31
+ const DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin";
32
+ function validateReferrerPolicy(referrerPolicy) {
33
+ if (!ReferrerPolicy.has(referrerPolicy)) {
34
+ throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
35
+ }
36
+ return referrerPolicy;
37
+ }
38
+ function isOriginPotentiallyTrustworthy(url) {
39
+ if (/^(http|ws)s:$/.test(url.protocol)) {
40
+ return true;
41
+ }
42
+ const hostIp = url.host.replace(/(^\[)|(]$)/g, "");
43
+ const hostIPVersion = isIP(hostIp);
44
+ if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
45
+ return true;
46
+ }
47
+ if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
48
+ return true;
49
+ }
50
+ if (url.host === "localhost" || url.host.endsWith(".localhost")) {
51
+ return false;
52
+ }
53
+ if (url.protocol === "file:") {
54
+ return true;
55
+ }
56
+ return false;
57
+ }
58
+ function isUrlPotentiallyTrustworthy(url) {
59
+ if (/^about:(blank|srcdoc)$/.test(url.toString())) {
60
+ return true;
61
+ }
62
+ if (typeof url === "string") {
63
+ url = new URL(url);
64
+ }
65
+ if (url.protocol === "data:") {
66
+ return true;
67
+ }
68
+ if (/^(blob|filesystem):$/.test(url.protocol)) {
69
+ return true;
70
+ }
71
+ return isOriginPotentiallyTrustworthy(url);
72
+ }
73
+ function determineRequestsReferrer(request, obj = {}) {
74
+ const { referrerURLCallback, referrerOriginCallback } = obj;
75
+ if (request.referrer === "no-referrer" || request.referrerPolicy === "") {
76
+ return null;
77
+ }
78
+ const policy = request.referrerPolicy;
79
+ if (request.referrer === "about:client") {
80
+ return "no-referrer";
81
+ }
82
+ const referrerSource = new URL(request.referrer);
83
+ let referrerURL = stripURLForUseAsAReferrer(referrerSource);
84
+ let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);
85
+ if (referrerURL.toString().length > 4096) {
86
+ referrerURL = referrerOrigin;
87
+ }
88
+ if (referrerURLCallback) {
89
+ referrerURL = referrerURLCallback(referrerURL);
90
+ }
91
+ if (referrerOriginCallback) {
92
+ referrerOrigin = referrerOriginCallback(referrerOrigin);
93
+ }
94
+ const currentURL = new URL(request.url);
95
+ switch (policy) {
96
+ case "no-referrer":
97
+ return "no-referrer";
98
+ case "origin":
99
+ return referrerOrigin;
100
+ case "unsafe-url":
101
+ return referrerURL;
102
+ case "strict-origin":
103
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
104
+ return "no-referrer";
105
+ }
106
+ return referrerOrigin.toString();
107
+ case "strict-origin-when-cross-origin":
108
+ if (referrerURL.origin === currentURL.origin) {
109
+ return referrerURL;
110
+ }
111
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
112
+ return "no-referrer";
113
+ }
114
+ return referrerOrigin;
115
+ case "same-origin":
116
+ if (referrerURL.origin === currentURL.origin) {
117
+ return referrerURL;
118
+ }
119
+ return "no-referrer";
120
+ case "origin-when-cross-origin":
121
+ if (referrerURL.origin === currentURL.origin) {
122
+ return referrerURL;
123
+ }
124
+ return referrerOrigin;
125
+ case "no-referrer-when-downgrade":
126
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
127
+ return "no-referrer";
128
+ }
129
+ return referrerURL;
130
+ default:
131
+ throw new TypeError(`Invalid referrerPolicy: ${policy}`);
132
+ }
133
+ }
134
+ function parseReferrerPolicyFromHeader(headers) {
135
+ const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
136
+ let policy = "";
137
+ for (const token of policyTokens) {
138
+ if (token && ReferrerPolicy.has(token)) {
139
+ policy = token;
140
+ }
141
+ }
142
+ return policy;
143
+ }
144
+ export {
145
+ DEFAULT_REFERRER_POLICY,
146
+ ReferrerPolicy,
147
+ determineRequestsReferrer,
148
+ isOriginPotentiallyTrustworthy,
149
+ isUrlPotentiallyTrustworthy,
150
+ parseReferrerPolicyFromHeader,
151
+ stripURLForUseAsAReferrer,
152
+ validateReferrerPolicy
153
+ };