make-service 3.1.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  A type-safe thin wrapper around the `fetch` API to better interact with external APIs.
8
8
 
9
- It adds a set of little features and allows you to parse responses with [zod](https://github.com/colinhacks/zod).
9
+ It adds a set of little features and allows you to parse responses with [standard-schema libraries](https://standardschema.dev).
10
10
 
11
11
  ## Features
12
12
  - 🤩 Type-safe return of `response.json()` and `response.text()`. Defaults to `unknown` instead of `any`.
@@ -37,6 +37,7 @@ const users = await response.json(usersSchema);
37
37
  - [makeService](#makeservice)
38
38
  - [Type-checking the response body](#type-checking-the-response-body)
39
39
  - [Runtime type-checking and parsing the response body](#runtime-type-checking-and-parsing-the-response-body)
40
+ - [Dealing with parsing errors](#dealing-with-parsing-errors)
40
41
  - [Supported HTTP Verbs](#supported-http-verbs)
41
42
  - [Headers](#headers)
42
43
  - [Passing a function as `headers`](#passing-a-function-as-headers)
@@ -52,13 +53,14 @@ const users = await response.json(usersSchema);
52
53
  - [makeFetcher](#makefetcher)
53
54
  - [enhancedFetch](#enhancedfetch)
54
55
  - [typedResponse](#typedresponse)
55
- - [Transform the Payload](#transform-the-payload)
56
+ - [Transform the payload](#transform-the-payload)
56
57
  - [Other available primitives](#other-available-primitives)
57
58
  - [addQueryToURL](#addquerytourl)
58
59
  - [ensureStringBody](#ensurestringbody)
59
60
  - [makeGetApiURL](#makegetapiurl)
60
61
  - [mergeHeaders](#mergeheaders)
61
62
  - [replaceURLParams](#replaceurlparams)
63
+ - [Contributors](#contributors)
62
64
  - [Acknowledgements](#acknowledgements)
63
65
 
64
66
  # Installation
@@ -119,8 +121,8 @@ const content = await response.text<`${string}@${string}`>()
119
121
  ```
120
122
 
121
123
  ### Runtime type-checking and parsing the response body
122
- Its [`typedResponse`](#typedresponse) can also be parsed with a zod schema. Here follows a little more complex example:
123
124
 
125
+ Its [`typedResponse`](#typedresponse) can also be parsed with a standard schema parser. Here follows a little more complex example with Zod:
124
126
  ```ts
125
127
  const response = await service.get("/users")
126
128
  const json = await response.json(
@@ -142,6 +144,20 @@ const content = await response.text(z.string().email())
142
144
  ```
143
145
  You can transform any `Response` in a `TypedResponse` like that by using the [`typedResponse`](#typedresponse) function.
144
146
 
147
+ #### Dealing with parsing errors
148
+ If the response body does not match the given schema, it will throw a **ParseResponseError** which will have a message carrying all the parsing issues and its messages. You can catch it to inspect the issues:
149
+
150
+ ```ts
151
+ try {
152
+ const response = await service.get("/users")
153
+ return await response.json(userSchema)
154
+ } catch(error) {
155
+ if (error instanceof ParseResponseError) {
156
+ console.log(error.issues)
157
+ }
158
+ }
159
+ ```
160
+
145
161
  ### Supported HTTP Verbs
146
162
  Other than the `get` it also accepts more HTTP verbs:
147
163
  ```ts
@@ -210,8 +226,8 @@ Note: Don't forget headers are case insensitive.
210
226
  const headers = new Headers({ 'Content-Type': 'application/json' })
211
227
  Object.fromEntries(headers) // equals to: { 'content-type': 'application/json' }
212
228
  ```
213
- All the features above are done by using the [`mergeHeaders`](#mergeheaders) function internally.
214
229
 
230
+ All the features above are done by using the [`mergeHeaders`](#mergeheaders) function internally.
215
231
 
216
232
  ### Base URL
217
233
  The service function can receive a `string` or `URL` as base `url` and it will be able to merge them correctly with the given path:
@@ -231,16 +247,28 @@ You can use the [`makeGetApiUrl`](#makegetapiurl) method to do that kind of URL
231
247
  `makeService` can also receive `requestTransformer` and `responseTransformer` as options that will be applied to all requests.
232
248
 
233
249
  #### Request transformers
234
- You can transform the request in any way you want, like:
250
+ You can transform the request in any way you want passing a transformer function as a parameter. This will be applied to all requests for that service.
251
+ A useful example is to implement a global request timeout for all endpoints of a service:
235
252
 
236
253
  ```ts
237
- const service = makeService('https://example.com/api', {
238
- requestTransformer: (request) => ({ ...request, query: { admin: 'true' } }),
239
- })
254
+ function timeoutRequestIn30Seconds(
255
+ request: EnhancedRequestInit<string>,
256
+ ): EnhancedRequestInit<string> {
257
+ const terminator = new AbortController()
258
+ terminator.signal.throwIfAborted()
259
+ setTimeout(() => terminator.abort(), 30000)
260
+
261
+ return {
262
+ ...request,
263
+ signal: terminator.signal,
264
+ }
265
+ }
266
+
267
+ const service = makeService('https://example.com/api', { requestTransformer: timeoutRequestIn30Seconds })
240
268
 
241
269
  const response = await service.get("/users")
242
270
 
243
- // It will call "https://example.com/api/users?admin=true"
271
+ // It will call "https://example.com/api/users" aborting (and throwing an exception) if it takes more than 30 seconds.
244
272
  ```
245
273
 
246
274
  Please note that the `headers` option will be applied _after_ the request transformer runs. If you're using a request transformer, we recommend adding custom headers inside your transformer instead of using both options.
@@ -415,7 +443,7 @@ The `trace` function can also return a `Promise<void>` in order to send traces t
415
443
 
416
444
  ## typedResponse
417
445
 
418
- A type-safe wrapper around the `Response` object. It adds a `json` and `text` method that will parse the response with a given zod schema. If you don't provide a schema, it will return `unknown` instead of `any`, then you can also give it a generic to type cast the result.
446
+ A type-safe wrapper around the `Response` object. It adds a `json` and `text` method that will parse the response with a given standard schema library. If you don't provide a schema, it will return `unknown` instead of `any`, then you can also give it a generic to type cast the result.
419
447
 
420
448
  ```ts
421
449
  import { typedResponse } from 'make-service'
@@ -449,11 +477,11 @@ import { deepCamelKeys, deepKebabKeys } from 'string-ts'
449
477
 
450
478
  const service = makeService("https://example.com/api")
451
479
  const response = service.get("/users")
452
- const users = await response.json(
480
+ const json = await response.json(
453
481
  z
454
482
  .array(z.object({ "first-name": z.string(), contact: z.object({ "home-address": z.string() }) }))
455
- .transform(deepCamelKeys)
456
483
  )
484
+ const users = deepCamelKeys(json)
457
485
  console.log(users)
458
486
  // ^? { firstName: string, contact: { homeAddress: string } }[]
459
487
 
@@ -592,9 +620,9 @@ The params will be **strongly-typed** which means they will be validated against
592
620
  <tbody>
593
621
  <tr>
594
622
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/gustavoguichard"><img src="https://avatars.githubusercontent.com/u/566971?v=4?s=100" width="100px;" alt="Guga Guichard"/><br /><sub><b>Guga Guichard</b></sub></a><br /><a href="#code-gustavoguichard" title="Code">💻</a> <a href="#projectManagement-gustavoguichard" title="Project Management">📆</a> <a href="#promotion-gustavoguichard" title="Promotion">📣</a> <a href="#maintenance-gustavoguichard" title="Maintenance">🚧</a> <a href="#doc-gustavoguichard" title="Documentation">📖</a> <a href="#bug-gustavoguichard" title="Bug reports">🐛</a> <a href="#infra-gustavoguichard" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="#question-gustavoguichard" title="Answering Questions">💬</a> <a href="#research-gustavoguichard" title="Research">🔬</a> <a href="#review-gustavoguichard" title="Reviewed Pull Requests">👀</a> <a href="#ideas-gustavoguichard" title="Ideas, Planning, & Feedback">🤔</a> <a href="#example-gustavoguichard" title="Examples">💡</a></td>
595
- <td align="center" valign="top" width="14.28%"><a href="https://www.linkedin.com/in/danielweinmann"><img src="https://avatars.githubusercontent.com/u/204765?v=4?s=100" width="100px;" alt="Daniel Weinmann"/><br /><sub><b>Daniel Weinmann</b></sub></a><br /><a href="#code-danielweinmann" title="Code">💻</a> <a href="#promotion-danielweinmann" title="Promotion">📣</a> <a href="#ideas-danielweinmann" title="Ideas, Planning, & Feedback">🤔</a> <a href="#doc-danielweinmann" title="Documentation">📖</a> <a href="#bug-danielweinmann" title="Bug reports">🐛</a></td>
623
+ <td align="center" valign="top" width="14.28%"><a href="https://www.linkedin.com/in/danielweinmann"><img src="https://avatars.githubusercontent.com/u/204765?v=4?s=100" width="100px;" alt="Daniel Weinmann"/><br /><sub><b>Daniel Weinmann</b></sub></a><br /><a href="#code-danielweinmann" title="Code">💻</a> <a href="#promotion-danielweinmann" title="Promotion">📣</a> <a href="#ideas-danielweinmann" title="Ideas, Planning, & Feedback">🤔</a> <a href="#doc-danielweinmann" title="Documentation">📖</a> <a href="#bug-danielweinmann" title="Bug reports">🐛</a> <a href="#review-danielweinmann" title="Reviewed Pull Requests">👀</a></td>
596
624
  <td align="center" valign="top" width="14.28%"><a href="https://luca.md"><img src="https://avatars.githubusercontent.com/u/1881266?v=4?s=100" width="100px;" alt="Andrei Luca"/><br /><sub><b>Andrei Luca</b></sub></a><br /><a href="#doc-iamandrewluca" title="Documentation">📖</a> <a href="#code-iamandrewluca" title="Code">💻</a> <a href="#promotion-iamandrewluca" title="Promotion">📣</a> <a href="#maintenance-iamandrewluca" title="Maintenance">🚧</a> <a href="#bug-iamandrewluca" title="Bug reports">🐛</a> <a href="#ideas-iamandrewluca" title="Ideas, Planning, & Feedback">🤔</a></td>
597
- <td align="center" valign="top" width="14.28%"><a href="https://github.com/diogob"><img src="https://avatars.githubusercontent.com/u/20662?v=4?s=100" width="100px;" alt="Diogo Biazus"/><br /><sub><b>Diogo Biazus</b></sub></a><br /><a href="#code-diogob" title="Code">💻</a></td>
625
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/diogob"><img src="https://avatars.githubusercontent.com/u/20662?v=4?s=100" width="100px;" alt="Diogo Biazus"/><br /><sub><b>Diogo Biazus</b></sub></a><br /><a href="#code-diogob" title="Code">💻</a> <a href="#doc-diogob" title="Documentation">📖</a></td>
598
626
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/garusis"><img src="https://avatars.githubusercontent.com/u/15615652?v=4?s=100" width="100px;" alt="Marcos Javier Alvarez Maestre"/><br /><sub><b>Marcos Javier Alvarez Maestre</b></sub></a><br /><a href="#code-garusis" title="Code">💻</a> <a href="#bug-garusis" title="Bug reports">🐛</a></td>
599
627
  </tr>
600
628
  </tbody>
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
+ import { StandardSchemaV1 } from 'zod/lib/standard-schema';
2
+ import { StandardSchemaV1 as StandardSchemaV1$1 } from '@standard-schema/spec';
3
+
1
4
  declare const HTTP_METHODS: readonly ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD", "CONNECT"];
2
5
 
3
- type Schema<T> = {
4
- parse: (d: unknown) => T;
5
- };
6
6
  type JSONValue = string | number | boolean | Date | {
7
7
  [x: string]: JSONValue | undefined | null;
8
8
  } | Array<JSONValue | undefined | null>;
@@ -11,7 +11,7 @@ type TypedResponse = Omit<Response, 'json' | 'text'> & {
11
11
  json: TypedResponseJson;
12
12
  text: TypedResponseText;
13
13
  };
14
- type PathParams<T> = T extends string ? ExtractPathParams<T> extends Record<string, unknown> ? ExtractPathParams<T> : Record<string, string> : Record<string, string>;
14
+ type PathParams<T> = T extends string ? ExtractPathParams<T> extends Record<string, unknown> ? ExtractPathParams<T> : Record<string, string | number> : Record<string, string | number>;
15
15
  type EnhancedRequestInit<T = string> = Omit<RequestInit, 'body' | 'method'> & {
16
16
  method?: HTTPMethod | Lowercase<HTTPMethod>;
17
17
  body?: JSONValue | BodyInit | null;
@@ -28,17 +28,17 @@ type BaseOptions = {
28
28
  responseTransformer?: ResponseTransformer;
29
29
  };
30
30
  type HTTPMethod = (typeof HTTP_METHODS)[number];
31
- type TypedResponseJson = <T = unknown>(schema?: Schema<T>) => Promise<T>;
32
- type TypedResponseText = <T extends string = string>(schema?: Schema<T>) => Promise<T>;
31
+ type TypedResponseJson = <T = unknown>(schema?: StandardSchemaV1<T>) => Promise<T>;
32
+ type TypedResponseText = <T extends string = string>(schema?: StandardSchemaV1<T>) => Promise<T>;
33
33
  type GetJson = (response: Response) => TypedResponseJson;
34
34
  type GetText = (response: Response) => TypedResponseText;
35
35
  type Prettify<T> = {
36
36
  [K in keyof T]: T[K];
37
37
  } & {};
38
38
  type ExtractPathParams<T extends string> = T extends `${infer _}:${infer Param}/${infer Rest}` ? Prettify<Omit<{
39
- [K in Param]: string;
39
+ [K in Param]: string | number;
40
40
  } & ExtractPathParams<Rest>, ''>> : T extends `${infer _}:${infer Param}` ? {
41
- [K in Param]: string;
41
+ [K in Param]: string | number;
42
42
  } : {};
43
43
 
44
44
  /**
@@ -140,5 +140,12 @@ declare function replaceURLParams<T extends string | URL>(url: T, params: PathPa
140
140
  * @returns the type of the value
141
141
  */
142
142
  declare function typeOf(t: unknown): "array" | "arraybuffer" | "bigint" | "blob" | "boolean" | "formdata" | "function" | "null" | "number" | "object" | "readablestream" | "string" | "symbol" | "undefined" | "url" | "urlsearchparams";
143
+ /**
144
+ * Error thrown when the response cannot be parsed.
145
+ */
146
+ declare class ParseResponseError extends Error {
147
+ issues: readonly StandardSchemaV1$1.Issue[];
148
+ constructor(message: string, issues: readonly StandardSchemaV1$1.Issue[]);
149
+ }
143
150
 
144
- export { type BaseOptions, type EnhancedRequestInit, type GetJson, type GetText, type HTTPMethod, type JSONValue, type PathParams, type RequestTransformer, type ResponseTransformer, type Schema, type SearchParams, type ServiceRequestInit, type TypedResponse, type TypedResponseJson, type TypedResponseText, addQueryToURL, enhancedFetch, ensureStringBody, makeFetcher, makeGetApiURL, makeService, mergeHeaders, replaceURLParams, typeOf, typedResponse };
151
+ export { type BaseOptions, type EnhancedRequestInit, type GetJson, type GetText, type HTTPMethod, type JSONValue, ParseResponseError, type PathParams, type RequestTransformer, type ResponseTransformer, type SearchParams, type ServiceRequestInit, type TypedResponse, type TypedResponseJson, type TypedResponseText, addQueryToURL, enhancedFetch, ensureStringBody, makeFetcher, makeGetApiURL, makeService, mergeHeaders, replaceURLParams, typeOf, typedResponse };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
+ import { StandardSchemaV1 } from 'zod/lib/standard-schema';
2
+ import { StandardSchemaV1 as StandardSchemaV1$1 } from '@standard-schema/spec';
3
+
1
4
  declare const HTTP_METHODS: readonly ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD", "CONNECT"];
2
5
 
3
- type Schema<T> = {
4
- parse: (d: unknown) => T;
5
- };
6
6
  type JSONValue = string | number | boolean | Date | {
7
7
  [x: string]: JSONValue | undefined | null;
8
8
  } | Array<JSONValue | undefined | null>;
@@ -11,7 +11,7 @@ type TypedResponse = Omit<Response, 'json' | 'text'> & {
11
11
  json: TypedResponseJson;
12
12
  text: TypedResponseText;
13
13
  };
14
- type PathParams<T> = T extends string ? ExtractPathParams<T> extends Record<string, unknown> ? ExtractPathParams<T> : Record<string, string> : Record<string, string>;
14
+ type PathParams<T> = T extends string ? ExtractPathParams<T> extends Record<string, unknown> ? ExtractPathParams<T> : Record<string, string | number> : Record<string, string | number>;
15
15
  type EnhancedRequestInit<T = string> = Omit<RequestInit, 'body' | 'method'> & {
16
16
  method?: HTTPMethod | Lowercase<HTTPMethod>;
17
17
  body?: JSONValue | BodyInit | null;
@@ -28,17 +28,17 @@ type BaseOptions = {
28
28
  responseTransformer?: ResponseTransformer;
29
29
  };
30
30
  type HTTPMethod = (typeof HTTP_METHODS)[number];
31
- type TypedResponseJson = <T = unknown>(schema?: Schema<T>) => Promise<T>;
32
- type TypedResponseText = <T extends string = string>(schema?: Schema<T>) => Promise<T>;
31
+ type TypedResponseJson = <T = unknown>(schema?: StandardSchemaV1<T>) => Promise<T>;
32
+ type TypedResponseText = <T extends string = string>(schema?: StandardSchemaV1<T>) => Promise<T>;
33
33
  type GetJson = (response: Response) => TypedResponseJson;
34
34
  type GetText = (response: Response) => TypedResponseText;
35
35
  type Prettify<T> = {
36
36
  [K in keyof T]: T[K];
37
37
  } & {};
38
38
  type ExtractPathParams<T extends string> = T extends `${infer _}:${infer Param}/${infer Rest}` ? Prettify<Omit<{
39
- [K in Param]: string;
39
+ [K in Param]: string | number;
40
40
  } & ExtractPathParams<Rest>, ''>> : T extends `${infer _}:${infer Param}` ? {
41
- [K in Param]: string;
41
+ [K in Param]: string | number;
42
42
  } : {};
43
43
 
44
44
  /**
@@ -140,5 +140,12 @@ declare function replaceURLParams<T extends string | URL>(url: T, params: PathPa
140
140
  * @returns the type of the value
141
141
  */
142
142
  declare function typeOf(t: unknown): "array" | "arraybuffer" | "bigint" | "blob" | "boolean" | "formdata" | "function" | "null" | "number" | "object" | "readablestream" | "string" | "symbol" | "undefined" | "url" | "urlsearchparams";
143
+ /**
144
+ * Error thrown when the response cannot be parsed.
145
+ */
146
+ declare class ParseResponseError extends Error {
147
+ issues: readonly StandardSchemaV1$1.Issue[];
148
+ constructor(message: string, issues: readonly StandardSchemaV1$1.Issue[]);
149
+ }
143
150
 
144
- export { type BaseOptions, type EnhancedRequestInit, type GetJson, type GetText, type HTTPMethod, type JSONValue, type PathParams, type RequestTransformer, type ResponseTransformer, type Schema, type SearchParams, type ServiceRequestInit, type TypedResponse, type TypedResponseJson, type TypedResponseText, addQueryToURL, enhancedFetch, ensureStringBody, makeFetcher, makeGetApiURL, makeService, mergeHeaders, replaceURLParams, typeOf, typedResponse };
151
+ export { type BaseOptions, type EnhancedRequestInit, type GetJson, type GetText, type HTTPMethod, type JSONValue, ParseResponseError, type PathParams, type RequestTransformer, type ResponseTransformer, type SearchParams, type ServiceRequestInit, type TypedResponse, type TypedResponseJson, type TypedResponseText, addQueryToURL, enhancedFetch, ensureStringBody, makeFetcher, makeGetApiURL, makeService, mergeHeaders, replaceURLParams, typeOf, typedResponse };
package/dist/index.js CHANGED
@@ -18,8 +18,9 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
 
20
20
  // src/index.ts
21
- var src_exports = {};
22
- __export(src_exports, {
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ParseResponseError: () => ParseResponseError,
23
24
  addQueryToURL: () => addQueryToURL,
24
25
  enhancedFetch: () => enhancedFetch,
25
26
  ensureStringBody: () => ensureStringBody,
@@ -31,7 +32,7 @@ __export(src_exports, {
31
32
  typeOf: () => typeOf,
32
33
  typedResponse: () => typedResponse
33
34
  });
34
- module.exports = __toCommonJS(src_exports);
35
+ module.exports = __toCommonJS(index_exports);
35
36
 
36
37
  // src/constants.ts
37
38
  var HTTP_METHODS = [
@@ -46,16 +47,6 @@ var HTTP_METHODS = [
46
47
  // 'TRACE', it has no support in most browsers yet
47
48
  ];
48
49
 
49
- // src/internals.ts
50
- var getJson = (response) => async (schema) => {
51
- const json = await response.json();
52
- return schema ? schema.parse(json) : json;
53
- };
54
- var getText = (response) => async (schema) => {
55
- const text = await response.text();
56
- return schema ? schema.parse(text) : text;
57
- };
58
-
59
50
  // src/primitives.ts
60
51
  function addQueryToURL(url, searchParams) {
61
52
  if (!searchParams) return url;
@@ -83,7 +74,7 @@ function makeGetApiURL(baseURL) {
83
74
  };
84
75
  }
85
76
  function mergeHeaders(...entries) {
86
- const result = /* @__PURE__ */ new Map();
77
+ const result = new Headers();
87
78
  for (const entry of entries) {
88
79
  const headers = new Headers(entry);
89
80
  for (const [key, value] of headers.entries()) {
@@ -94,7 +85,7 @@ function mergeHeaders(...entries) {
94
85
  }
95
86
  }
96
87
  }
97
- return new Headers(Array.from(result.entries()));
88
+ return result;
98
89
  }
99
90
  function replaceURLParams(url, params) {
100
91
  if (!params) return url;
@@ -107,6 +98,34 @@ function replaceURLParams(url, params) {
107
98
  function typeOf(t) {
108
99
  return Object.prototype.toString.call(t).replace(/^\[object (.+)\]$/, "$1").toLowerCase();
109
100
  }
101
+ var ParseResponseError = class extends Error {
102
+ constructor(message, issues) {
103
+ super(JSON.stringify({ message, issues }, null, 2));
104
+ this.issues = issues;
105
+ this.name = "ParseResponseError";
106
+ this.issues = issues;
107
+ }
108
+ };
109
+
110
+ // src/internals.ts
111
+ var getJson = (response) => async (schema) => {
112
+ const json = await response.json();
113
+ if (!schema) return json;
114
+ const result = await schema["~standard"].validate(json);
115
+ if (result.issues) {
116
+ throw new ParseResponseError("Failed to parse response.json", result.issues);
117
+ }
118
+ return result.value;
119
+ };
120
+ var getText = (response) => async (schema) => {
121
+ const text = await response.text();
122
+ if (!schema) return text;
123
+ const result = await schema["~standard"].validate(text);
124
+ if (result.issues) {
125
+ throw new ParseResponseError("Failed to parse response.text", result.issues);
126
+ }
127
+ return result.value;
128
+ };
110
129
 
111
130
  // src/api.ts
112
131
  var identity = (value) => value;
@@ -170,6 +189,7 @@ function makeService(baseURL, baseOptions) {
170
189
  }
171
190
  // Annotate the CommonJS export names for ESM import in node:
172
191
  0 && (module.exports = {
192
+ ParseResponseError,
173
193
  addQueryToURL,
174
194
  enhancedFetch,
175
195
  ensureStringBody,
package/dist/index.mjs CHANGED
@@ -11,16 +11,6 @@ var HTTP_METHODS = [
11
11
  // 'TRACE', it has no support in most browsers yet
12
12
  ];
13
13
 
14
- // src/internals.ts
15
- var getJson = (response) => async (schema) => {
16
- const json = await response.json();
17
- return schema ? schema.parse(json) : json;
18
- };
19
- var getText = (response) => async (schema) => {
20
- const text = await response.text();
21
- return schema ? schema.parse(text) : text;
22
- };
23
-
24
14
  // src/primitives.ts
25
15
  function addQueryToURL(url, searchParams) {
26
16
  if (!searchParams) return url;
@@ -48,7 +38,7 @@ function makeGetApiURL(baseURL) {
48
38
  };
49
39
  }
50
40
  function mergeHeaders(...entries) {
51
- const result = /* @__PURE__ */ new Map();
41
+ const result = new Headers();
52
42
  for (const entry of entries) {
53
43
  const headers = new Headers(entry);
54
44
  for (const [key, value] of headers.entries()) {
@@ -59,7 +49,7 @@ function mergeHeaders(...entries) {
59
49
  }
60
50
  }
61
51
  }
62
- return new Headers(Array.from(result.entries()));
52
+ return result;
63
53
  }
64
54
  function replaceURLParams(url, params) {
65
55
  if (!params) return url;
@@ -72,6 +62,34 @@ function replaceURLParams(url, params) {
72
62
  function typeOf(t) {
73
63
  return Object.prototype.toString.call(t).replace(/^\[object (.+)\]$/, "$1").toLowerCase();
74
64
  }
65
+ var ParseResponseError = class extends Error {
66
+ constructor(message, issues) {
67
+ super(JSON.stringify({ message, issues }, null, 2));
68
+ this.issues = issues;
69
+ this.name = "ParseResponseError";
70
+ this.issues = issues;
71
+ }
72
+ };
73
+
74
+ // src/internals.ts
75
+ var getJson = (response) => async (schema) => {
76
+ const json = await response.json();
77
+ if (!schema) return json;
78
+ const result = await schema["~standard"].validate(json);
79
+ if (result.issues) {
80
+ throw new ParseResponseError("Failed to parse response.json", result.issues);
81
+ }
82
+ return result.value;
83
+ };
84
+ var getText = (response) => async (schema) => {
85
+ const text = await response.text();
86
+ if (!schema) return text;
87
+ const result = await schema["~standard"].validate(text);
88
+ if (result.issues) {
89
+ throw new ParseResponseError("Failed to parse response.text", result.issues);
90
+ }
91
+ return result.value;
92
+ };
75
93
 
76
94
  // src/api.ts
77
95
  var identity = (value) => value;
@@ -134,6 +152,7 @@ function makeService(baseURL, baseOptions) {
134
152
  return service;
135
153
  }
136
154
  export {
155
+ ParseResponseError,
137
156
  addQueryToURL,
138
157
  enhancedFetch,
139
158
  ensureStringBody,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "make-service",
3
- "version": "3.1.0",
3
+ "version": "4.0.0",
4
4
  "description": "Some utilities to extend the 'fetch' API to better interact with external APIs.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -15,9 +15,11 @@
15
15
  "test": "vitest run"
16
16
  },
17
17
  "devDependencies": {
18
+ "@standard-schema/spec": "^1.0.0",
18
19
  "@types/node": "^22.1.0",
19
20
  "@typescript-eslint/eslint-plugin": "^8.0.0",
20
21
  "@typescript-eslint/parser": "^8.0.0",
22
+ "arktype": "^2.0.4",
21
23
  "eslint": "^9.8.0",
22
24
  "jsdom": "^24.1.1",
23
25
  "prettier": "latest",