@openid4vc/utils 0.3.0-alpha-20251001121503 → 0.3.0-alpha-20251017092354

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/dist/index.mjs CHANGED
@@ -1,438 +1,409 @@
1
- // src/globals.ts
2
- var _URL = URL;
3
- var _URLSearchParams = URLSearchParams;
4
- var _Headers = Headers;
1
+ import { Buffer } from "buffer";
2
+ import z, { ZodIssueCode } from "zod";
3
+
4
+ //#region src/array.ts
5
+ /**
6
+ * Only primitive types allowed
7
+ * Must have not duplicate entries (will always return false in this case)
8
+ */
9
+ function arrayEqualsIgnoreOrder(a, b) {
10
+ if (new Set(a).size !== new Set(b).size) return false;
11
+ if (a.length !== b.length) return false;
12
+ return a.every((k) => b.includes(k));
13
+ }
14
+
15
+ //#endregion
16
+ //#region src/config.ts
17
+ let GLOBAL_CONFIG = { allowInsecureUrls: false };
18
+ function setGlobalConfig(config) {
19
+ GLOBAL_CONFIG = config;
20
+ }
21
+ function getGlobalConfig() {
22
+ return GLOBAL_CONFIG;
23
+ }
5
24
 
6
- // src/content-type.ts
7
- var ContentType = /* @__PURE__ */ ((ContentType2) => {
8
- ContentType2["XWwwFormUrlencoded"] = "application/x-www-form-urlencoded";
9
- ContentType2["Json"] = "application/json";
10
- ContentType2["JwkSet"] = "application/jwk-set+json";
11
- ContentType2["OAuthAuthorizationRequestJwt"] = "application/oauth-authz-req+jwt";
12
- ContentType2["Jwt"] = "application/jwt";
13
- ContentType2["Html"] = "text/html";
14
- return ContentType2;
15
- })(ContentType || {});
25
+ //#endregion
26
+ //#region src/content-type.ts
27
+ let ContentType = /* @__PURE__ */ function(ContentType$1) {
28
+ ContentType$1["XWwwFormUrlencoded"] = "application/x-www-form-urlencoded";
29
+ ContentType$1["Json"] = "application/json";
30
+ ContentType$1["JwkSet"] = "application/jwk-set+json";
31
+ ContentType$1["OAuthAuthorizationRequestJwt"] = "application/oauth-authz-req+jwt";
32
+ ContentType$1["Jwt"] = "application/jwt";
33
+ ContentType$1["Html"] = "text/html";
34
+ return ContentType$1;
35
+ }({});
16
36
  function isContentType(contentType, value) {
17
- return value.toLowerCase().includes(contentType);
37
+ return value.toLowerCase().includes(contentType);
18
38
  }
19
39
  function isResponseContentType(contentType, response) {
20
- const contentTypeArray = Array.isArray(contentType) ? contentType : [contentType];
21
- const header = response.headers.get("Content-Type");
22
- if (!header) return false;
23
- return contentTypeArray.some((contentTypeEntry) => isContentType(contentTypeEntry, header));
40
+ const contentTypeArray = Array.isArray(contentType) ? contentType : [contentType];
41
+ const header = response.headers.get("Content-Type");
42
+ if (!header) return false;
43
+ return contentTypeArray.some((contentTypeEntry) => isContentType(contentTypeEntry, header));
44
+ }
45
+
46
+ //#endregion
47
+ //#region src/date.ts
48
+ /**
49
+ * Get the time in seconds since epoch for a date.
50
+ * If date is not provided the current time will be used.
51
+ */
52
+ function dateToSeconds(date) {
53
+ const milliseconds = date?.getTime() ?? Date.now();
54
+ return Math.floor(milliseconds / 1e3);
55
+ }
56
+ function addSecondsToDate(date, seconds) {
57
+ return new Date(date.getTime() + seconds * 1e3);
24
58
  }
25
59
 
