@sapphire/fetch 2.0.4 → 2.1.0-next.365a53a.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.
package/README.md CHANGED
@@ -165,6 +165,10 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
165
165
  <td align="center"><a href="https://gitlab.com/DavidPH/"><img src="https://avatars.githubusercontent.com/u/44669930?v=4?s=100" width="100px;" alt=""/><br /><sub><b>David</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=DavidPHH" title="Code">💻</a></td>
166
166
  <td align="center"><a href="https://github.com/apps/renovate"><img src="https://avatars.githubusercontent.com/in/2740?v=4?s=100" width="100px;" alt=""/><br /><sub><b>renovate[bot]</b></sub></a><br /><a href="#maintenance-renovate[bot]" title="Maintenance">🚧</a></td>
167
167
  <td align="center"><a href="https://renovate.whitesourcesoftware.com/"><img src="https://avatars.githubusercontent.com/u/25180681?v=4?s=100" width="100px;" alt=""/><br /><sub><b>WhiteSource Renovate</b></sub></a><br /><a href="#maintenance-renovate-bot" title="Maintenance">🚧</a></td>
168
+ <td align="center"><a href="https://fc5570.me/"><img src="https://avatars.githubusercontent.com/u/68158483?v=4?s=100" width="100px;" alt=""/><br /><sub><b>FC</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=FC5570" title="Code">💻</a></td>
169
+ <td align="center"><a href="https://github.com/Tokipudi"><img src="https://avatars.githubusercontent.com/u/29551076?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jérémy de Saint Denis</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Tokipudi" title="Code">💻</a></td>
170
+ <td align="center"><a href="https://github.com/ItsMrCube"><img src="https://avatars.githubusercontent.com/u/25201357?v=4?s=100" width="100px;" alt=""/><br /><sub><b>MrCube</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=ItsMrCube" title="Code">💻</a></td>
171
+ <td align="center"><a href="https://github.com/bitomic"><img src="https://avatars.githubusercontent.com/u/35199700?v=4?s=100" width="100px;" alt=""/><br /><sub><b>bitomic</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=bitomic" title="Code">💻</a></td>
168
172
  </tr>
169
173
  </table>
170
174
 
