@gjsify/fetch 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +27 -2
  2. package/globals.mjs +12 -0
  3. package/lib/body.d.ts +69 -0
  4. package/lib/body.js +375 -0
  5. package/lib/errors/abort-error.d.ts +7 -0
  6. package/lib/errors/abort-error.js +9 -0
  7. package/lib/errors/base.d.ts +6 -0
  8. package/lib/errors/base.js +17 -0
  9. package/lib/errors/fetch-error.d.ts +16 -0
  10. package/lib/errors/fetch-error.js +23 -0
  11. package/lib/esm/body.js +104 -56
  12. package/lib/esm/errors/base.js +3 -1
  13. package/lib/esm/headers.js +116 -131
  14. package/lib/esm/index.js +145 -190
  15. package/lib/esm/request.js +42 -41
  16. package/lib/esm/response.js +19 -4
  17. package/lib/esm/utils/blob-from.js +2 -98
  18. package/lib/esm/utils/data-uri.js +23 -0
  19. package/lib/esm/utils/is.js +7 -3
  20. package/lib/esm/utils/multipart-parser.js +5 -2
  21. package/lib/esm/utils/referrer.js +10 -10
  22. package/lib/esm/utils/soup-helpers.js +22 -0
  23. package/lib/headers.d.ts +33 -0
  24. package/lib/headers.js +195 -0
  25. package/lib/index.d.ts +18 -0
  26. package/lib/index.js +205 -0
  27. package/lib/request.d.ts +101 -0
  28. package/lib/request.js +308 -0
  29. package/lib/response.d.ts +73 -0
  30. package/lib/response.js +158 -0
  31. package/lib/types/index.d.ts +1 -0
  32. package/lib/types/index.js +1 -0
  33. package/lib/types/system-error.d.ts +11 -0
  34. package/lib/types/system-error.js +2 -0
  35. package/lib/utils/blob-from.d.ts +2 -0
  36. package/lib/utils/blob-from.js +4 -0
  37. package/lib/utils/data-uri.d.ts +10 -0
  38. package/lib/utils/data-uri.js +27 -0
  39. package/lib/utils/get-search.d.ts +1 -0
  40. package/lib/utils/get-search.js +8 -0
  41. package/lib/utils/is-redirect.d.ts +7 -0
  42. package/lib/utils/is-redirect.js +10 -0
  43. package/lib/utils/is.d.ts +35 -0
  44. package/lib/utils/is.js +74 -0
  45. package/lib/utils/multipart-parser.d.ts +2 -0
  46. package/lib/utils/multipart-parser.js +396 -0
  47. package/lib/utils/referrer.d.ts +76 -0
  48. package/lib/utils/referrer.js +283 -0
  49. package/lib/utils/soup-helpers.d.ts +12 -0
  50. package/lib/utils/soup-helpers.js +25 -0
  51. package/package.json +23 -27
  52. package/src/body.ts +181 -169
  53. package/src/errors/base.ts +3 -1
  54. package/src/headers.ts +155 -202
  55. package/src/index.spec.ts +268 -3
  56. package/src/index.ts +199 -312
  57. package/src/request.ts +84 -75
  58. package/src/response.ts +48 -18
  59. package/src/test.mts +1 -1
  60. package/src/utils/blob-from.ts +4 -164
  61. package/src/utils/data-uri.ts +29 -0
  62. package/src/utils/is.ts +15 -15
  63. package/src/utils/multipart-parser.ts +3 -3
  64. package/src/utils/referrer.ts +11 -11
  65. package/src/utils/soup-helpers.ts +37 -0
  66. package/tsconfig.json +5 -5
  67. package/tsconfig.tsbuildinfo +1 -0
  68. package/lib/cjs/body.js +0 -255
  69. package/lib/cjs/errors/abort-error.js +0 -9
  70. package/lib/cjs/errors/base.js +0 -17
  71. package/lib/cjs/errors/fetch-error.js +0 -21
  72. package/lib/cjs/headers.js +0 -202
  73. package/lib/cjs/index.js +0 -224
  74. package/lib/cjs/request.js +0 -281
  75. package/lib/cjs/response.js +0 -133
  76. package/lib/cjs/types/index.js +0 -1
  77. package/lib/cjs/types/system-error.js +0 -1
  78. package/lib/cjs/utils/blob-from.js +0 -101
  79. package/lib/cjs/utils/get-search.js +0 -11
  80. package/lib/cjs/utils/is-redirect.js +0 -7
  81. package/lib/cjs/utils/is.js +0 -28
  82. package/lib/cjs/utils/multipart-parser.js +0 -353
  83. package/lib/cjs/utils/referrer.js +0 -153
  84. package/test.gjs.js +0 -34758
  85. package/test.gjs.mjs +0 -53177
  86. package/test.node.js +0 -1226
  87. package/test.node.mjs +0 -6294
  88. package/tsconfig.types.json +0 -8