26
- // src/error/InvalidFetchResponseError.ts
60
+ //#endregion
61
+ //#region src/encoding.ts
62
+ function decodeUtf8String(string) {
63
+ return new Uint8Array(Buffer.from(string, "utf-8"));
64
+ }
65
+ function encodeToUtf8String(data) {
66
+ return Buffer.from(data).toString("utf-8");
67
+ }
68
+ /**
69
+ * Also supports base64 url
70
+ */
71
+ function decodeBase64(base64) {
72
+ return new Uint8Array(Buffer.from(base64, "base64"));
73
+ }
74
+ function encodeToBase64(data) {
75
+ if (typeof data === "string") return Buffer.from(data).toString("base64");
76
+ return Buffer.from(data).toString("base64");
77
+ }
78
+ function encodeToBase64Url(data) {
79
+ return base64ToBase64Url(encodeToBase64(data));
80
+ }
81
+ /**
82
+ * The 'buffer' npm library does not support base64url.
83
+ */
84
+ function base64ToBase64Url(base64) {
85
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
86
+ }
87
+
88
+ //#endregion
89
+ //#region src/error/InvalidFetchResponseError.ts
27
90
  var InvalidFetchResponseError = class extends Error {
28
- constructor(message, textResponse, response) {
29
- const textResponseMessage = isResponseContentType("text/html" /* Html */, response) ? void 0 : textResponse.substring(0, 1e3);
30
- super(textResponseMessage ? `${message}
31
- ${textResponseMessage}` : message);
32
- this.textResponse = textResponse;
33
- this.response = response.clone();
34
- }
91
+ constructor(message, textResponse, response) {
92
+ const textResponseMessage = isResponseContentType(ContentType.Html, response) ? void 0 : textResponse.substring(0, 1e3);
93
+ super(textResponseMessage ? `${message}\n${textResponseMessage}` : message);
94
+ this.textResponse = textResponse;
95
+ this.response = response.clone();
96
+ }
35
97
  };
36
98
 
37
- // src/error/JsonParseError.ts
99
+ //#endregion
100
+ //#region src/error/JsonParseError.ts
38
101
  var JsonParseError = class extends Error {
39
- constructor(message, jsonString) {
40
- super(`${message}
41
- ${jsonString}`);
42
- }
102
+ constructor(message, jsonString) {
103
+ super(`${message}\n${jsonString}`);
104
+ }
43
105
  };
44
106
 