@@ -0,0 +1,136 @@
1
+ var SapphireFetch = (() => {
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __reExport = (target, module, copyDefault, desc) => {
14
+ if (module && typeof module === "object" || typeof module === "function") {
15
+ for (let key of __getOwnPropNames(module))
16
+ if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
17
+ __defProp(target, key, { get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable });
18
+ }
19
+ return target;
20
+ };
21
+ var __toCommonJS = /* @__PURE__ */ ((cache) => {
22
+ return (module, temp) => {
23
+ return cache && cache.get(module) || (temp = __reExport(__markAsModule({}), module, 1), cache && cache.set(module, temp), temp);
24
+ };
25
+ })(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
26
+ var __publicField = (obj, key, value) => {
27
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
28
+ return value;
29
+ };
30
+ var __accessCheck = (obj, member, msg) => {
31
+ if (!member.has(obj))
32
+ throw TypeError("Cannot " + msg);
33
+ };
34
+ var __privateGet = (obj, member, getter) => {
35
+ __accessCheck(obj, member, "read from private field");
36
+ return getter ? getter.call(obj) : member.get(obj);
37
+ };
38
+ var __privateAdd = (obj, member, value) => {
39
+ if (member.has(obj))
40
+ throw TypeError("Cannot add the same private member more than once");
41
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
42
+ };
43
+ var __privateSet = (obj, member, value, setter) => {
44
+ __accessCheck(obj, member, "write to private field");
45
+ setter ? setter.call(obj, value) : member.set(obj, value);
46
+ return value;
47
+ };
48
+
49
+ // src/index.ts
50
+ var src_exports = {};
51
+ __export(src_exports, {
52
+ FetchMethods: () => FetchMethods,
53
+ FetchResultTypes: () => FetchResultTypes,
54
+ QueryError: () => QueryError,
55
+ fetch: () => fetch
56
+ });
57
+
58
+ // src/lib/QueryError.ts
59
+ var _json;
60
+ var QueryError = class extends Error {
61
+ constructor(url, code, response, body) {
62
+ super(`Failed to request '${url}' with code ${code}.`);
63
+ __publicField(this, "url");
64
+ __publicField(this, "code");
65
+ __publicField(this, "body");
66
+ __publicField(this, "response");
67
+ __privateAdd(this, _json, void 0);
68
+ this.url = url;
69
+ this.code = code;
70
+ this.body = body;
71
+ this.response = response;
72
+ __privateSet(this, _json, null);
73
+ }
74
+ toJSON() {
75
+ return __privateGet(this, _json) ?? __privateSet(this, _json, JSON.parse(this.body));
76
+ }
77
+ };
78
+ __name(QueryError, "QueryError");
79
+ _json = new WeakMap();
80
+
81
+ // src/lib/types.ts
82
+ var FetchResultTypes = /* @__PURE__ */ ((FetchResultTypes2) => {
83
+ FetchResultTypes2["JSON"] = "json";
84
+ FetchResultTypes2["Buffer"] = "buffer";
85
+ FetchResultTypes2["Blob"] = "blob";
86
+ FetchResultTypes2["Text"] = "text";
87
+ FetchResultTypes2["Result"] = "result";
88
+ return FetchResultTypes2;
89
+ })(FetchResultTypes || {});
90
+ var FetchMethods = /* @__PURE__ */ ((FetchMethods2) => {
91
+ FetchMethods2["Get"] = "GET";
92
+ FetchMethods2["Head"] = "HEAD";
93
+ FetchMethods2["Post"] = "POST";
94
+ FetchMethods2["Put"] = "PUT";
95
+ FetchMethods2["Delete"] = "DELETE";
96
+ FetchMethods2["Connect"] = "CONNECT";
97
+ FetchMethods2["Options"] = "OPTIONS";
98
+ FetchMethods2["Trace"] = "TRACE";
99
+ FetchMethods2["Patch"] = "PATCH";
100
+ return FetchMethods2;
101
+ })(FetchMethods || {});
102
+
103
+ // src/lib/fetch.ts
104
+ async function fetch(url, options, type) {
105
+ if (typeof options === "undefined") {
106
+ options = {};
107
+ type = "json" /* JSON */;
108
+ } else if (typeof options === "string") {
109
+ type = options;
110
+ options = {};
111
+ } else if (typeof type === "undefined") {
112
+ type = "json" /* JSON */;
113
+ }
114
+ const stringUrl = String(url);
115
+ const result = await globalThis.fetch(stringUrl, options);
116
+ if (!result.ok)
117
+ throw new QueryError(stringUrl, result.status, result, await result.clone().text());
118
+ switch (type) {
119
+ case "result" /* Result */:
120
+ return result;
121
+ case "buffer" /* Buffer */:
122
+ return Buffer.from(await (await result.blob()).arrayBuffer());
123
+ case "blob" /* Blob */:
124
+ return result.blob();
125
+ case "json" /* JSON */:
126
+ return result.json();
127
+ case "text" /* Text */:
128
+ return result.text();
129
+ default:
130
+ throw new Error(`Unknown type "${type}"`);
131
+ }
132
+ }
133
+ __name(fetch, "fetch");
134
+ return __toCommonJS(src_exports);
135
+ })();
136
+ //# sourceMappingURL=index.global.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/lib/QueryError.ts","../src/lib/types.ts","../src/lib/fetch.ts"],"sourcesContent":["export * from './lib/fetch';\nexport * from './lib/QueryError';\nexport * from './lib/types';\n","// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\n/**\n * The QueryError class which is thrown by the `fetch` method\n */\nexport class QueryError extends Error {\n\t/** The requested url. */\n\tpublic readonly url: string;\n\t/** The HTTP status code. */\n\tpublic readonly code: number;\n\t/** The returned response body as a string */\n\tpublic readonly body: string;\n\t/** The original {@link Response} object */\n\tpublic readonly response: Response;\n\n\t#json: unknown;\n\n\tpublic constructor(url: string, code: number, response: Response, body: string) {\n\t\tsuper(`Failed to request '${url}' with code ${code}.`);\n\t\tthis.url = url;\n\t\tthis.code = code;\n\t\tthis.body = body;\n\t\tthis.response = response;\n\t\tthis.#json = null;\n\t}\n\n\tpublic toJSON() {\n\t\treturn this.#json ?? (this.#json = JSON.parse(this.body));\n\t}\n}\n","/**\n * The supported return types for the `fetch` method\n */\nexport const enum FetchResultTypes {\n\t/**\n\t * Returns only the body, as JSON. Similar to [`Body.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json).\n\t *\n\t * You should provide your own type cast (either through the generic return type, or with `as <type>`) to the response to define\n\t * the JSON structure, otherwise the result will be `unknown`.\n\t */\n\tJSON = 'json',\n\t/**\n\t * Returns only the body, as a [Buffer](https://nodejs.org/api/buffer.html).\n\t * @remark Does not work in a Browser environment. For browsers use {@link FetchResultTypes.Blob} instead.\n\t * If you use this type in a Browsers environment a {@link ReferenceError `ReferenceError: Buffer is not defined`} will be thrown!\n\t */\n\tBuffer = 'buffer',\n\t/**\n\t * Returns only the body, as a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n\t * @remark For NodeJS environment other `FetchResultTypes` are recommended, but you can use a Blob if you want to.\n\t */\n\tBlob = 'blob',\n\t/**\n\t * Returns only the body, as plain text. Similar to [`Body.text()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/text).\n\t */\n\tText = 'text',\n\t/**\n\t * Returns the entire response and doesn't parse the `body` in any way.\n\t */\n\tResult = 'result'\n}\n\n/**\n * The list of [HTTP Methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)\n */\nexport const enum FetchMethods {\n\t/**\n\t * The `GET` method requests a representation of the specified resource. Requests using `GET` should only retrieve data.\n\t * @see [MDN / Web / HTTP / Methods / GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET)\n\t */\n\tGet = 'GET',\n\t/**\n\t * The `HEAD` method asks for a response identical to that of a {@link FetchMethods.Get `GET`} request, but without the response body.\n\t * @see [MDN / Web / HTTP / Methods / HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD)\n\t */\n\tHead = 'HEAD',\n\t/**\n\t * The `POST` method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.\n\t * @see [MDN / Web / HTTP / Methods / POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)\n\t */\n\tPost = 'POST',\n\t/**\n\t * The `PUT` method replaces all current representations of the target resource with the request payload.\n\t * @see [MDN / Web / HTTP / Methods / PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT)\n\t */\n\tPut = 'PUT',\n\t/**\n\t * The `DELETE` method deletes the specified resource.\n\t * @see [MDN / Web / HTTP / Methods / DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE)\n\t */\n\tDelete = 'DELETE',\n\t/**\n\t * The `CONNECT` method establishes a tunnel to the server identified by the target resource\n\t * @see [MDN / Web / HTTP / Methods / CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT)\n\t */\n\tConnect = 'CONNECT',\n\t/**\n\t * The `OPTIONS` method is used to describe the communication options for the target resource.\n\t * @see [MDN / Web / HTTP / Methods / OPTIONS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS)\n\t */\n\tOptions = 'OPTIONS',\n\t/**\n\t * The `TRACE` method performs a message loop-back test along the path to the target resource.\n\t * @see [MDN / Web / HTTP / Methods / TRACE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE)\n\t */\n\tTrace = 'TRACE',\n\t/**\n\t * The `PATCH` method is used to apply partial modifications to a resource.\n\t * @see [MDN / Web / HTTP / Methods / PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH)\n\t */\n\tPatch = 'PATCH'\n}\n","// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\nimport { QueryError } from './QueryError';\nimport { FetchResultTypes } from './types';\n\n/**\n * Performs an HTTP(S) fetch\n * @param url The URL to send the request to. Can be either a `string` or an `URL` object.\n * `url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n * @param optionsOrType Either the [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript) or one of the {@link FetchResultTypes}\n * @param type Only needs to be provided if the second parameter are [Request options](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript). One of the {@link FetchResultTypes} that will determine how the result is returned.\n * @returns The return type is determined by the provided `type`.\n * - When using `FetchResultTypes.JSON` then the return type is `unknown` by default. The type should be specified by filling in the generic type of the function, or casting the result.\n * - When using `FetchResultTypes.Buffer` the return type will be [`Buffer`](https://nodejs.org/api/buffer.html).\n * - When using `FetchResultTypes.Blob` the return type will be a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n * - When using `FetchResultTypes.Text` the return type will be a `string`\n * - When using `FetchResultTypes.Result` the return type will be a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) ({@link Response} in typescript)\n */\nexport async function fetch<R>(url: URL | string, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type: FetchResultTypes): Promise<Response | Blob | Buffer | string | R>;\nexport async function fetch(url: URL | string, options?: RequestInit | FetchResultTypes, type?: FetchResultTypes) {\n\tif (typeof options === 'undefined') {\n\t\toptions = {};\n\t\ttype = FetchResultTypes.JSON;\n\t} else if (typeof options === 'string') {\n\t\ttype = options;\n\t\toptions = {};\n\t} else if (typeof type === 'undefined') {\n\t\ttype = FetchResultTypes.JSON;\n\t}\n\n\t// Transform the URL to a String, in case an URL object was passed\n\tconst stringUrl = String(url);\n\n\tconst result: Response = await globalThis.fetch(stringUrl, options);\n\tif (!result.ok) throw new QueryError(stringUrl, result.status, result, await result.clone().text());\n\n\tswitch (type) {\n\t\tcase FetchResultTypes.Result:\n\t\t\treturn result;\n\t\tcase FetchResultTypes.Buffer:\n\t\t\treturn Buffer.from(await (await result.blob()).arrayBuffer());\n\t\tcase FetchResultTypes.Blob:\n\t\t\treturn result.blob();\n\t\tcase FetchResultTypes.JSON:\n\t\t\treturn result.json();\n\t\tcase FetchResultTypes.Text:\n\t\t\treturn result.text();\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown type \"${type}\"`);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAMO,iCAAyB,MAAM;AAAA,IAY9B,YAAY,KAAa,MAAc,UAAoB,MAAc;AAC/E,YAAM,sBAAsB,kBAAkB;AAX/B;AAEA;AAEA;AAEA;AAEhB;AAIC,WAAK,MAAM;AACX,WAAK,OAAO;AACZ,WAAK,OAAO;AACZ,WAAK,WAAW;AAChB,yBAAK,OAAQ;AAAA;AAAA,IAGP,SAAS;AACf,aAAO,mBAAK,UAAU,mBAAK,OAAQ,KAAK,MAAM,KAAK;AAAA;AAAA;AAtB9C;AAUN;;;ACbM,MAAW,mBAAX,kBAAW,sBAAX;AAON,gCAAO;AAMP,kCAAS;AAKT,gCAAO;AAIP,gCAAO;AAIP,kCAAS;AA1BQ;AAAA;AAgCX,MAAW,eAAX,kBAAW,kBAAX;AAKN,2BAAM;AAKN,4BAAO;AAKP,4BAAO;AAKP,2BAAM;AAKN,8BAAS;AAKT,+BAAU;AAKV,+BAAU;AAKV,6BAAQ;AAKR,6BAAQ;AA7CS;AAAA;;;ACLlB,uBAA4B,KAAmB,SAA0C,MAAyB;AACjH,QAAI,OAAO,YAAY,aAAa;AACnC,gBAAU;AACV,aAAO;AAAA,eACG,OAAO,YAAY,UAAU;AACvC,aAAO;AACP,gBAAU;AAAA,eACA,OAAO,SAAS,aAAa;AACvC,aAAO;AAAA;AAIR,UAAM,YAAY,OAAO;AAEzB,UAAM,SAAmB,MAAM,WAAW,MAAM,WAAW;AAC3D,QAAI,CAAC,OAAO;AAAI,YAAM,IAAI,WAAW,WAAW,OAAO,QAAQ,QAAQ,MAAM,OAAO,QAAQ;AAE5F,YAAQ;AAAA,WACF;AACJ,eAAO;AAAA,WACH;AACJ,eAAO,OAAO,KAAK,MAAO,OAAM,OAAO,QAAQ;AAAA,WAC3C;AACJ,eAAO,OAAO;AAAA,WACV;AACJ,eAAO,OAAO;AAAA,WACV;AACJ,eAAO,OAAO;AAAA;AAEd,cAAM,IAAI,MAAM,iBAAiB;AAAA;AAAA;AA7Bd;","names":[]}
package/dist/index.js CHANGED
@@ -1,205 +1,143 @@
1
- 'use strict';
1
+ "use strict";
2
+ globalThis && globalThis.fetch ? globalThis.fetch : globalThis.fetch = require("cross-fetch");
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __reExport = (target, module2, copyDefault, desc) => {
15
+ if (module2 && typeof module2 === "object" || typeof module2 === "function") {
16
+ for (let key of __getOwnPropNames(module2))
17
+ if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
18
+ __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
19
+ }
20
+ return target;
21
+ };
22
+ var __toCommonJS = /* @__PURE__ */ ((cache) => {
23
+ return (module2, temp) => {
24
+ return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
25
+ };
26
+ })(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
27
+ var __publicField = (obj, key, value) => {
28
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
29
+ return value;
30
+ };
31
+ var __accessCheck = (obj, member, msg) => {
32
+ if (!member.has(obj))
33
+ throw TypeError("Cannot " + msg);
34
+ };
35
+ var __privateGet = (obj, member, getter) => {
36
+ __accessCheck(obj, member, "read from private field");
37
+ return getter ? getter.call(obj) : member.get(obj);
38
+ };
39
+ var __privateAdd = (obj, member, value) => {
40
+ if (member.has(obj))
41
+ throw TypeError("Cannot add the same private member more than once");
42
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
43
+ };
44
+ var __privateSet = (obj, member, value, setter) => {
45
+ __accessCheck(obj, member, "write to private field");
46
+ setter ? setter.call(obj, value) : member.set(obj, value);
47
+ return value;
48
+ };
2
49
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
50
+ // src/index.ts
51
+ var src_exports = {};
52
+ __export(src_exports, {
53
+ FetchMethods: () => FetchMethods,
54
+ FetchResultTypes: () => FetchResultTypes,
55
+ QueryError: () => QueryError,
56
+ fetch: () => fetch
57
+ });
4
58
 
5
- var crossFetch = require('cross-fetch');
59
+ // src/lib/QueryError.ts
60
+ var _json;
61
+ var QueryError = class extends Error {
62
+ constructor(url, code, response, body) {
63
+ super(`Failed to request '${url}' with code ${code}.`);
64
+ __publicField(this, "url");
65
+ __publicField(this, "code");
66
+ __publicField(this, "body");
67
+ __publicField(this, "response");
68
+ __privateAdd(this, _json, void 0);
69
+ this.url = url;
70
+ this.code = code;
71
+ this.body = body;
72
+ this.response = response;
73
+ __privateSet(this, _json, null);
74
+ }
75
+ toJSON() {
76
+ return __privateGet(this, _json) ?? __privateSet(this, _json, JSON.parse(this.body));
77
+ }
78
+ };
79
+ __name(QueryError, "QueryError");
80
+ _json = new WeakMap();
6
81
 
7
- /*! *****************************************************************************
8
- Copyright (c) Microsoft Corporation.
9
-
10
- Permission to use, copy, modify, and/or distribute this software for any
11
- purpose with or without fee is hereby granted.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
- PERFORMANCE OF THIS SOFTWARE.
20
- ***************************************************************************** */
21
-
22
- function __classPrivateFieldGet(receiver, state, kind, f) {
23
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
24
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
25
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
26
- }
27
-
28
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
29
- if (kind === "m") throw new TypeError("Private method is not writable");
30
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
31
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
32
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
33
- }
34
-
35
- // eslint-disable-next-line spaced-comment
36
- /// <reference lib="dom" />
37
- var _QueryError_json;
38
- /**
39
- * The QueryError class which is thrown by the `fetch` method
40
- */
41
- class QueryError extends Error {
42
- constructor(url, code, response, body) {
43
- super(`Failed to request '${url}' with code ${code}.`);
44
- /** The requested url. */
45
- Object.defineProperty(this, "url", {
46
- enumerable: true,
47
- configurable: true,
48
- writable: true,
49
- value: void 0
50
- });
51
- /** The HTTP status code. */
52
- Object.defineProperty(this, "code", {
53
- enumerable: true,
54
- configurable: true,
55
- writable: true,
56
- value: void 0
57
- });
58
- /** The returned response body as a string */
59
- Object.defineProperty(this, "body", {
60
- enumerable: true,
61
- configurable: true,
62
- writable: true,
63
- value: void 0
64
- });
65
- /** The original {@link Response} object */
66
- Object.defineProperty(this, "response", {
67
- enumerable: true,
68
- configurable: true,
69
- writable: true,
70
- value: void 0
71
- });
72
- _QueryError_json.set(this, void 0);
73
- this.url = url;
74
- this.code = code;
75
- this.body = body;
76
- this.response = response;
77
- __classPrivateFieldSet(this, _QueryError_json, null, "f");
78
- }
79
- toJSON() {
80
- return __classPrivateFieldGet(this, _QueryError_json, "f") ?? (__classPrivateFieldSet(this, _QueryError_json, JSON.parse(this.body), "f"));
81
- }
82
- }
83
- _QueryError_json = new WeakMap();
82
+ // src/lib/types.ts
83
+ var FetchResultTypes = /* @__PURE__ */ ((FetchResultTypes2) => {
84
+ FetchResultTypes2["JSON"] = "json";
85
+ FetchResultTypes2["Buffer"] = "buffer";
86
+ FetchResultTypes2["Blob"] = "blob";
87
+ FetchResultTypes2["Text"] = "text";
88
+ FetchResultTypes2["Result"] = "result";
89
+ return FetchResultTypes2;
90
+ })(FetchResultTypes || {});
91
+ var FetchMethods = /* @__PURE__ */ ((FetchMethods2) => {
92
+ FetchMethods2["Get"] = "GET";
93
+ FetchMethods2["Head"] = "HEAD";
94
+ FetchMethods2["Post"] = "POST";
95
+ FetchMethods2["Put"] = "PUT";
96
+ FetchMethods2["Delete"] = "DELETE";
97
+ FetchMethods2["Connect"] = "CONNECT";
98
+ FetchMethods2["Options"] = "OPTIONS";
99
+ FetchMethods2["Trace"] = "TRACE";
100
+ FetchMethods2["Patch"] = "PATCH";
101
+ return FetchMethods2;
102
+ })(FetchMethods || {});
84
103
 
85
- /**
86
- * The supported return types for the `fetch` method
87
- */
88
- exports.FetchResultTypes = void 0;
89
- (function (FetchResultTypes) {
90
- /**
91
- * Returns only the body, as JSON. Similar to [`Body.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json).
92
- *
93
- * You should provide your own type cast (either through the generic return type, or with `as <type>`) to the response to define
94
- * the JSON structure, otherwise the result will be `unknown`.
95
- */
96
- FetchResultTypes["JSON"] = "json";
97
- /**
98
- * Returns only the body, as a [Buffer](https://nodejs.org/api/buffer.html).
99
- * @remark Does not work in a Browser environment. For browsers use {@link FetchResultTypes.Blob} instead.
100
- * If you use this type in a Browsers environment a {@link ReferenceError `ReferenceError: Buffer is not defined`} will be thrown!
101
- */
102
- FetchResultTypes["Buffer"] = "buffer";
103
- /**
104
- * Returns only the body, as a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
105
- * @remark For NodeJS environment other `FetchResultTypes` are recommended, but you can use a Blob if you want to.
106
- */
107
- FetchResultTypes["Blob"] = "blob";
108
- /**
109
- * Returns only the body, as plain text. Similar to [`Body.text()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/text).
110
- */
111
- FetchResultTypes["Text"] = "text";
112
- /**
113
- * Returns the entire response and doesn't parse the `body` in any way.
114
- */
115
- FetchResultTypes["Result"] = "result";
116
- })(exports.FetchResultTypes || (exports.FetchResultTypes = {}));
117
- /**
118
- * The list of [HTTP Methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)
119
- */
120
- exports.FetchMethods = void 0;
121
- (function (FetchMethods) {
122
- /**
123
- * The `GET` method requests a representation of the specified resource. Requests using `GET` should only retrieve data.
124
- * @see [MDN / Web / HTTP / Methods / GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET)
125
- */
126
- FetchMethods["Get"] = "GET";
127
- /**
128
- * The `HEAD` method asks for a response identical to that of a {@link FetchMethods.Get `GET`} request, but without the response body.
129
- * @see [MDN / Web / HTTP / Methods / HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD)
130
- */
131
- FetchMethods["Head"] = "HEAD";
132
- /**
133
- * The `POST` method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.
134
- * @see [MDN / Web / HTTP / Methods / POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)
135
- */
136
- FetchMethods["Post"] = "POST";
137
- /**
138
- * The `PUT` method replaces all current representations of the target resource with the request payload.
139
- * @see [MDN / Web / HTTP / Methods / PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT)
140
- */
141
- FetchMethods["Put"] = "PUT";
142
- /**
143
- * The `DELETE` method deletes the specified resource.
144
- * @see [MDN / Web / HTTP / Methods / DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE)
145
- */
146
- FetchMethods["Delete"] = "DELETE";
147
- /**
148
- * The `CONNECT` method establishes a tunnel to the server identified by the target resource
149
- * @see [MDN / Web / HTTP / Methods / CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT)
150
- */
151
- FetchMethods["Connect"] = "CONNECT";
152
- /**
153
- * The `OPTIONS` method is used to describe the communication options for the target resource.
154
- * @see [MDN / Web / HTTP / Methods / OPTIONS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS)
155
- */
156
- FetchMethods["Options"] = "OPTIONS";
157
- /**
158
- * The `TRACE` method performs a message loop-back test along the path to the target resource.
159
- * @see [MDN / Web / HTTP / Methods / TRACE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE)
160
- */
161
- FetchMethods["Trace"] = "TRACE";
162
- /**
163
- * The `PATCH` method is used to apply partial modifications to a resource.
164
- * @see [MDN / Web / HTTP / Methods / PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH)
165
- */
166
- FetchMethods["Patch"] = "PATCH";
167
- })(exports.FetchMethods || (exports.FetchMethods = {}));
168
-
169
- // eslint-disable-next-line spaced-comment
104
+ // src/lib/fetch.ts
170
105
  async function fetch(url, options, type) {
171
- if (typeof options === 'undefined') {
172
- options = {};
173
- type = "json" /* JSON */;
174
- }
175
- else if (typeof options === 'string') {
176
- type = options;
177
- options = {};
178
- }
179
- else if (typeof type === 'undefined') {
180
- type = "json" /* JSON */;
181
- }
182
- // Transform the URL to a String, in case an URL object was passed
183
- const stringUrl = String(url);
184
- const result = await crossFetch.fetch(stringUrl, options);
185
- if (!result.ok)
186
- throw new QueryError(stringUrl, result.status, result, await result.clone().text());
187
- switch (type) {
188
- case "result" /* Result */:
189
- return result;
190
- case "buffer" /* Buffer */:
191
- return Buffer.from(await (await result.blob()).arrayBuffer());
192
- case "blob" /* Blob */:
193
- return result.blob();
194
- case "json" /* JSON */:
195
- return result.json();
196
- case "text" /* Text */:
197
- return result.text();
198
- default:
199
- throw new Error(`Unknown type "${type}"`);
200
- }
106
+ if (typeof options === "undefined") {
107
+ options = {};
108
+ type = "json" /* JSON */;
109
+ } else if (typeof options === "string") {
110
+ type = options;
111
+ options = {};
112
+ } else if (typeof type === "undefined") {
113
+ type = "json" /* JSON */;
114
+ }
115
+ const stringUrl = String(url);
116
+ const result = await globalThis.fetch(stringUrl, options);
117
+ if (!result.ok)
118
+ throw new QueryError(stringUrl, result.status, result, await result.clone().text());
119
+ switch (type) {
120
+ case "result" /* Result */:
121
+ return result;
122
+ case "buffer" /* Buffer */:
123
+ return Buffer.from(await (await result.blob()).arrayBuffer());
124
+ case "blob" /* Blob */:
125
+ return result.blob();
126
+ case "json" /* JSON */:
127
+ return result.json();
128
+ case "text" /* Text */:
129
+ return result.text();
130
+ default:
131
+ throw new Error(`Unknown type "${type}"`);
132
+ }
201
133
  }
202
-
203
- exports.QueryError = QueryError;
204
- exports.fetch = fetch;
205
- //# sourceMappingURL=index.js.map
134
+ __name(fetch, "fetch");
135
+ module.exports = __toCommonJS(src_exports);
136
+ // Annotate the CommonJS export names for ESM import in node:
137
+ 0 && (module.exports = {
138
+ FetchMethods,
139
+ FetchResultTypes,
140
+ QueryError,
141
+ fetch
142
+ });
143
+ //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/lib/QueryError.ts","../src/lib/types.ts","../src/lib/fetch.ts"],"sourcesContent":["// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\n/**\n * The QueryError class which is thrown by the `fetch` method\n */\nexport class QueryError extends Error {\n\t/** The requested url. */\n\tpublic readonly url: string;\n\t/** The HTTP status code. */\n\tpublic readonly code: number;\n\t/** The returned response body as a string */\n\tpublic readonly body: string;\n\t/** The original {@link Response} object */\n\tpublic readonly response: Response;\n\n\t#json: unknown;\n\n\tpublic constructor(url: string, code: number, response: Response, body: string) {\n\t\tsuper(`Failed to request '${url}' with code ${code}.`);\n\t\tthis.url = url;\n\t\tthis.code = code;\n\t\tthis.body = body;\n\t\tthis.response = response;\n\t\tthis.#json = null;\n\t}\n\n\tpublic toJSON() {\n\t\treturn this.#json ?? (this.#json = JSON.parse(this.body));\n\t}\n}\n","/**\n * The supported return types for the `fetch` method\n */\nexport const enum FetchResultTypes {\n\t/**\n\t * Returns only the body, as JSON. Similar to [`Body.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json).\n\t *\n\t * You should provide your own type cast (either through the generic return type, or with `as <type>`) to the response to define\n\t * the JSON structure, otherwise the result will be `unknown`.\n\t */\n\tJSON = 'json',\n\t/**\n\t * Returns only the body, as a [Buffer](https://nodejs.org/api/buffer.html).\n\t * @remark Does not work in a Browser environment. For browsers use {@link FetchResultTypes.Blob} instead.\n\t * If you use this type in a Browsers environment a {@link ReferenceError `ReferenceError: Buffer is not defined`} will be thrown!\n\t */\n\tBuffer = 'buffer',\n\t/**\n\t * Returns only the body, as a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n\t * @remark For NodeJS environment other `FetchResultTypes` are recommended, but you can use a Blob if you want to.\n\t */\n\tBlob = 'blob',\n\t/**\n\t * Returns only the body, as plain text. Similar to [`Body.text()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/text).\n\t */\n\tText = 'text',\n\t/**\n\t * Returns the entire response and doesn't parse the `body` in any way.\n\t */\n\tResult = 'result'\n}\n\n/**\n * The list of [HTTP Methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)\n */\nexport const enum FetchMethods {\n\t/**\n\t * The `GET` method requests a representation of the specified resource. Requests using `GET` should only retrieve data.\n\t * @see [MDN / Web / HTTP / Methods / GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET)\n\t */\n\tGet = 'GET',\n\t/**\n\t * The `HEAD` method asks for a response identical to that of a {@link FetchMethods.Get `GET`} request, but without the response body.\n\t * @see [MDN / Web / HTTP / Methods / HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD)\n\t */\n\tHead = 'HEAD',\n\t/**\n\t * The `POST` method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.\n\t * @see [MDN / Web / HTTP / Methods / POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)\n\t */\n\tPost = 'POST',\n\t/**\n\t * The `PUT` method replaces all current representations of the target resource with the request payload.\n\t * @see [MDN / Web / HTTP / Methods / PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT)\n\t */\n\tPut = 'PUT',\n\t/**\n\t * The `DELETE` method deletes the specified resource.\n\t * @see [MDN / Web / HTTP / Methods / DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE)\n\t */\n\tDelete = 'DELETE',\n\t/**\n\t * The `CONNECT` method establishes a tunnel to the server identified by the target resource\n\t * @see [MDN / Web / HTTP / Methods / CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT)\n\t */\n\tConnect = 'CONNECT',\n\t/**\n\t * The `OPTIONS` method is used to describe the communication options for the target resource.\n\t * @see [MDN / Web / HTTP / Methods / OPTIONS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS)\n\t */\n\tOptions = 'OPTIONS',\n\t/**\n\t * The `TRACE` method performs a message loop-back test along the path to the target resource.\n\t * @see [MDN / Web / HTTP / Methods / TRACE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE)\n\t */\n\tTrace = 'TRACE',\n\t/**\n\t * The `PATCH` method is used to apply partial modifications to a resource.\n\t * @see [MDN / Web / HTTP / Methods / PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH)\n\t */\n\tPatch = 'PATCH'\n}\n","// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\nimport { fetch as nodeFetch } from 'cross-fetch';\nimport { QueryError } from './QueryError';\nimport { FetchResultTypes } from './types';\n\n/**\n * Performs an HTTP(S) fetch\n * @param url The URL to send the request to. Can be either a `string` or an `URL` object.\n * `url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n * @param optionsOrType Either the [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript) or one of the {@link FetchResultTypes}\n * @param type Only needs to be provided if the second parameter are [Request options](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript). One of the {@link FetchResultTypes} that will determine how the result is returned.\n * @returns The return type is determined by the provided `type`.\n * - When using `FetchResultTypes.JSON` then the return type is `unknown` by default. The type should be specified by filling in the generic type of the function, or casting the result.\n * - When using `FetchResultTypes.Buffer` the return type will be [`Buffer`](https://nodejs.org/api/buffer.html).\n * - When using `FetchResultTypes.Blob` the return type will be a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n * - When using `FetchResultTypes.Text` the return type will be a `string`\n * - When using `FetchResultTypes.Result` the return type will be a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) ({@link Response} in typescript)\n */\nexport async function fetch<R>(url: URL | string, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type: FetchResultTypes): Promise<Response | Blob | Buffer | string | R>;\nexport async function fetch(url: URL | string, options?: RequestInit | FetchResultTypes, type?: FetchResultTypes) {\n\tif (typeof options === 'undefined') {\n\t\toptions = {};\n\t\ttype = FetchResultTypes.JSON;\n\t} else if (typeof options === 'string') {\n\t\ttype = options;\n\t\toptions = {};\n\t} else if (typeof type === 'undefined') {\n\t\ttype = FetchResultTypes.JSON;\n\t}\n\n\t// Transform the URL to a String, in case an URL object was passed\n\tconst stringUrl = String(url);\n\n\tconst result: Response = await nodeFetch(stringUrl, options);\n\tif (!result.ok) throw new QueryError(stringUrl, result.status, result, await result.clone().text());\n\n\tswitch (type) {\n\t\tcase FetchResultTypes.Result:\n\t\t\treturn result;\n\t\tcase FetchResultTypes.Buffer:\n\t\t\treturn Buffer.from(await (await result.blob()).arrayBuffer());\n\t\tcase FetchResultTypes.Blob:\n\t\t\treturn result.blob();\n\t\tcase FetchResultTypes.JSON:\n\t\t\treturn result.json();\n\t\tcase FetchResultTypes.Text:\n\t\t\treturn result.text();\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown type \"${type}\"`);\n\t}\n}\n"],"names":["FetchResultTypes","FetchMethods","nodeFetch"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;;AAEA;;;MAGa,UAAW,SAAQ,KAAK;IAYpC,YAAmB,GAAW,EAAE,IAAY,EAAE,QAAkB,EAAE,IAAY;QAC7E,KAAK,CAAC,sBAAsB,GAAG,eAAe,IAAI,GAAG,CAAC,CAAC;;QAXxD;;;;;WAA4B;;QAE5B;;;;;WAA6B;;QAE7B;;;;;WAA6B;;QAE7B;;;;;WAAmC;QAEnC,mCAAe;QAId,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,uBAAA,IAAI,oBAAS,IAAI,MAAA,CAAC;KAClB;IAEM,MAAM;QACZ,OAAO,uBAAA,IAAI,wBAAM,KAAK,uBAAA,IAAI,oBAAS,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,MAAA,CAAC,CAAC;KAC1D;CACD;;;AC9BD;;;AAGkBA;AAAlB,WAAkB,gBAAgB;;;;;;;IAOjC,iCAAa,CAAA;;;;;;IAMb,qCAAiB,CAAA;;;;;IAKjB,iCAAa,CAAA;;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AO,MAAM,CAAC,IAAI,EAAE,CAAC;QACtB;YACC,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC;QACtB;YACC,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC;QACtB;YACC,MAAM,IAAI,KAAK,CAAC,iBAAiB,IAAI,GAAG,CAAC,CAAC;KAC3C;AACF;;;;;"}
1
+ {"version":3,"sources":["../src/index.ts","../src/lib/QueryError.ts","../src/lib/types.ts","../src/lib/fetch.ts"],"sourcesContent":["export * from './lib/fetch';\nexport * from './lib/QueryError';\nexport * from './lib/types';\n","// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\n/**\n * The QueryError class which is thrown by the `fetch` method\n */\nexport class QueryError extends Error {\n\t/** The requested url. */\n\tpublic readonly url: string;\n\t/** The HTTP status code. */\n\tpublic readonly code: number;\n\t/** The returned response body as a string */\n\tpublic readonly body: string;\n\t/** The original {@link Response} object */\n\tpublic readonly response: Response;\n\n\t#json: unknown;\n\n\tpublic constructor(url: string, code: number, response: Response, body: string) {\n\t\tsuper(`Failed to request '${url}' with code ${code}.`);\n\t\tthis.url = url;\n\t\tthis.code = code;\n\t\tthis.body = body;\n\t\tthis.response = response;\n\t\tthis.#json = null;\n\t}\n\n\tpublic toJSON() {\n\t\treturn this.#json ?? (this.#json = JSON.parse(this.body));\n\t}\n}\n","/**\n * The supported return types for the `fetch` method\n */\nexport const enum FetchResultTypes {\n\t/**\n\t * Returns only the body, as JSON. Similar to [`Body.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json).\n\t *\n\t * You should provide your own type cast (either through the generic return type, or with `as <type>`) to the response to define\n\t * the JSON structure, otherwise the result will be `unknown`.\n\t */\n\tJSON = 'json',\n\t/**\n\t * Returns only the body, as a [Buffer](https://nodejs.org/api/buffer.html).\n\t * @remark Does not work in a Browser environment. For browsers use {@link FetchResultTypes.Blob} instead.\n\t * If you use this type in a Browsers environment a {@link ReferenceError `ReferenceError: Buffer is not defined`} will be thrown!\n\t */\n\tBuffer = 'buffer',\n\t/**\n\t * Returns only the body, as a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n\t * @remark For NodeJS environment other `FetchResultTypes` are recommended, but you can use a Blob if you want to.\n\t */\n\tBlob = 'blob',\n\t/**\n\t * Returns only the body, as plain text. Similar to [`Body.text()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/text).\n\t */\n\tText = 'text',\n\t/**\n\t * Returns the entire response and doesn't parse the `body` in any way.\n\t */\n\tResult = 'result'\n}\n\n/**\n * The list of [HTTP Methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)\n */\nexport const enum FetchMethods {\n\t/**\n\t * The `GET` method requests a representation of the specified resource. Requests using `GET` should only retrieve data.\n\t * @see [MDN / Web / HTTP / Methods / GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET)\n\t */\n\tGet = 'GET',\n\t/**\n\t * The `HEAD` method asks for a response identical to that of a {@link FetchMethods.Get `GET`} request, but without the response body.\n\t * @see [MDN / Web / HTTP / Methods / HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD)\n\t */\n\tHead = 'HEAD',\n\t/**\n\t * The `POST` method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.\n\t * @see [MDN / Web / HTTP / Methods / POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)\n\t */\n\tPost = 'POST',\n\t/**\n\t * The `PUT` method replaces all current representations of the target resource with the request payload.\n\t * @see [MDN / Web / HTTP / Methods / PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT)\n\t */\n\tPut = 'PUT',\n\t/**\n\t * The `DELETE` method deletes the specified resource.\n\t * @see [MDN / Web / HTTP / Methods / DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE)\n\t */\n\tDelete = 'DELETE',\n\t/**\n\t * The `CONNECT` method establishes a tunnel to the server identified by the target resource\n\t * @see [MDN / Web / HTTP / Methods / CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT)\n\t */\n\tConnect = 'CONNECT',\n\t/**\n\t * The `OPTIONS` method is used to describe the communication options for the target resource.\n\t * @see [MDN / Web / HTTP / Methods / OPTIONS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS)\n\t */\n\tOptions = 'OPTIONS',\n\t/**\n\t * The `TRACE` method performs a message loop-back test along the path to the target resource.\n\t * @see [MDN / Web / HTTP / Methods / TRACE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE)\n\t */\n\tTrace = 'TRACE',\n\t/**\n\t * The `PATCH` method is used to apply partial modifications to a resource.\n\t * @see [MDN / Web / HTTP / Methods / PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH)\n\t */\n\tPatch = 'PATCH'\n}\n","// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\nimport { QueryError } from './QueryError';\nimport { FetchResultTypes } from './types';\n\n/**\n * Performs an HTTP(S) fetch\n * @param url The URL to send the request to. Can be either a `string` or an `URL` object.\n * `url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n * @param optionsOrType Either the [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript) or one of the {@link FetchResultTypes}\n * @param type Only needs to be provided if the second parameter are [Request options](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript). One of the {@link FetchResultTypes} that will determine how the result is returned.\n * @returns The return type is determined by the provided `type`.\n * - When using `FetchResultTypes.JSON` then the return type is `unknown` by default. The type should be specified by filling in the generic type of the function, or casting the result.\n * - When using `FetchResultTypes.Buffer` the return type will be [`Buffer`](https://nodejs.org/api/buffer.html).\n * - When using `FetchResultTypes.Blob` the return type will be a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n * - When using `FetchResultTypes.Text` the return type will be a `string`\n * - When using `FetchResultTypes.Result` the return type will be a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) ({@link Response} in typescript)\n */\nexport async function fetch<R>(url: URL | string, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type: FetchResultTypes): Promise<Response | Blob | Buffer | string | R>;\nexport async function fetch(url: URL | string, options?: RequestInit | FetchResultTypes, type?: FetchResultTypes) {\n\tif (typeof options === 'undefined') {\n\t\toptions = {};\n\t\ttype = FetchResultTypes.JSON;\n\t} else if (typeof options === 'string') {\n\t\ttype = options;\n\t\toptions = {};\n\t} else if (typeof type === 'undefined') {\n\t\ttype = FetchResultTypes.JSON;\n\t}\n\n\t// Transform the URL to a String, in case an URL object was passed\n\tconst stringUrl = String(url);\n\n\tconst result: Response = await globalThis.fetch(stringUrl, options);\n\tif (!result.ok) throw new QueryError(stringUrl, result.status, result, await result.clone().text());\n\n\tswitch (type) {\n\t\tcase FetchResultTypes.Result:\n\t\t\treturn result;\n\t\tcase FetchResultTypes.Buffer:\n\t\t\treturn Buffer.from(await (await result.blob()).arrayBuffer());\n\t\tcase FetchResultTypes.Blob:\n\t\t\treturn result.blob();\n\t\tcase FetchRes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,SACF;AACJ,aAAO;AAAA,SACH;AACJ,aAAO,OAAO,KAAK,MAAO,OAAM,OAAO,QAAQ;AAAA,SAC3C;AACJ,aAAO,OAAO;AAAA,SACV;AACJ,aAAO,OAAO;AAAA,SACV;AACJ,aAAO,OAAO;AAAA;AAEd,YAAM,IAAI,MAAM,iBAAiB;AAAA;AAAA;AA7Bd;","names":[]}
package/dist/index.mjs CHANGED
@@ -1,200 +1,111 @@
1
- import { fetch as fetch$1 } from 'cross-fetch';
1
+ import crossFetch from "cross-fetch";
2
+ globalThis && globalThis.fetch ? globalThis.fetch : globalThis.fetch = crossFetch;
3
+ var __defProp = Object.defineProperty;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+ var __publicField = (obj, key, value) => {
7
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
+ return value;
9
+ };
10
+ var __accessCheck = (obj, member, msg) => {
11
+ if (!member.has(obj))
12
+ throw TypeError("Cannot " + msg);
13
+ };
14
+ var __privateGet = (obj, member, getter) => {
15
+ __accessCheck(obj, member, "read from private field");
16
+ return getter ? getter.call(obj) : member.get(obj);
17
+ };
18
+ var __privateAdd = (obj, member, value) => {
19
+ if (member.has(obj))
20
+ throw TypeError("Cannot add the same private member more than once");
21
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
22
+ };
23
+ var __privateSet = (obj, member, value, setter) => {
24
+ __accessCheck(obj, member, "write to private field");
25
+ setter ? setter.call(obj, value) : member.set(obj, value);
26
+ return value;
27
+ };
2
28
 
3
- /*! *****************************************************************************
4
- Copyright (c) Microsoft Corporation.
5
-
6
- Permission to use, copy, modify, and/or distribute this software for any
7
- purpose with or without fee is hereby granted.
8
-
9
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
- PERFORMANCE OF THIS SOFTWARE.
16
- ***************************************************************************** */
17
-
18
- function __classPrivateFieldGet(receiver, state, kind, f) {
19
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
20
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
21
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
22
- }
23
-
24
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
25
- if (kind === "m") throw new TypeError("Private method is not writable");
26
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
27
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
28
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
29
- }
30
-
31
- // eslint-disable-next-line spaced-comment
32
- /// <reference lib="dom" />
33
- var _QueryError_json;
34
- /**
35
- * The QueryError class which is thrown by the `fetch` method
36
- */
37
- class QueryError extends Error {
38
- constructor(url, code, response, body) {
39
- super(`Failed to request '${url}' with code ${code}.`);
40
- /** The requested url. */
41
- Object.defineProperty(this, "url", {
42
- enumerable: true,
43
- configurable: true,
44
- writable: true,
45
- value: void 0
46
- });
47
- /** The HTTP status code. */
48
- Object.defineProperty(this, "code", {
49
- enumerable: true,
50
- configurable: true,
51
- writable: true,
52
- value: void 0
53
- });
54
- /** The returned response body as a string */
55
- Object.defineProperty(this, "body", {
56
- enumerable: true,
57
- configurable: true,
58
- writable: true,
59
- value: void 0
60
- });
61
- /** The original {@link Response} object */
62
- Object.defineProperty(this, "response", {
63
- enumerable: true,
64
- configurable: true,
65
- writable: true,
66
- value: void 0
67
- });
68
- _QueryError_json.set(this, void 0);
69
- this.url = url;
70
- this.code = code;
71
- this.body = body;
72
- this.response = response;
73
- __classPrivateFieldSet(this, _QueryError_json, null, "f");
74
- }
75
- toJSON() {
76
- return __classPrivateFieldGet(this, _QueryError_json, "f") ?? (__classPrivateFieldSet(this, _QueryError_json, JSON.parse(this.body), "f"));
77
- }
78
- }
79
- _QueryError_json = new WeakMap();
29
+ // src/lib/QueryError.ts
30
+ var _json;
31
+ var QueryError = class extends Error {
32
+ constructor(url, code, response, body) {
33
+ super(`Failed to request '${url}' with code ${code}.`);
34
+ __publicField(this, "url");
35
+ __publicField(this, "code");
36
+ __publicField(this, "body");
37
+ __publicField(this, "response");
38
+ __privateAdd(this, _json, void 0);
39
+ this.url = url;
40
+ this.code = code;
41
+ this.body = body;
42
+ this.response = response;
43
+ __privateSet(this, _json, null);
44
+ }
45
+ toJSON() {
46
+ return __privateGet(this, _json) ?? __privateSet(this, _json, JSON.parse(this.body));
47
+ }
48
+ };
49
+ __name(QueryError, "QueryError");
50
+ _json = new WeakMap();
80
51
 
81
- /**
82
- * The supported return types for the `fetch` method
83
- */
84
- var FetchResultTypes;
85
- (function (FetchResultTypes) {
86
- /**
87
- * Returns only the body, as JSON. Similar to [`Body.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json).
88
- *
89
- * You should provide your own type cast (either through the generic return type, or with `as <type>`) to the response to define
90
- * the JSON structure, otherwise the result will be `unknown`.
91
- */
92
- FetchResultTypes["JSON"] = "json";
93
- /**
94
- * Returns only the body, as a [Buffer](https://nodejs.org/api/buffer.html).
95
- * @remark Does not work in a Browser environment. For browsers use {@link FetchResultTypes.Blob} instead.
96
- * If you use this type in a Browsers environment a {@link ReferenceError `ReferenceError: Buffer is not defined`} will be thrown!
97
- */
98
- FetchResultTypes["Buffer"] = "buffer";
99
- /**
100
- * Returns only the body, as a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
101
- * @remark For NodeJS environment other `FetchResultTypes` are recommended, but you can use a Blob if you want to.
102
- */
103
- FetchResultTypes["Blob"] = "blob";
104
- /**
105
- * Returns only the body, as plain text. Similar to [`Body.text()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/text).
106
- */
107
- FetchResultTypes["Text"] = "text";
108
- /**
109
- * Returns the entire response and doesn't parse the `body` in any way.
110
- */
111
- FetchResultTypes["Result"] = "result";
112
- })(FetchResultTypes || (FetchResultTypes = {}));
113
- /**
114
- * The list of [HTTP Methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)
115
- */
116
- var FetchMethods;
117
- (function (FetchMethods) {
118
- /**
119
- * The `GET` method requests a representation of the specified resource. Requests using `GET` should only retrieve data.
120
- * @see [MDN / Web / HTTP / Methods / GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET)
121
- */
122
- FetchMethods["Get"] = "GET";
123
- /**
124
- * The `HEAD` method asks for a response identical to that of a {@link FetchMethods.Get `GET`} request, but without the response body.
125
- * @see [MDN / Web / HTTP / Methods / HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD)
126
- */
127
- FetchMethods["Head"] = "HEAD";
128
- /**
129
- * The `POST` method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.
130
- * @see [MDN / Web / HTTP / Methods / POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)
131
- */
132
- FetchMethods["Post"] = "POST";
133
- /**
134
- * The `PUT` method replaces all current representations of the target resource with the request payload.
135
- * @see [MDN / Web / HTTP / Methods / PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT)
136
- */
137
- FetchMethods["Put"] = "PUT";
138
- /**
139
- * The `DELETE` method deletes the specified resource.
140
- * @see [MDN / Web / HTTP / Methods / DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE)
141
- */
142
- FetchMethods["Delete"] = "DELETE";
143
- /**
144
- * The `CONNECT` method establishes a tunnel to the server identified by the target resource
145
- * @see [MDN / Web / HTTP / Methods / CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT)
146
- */
147
- FetchMethods["Connect"] = "CONNECT";
148
- /**
149
- * The `OPTIONS` method is used to describe the communication options for the target resource.
150
- * @see [MDN / Web / HTTP / Methods / OPTIONS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS)
151
- */
152
- FetchMethods["Options"] = "OPTIONS";
153
- /**
154
- * The `TRACE` method performs a message loop-back test along the path to the target resource.
155
- * @see [MDN / Web / HTTP / Methods / TRACE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE)
156
- */
157
- FetchMethods["Trace"] = "TRACE";
158
- /**
159
- * The `PATCH` method is used to apply partial modifications to a resource.
160
- * @see [MDN / Web / HTTP / Methods / PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH)
161
- */
162
- FetchMethods["Patch"] = "PATCH";
163
- })(FetchMethods || (FetchMethods = {}));
52
+ // src/lib/types.ts
53
+ var FetchResultTypes = /* @__PURE__ */ ((FetchResultTypes2) => {
54
+ FetchResultTypes2["JSON"] = "json";
55
+ FetchResultTypes2["Buffer"] = "buffer";
56
+ FetchResultTypes2["Blob"] = "blob";
57
+ FetchResultTypes2["Text"] = "text";
58
+ FetchResultTypes2["Result"] = "result";
59
+ return FetchResultTypes2;
60
+ })(FetchResultTypes || {});
61
+ var FetchMethods = /* @__PURE__ */ ((FetchMethods2) => {
62
+ FetchMethods2["Get"] = "GET";
63
+ FetchMethods2["Head"] = "HEAD";
64
+ FetchMethods2["Post"] = "POST";
65
+ FetchMethods2["Put"] = "PUT";
66
+ FetchMethods2["Delete"] = "DELETE";
67
+ FetchMethods2["Connect"] = "CONNECT";
68
+ FetchMethods2["Options"] = "OPTIONS";
69
+ FetchMethods2["Trace"] = "TRACE";
70
+ FetchMethods2["Patch"] = "PATCH";
71
+ return FetchMethods2;
72
+ })(FetchMethods || {});
164
73
 
165
- // eslint-disable-next-line spaced-comment
74
+ // src/lib/fetch.ts
166
75
  async function fetch(url, options, type) {
167
- if (typeof options === 'undefined') {
168
- options = {};
169
- type = "json" /* JSON */;
170
- }
171
- else if (typeof options === 'string') {
172
- type = options;
173
- options = {};
174
- }
175
- else if (typeof type === 'undefined') {
176
- type = "json" /* JSON */;
177
- }
178
- // Transform the URL to a String, in case an URL object was passed
179
- const stringUrl = String(url);
180
- const result = await fetch$1(stringUrl, options);
181
- if (!result.ok)
182
- throw new QueryError(stringUrl, result.status, result, await result.clone().text());
183
- switch (type) {
184
- case "result" /* Result */:
185
- return result;
186
- case "buffer" /* Buffer */:
187
- return Buffer.from(await (await result.blob()).arrayBuffer());
188
- case "blob" /* Blob */:
189
- return result.blob();
190
- case "json" /* JSON */:
191
- return result.json();
192
- case "text" /* Text */:
193
- return result.text();
194
- default:
195
- throw new Error(`Unknown type "${type}"`);
196
- }
76
+ if (typeof options === "undefined") {
77
+ options = {};
78
+ type = "json" /* JSON */;
79
+ } else if (typeof options === "string") {
80
+ type = options;
81
+ options = {};
82
+ } else if (typeof type === "undefined") {
83
+ type = "json" /* JSON */;
84
+ }
85
+ const stringUrl = String(url);
86
+ const result = await globalThis.fetch(stringUrl, options);
87
+ if (!result.ok)
88
+ throw new QueryError(stringUrl, result.status, result, await result.clone().text());
89
+ switch (type) {
90
+ case "result" /* Result */:
91
+ return result;
92
+ case "buffer" /* Buffer */:
93
+ return Buffer.from(await (await result.blob()).arrayBuffer());
94
+ case "blob" /* Blob */:
95
+ return result.blob();
96
+ case "json" /* JSON */:
97
+ return result.json();
98
+ case "text" /* Text */:
99
+ return result.text();
100
+ default:
101
+ throw new Error(`Unknown type "${type}"`);
102
+ }
197
103
  }
198
-
199
- export { FetchMethods, FetchResultTypes, QueryError, fetch };
200
- //# sourceMappingURL=index.mjs.map
104
+ __name(fetch, "fetch");
105
+ export {
106
+ FetchMethods,
107
+ FetchResultTypes,
108
+ QueryError,
109
+ fetch
110
+ };
111
+ //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/lib/QueryError.ts","../src/lib/types.ts","../src/lib/fetch.ts"],"sourcesContent":["// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\n/**\n * The QueryError class which is thrown by the `fetch` method\n */\nexport class QueryError extends Error {\n\t/** The requested url. */\n\tpublic readonly url: string;\n\t/** The HTTP status code. */\n\tpublic readonly code: number;\n\t/** The returned response body as a string */\n\tpublic readonly body: string;\n\t/** The original {@link Response} object */\n\tpublic readonly response: Response;\n\n\t#json: unknown;\n\n\tpublic constructor(url: string, code: number, response: Response, body: string) {\n\t\tsuper(`Failed to request '${url}' with code ${code}.`);\n\t\tthis.url = url;\n\t\tthis.code = code;\n\t\tthis.body = body;\n\t\tthis.response = response;\n\t\tthis.#json = null;\n\t}\n\n\tpublic toJSON() {\n\t\treturn this.#json ?? (this.#json = JSON.parse(this.body));\n\t}\n}\n","/**\n * The supported return types for the `fetch` method\n */\nexport const enum FetchResultTypes {\n\t/**\n\t * Returns only the body, as JSON. Similar to [`Body.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json).\n\t *\n\t * You should provide your own type cast (either through the generic return type, or with `as <type>`) to the response to define\n\t * the JSON structure, otherwise the result will be `unknown`.\n\t */\n\tJSON = 'json',\n\t/**\n\t * Returns only the body, as a [Buffer](https://nodejs.org/api/buffer.html).\n\t * @remark Does not work in a Browser environment. For browsers use {@link FetchResultTypes.Blob} instead.\n\t * If you use this type in a Browsers environment a {@link ReferenceError `ReferenceError: Buffer is not defined`} will be thrown!\n\t */\n\tBuffer = 'buffer',\n\t/**\n\t * Returns only the body, as a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n\t * @remark For NodeJS environment other `FetchResultTypes` are recommended, but you can use a Blob if you want to.\n\t */\n\tBlob = 'blob',\n\t/**\n\t * Returns only the body, as plain text. Similar to [`Body.text()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/text).\n\t */\n\tText = 'text',\n\t/**\n\t * Returns the entire response and doesn't parse the `body` in any way.\n\t */\n\tResult = 'result'\n}\n\n/**\n * The list of [HTTP Methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)\n */\nexport const enum FetchMethods {\n\t/**\n\t * The `GET` method requests a representation of the specified resource. Requests using `GET` should only retrieve data.\n\t * @see [MDN / Web / HTTP / Methods / GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET)\n\t */\n\tGet = 'GET',\n\t/**\n\t * The `HEAD` method asks for a response identical to that of a {@link FetchMethods.Get `GET`} request, but without the response body.\n\t * @see [MDN / Web / HTTP / Methods / HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD)\n\t */\n\tHead = 'HEAD',\n\t/**\n\t * The `POST` method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.\n\t * @see [MDN / Web / HTTP / Methods / POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)\n\t */\n\tPost = 'POST',\n\t/**\n\t * The `PUT` method replaces all current representations of the target resource with the request payload.\n\t * @see [MDN / Web / HTTP / Methods / PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT)\n\t */\n\tPut = 'PUT',\n\t/**\n\t * The `DELETE` method deletes the specified resource.\n\t * @see [MDN / Web / HTTP / Methods / DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE)\n\t */\n\tDelete = 'DELETE',\n\t/**\n\t * The `CONNECT` method establishes a tunnel to the server identified by the target resource\n\t * @see [MDN / Web / HTTP / Methods / CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT)\n\t */\n\tConnect = 'CONNECT',\n\t/**\n\t * The `OPTIONS` method is used to describe the communication options for the target resource.\n\t * @see [MDN / Web / HTTP / Methods / OPTIONS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS)\n\t */\n\tOptions = 'OPTIONS',\n\t/**\n\t * The `TRACE` method performs a message loop-back test along the path to the target resource.\n\t * @see [MDN / Web / HTTP / Methods / TRACE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE)\n\t */\n\tTrace = 'TRACE',\n\t/**\n\t * The `PATCH` method is used to apply partial modifications to a resource.\n\t * @see [MDN / Web / HTTP / Methods / PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH)\n\t */\n\tPatch = 'PATCH'\n}\n","// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\nimport { fetch as nodeFetch } from 'cross-fetch';\nimport { QueryError } from './QueryError';\nimport { FetchResultTypes } from './types';\n\n/**\n * Performs an HTTP(S) fetch\n * @param url The URL to send the request to. Can be either a `string` or an `URL` object.\n * `url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n * @param optionsOrType Either the [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript) or one of the {@link FetchResultTypes}\n * @param type Only needs to be provided if the second parameter are [Request options](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript). One of the {@link FetchResultTypes} that will determine how the result is returned.\n * @returns The return type is determined by the provided `type`.\n * - When using `FetchResultTypes.JSON` then the return type is `unknown` by default. The type should be specified by filling in the generic type of the function, or casting the result.\n * - When using `FetchResultTypes.Buffer` the return type will be [`Buffer`](https://nodejs.org/api/buffer.html).\n * - When using `FetchResultTypes.Blob` the return type will be a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n * - When using `FetchResultTypes.Text` the return type will be a `string`\n * - When using `FetchResultTypes.Result` the return type will be a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) ({@link Response} in typescript)\n */\nexport async function fetch<R>(url: URL | string, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type: FetchResultTypes): Promise<Response | Blob | Buffer | string | R>;\nexport async function fetch(url: URL | string, options?: RequestInit | FetchResultTypes, type?: FetchResultTypes) {\n\tif (typeof options === 'undefined') {\n\t\toptions = {};\n\t\ttype = FetchResultTypes.JSON;\n\t} else if (typeof options === 'string') {\n\t\ttype = options;\n\t\toptions = {};\n\t} else if (typeof type === 'undefined') {\n\t\ttype = FetchResultTypes.JSON;\n\t}\n\n\t// Transform the URL to a String, in case an URL object was passed\n\tconst stringUrl = String(url);\n\n\tconst result: Response = await nodeFetch(stringUrl, options);\n\tif (!result.ok) throw new QueryError(stringUrl, result.status, result, await result.clone().text());\n\n\tswitch (type) {\n\t\tcase FetchResultTypes.Result:\n\t\t\treturn result;\n\t\tcase FetchResultTypes.Buffer:\n\t\t\treturn Buffer.from(await (await result.blob()).arrayBuffer());\n\t\tcase FetchResultTypes.Blob:\n\t\t\treturn result.blob();\n\t\tcase FetchResultTypes.JSON:\n\t\t\treturn result.json();\n\t\tcase FetchResultTypes.Text:\n\t\t\treturn result.text();\n\t\tdefault:\n\t\t\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YAAY,KAAZ,YAAY;;ACnC9B;AA+BO,eAAe,KAAK,CAAC,GAAiB,EAAE,OAAwC,EAAE,IAAuB;IAC/G,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QACnC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,qBAAyB;KAC7B;SAAM,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QACvC,IAAI,GAAG,OAAO,CAAC;QACf,OAAO,GAAG,EAAE,CAAC;KACb;SAAM,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;QACvC,IAAI,qBAAyB;KAC7B;;IAGD,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IAE9B,MAAM,MAAM,GAAa,MAAMA,OAAS,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAC7D,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,IAAI,UAAU,CAAC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;IAEpG,QAAQ,IAAI;QACX;YACC,OAAO,MAAM,CAAC;QACf;YACC,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,MAAM,CAAC,IAAI,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC;QAC/D;YACC,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC;QACtB;YACC,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC;QACtB;YACC,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC;QACtB;YACC,MAAM,IAAI,KAAK,CAAC,iBAAiB,IAAI,GAAG,CAAC,CAAC;KAC3C;AACF;;;;"}
1
+ {"version":3,"sources":["../src/lib/QueryError.ts","../src/lib/types.ts","../src/lib/fetch.ts"],"sourcesContent":["// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\n/**\n * The QueryError class which is thrown by the `fetch` method\n */\nexport class QueryError extends Error {\n\t/** The requested url. */\n\tpublic readonly url: string;\n\t/** The HTTP status code. */\n\tpublic readonly code: number;\n\t/** The returned response body as a string */\n\tpublic readonly body: string;\n\t/** The original {@link Response} object */\n\tpublic readonly response: Response;\n\n\t#json: unknown;\n\n\tpublic constructor(url: string, code: number, response: Response, body: string) {\n\t\tsuper(`Failed to request '${url}' with code ${code}.`);\n\t\tthis.url = url;\n\t\tthis.code = code;\n\t\tthis.body = body;\n\t\tthis.response = response;\n\t\tthis.#json = null;\n\t}\n\n\tpublic toJSON() {\n\t\treturn this.#json ?? (this.#json = JSON.parse(this.body));\n\t}\n}\n","/**\n * The supported return types for the `fetch` method\n */\nexport const enum FetchResultTypes {\n\t/**\n\t * Returns only the body, as JSON. Similar to [`Body.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json).\n\t *\n\t * You should provide your own type cast (either through the generic return type, or with `as <type>`) to the response to define\n\t * the JSON structure, otherwise the result will be `unknown`.\n\t */\n\tJSON = 'json',\n\t/**\n\t * Returns only the body, as a [Buffer](https://nodejs.org/api/buffer.html).\n\t * @remark Does not work in a Browser environment. For browsers use {@link FetchResultTypes.Blob} instead.\n\t * If you use this type in a Browsers environment a {@link ReferenceError `ReferenceError: Buffer is not defined`} will be thrown!\n\t */\n\tBuffer = 'buffer',\n\t/**\n\t * Returns only the body, as a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n\t * @remark For NodeJS environment other `FetchResultTypes` are recommended, but you can use a Blob if you want to.\n\t */\n\tBlob = 'blob',\n\t/**\n\t * Returns only the body, as plain text. Similar to [`Body.text()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/text).\n\t */\n\tText = 'text',\n\t/**\n\t * Returns the entire response and doesn't parse the `body` in any way.\n\t */\n\tResult = 'result'\n}\n\n/**\n * The list of [HTTP Methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)\n */\nexport const enum FetchMethods {\n\t/**\n\t * The `GET` method requests a representation of the specified resource. Requests using `GET` should only retrieve data.\n\t * @see [MDN / Web / HTTP / Methods / GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET)\n\t */\n\tGet = 'GET',\n\t/**\n\t * The `HEAD` method asks for a response identical to that of a {@link FetchMethods.Get `GET`} request, but without the response body.\n\t * @see [MDN / Web / HTTP / Methods / HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD)\n\t */\n\tHead = 'HEAD',\n\t/**\n\t * The `POST` method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.\n\t * @see [MDN / Web / HTTP / Methods / POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)\n\t */\n\tPost = 'POST',\n\t/**\n\t * The `PUT` method replaces all current representations of the target resource with the request payload.\n\t * @see [MDN / Web / HTTP / Methods / PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT)\n\t */\n\tPut = 'PUT',\n\t/**\n\t * The `DELETE` method deletes the specified resource.\n\t * @see [MDN / Web / HTTP / Methods / DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE)\n\t */\n\tDelete = 'DELETE',\n\t/**\n\t * The `CONNECT` method establishes a tunnel to the server identified by the target resource\n\t * @see [MDN / Web / HTTP / Methods / CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT)\n\t */\n\tConnect = 'CONNECT',\n\t/**\n\t * The `OPTIONS` method is used to describe the communication options for the target resource.\n\t * @see [MDN / Web / HTTP / Methods / OPTIONS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS)\n\t */\n\tOptions = 'OPTIONS',\n\t/**\n\t * The `TRACE` method performs a message loop-back test along the path to the target resource.\n\t * @see [MDN / Web / HTTP / Methods / TRACE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE)\n\t */\n\tTrace = 'TRACE',\n\t/**\n\t * The `PATCH` method is used to apply partial modifications to a resource.\n\t * @see [MDN / Web / HTTP / Methods / PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH)\n\t */\n\tPatch = 'PATCH'\n}\n","// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\nimport { QueryError } from './QueryError';\nimport { FetchResultTypes } from './types';\n\n/**\n * Performs an HTTP(S) fetch\n * @param url The URL to send the request to. Can be either a `string` or an `URL` object.\n * `url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n * @param optionsOrType Either the [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript) or one of the {@link FetchResultTypes}\n * @param type Only needs to be provided if the second parameter are [Request options](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript). One of the {@link FetchResultTypes} that will determine how the result is returned.\n * @returns The return type is determined by the provided `type`.\n * - When using `FetchResultTypes.JSON` then the return type is `unknown` by default. The type should be specified by filling in the generic type of the function, or casting the result.\n * - When using `FetchResultTypes.Buffer` the return type will be [`Buffer`](https://nodejs.org/api/buffer.html).\n * - When using `FetchResultTypes.Blob` the return type will be a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n * - When using `FetchResultTypes.Text` the return type will be a `string`\n * - When using `FetchResultTypes.Result` the return type will be a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) ({@link Response} in typescript)\n */\nexport async function fetch<R>(url: URL | string, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type: FetchResultTypes): Promise<Response | Blob | Buffer | string | R>;\nexport async function fetch(url: URL | string, options?: RequestInit | FetchResultTypes, type?: FetchResultTypes) {\n\tif (typeof options === 'undefined') {\n\t\toptions = {};\n\t\ttype = FetchResultTypes.JSON;\n\t} else if (typeof options === 'string') {\n\t\ttype = options;\n\t\toptions = {};\n\t} else if (typeof type === 'undefined') {\n\t\ttype = FetchResultTypes.JSON;\n\t}\n\n\t// Transform the URL to a String, in case an URL object was passed\n\tconst stringUrl = String(url);\n\n\tconst result: Response = await globalThis.fetch(stringUrl, options);\n\tif (!result.ok) throw new QueryError(stringUrl, result.status, result, await result.clone().text());\n\n\tswitch (type) {\n\t\tcase FetchResultTypes.Result:\n\t\t\treturn result;\n\t\tcase FetchResultTypes.Buffer:\n\t\t\treturn Buffer.from(await (await result.blob()).arrayBuffer());\n\t\tcase FetchResultTypes.Blob:\n\t\t\treturn result.blob();\n\t\tcase FetchResultTypes.JSON:\n\t\t\treturn result.json();\n\t\tcase FetchResultTypes.Text:\n\t\t\treturn result.text();\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown type \"${type}\"`);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAMO,+BAAyB,MAAM;AAAA,EAY9B,YAAY,KAAa,MAAc,UAAoB,MAAc;AAC/E,UAAM,sBAAsB,kBAAkB;AAX/B;AAEA;AAEA;AAEA;AAEhB;AAIC,SAAK,MAAM;AACX,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,uBAAK,OAAQ;AAAA;AAAA,EAGP,SAAS;AACf,WAAO,mBAAK,UAAU,mB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,wBAAsB,KAAK,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,gBAAgB,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AACjH,wBAAsB,KAAK,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,IAAI,EAAE,gBAAgB,CAAC,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAC7F,wBAAsB,KAAK,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,gBAAgB,CAAC,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AACnH,wBAAsB,KAAK,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AACjG,wBAAsB,KAAK,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AACvH,wBAAsB,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,GAAG,MAAM,GAAG,MAAM,GAAG,CAAC,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@sapphire/fetch",
3
- "version": "2.0.4",
4
- "description": "Tiny wrapper around cross-fetch for improved TypeScript and data type support",
3
+ "version": "2.1.0-next.365a53a.0",
4
+ "description": "Tiny wrapper around cross-fetch (for NodeJS) and window.fetch (for Browsers) for improved TypeScript and data type support",
5
5
  "author": "@sapphire",
6
6
  "license": "MIT",
7
7
  "main": "dist/index.js",
8
8
  "module": "dist/index.mjs",
9
- "browser": "dist/index.umd.js",
10
- "unpkg": "dist/index.umd.js",
9
+ "browser": "dist/index.global.js",
10
+ "unpkg": "dist/index.global.js",
11
11
  "types": "dist/index.d.ts",
12
12
  "typedocMain": "src/index.ts",
13
13
  "exports": {
@@ -19,12 +19,11 @@
19
19
  "scripts": {
20
20
  "test": "jest",
21
21
  "lint": "eslint src tests --ext ts --fix -c ../../.eslintrc",
22
- "build": "rollup -c",
23
- "start": "yarn build -w",
22
+ "build": "tsup && tsc -b src",
24
23
  "prepublishOnly": "yarn build"
25
24
  },
26
25
  "dependencies": {
27
- "cross-fetch": "^3.1.4"
26
+ "cross-fetch": "^3.1.5"
28
27
  },
29
28
  "repository": {
30
29
  "type": "git",
@@ -55,5 +54,5 @@
55
54
  "publishConfig": {
56
55
  "access": "public"
57
56
  },
58
- "gitHead": "3a1f23df5fa8191c90760af66fbc72115fa2b13e"
57
+ "gitHead": "365a53a5517a01a0926cf28a83c96b63f32ed9f8"
59
58
  }
package/dist/index.umd.js DELETED
@@ -1,209 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('cross-fetch')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'cross-fetch'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.SapphireFetch = {}, global.window));
5
- })(this, (function (exports, crossFetch) { 'use strict';
6
-
7
- /*! *****************************************************************************
8
- Copyright (c) Microsoft Corporation.
9
-
10
- Permission to use, copy, modify, and/or distribute this software for any
11
- purpose with or without fee is hereby granted.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
- PERFORMANCE OF THIS SOFTWARE.
20
- ***************************************************************************** */
21
-
22
- function __classPrivateFieldGet(receiver, state, kind, f) {
23
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
24
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
25
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
26
- }
27
-
28
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
29
- if (kind === "m") throw new TypeError("Private method is not writable");
30
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
31
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
32
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
33
- }
34
-
35
- // eslint-disable-next-line spaced-comment
36
- /// <reference lib="dom" />
37
- var _QueryError_json;
38
- /**
39
- * The QueryError class which is thrown by the `fetch` method
40
- */
41
- class QueryError extends Error {
42
- constructor(url, code, response, body) {
43
- super(`Failed to request '${url}' with code ${code}.`);
44
- /** The requested url. */
45
- Object.defineProperty(this, "url", {
46
- enumerable: true,
47
- configurable: true,
48
- writable: true,
49
- value: void 0
50
- });
51
- /** The HTTP status code. */
52
- Object.defineProperty(this, "code", {
53
- enumerable: true,
54
- configurable: true,
55
- writable: true,
56
- value: void 0
57
- });
58
- /** The returned response body as a string */
59
- Object.defineProperty(this, "body", {
60
- enumerable: true,
61
- configurable: true,
62
- writable: true,
63
- value: void 0
64
- });
65
- /** The original {@link Response} object */
66
- Object.defineProperty(this, "response", {
67
- enumerable: true,
68
- configurable: true,
69
- writable: true,
70
- value: void 0
71
- });
72
- _QueryError_json.set(this, void 0);
73
- this.url = url;
74
- this.code = code;
75
- this.body = body;
76
- this.response = response;
77
- __classPrivateFieldSet(this, _QueryError_json, null, "f");
78
- }
79
- toJSON() {
80
- return __classPrivateFieldGet(this, _QueryError_json, "f") ?? (__classPrivateFieldSet(this, _QueryError_json, JSON.parse(this.body), "f"));
81
- }
82
- }
83
- _QueryError_json = new WeakMap();
84
-
85
- /**
86
- * The supported return types for the `fetch` method
87
- */
88
- exports.FetchResultTypes = void 0;
89
- (function (FetchResultTypes) {
90
- /**
91
- * Returns only the body, as JSON. Similar to [`Body.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json).
92
- *
93
- * You should provide your own type cast (either through the generic return type, or with `as <type>`) to the response to define
94
- * the JSON structure, otherwise the result will be `unknown`.
95
- */
96
- FetchResultTypes["JSON"] = "json";
97
- /**
98
- * Returns only the body, as a [Buffer](https://nodejs.org/api/buffer.html).
99
- * @remark Does not work in a Browser environment. For browsers use {@link FetchResultTypes.Blob} instead.
100
- * If you use this type in a Browsers environment a {@link ReferenceError `ReferenceError: Buffer is not defined`} will be thrown!
101
- */
102
- FetchResultTypes["Buffer"] = "buffer";
103
- /**
104
- * Returns only the body, as a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
105
- * @remark For NodeJS environment other `FetchResultTypes` are recommended, but you can use a Blob if you want to.
106
- */
107
- FetchResultTypes["Blob"] = "blob";
108
- /**
109
- * Returns only the body, as plain text. Similar to [`Body.text()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/text).
110
- */
111
- FetchResultTypes["Text"] = "text";
112
- /**
113
- * Returns the entire response and doesn't parse the `body` in any way.
114
- */
115
- FetchResultTypes["Result"] = "result";
116
- })(exports.FetchResultTypes || (exports.FetchResultTypes = {}));
117
- /**
118
- * The list of [HTTP Methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)
119
- */
120
- exports.FetchMethods = void 0;
121
- (function (FetchMethods) {
122
- /**
123
- * The `GET` method requests a representation of the specified resource. Requests using `GET` should only retrieve data.
124
- * @see [MDN / Web / HTTP / Methods / GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET)
125
- */
126
- FetchMethods["Get"] = "GET";
127
- /**
128
- * The `HEAD` method asks for a response identical to that of a {@link FetchMethods.Get `GET`} request, but without the response body.
129
- * @see [MDN / Web / HTTP / Methods / HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD)
130
- */
131
- FetchMethods["Head"] = "HEAD";
132
- /**
133
- * The `POST` method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.
134
- * @see [MDN / Web / HTTP / Methods / POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)
135
- */
136
- FetchMethods["Post"] = "POST";
137
- /**
138
- * The `PUT` method replaces all current representations of the target resource with the request payload.
139
- * @see [MDN / Web / HTTP / Methods / PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT)
140
- */
141
- FetchMethods["Put"] = "PUT";
142
- /**
143
- * The `DELETE` method deletes the specified resource.
144
- * @see [MDN / Web / HTTP / Methods / DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE)
145
- */
146
- FetchMethods["Delete"] = "DELETE";
147
- /**
148
- * The `CONNECT` method establishes a tunnel to the server identified by the target resource
149
- * @see [MDN / Web / HTTP / Methods / CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT)
150
- */
151
- FetchMethods["Connect"] = "CONNECT";
152
- /**
153
- * The `OPTIONS` method is used to describe the communication options for the target resource.
154
- * @see [MDN / Web / HTTP / Methods / OPTIONS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS)
155
- */
156
- FetchMethods["Options"] = "OPTIONS";
157
- /**
158
- * The `TRACE` method performs a message loop-back test along the path to the target resource.
159
- * @see [MDN / Web / HTTP / Methods / TRACE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE)
160
- */
161
- FetchMethods["Trace"] = "TRACE";
162
- /**
163
- * The `PATCH` method is used to apply partial modifications to a resource.
164
- * @see [MDN / Web / HTTP / Methods / PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH)
165
- */
166
- FetchMethods["Patch"] = "PATCH";
167
- })(exports.FetchMethods || (exports.FetchMethods = {}));
168
-
169
- // eslint-disable-next-line spaced-comment
170
- async function fetch(url, options, type) {
171
- if (typeof options === 'undefined') {
172
- options = {};
173
- type = "json" /* JSON */;
174
- }
175
- else if (typeof options === 'string') {
176
- type = options;
177
- options = {};
178
- }
179
- else if (typeof type === 'undefined') {
180
- type = "json" /* JSON */;
181
- }
182
- // Transform the URL to a String, in case an URL object was passed
183
- const stringUrl = String(url);
184
- const result = await crossFetch.fetch(stringUrl, options);
185
- if (!result.ok)
186
- throw new QueryError(stringUrl, result.status, result, await result.clone().text());
187
- switch (type) {
188
- case "result" /* Result */:
189
- return result;
190
- case "buffer" /* Buffer */:
191
- return Buffer.from(await (await result.blob()).arrayBuffer());
192
- case "blob" /* Blob */:
193
- return result.blob();
194
- case "json" /* JSON */:
195
- return result.json();
196
- case "text" /* Text */:
197
- return result.text();
198
- default:
199
- throw new Error(`Unknown type "${type}"`);
200
- }
201
- }
202
-
203
- exports.QueryError = QueryError;
204
- exports.fetch = fetch;
205
-
206
- Object.defineProperty(exports, '__esModule', { value: true });
207
-
208
- }));
209
- //# sourceMappingURL=index.umd.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.umd.js","sources":["../src/lib/QueryError.ts","../src/lib/types.ts","../src/lib/fetch.ts"],"sourcesContent":["// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\n/**\n * The QueryError class which is thrown by the `fetch` method\n */\nexport class QueryError extends Error {\n\t/** The requested url. */\n\tpublic readonly url: string;\n\t/** The HTTP status code. */\n\tpublic readonly code: number;\n\t/** The returned response body as a string */\n\tpublic readonly body: string;\n\t/** The original {@link Response} object */\n\tpublic readonly response: Response;\n\n\t#json: unknown;\n\n\tpublic constructor(url: string, code: number, response: Response, body: string) {\n\t\tsuper(`Failed to request '${url}' with code ${code}.`);\n\t\tthis.url = url;\n\t\tthis.code = code;\n\t\tthis.body = body;\n\t\tthis.response = response;\n\t\tthis.#json = null;\n\t}\n\n\tpublic toJSON() {\n\t\treturn this.#json ?? (this.#json = JSON.parse(this.body));\n\t}\n}\n","/**\n * The supported return types for the `fetch` method\n */\nexport const enum FetchResultTypes {\n\t/**\n\t * Returns only the body, as JSON. Similar to [`Body.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json).\n\t *\n\t * You should provide your own type cast (either through the generic return type, or with `as <type>`) to the response to define\n\t * the JSON structure, otherwise the result will be `unknown`.\n\t */\n\tJSON = 'json',\n\t/**\n\t * Returns only the body, as a [Buffer](https://nodejs.org/api/buffer.html).\n\t * @remark Does not work in a Browser environment. For browsers use {@link FetchResultTypes.Blob} instead.\n\t * If you use this type in a Browsers environment a {@link ReferenceError `ReferenceError: Buffer is not defined`} will be thrown!\n\t */\n\tBuffer = 'buffer',\n\t/**\n\t * Returns only the body, as a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n\t * @remark For NodeJS environment other `FetchResultTypes` are recommended, but you can use a Blob if you want to.\n\t */\n\tBlob = 'blob',\n\t/**\n\t * Returns only the body, as plain text. Similar to [`Body.text()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/text).\n\t */\n\tText = 'text',\n\t/**\n\t * Returns the entire response and doesn't parse the `body` in any way.\n\t */\n\tResult = 'result'\n}\n\n/**\n * The list of [HTTP Methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)\n */\nexport const enum FetchMethods {\n\t/**\n\t * The `GET` method requests a representation of the specified resource. Requests using `GET` should only retrieve data.\n\t * @see [MDN / Web / HTTP / Methods / GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET)\n\t */\n\tGet = 'GET',\n\t/**\n\t * The `HEAD` method asks for a response identical to that of a {@link FetchMethods.Get `GET`} request, but without the response body.\n\t * @see [MDN / Web / HTTP / Methods / HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD)\n\t */\n\tHead = 'HEAD',\n\t/**\n\t * The `POST` method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.\n\t * @see [MDN / Web / HTTP / Methods / POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)\n\t */\n\tPost = 'POST',\n\t/**\n\t * The `PUT` method replaces all current representations of the target resource with the request payload.\n\t * @see [MDN / Web / HTTP / Methods / PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT)\n\t */\n\tPut = 'PUT',\n\t/**\n\t * The `DELETE` method deletes the specified resource.\n\t * @see [MDN / Web / HTTP / Methods / DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE)\n\t */\n\tDelete = 'DELETE',\n\t/**\n\t * The `CONNECT` method establishes a tunnel to the server identified by the target resource\n\t * @see [MDN / Web / HTTP / Methods / CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT)\n\t */\n\tConnect = 'CONNECT',\n\t/**\n\t * The `OPTIONS` method is used to describe the communication options for the target resource.\n\t * @see [MDN / Web / HTTP / Methods / OPTIONS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS)\n\t */\n\tOptions = 'OPTIONS',\n\t/**\n\t * The `TRACE` method performs a message loop-back test along the path to the target resource.\n\t * @see [MDN / Web / HTTP / Methods / TRACE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE)\n\t */\n\tTrace = 'TRACE',\n\t/**\n\t * The `PATCH` method is used to apply partial modifications to a resource.\n\t * @see [MDN / Web / HTTP / Methods / PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH)\n\t */\n\tPatch = 'PATCH'\n}\n","// eslint-disable-next-line spaced-comment\n/// <reference lib=\"dom\" />\n\nimport { fetch as nodeFetch } from 'cross-fetch';\nimport { QueryError } from './QueryError';\nimport { FetchResultTypes } from './types';\n\n/**\n * Performs an HTTP(S) fetch\n * @param url The URL to send the request to. Can be either a `string` or an `URL` object.\n * `url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n * @param optionsOrType Either the [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript) or one of the {@link FetchResultTypes}\n * @param type Only needs to be provided if the second parameter are [Request options](https://developer.mozilla.org/en-US/docs/Web/API/Request) ({@link RequestInit} for TypeScript). One of the {@link FetchResultTypes} that will determine how the result is returned.\n * @returns The return type is determined by the provided `type`.\n * - When using `FetchResultTypes.JSON` then the return type is `unknown` by default. The type should be specified by filling in the generic type of the function, or casting the result.\n * - When using `FetchResultTypes.Buffer` the return type will be [`Buffer`](https://nodejs.org/api/buffer.html).\n * - When using `FetchResultTypes.Blob` the return type will be a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n * - When using `FetchResultTypes.Text` the return type will be a `string`\n * - When using `FetchResultTypes.Result` the return type will be a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) ({@link Response} in typescript)\n */\nexport async function fetch<R>(url: URL | string, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type?: FetchResultTypes.JSON): Promise<R>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Buffer): Promise<Buffer>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Blob): Promise<Blob>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Text): Promise<string>;\nexport async function fetch(url: URL | string, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch(url: URL | string, options: RequestInit, type: FetchResultTypes.Result): Promise<Response>;\nexport async function fetch<R>(url: URL | string, options: RequestInit, type: FetchResultTypes): Promise<Response | Blob | Buffer | string | R>;\nexport async function fetch(url: URL | string, options?: RequestInit | FetchResultTypes, type?: FetchResultTypes) {\n\tif (typeof options === 'undefined') {\n\t\toptions = {};\n\t\ttype = FetchResultTypes.JSON;\n\t} else if (typeof options === 'string') {\n\t\ttype = options;\n\t\toptions = {};\n\t} else if (typeof type === 'undefined') {\n\t\ttype = FetchResultTypes.JSON;\n\t}\n\n\t// Transform the URL to a String, in case an URL object was passed\n\tconst stringUrl = String(url);\n\n\tconst result: Response = await nodeFetch(stringUrl, options);\n\tif (!result.ok) throw new QueryError(stringUrl, result.status, result, await result.clone().text());\n\n\tswitch (type) {\n\t\tcase FetchResultTypes.Result:\n\t\t\treturn result;\n\t\tcase FetchResultTypes.Buffer:\n\t\t\treturn Buffer.from(await (await result.blob()).arrayBuffer());\n\t\tcase FetchResultTypes.Blob:\n\t\t\treturn result.blob();\n\t\tcase FetchResultTypes.JSON:\n\t\t\treturn result.json();\n\t\tcase FetchResultTypes.Text:\n\t\t\treturn result.text();\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown type \"${type}\"`);\n\t}\n}\n"],"names":["FetchResultTypes","FetchMethods","nodeFetch"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAA;IACA;;IAEA;;;UAGa,UAAW,SAAQ,KAAK;QAYpC,YAAmB,GAAW,EAAE,IAAY,EAAE,QAAkB,EAAE,IAAY;YAC7E,KAAK,CAAC,sBAAsB,GAAG,eAAe,IAAI,GAAG,CAAC,CAAC;;YAXxD;;;;;eAA4B;;YAE5B;;;;;eAA6B;;YAE7B;;;;;eAA6B;;YAE7B;;;;;eAAmC;YAEnC,mCAAe;YAId,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;YACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;YACjB,IAAI,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