@@ -0,0 +1,158 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Adapted from node-fetch (https://github.com/node-fetch/node-fetch/blob/main/src/response.js)
3
+ // Copyright (c) node-fetch contributors. MIT license.
4
+ // Modifications: Rewritten for GJS using Gio streams and GLib
5
+ import GLib from '@girs/glib-2.0';
6
+ import Gio from '@girs/gio-2.0';
7
+ import Headers from './headers.js';
8
+ import Body, { clone, extractContentType } from './body.js';
9
+ import { isRedirect } from './utils/is-redirect.js';
10
+ import { URL } from '@gjsify/url';
11
+ const INTERNALS = Symbol('Response internals');
12
+ /**
13
+ * Response class
14
+ *
15
+ * Ref: https://fetch.spec.whatwg.org/#response-class
16
+ *
17
+ * @param body Readable stream
18
+ * @param opts Response options
19
+ */
20
+ export class Response extends Body {
21
+ [INTERNALS];
22
+ _inputStream = null;
23
+ constructor(body = null, options = {}) {
24
+ super(body, options);
25
+ // eslint-disable-next-line no-eq-null, eqeqeq, no-negated-condition
26
+ const status = options.status != null ? options.status : 200;
27
+ const headers = new Headers(options.headers);
28
+ if (body !== null && !headers.has('Content-Type')) {
29
+ const contentType = extractContentType(body, this);
30
+ if (contentType) {
31
+ headers.append('Content-Type', contentType);
32
+ }
33
+ }
34
+ this[INTERNALS] = {
35
+ type: 'default',
36
+ url: options.url,
37
+ status,
38
+ statusText: options.statusText || '',
39
+ headers,
40
+ counter: options.counter,
41
+ highWaterMark: options.highWaterMark
42
+ };
43
+ }
44
+ get type() {
45
+ return this[INTERNALS].type;
46
+ }
47
+ get url() {
48
+ return this[INTERNALS].url || '';
49
+ }
50
+ get status() {
51
+ return this[INTERNALS].status;
52
+ }
53
+ /**
54
+ * Convenience property representing if the request ended normally
55
+ */
56
+ get ok() {
57
+ return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300;
58
+ }
59
+ get redirected() {
60
+ return this[INTERNALS].counter > 0;
61
+ }
62
+ get statusText() {
63
+ return this[INTERNALS].statusText;
64
+ }
65
+ get headers() {
66
+ return this[INTERNALS].headers;
67
+ }
68
+ get highWaterMark() {
69
+ return this[INTERNALS].highWaterMark;
70
+ }
71
+ /**
72
+ * Clone this response
73
+ *
74
+ * @return Response
75
+ */
76
+ clone() {
77
+ return new Response(clone(this, this.highWaterMark), {
78
+ type: this.type,
79
+ url: this.url,
80
+ status: this.status,
81
+ statusText: this.statusText,
82
+ headers: this.headers,
83
+ ok: this.ok,
84
+ redirected: this.redirected,
85
+ size: this.size,
86
+ highWaterMark: this.highWaterMark
87
+ });
88
+ }
89
+ /**
90
+ * @param url The URL that the new response is to originate from.
91
+ * @param status An optional status code for the response (e.g., 302.)
92
+ * @returns A Response object.
93
+ */
94
+ static redirect(url, status = 302) {
95
+ if (!isRedirect(status)) {
96
+ throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
97
+ }
98
+ return new Response(null, {
99
+ headers: {
100
+ location: new URL(url).toString()
101
+ },
102
+ status
103
+ });
104
+ }
105
+ static error() {
106
+ const response = new Response(null, { status: 0, statusText: '' });
107
+ response[INTERNALS].type = 'error';
108
+ return response;
109
+ }
110
+ /**
111
+ * Create a Response with a JSON body.
112
+ * @param data The data to serialize as JSON.
113
+ * @param init Optional response init options.
114
+ * @returns A Response with the JSON body and appropriate content-type header.
115
+ */
116
+ static json(data, init) {
117
+ const body = JSON.stringify(data);
118
+ const options = { ...init };
119
+ const headers = new Headers(options.headers);
120
+ if (!headers.has('content-type')) {
121
+ headers.set('content-type', 'application/json');
122
+ }
123
+ options.headers = headers;
124
+ return new Response(body, options);
125
+ }
126
+ get [Symbol.toStringTag]() {
127
+ return 'Response';
128
+ }
129
+ async text() {
130
+ if (!this._inputStream) {
131
+ return super.text();
132
+ }
133
+ const outputStream = Gio.MemoryOutputStream.new_resizable();
134
+ await new Promise((resolve, reject) => {
135
+ outputStream.splice_async(this._inputStream, Gio.OutputStreamSpliceFlags.CLOSE_TARGET | Gio.OutputStreamSpliceFlags.CLOSE_SOURCE, GLib.PRIORITY_DEFAULT, null, (_self, res) => {
136
+ try {
137
+ resolve(outputStream.splice_finish(res));
138
+ }
139
+ catch (error) {
140
+ reject(error);
141
+ }
142
+ });
143
+ });
144
+ const bytes = outputStream.steal_as_bytes();
145
+ return new TextDecoder().decode(bytes.toArray());
146
+ }
147
+ }
148
+ Object.defineProperties(Response.prototype, {
149
+ type: { enumerable: true },
150
+ url: { enumerable: true },
151
+ status: { enumerable: true },
152
+ ok: { enumerable: true },
153
+ redirected: { enumerable: true },
154
+ statusText: { enumerable: true },
155
+ headers: { enumerable: true },
156
+ clone: { enumerable: true }
157
+ });
158
+ export default Response;
@@ -0,0 +1 @@
1
+ export * from './system-error.js';
@@ -0,0 +1 @@
1
+ export * from './system-error.js';
@@ -0,0 +1,11 @@
1
+ export interface SystemError {
2
+ address?: string;
3
+ code: string;
4
+ dest?: string;
5
+ errno: number;
6
+ info?: object;
7
+ message: string;
8
+ path?: string;
9
+ port?: number;
10
+ syscall: string;
11
+ }
@@ -0,0 +1,2 @@
1
+ ;
2
+ export {};
@@ -0,0 +1,2 @@
1
+ import { Blob, File } from 'node:buffer';
2
+ export { Blob, File, };
@@ -0,0 +1,4 @@
1
+ // Re-export Blob/File from buffer (which provides the polyfill on GJS)
2
+ // Reference: Node.js buffer.Blob (available since v18)
3
+ import { Blob, File } from 'node:buffer';
4
+ export { Blob, File, };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Parse a data: URI into its components.
3
+ * Replaces the `data-uri-to-buffer` npm package.
4
+ *
5
+ * Format: data:[<mediatype>][;base64],<data>
6
+ */
7
+ export declare function parseDataUri(uri: string): {
8
+ buffer: Uint8Array;
9
+ typeFull: string;
10
+ };
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Parse a data: URI into its components.
3
+ * Replaces the `data-uri-to-buffer` npm package.
4
+ *
5
+ * Format: data:[<mediatype>][;base64],<data>
6
+ */
7
+ export function parseDataUri(uri) {
8
+ const match = uri.match(/^data:([^,]*?)(;base64)?,(.*)$/s);
9
+ if (!match) {
10
+ throw new TypeError(`Invalid data URI: ${uri.slice(0, 50)}...`);
11
+ }
12
+ const typeFull = match[1] || 'text/plain;charset=US-ASCII';
13
+ const isBase64 = !!match[2];
14
+ const data = match[3];
15
+ let buffer;
16
+ if (isBase64) {
17
+ const binaryString = atob(data);
18
+ buffer = new Uint8Array(binaryString.length);
19
+ for (let i = 0; i < binaryString.length; i++) {
20
+ buffer[i] = binaryString.charCodeAt(i);
21
+ }
22
+ }
23
+ else {
24
+ buffer = new TextEncoder().encode(decodeURIComponent(data));
25
+ }
26
+ return { buffer, typeFull };
27
+ }
@@ -0,0 +1 @@
1
+ export declare const getSearch: (parsedURL: URL) => string;
@@ -0,0 +1,8 @@
1
+ export 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
+ };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Redirect code matching
3
+ *
4
+ * @param {number} code - Status code
5
+ * @return {boolean}
6
+ */
7
+ export declare const isRedirect: (code: any) => boolean;
@@ -0,0 +1,10 @@
1
+ const redirectStatus = new Set([301, 302, 303, 307, 308]);
2
+ /**
3
+ * Redirect code matching
4
+ *
5
+ * @param {number} code - Status code
6
+ * @return {boolean}
7
+ */
8
+ export const isRedirect = code => {
9
+ return redirectStatus.has(code);
10
+ };
@@ -0,0 +1,35 @@
1
+ import { Blob } from './blob-from.js';
2
+ /**
3
+ * Check if `obj` is a URLSearchParams object
4
+ * ref: https://github.com/node-fetch/node-fetch/issues/296#issuecomment-307598143
5
+ * @param {*} object - Object to check for
6
+ * @return {boolean}
7
+ */
8
+ export declare const isURLSearchParameters: (object: any) => boolean;
9
+ /**
10
+ * Check if `object` is a W3C `Blob` object (which `File` inherits from)
11
+ * @param object Object to check for
12
+ */
13
+ export declare const isBlob: (value: unknown) => value is Blob;
14
+ /**
15
+ * Check if `obj` is an instance of AbortSignal.
16
+ * @param object - Object to check for
17
+ */
18
+ export declare const isAbortSignal: (object: unknown) => object is AbortSignal;
19
+ /**
20
+ * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of
21
+ * the parent domain.
22
+ *
23
+ * Both domains must already be in canonical form.
24
+ * @param {string|URL} original
25
+ * @param {string|URL} destination
26
+ */
27
+ export declare const isDomainOrSubdomain: (destination: any, original: any) => boolean;
28
+ /**
29
+ * isSameProtocol reports whether the two provided URLs use the same protocol.
30
+ *
31
+ * Both domains must already be in canonical form.
32
+ * @param {string|URL} original
33
+ * @param {string|URL} destination
34
+ */
35
+ export declare const isSameProtocol: (destination: any, original: any) => boolean;
@@ -0,0 +1,74 @@
1
+ import { URL } from '@gjsify/url';
2
+ /**
3
+ * Is.js
4
+ *
5
+ * Object type checks.
6
+ */
7
+ const NAME = Symbol.toStringTag;
8
+ /**
9
+ * Check if `obj` is a URLSearchParams object
10
+ * ref: https://github.com/node-fetch/node-fetch/issues/296#issuecomment-307598143
11
+ * @param {*} object - Object to check for
12
+ * @return {boolean}
13
+ */
14
+ export const isURLSearchParameters = object => {
15
+ return (typeof object === 'object' &&
16
+ typeof object.append === 'function' &&
17
+ typeof object.delete === 'function' &&
18
+ typeof object.get === 'function' &&
19
+ typeof object.getAll === 'function' &&
20
+ typeof object.has === 'function' &&
21
+ typeof object.set === 'function' &&
22
+ typeof object.sort === 'function' &&
23
+ object[NAME] === 'URLSearchParams');
24
+ };
25
+ /**
26
+ * Check if `object` is a W3C `Blob` object (which `File` inherits from)
27
+ * @param object Object to check for
28
+ */
29
+ export const isBlob = (value) => {
30
+ if (!value || typeof value !== 'object')
31
+ return false;
32
+ const obj = value;
33
+ return (typeof obj.arrayBuffer === 'function' &&
34
+ typeof obj.type === 'string' &&
35
+ typeof obj.stream === 'function' &&
36
+ typeof obj.constructor === 'function' &&
37
+ /^(Blob|File)$/.test(obj[NAME]));
38
+ };
39
+ /**
40
+ * Check if `obj` is an instance of AbortSignal.
41
+ * @param object - Object to check for
42
+ */
43
+ export const isAbortSignal = (object) => {
44
+ if (typeof object !== 'object' || object === null)
45
+ return false;
46
+ const obj = object;
47
+ return (obj[NAME] === 'AbortSignal' ||
48
+ obj[NAME] === 'EventTarget');
49
+ };
50
+ /**
51
+ * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of
52
+ * the parent domain.
53
+ *
54
+ * Both domains must already be in canonical form.
55
+ * @param {string|URL} original
56
+ * @param {string|URL} destination
57
+ */
58
+ export const isDomainOrSubdomain = (destination, original) => {
59
+ const orig = new URL(original).hostname;
60
+ const dest = new URL(destination).hostname;
61
+ return orig === dest || orig.endsWith(`.${dest}`);
62
+ };
63
+ /**
64
+ * isSameProtocol reports whether the two provided URLs use the same protocol.
65
+ *
66
+ * Both domains must already be in canonical form.
67
+ * @param {string|URL} original
68
+ * @param {string|URL} destination
69
+ */
70
+ export const isSameProtocol = (destination, original) => {
71
+ const orig = new URL(original).protocol;
72
+ const dest = new URL(destination).protocol;
73
+ return orig === dest;
74
+ };
@@ -0,0 +1,2 @@
1
+ import { FormData } from '@gjsify/formdata';
2
+ export declare function toFormData(Body: any, ct: any): Promise<FormData>;