45
- // src/zod-error.ts
46
- import { ZodIssueCode } from "zod";
47
- var constants = {
48
- // biome-ignore lint/suspicious/noMisleadingCharacterClass: expected
49
- identifierRegex: /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u,
50
- unionSeparator: ", or ",
51
- issueSeparator: "\n - "
107
+ //#endregion
108
+ //#region src/zod-error.ts
109
+ /**
110
+ * Some code comes from `zod-validation-error` package (MIT License) and
111
+ * was slightly simplified to fit our needs.
112
+ */
113
+ const constants = {
114
+ identifierRegex: /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u,
115
+ unionSeparator: ", or ",
116
+ issueSeparator: "\n - "
52
117
  };
53
118
  function escapeQuotes(str) {
54
- return str.replace(/"/g, '\\"');
119
+ return str.replace(/"/g, "\\\"");
55
120
  }
56
121
  function joinPath(path) {
57
- if (path.length === 1) {
58
- return path[0].toString();
59
- }
60
- return path.reduce((acc, item) => {
61
- if (typeof item === "number") {
62
- return `${acc}[${item.toString()}]`;
63
- }
64
- if (item.includes('"')) {
65
- return `${acc}["${escapeQuotes(item)}"]`;
66
- }
67
- if (!constants.identifierRegex.test(item)) {
68
- return `${acc}["${item}"]`;
69
- }
70
- const separator = acc.length === 0 ? "" : ".";
71
- return acc + separator + item;
72
- }, "");
122
+ if (path.length === 1) return path[0].toString();
123
+ return path.reduce((acc, item) => {
124
+ if (typeof item === "number") return `${acc}[${item.toString()}]`;
125
+ if (item.includes("\"")) return `${acc}["${escapeQuotes(item)}"]`;
126
+ if (!constants.identifierRegex.test(item)) return `${acc}["${item}"]`;
127
+ return acc + (acc.length === 0 ? "" : ".") + item;
128
+ }, "");
73
129
  }
74
130
  function getMessageFromZodIssue(issue) {
75
- if (issue.code === ZodIssueCode.invalid_union) {
76
- return getMessageFromUnionErrors(issue.unionErrors);
77
- }
78
- if (issue.code === ZodIssueCode.invalid_arguments) {
79
- return [issue.message, ...issue.argumentsError.issues.map((issue2) => getMessageFromZodIssue(issue2))].join(
80
- constants.issueSeparator
81
- );
82
- }
83
- if (issue.code === ZodIssueCode.invalid_return_type) {
84
- return [issue.message, ...issue.returnTypeError.issues.map((issue2) => getMessageFromZodIssue(issue2))].join(
85
- constants.issueSeparator
86
- );
87
- }
88
- if (issue.path.length !== 0) {
89
- if (issue.path.length === 1) {
90
- const identifier = issue.path[0];
91
- if (typeof identifier === "number") {
92
- return `${issue.message} at index ${identifier}`;
93
- }
94
- }
95
- return `${issue.message} at "${joinPath(issue.path)}"`;
96
- }
97
- return issue.message;
131
+ if (issue.code === ZodIssueCode.invalid_union) return getMessageFromUnionErrors(issue.unionErrors);
132
+ if (issue.code === ZodIssueCode.invalid_arguments) return [issue.message, ...issue.argumentsError.issues.map((issue$1) => getMessageFromZodIssue(issue$1))].join(constants.issueSeparator);
133
+ if (issue.code === ZodIssueCode.invalid_return_type) return [issue.message, ...issue.returnTypeError.issues.map((issue$1) => getMessageFromZodIssue(issue$1))].join(constants.issueSeparator);
134
+ if (issue.path.length !== 0) {
135
+ if (issue.path.length === 1) {
136
+ const identifier = issue.path[0];
137
+ if (typeof identifier === "number") return `${issue.message} at index ${identifier}`;
138
+ }
139
+ return `${issue.message} at "${joinPath(issue.path)}"`;
140
+ }
141
+ return issue.message;
98
142
  }
99
143
  function getMessageFromUnionErrors(unionErrors) {
100
- return unionErrors.reduce((acc, zodError) => {
101
- const newIssues = zodError.issues.map((issue) => getMessageFromZodIssue(issue)).join(constants.issueSeparator);
102
- if (!acc.includes(newIssues)) acc.push(newIssues);
103
- return acc;
104
- }, []).join(constants.unionSeparator);
144
+ return unionErrors.reduce((acc, zodError) => {
145
+ const newIssues = zodError.issues.map((issue) => getMessageFromZodIssue(issue)).join(constants.issueSeparator);
146
+ if (!acc.includes(newIssues)) acc.push(newIssues);
147
+ return acc;
148
+ }, []).join(constants.unionSeparator);
105
149
  }
106
150
  function formatZodError(error) {
107
- if (!error) return "";
108
- return ` - ${error?.issues.map((issue) => getMessageFromZodIssue(issue)).join(constants.issueSeparator)}`;
151
+ if (!error) return "";
152
+ return `\t- ${error?.issues.map((issue) => getMessageFromZodIssue(issue)).join(constants.issueSeparator)}`;
109
153
  }
110
154
 
111
- // src/error/ValidationError.ts
155
+ //#endregion
156
+ //#region src/error/ValidationError.ts
112
157
  var ValidationError = class extends Error {
113
- constructor(message, zodError) {
114
- super(message);
115
- const formattedError = formatZodError(zodError);
116
- this.message = `${message}
117
- ${formattedError}`;
118
- Object.defineProperty(this, "zodError", {
119
- value: zodError,
120
- writable: false,
121
- enumerable: false
122
- });
123
- }
158
+ constructor(message, zodError) {
159
+ super(message);
160
+ this.message = `${message}\n${formatZodError(zodError)}`;
161
+ Object.defineProperty(this, "zodError", {
162
+ value: zodError,
163
+ writable: false,
164
+ enumerable: false
165
+ });
166
+ }
124
167
  };
125
168
 
126
- // src/array.ts
127
- function arrayEqualsIgnoreOrder(a, b) {
128
- if (new Set(a).size !== new Set(b).size) return false;
129
- if (a.length !== b.length) return false;
130
- return a.every((k) => b.includes(k));
131
- }
132
-
133
- // src/config.ts
134
- var GLOBAL_CONFIG = {
135
- allowInsecureUrls: false
169
+ //#endregion
170
+ //#region src/error/FetchError.ts
171
+ var FetchError = class extends Error {
172
+ constructor(message, { cause } = {}) {
173
+ super(`${message}\nCause: ${cause?.message}`);
174
+ this.cause = cause;
175
+ }
136
176
  };
137
- function setGlobalConfig(config) {
138
- GLOBAL_CONFIG = config;
139
- }
140
- function getGlobalConfig() {
141
- return GLOBAL_CONFIG;
142
- }
143
177
 
144
- // src/date.ts
145
- function dateToSeconds(date) {
146
- const milliseconds = date?.getTime() ?? Date.now();
147
- return Math.floor(milliseconds / 1e3);
148
- }
149
- function addSecondsToDate(date, seconds) {
150
- return new Date(date.getTime() + seconds * 1e3);
151
- }
178
+ //#endregion
179
+ //#region src/globals.ts
180
+ const _URL = URL;
181
+ const _URLSearchParams = URLSearchParams;
182
+ const _Headers = Headers;
152
183
 
153
- // src/encoding.ts
154
- import { Buffer } from "buffer";
155
- function decodeUtf8String(string) {
156
- return new Uint8Array(Buffer.from(string, "utf-8"));
157
- }
158
- function encodeToUtf8String(data) {
159
- return Buffer.from(data).toString("utf-8");
160
- }
161
- function decodeBase64(base64) {
162
- return new Uint8Array(Buffer.from(base64, "base64"));
163
- }
164
- function encodeToBase64(data) {
165
- if (typeof data === "string") {
166
- return Buffer.from(data).toString("base64");
167
- }
168
- return Buffer.from(data).toString("base64");
169
- }
170
- function encodeToBase64Url(data) {
171
- return base64ToBase64Url(encodeToBase64(data));
184
+ //#endregion
185
+ //#region src/fetcher.ts
186
+ /**
187
+ * The default fetcher used by createZodFetcher when no
188
+ * fetcher is provided.
189
+ */
190
+ const defaultFetcher = fetch;
191
+ function createFetcher(fetcher = defaultFetcher) {
192
+ return (input, init, ...args) => {
193
+ return fetcher(input, init ? {
194
+ ...init,
195
+ body: init.body instanceof _URLSearchParams ? init.body.toString() : init.body
196
+ } : void 0, ...args).catch((error) => {
197
+ throw new FetchError(`Unknown error occurred during fetch to '${input}'`, { cause: error });
198
+ });
199
+ };
172
200
  }
173
- function base64ToBase64Url(base64) {
174
- return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
201
+ /**
202
+ * Creates a `fetchWithZod` function that takes in a schema of
203
+ * the expected response, and the arguments to the fetcher
204
+ * you provided.
205
+ *
206
+ * @example
207
+ *
208
+ * const fetchWithZod = createZodFetcher((url) => {
209
+ * return fetch(url).then((res) => res.json());
210
+ * });
211
+ *
212
+ * const response = await fetchWithZod(
213
+ * z.object({
214
+ * hello: z.string(),
215
+ * }),
216
+ * "https://example.com",
217
+ * );
218
+ */
219
+ function createZodFetcher(fetcher) {
220
+ return async (schema, expectedContentType, ...args) => {
221
+ const response = await createFetcher(fetcher)(...args);
222
+ const expectedContentTypeArray = Array.isArray(expectedContentType) ? expectedContentType : [expectedContentType];
223
+ if (response.ok && !isResponseContentType(expectedContentTypeArray, response)) throw new InvalidFetchResponseError(`Expected response to match content type ${expectedContentTypeArray.join(" | ")}, but received '${response.headers.get("Content-Type")}'`, await response.clone().text(), response);
224
+ if (expectedContentTypeArray.includes(ContentType.OAuthAuthorizationRequestJwt)) return {
225
+ response,
226
+ result: response.ok ? schema.safeParse(await response.text()) : void 0
227
+ };
228
+ return {
229
+ response,
230
+ result: response.ok ? schema.safeParse(await response.json()) : void 0
231
+ };
232
+ };
175
233
  }
176
234
 
177
- // src/object.ts
235
+ //#endregion
236
+ //#region src/object.ts
178
237
  function isObject(item) {
179
- return item != null && typeof item === "object" && !Array.isArray(item);
238
+ return item != null && typeof item === "object" && !Array.isArray(item);
180
239
  }
240
+ /**
241
+ * Deep merge two objects.
242
+ * @param target
243
+ * @param ...sources
244
+ */
181
245
  function mergeDeep(target, ...sources) {
182
- if (!sources.length) return target;
183
- const source = sources.shift();
184
- if (isObject(target) && isObject(source)) {
185
- for (const key in source) {
186
- if (isObject(source[key])) {
187
- if (!target[key]) Object.assign(target, { [key]: {} });
188
- mergeDeep(target[key], source[key]);
189
- } else {
190
- Object.assign(target, { [key]: source[key] });
191
- }
192
- }
193
- }
194
- return mergeDeep(target, ...sources);
246
+ if (!sources.length) return target;
247
+ const source = sources.shift();
248
+ if (isObject(target) && isObject(source)) for (const key in source) if (isObject(source[key])) {
249
+ if (!target[key]) Object.assign(target, { [key]: {} });
250
+ mergeDeep(target[key], source[key]);
251
+ } else Object.assign(target, { [key]: source[key] });
252
+ return mergeDeep(target, ...sources);
195
253
  }
196
254
 
197
- // src/parse.ts
255
+ //#endregion
256
+ //#region src/parse.ts
198
257
  function stringToJsonWithErrorHandling(string, errorMessage) {
199
- try {
200
- return JSON.parse(string);
201
- } catch (error) {
202
- throw new JsonParseError(errorMessage ?? "Unable to parse string to JSON.", string);
203
- }
258
+ try {
259
+ return JSON.parse(string);
260
+ } catch (_error) {
261
+ throw new JsonParseError(errorMessage ?? "Unable to parse string to JSON.", string);
262
+ }
204
263
  }
205
264
  function parseIfJson(data) {
206
- if (typeof data !== "string") {
207
- return data;
208
- }
209
- try {
210
- return JSON.parse(data);
211
- } catch (error) {
212
- }
213
- return data;
265
+ if (typeof data !== "string") return data;
266
+ try {
267
+ return JSON.parse(data);
268
+ } catch (_error) {}
269
+ return data;
214
270
  }
215
271
  function parseWithErrorHandling(schema, data, customErrorMessage) {
216
- const parseResult = schema.safeParse(data);
217
- if (!parseResult.success) {
218
- throw new ValidationError(
219
- customErrorMessage ?? `Error validating schema with data ${JSON.stringify(data)}`,
220
- parseResult.error
221
- );
222
- }
223
- return parseResult.data;
272
+ const parseResult = schema.safeParse(data);
273
+ if (!parseResult.success) throw new ValidationError(customErrorMessage ?? `Error validating schema with data ${JSON.stringify(data)}`, parseResult.error);
274
+ return parseResult.data;
224
275
  }
225
276
 
226
- // src/path.ts
277
+ //#endregion
278
+ //#region src/path.ts
279
+ /**
280
+ * Combine multiple uri parts into a single uri taking into account slashes.
281
+ *
282
+ * @param parts the parts to combine
283
+ * @returns the combined url
284
+ */
227
285
  function joinUriParts(base, parts) {
228
- if (parts.length === 0) return base;
229
- let combined = base.trim();
230
- combined = base.endsWith("/") ? base.slice(0, base.length - 1) : base;
231
- for (const part of parts) {
232
- let strippedPart = part.trim();
233
- strippedPart = strippedPart.startsWith("/") ? strippedPart.slice(1) : strippedPart;
234
- strippedPart = strippedPart.endsWith("/") ? strippedPart.slice(0, strippedPart.length - 1) : strippedPart;
235
- if (strippedPart === "") continue;
236
- combined += `/${strippedPart}`;
237
- }
238
- return combined;
286
+ if (parts.length === 0) return base;
287
+ let combined = base.trim();
288
+ combined = base.endsWith("/") ? base.slice(0, base.length - 1) : base;
289
+ for (const part of parts) {
290
+ let strippedPart = part.trim();
291
+ strippedPart = strippedPart.startsWith("/") ? strippedPart.slice(1) : strippedPart;
292
+ strippedPart = strippedPart.endsWith("/") ? strippedPart.slice(0, strippedPart.length - 1) : strippedPart;
293
+ if (strippedPart === "") continue;
294
+ combined += `/${strippedPart}`;
295
+ }
296
+ return combined;
239
297
  }
240
298
 
241
- // src/url.ts
299
+ //#endregion
300
+ //#region src/url.ts
242
301
  function getQueryParams(url) {
243
- const parsedUrl = new _URL(url);
244
- const searchParams = new _URLSearchParams(parsedUrl.search);
245
- const params = {};
246
- searchParams.forEach((value, key) => {
247
- params[key] = value;
248
- });
249
- return params;
302
+ const searchParams = new _URLSearchParams(new _URL(url).search);
303
+ const params = {};
304
+ searchParams.forEach((value, key) => {
305
+ params[key] = value;
306
+ });
307
+ return params;
250
308
  }
251
309
  function objectToQueryParams(object) {
252
- const params = new _URLSearchParams();
253
- for (const [key, value] of Object.entries(object)) {
254
- if (value != null) {
255
- params.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
256
- }
257
- }
258
- return params;
310
+ const params = new _URLSearchParams();
311
+ for (const [key, value] of Object.entries(object)) if (value != null) params.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
312
+ return params;
259
313
  }
260
314
 
261
- // src/error/FetchError.ts
262
- var FetchError = class extends Error {
263
- constructor(message, { cause } = {}) {
264
- super(`${message}
265
- Cause: ${cause?.message}`);
266
- this.cause = cause;
267
- }
268
- };
269
-
270
- // src/fetcher.ts
271
- var defaultFetcher = fetch;
272
- function createFetcher(fetcher = defaultFetcher) {
273
- return (input, init, ...args) => {
274
- return fetcher(
275
- input,
276
- init ? {
277
- ...init,
278
- // React Native does not seem to handle the toString(). This is hard to catch when running
279
- // tests in Node.JS where this does work correctly. so we handle it here.
280
- body: init.body instanceof _URLSearchParams ? init.body.toString() : init.body
281
- } : void 0,
282
- ...args
283
- ).catch((error) => {
284
- throw new FetchError(`Unknown error occurred during fetch to '${input}'`, { cause: error });
285
- });
286
- };
287
- }
288
- function createZodFetcher(fetcher) {
289
- return async (schema, expectedContentType, ...args) => {
290
- const response = await createFetcher(fetcher)(...args);
291
- const expectedContentTypeArray = Array.isArray(expectedContentType) ? expectedContentType : [expectedContentType];
292
- if (response.ok && !isResponseContentType(expectedContentTypeArray, response)) {
293
- throw new InvalidFetchResponseError(
294
- `Expected response to match content type ${expectedContentTypeArray.join(" | ")}, but received '${response.headers.get("Content-Type")}'`,
295
- await response.clone().text(),
296
- response
297
- );
298
- }
299
- if (expectedContentTypeArray.includes("application/oauth-authz-req+jwt" /* OAuthAuthorizationRequestJwt */)) {
300
- return {
301
- response,
302
- result: response.ok ? schema.safeParse(await response.text()) : void 0
303
- };
304
- }
305
- return {
306
- response,
307
- result: response.ok ? schema.safeParse(await response.json()) : void 0
308
- };
309
- };
310
- }
311
-
312
- // src/validation.ts
313
- import z from "zod";
314
- var zHttpsUrl = z.string().url().refine(
315
- (url) => {
316
- const { allowInsecureUrls } = getGlobalConfig();
317
- return allowInsecureUrls ? url.startsWith("http://") || url.startsWith("https://") : url.startsWith("https://");
318
- },
319
- { message: "url must be an https:// url" }
320
- );
321
- var zInteger = z.number().int();
322
- var zHttpMethod = z.enum(["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "TRACE", "CONNECT", "PATCH"]);
323
- var zStringToJson = z.string().transform((string, ctx) => {
324
- try {
325
- return JSON.parse(string);
326
- } catch (error) {
327
- ctx.addIssue({
328
- code: "custom",
329
- message: "Expected a JSON string, but could not parse the string to JSON"
330
- });
331
- return z.NEVER;
332
- }
315
+ //#endregion
316
+ //#region src/validation.ts
317
+ const zHttpsUrl = z.string().url().refine((url) => {
318
+ const { allowInsecureUrls } = getGlobalConfig();
319
+ return allowInsecureUrls ? url.startsWith("http://") || url.startsWith("https://") : url.startsWith("https://");
320
+ }, { message: "url must be an https:// url" });
321
+ const zInteger = z.number().int();
322
+ const zHttpMethod = z.enum([
323
+ "GET",
324
+ "POST",
325
+ "PUT",
326
+ "DELETE",
327
+ "HEAD",
328
+ "OPTIONS",
329
+ "TRACE",
330
+ "CONNECT",
331
+ "PATCH"
332
+ ]);
333
+ const zStringToJson = z.string().transform((string, ctx) => {
334
+ try {
335
+ return JSON.parse(string);
336
+ } catch (_error) {
337
+ ctx.addIssue({
338
+ code: "custom",
339
+ message: "Expected a JSON string, but could not parse the string to JSON"
340
+ });
341
+ return z.NEVER;
342
+ }
333
343
  });
334
- var zIs = (schema, data) => schema.safeParse(data).success;
344
+ const zIs = (schema, data) => schema.safeParse(data).success;
335
345
 
336
- // src/www-authenticate.ts
337
- var unquote = (value) => value.substring(1, value.length - 1).replace(/\\"/g, '"');
338
- var sanitize = (value) => value.charAt(0) === '"' ? unquote(value) : value.trim();
339
- var body = (
340
- // biome-ignore lint/suspicious/noControlCharactersInRegex: <explanation>
341
- /((?:[a-zA-Z0-9._~+\/-]+=*(?:\s+|$))|[^\u0000-\u001F\u007F()<>@,;:\\"/?={}\[\]\u0020\u0009]+)(?:=([^\\"=\s,]+|"(?:[^"\\]|\\.)*"))?/g
342
- );
343
- var parsePayload = (scheme, string) => {
344
- const payload = {};
345
- while (true) {
346
- const res = body.exec(string);
347
- if (!res) break;
348
- const [, key, newValue] = res;
349
- const payloadValue = payload[key];
350
- if (newValue) {
351
- const sanitizedValue = sanitize(newValue);
352
- payload[key] = payloadValue ? Array.isArray(payloadValue) ? [...payloadValue, sanitizedValue] : [payloadValue, sanitizedValue] : sanitizedValue;
353
- } else if (!payloadValue) {
354
- payload[key] = null;
355
- }
356
- }
357
- return { scheme, payload };
346
+ //#endregion
347
+ //#region src/www-authenticate.ts
348
+ const unquote = (value) => value.substring(1, value.length - 1).replace(/\\"/g, "\"");
349
+ const sanitize = (value) => value.charAt(0) === "\"" ? unquote(value) : value.trim();
350
+ const body = /((?:[a-zA-Z0-9._~+/-]+=*(?:\s+|$))|[^\u0000-\u001F\u007F()<>@,;:\\"/?={}[\]\u0020\u0009]+)(?:=([^\\"=\s,]+|"(?:[^"\\]|\\.)*"))?/g;
351
+ const parsePayload = (scheme, string) => {
352
+ const payload = {};
353
+ while (true) {
354
+ const res = body.exec(string);
355
+ if (!res) break;
356
+ const [, key, newValue] = res;
357
+ const payloadValue = payload[key];
358
+ if (newValue) {
359
+ const sanitizedValue = sanitize(newValue);
360
+ payload[key] = payloadValue ? Array.isArray(payloadValue) ? [...payloadValue, sanitizedValue] : [payloadValue, sanitizedValue] : sanitizedValue;
361
+ } else if (!payloadValue) payload[key] = null;
362
+ }
363
+ return {
364
+ scheme,
365
+ payload
366
+ };
358
367
  };
359
368
  function parseWwwAuthenticateHeader(str) {
360
- const start = str.indexOf(" ");
361
- let scheme = str.substring(0, start);
362
- let value = str.substring(start);
363
- const challenges = [];
364
- const endsWithSchemeRegex = /, ?(Bearer|DPoP|Basic)$/;
365
- const endsWithSchemeTest = endsWithSchemeRegex.exec(value);
366
- let endsWithScheme = void 0;
367
- if (endsWithSchemeTest) {
368
- value = value.substring(0, value.length - endsWithSchemeTest[0].length);
369
- endsWithScheme = endsWithSchemeTest[1];
370
- }
371
- const additionalSchemesRegex = /(.*?)(, ?)(Bearer|DPoP|Basic)[, ]/;
372
- let match = additionalSchemesRegex.exec(value);
373
- while (match) {
374
- challenges.push(parsePayload(scheme, match[1]));
375
- value = value.substring(match[0].length - 1);
376
- scheme = match[3];
377
- match = additionalSchemesRegex.exec(value);
378
- }
379
- challenges.push(parsePayload(scheme, value));
380
- if (endsWithScheme) {
381
- challenges.push({ scheme: endsWithScheme, payload: {} });
382
- }
383
- return challenges;
369
+ const start = str.indexOf(" ");
370
+ let scheme = str.substring(0, start);
371
+ let value = str.substring(start);
372
+ const challenges = [];
373
+ const endsWithSchemeTest = /, ?(Bearer|DPoP|Basic)$/.exec(value);
374
+ let endsWithScheme;
375
+ if (endsWithSchemeTest) {
376
+ value = value.substring(0, value.length - endsWithSchemeTest[0].length);
377
+ endsWithScheme = endsWithSchemeTest[1];
378
+ }
379
+ const additionalSchemesRegex = /(.*?)(, ?)(Bearer|DPoP|Basic)[, ]/;
380
+ let match = additionalSchemesRegex.exec(value);
381
+ while (match) {
382
+ challenges.push(parsePayload(scheme, match[1]));
383
+ value = value.substring(match[0].length - 1);
384
+ scheme = match[3];
385
+ match = additionalSchemesRegex.exec(value);
386
+ }
387
+ challenges.push(parsePayload(scheme, value));
388
+ if (endsWithScheme) challenges.push({
389
+ scheme: endsWithScheme,
390
+ payload: {}
391
+ });
392
+ return challenges;
384
393
  }
385
394
  function encodeWwwAuthenticateHeader(challenges) {
386
- const entries = [];
387
- for (const challenge of challenges) {
388
- const encodedParams = Object.entries(challenge.payload).flatMap(([key, value]) => {
389
- const encode = (s) => s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
390
- if (Array.isArray(value)) {
391
- return value.map((v) => `${key}="${encode(v)}"`);
392
- }
393
- return value ? `${key}="${encode(value)}"` : key;
394
- });
395
- entries.push(encodedParams.length === 0 ? challenge.scheme : `${challenge.scheme} ${encodedParams.join(", ")}`);
396
- }
397
- return entries.join(", ");
395
+ const entries = [];
396
+ for (const challenge of challenges) {
397
+ const encodedParams = Object.entries(challenge.payload).flatMap(([key, value]) => {
398
+ const encode = (s) => s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
399
+ if (Array.isArray(value)) return value.map((v) => `${key}="${encode(v)}"`);
400
+ return value ? `${key}="${encode(value)}"` : key;
401
+ });
402
+ entries.push(encodedParams.length === 0 ? challenge.scheme : `${challenge.scheme} ${encodedParams.join(", ")}`);
403
+ }
404
+ return entries.join(", ");
398
405
  }
399
- export {
400
- ContentType,
401
- _Headers as Headers,
402
- InvalidFetchResponseError,
403
- JsonParseError,
404
- _URL as URL,
405
- _URLSearchParams as URLSearchParams,
406
- ValidationError,
407
- addSecondsToDate,
408
- arrayEqualsIgnoreOrder,
409
- createFetcher,
410
- createZodFetcher,
411
- dateToSeconds,
412
- decodeBase64,
413
- decodeUtf8String,
414
- encodeToBase64,
415
- encodeToBase64Url,
416
- encodeToUtf8String,
417
- encodeWwwAuthenticateHeader,
418
- formatZodError,
419
- getGlobalConfig,
420
- getQueryParams,
421
- isContentType,
422
- isObject,
423
- isResponseContentType,
424
- joinUriParts,
425
- mergeDeep,
426
- objectToQueryParams,
427
- parseIfJson,
428
- parseWithErrorHandling,
429
- parseWwwAuthenticateHeader,
430
- setGlobalConfig,
431
- stringToJsonWithErrorHandling,
432
- zHttpMethod,
433
- zHttpsUrl,
434
- zInteger,
435
- zIs,
436
- zStringToJson
437
- };
406
+
407
+ //#endregion
408
+ export { ContentType, _Headers as Headers, InvalidFetchResponseError, JsonParseError, _URL as URL, _URLSearchParams as URLSearchParams, ValidationError, addSecondsToDate, arrayEqualsIgnoreOrder, createFetcher, createZodFetcher, dateToSeconds, decodeBase64, decodeUtf8String, encodeToBase64, encodeToBase64Url, encodeToUtf8String, encodeWwwAuthenticateHeader, formatZodError, getGlobalConfig, getQueryParams, isContentType, isObject, isResponseContentType, joinUriParts, mergeDeep, objectToQueryParams, parseIfJson, parseWithErrorHandling, parseWwwAuthenticateHeader, setGlobalConfig, stringToJsonWithErrorHandling, zHttpMethod, zHttpsUrl, zInteger, zIs, zStringToJson };
438
409
  //# sourceMappingURL=index.mjs.map