@oxog/querystring 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +54 -72
  3. package/dist/index.d.mts +343 -0
  4. package/dist/index.d.ts +333 -39
  5. package/dist/index.js +2333 -88
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +2284 -49
  8. package/dist/index.mjs.map +1 -0
  9. package/package.json +36 -18
  10. package/dist/builder.d.ts +0 -42
  11. package/dist/builder.d.ts.map +0 -1
  12. package/dist/builder.js +0 -216
  13. package/dist/builder.js.map +0 -1
  14. package/dist/esm/builder.d.ts +0 -42
  15. package/dist/esm/builder.d.ts.map +0 -1
  16. package/dist/esm/builder.js.map +0 -1
  17. package/dist/esm/builder.mjs +0 -212
  18. package/dist/esm/index.d.ts +0 -49
  19. package/dist/esm/index.d.ts.map +0 -1
  20. package/dist/esm/index.js.map +0 -1
  21. package/dist/esm/index.mjs +0 -49
  22. package/dist/esm/parser.d.ts +0 -7
  23. package/dist/esm/parser.d.ts.map +0 -1
  24. package/dist/esm/parser.js.map +0 -1
  25. package/dist/esm/parser.mjs +0 -170
  26. package/dist/esm/plugins.d.ts +0 -25
  27. package/dist/esm/plugins.d.ts.map +0 -1
  28. package/dist/esm/plugins.js.map +0 -1
  29. package/dist/esm/plugins.mjs +0 -223
  30. package/dist/esm/schema.d.ts +0 -23
  31. package/dist/esm/schema.d.ts.map +0 -1
  32. package/dist/esm/schema.js.map +0 -1
  33. package/dist/esm/schema.mjs +0 -674
  34. package/dist/esm/security.d.ts +0 -14
  35. package/dist/esm/security.d.ts.map +0 -1
  36. package/dist/esm/security.js.map +0 -1
  37. package/dist/esm/security.mjs +0 -224
  38. package/dist/esm/stringifier.d.ts +0 -4
  39. package/dist/esm/stringifier.d.ts.map +0 -1
  40. package/dist/esm/stringifier.js.map +0 -1
  41. package/dist/esm/stringifier.mjs +0 -193
  42. package/dist/esm/types/index.d.ts +0 -184
  43. package/dist/esm/types/index.d.ts.map +0 -1
  44. package/dist/esm/types/index.js.map +0 -1
  45. package/dist/esm/types/index.mjs +0 -2
  46. package/dist/esm/types/schema.d.ts +0 -37
  47. package/dist/esm/types/schema.d.ts.map +0 -1
  48. package/dist/esm/types/schema.js.map +0 -1
  49. package/dist/esm/types/schema.mjs +0 -2
  50. package/dist/esm/utils/array.d.ts +0 -11
  51. package/dist/esm/utils/array.d.ts.map +0 -1
  52. package/dist/esm/utils/array.js.map +0 -1
  53. package/dist/esm/utils/array.mjs +0 -116
  54. package/dist/esm/utils/encoding.d.ts +0 -13
  55. package/dist/esm/utils/encoding.d.ts.map +0 -1
  56. package/dist/esm/utils/encoding.js.map +0 -1
  57. package/dist/esm/utils/encoding.mjs +0 -126
  58. package/dist/esm/utils/object.d.ts +0 -12
  59. package/dist/esm/utils/object.d.ts.map +0 -1
  60. package/dist/esm/utils/object.js.map +0 -1
  61. package/dist/esm/utils/object.mjs +0 -140
  62. package/dist/index.d.ts.map +0 -1
  63. package/dist/parser.d.ts +0 -7
  64. package/dist/parser.d.ts.map +0 -1
  65. package/dist/parser.js +0 -174
  66. package/dist/parser.js.map +0 -1
  67. package/dist/plugins.d.ts +0 -25
  68. package/dist/plugins.d.ts.map +0 -1
  69. package/dist/plugins.js +0 -229
  70. package/dist/plugins.js.map +0 -1
  71. package/dist/schema.d.ts +0 -23
  72. package/dist/schema.d.ts.map +0 -1
  73. package/dist/schema.js +0 -680
  74. package/dist/schema.js.map +0 -1
  75. package/dist/security.d.ts +0 -14
  76. package/dist/security.d.ts.map +0 -1
  77. package/dist/security.js +0 -233
  78. package/dist/security.js.map +0 -1
  79. package/dist/stringifier.d.ts +0 -4
  80. package/dist/stringifier.d.ts.map +0 -1
  81. package/dist/stringifier.js +0 -197
  82. package/dist/stringifier.js.map +0 -1
  83. package/dist/types/index.d.ts +0 -184
  84. package/dist/types/index.d.ts.map +0 -1
  85. package/dist/types/index.js +0 -3
  86. package/dist/types/index.js.map +0 -1
  87. package/dist/types/schema.d.ts +0 -37
  88. package/dist/types/schema.d.ts.map +0 -1
  89. package/dist/types/schema.js +0 -3
  90. package/dist/types/schema.js.map +0 -1
  91. package/dist/utils/array.d.ts +0 -11
  92. package/dist/utils/array.d.ts.map +0 -1
  93. package/dist/utils/array.js +0 -127
  94. package/dist/utils/array.js.map +0 -1
  95. package/dist/utils/encoding.d.ts +0 -13
  96. package/dist/utils/encoding.d.ts.map +0 -1
  97. package/dist/utils/encoding.js +0 -137
  98. package/dist/utils/encoding.js.map +0 -1
  99. package/dist/utils/object.d.ts +0 -12
  100. package/dist/utils/object.d.ts.map +0 -1
  101. package/dist/utils/object.js +0 -150
  102. package/dist/utils/object.js.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,49 +1,2284 @@
1
- export { parse, parseUrl } from './parser';
2
- export { stringify, stringifyUrl } from './stringifier';
3
- export { QueryBuilder } from './builder';
4
- export { q, schema, validate, isValid } from './schema';
5
- export { PluginManager, createPlugin, timestampPlugin, sortKeysPlugin, lowercaseKeysPlugin, filterEmptyPlugin, base64Plugin, compressPlugin, normalizePlugin, createCustomPlugin, } from './plugins';
6
- export { sanitizeInput, validateSecurity, countKeys, hasPrototypePollution, detectXSS, secureStringify, createSecureParser, } from './security';
7
- export * from './types';
8
- import { parse as _parse, parseUrl as _parseUrl } from './parser';
9
- import { stringify as _stringify, stringifyUrl as _stringifyUrl } from './stringifier';
10
- import { QueryBuilder as _QueryBuilder } from './builder';
11
- import { q as _q, schema as _schema, validate as _validate, isValid as _isValid } from './schema';
12
- import { PluginManager } from './plugins';
13
- import { createSecureParser } from './security';
14
- const defaultPluginManager = new PluginManager();
15
- export const querystring = {
16
- parse: (input, options) => {
17
- const { plugins, ...parseOptions } = options || {};
18
- const pluginManager = plugins === true ? defaultPluginManager : plugins instanceof PluginManager ? plugins : null;
19
- if (pluginManager) {
20
- const processedInput = pluginManager.applyBeforeParse(input, parseOptions);
21
- const result = _parse(processedInput, parseOptions);
22
- return pluginManager.applyAfterParse(result, parseOptions);
23
- }
24
- return _parse(input, parseOptions);
25
- },
26
- stringify: (obj, options) => {
27
- const { plugins, ...stringifyOptions } = options || {};
28
- const pluginManager = plugins === true ? defaultPluginManager : plugins instanceof PluginManager ? plugins : null;
29
- if (pluginManager) {
30
- const processedObj = pluginManager.applyBeforeStringify(obj, stringifyOptions);
31
- const result = _stringify(processedObj, stringifyOptions);
32
- return pluginManager.applyAfterStringify(result, stringifyOptions);
33
- }
34
- return _stringify(obj, stringifyOptions);
35
- },
36
- parseUrl: _parseUrl,
37
- stringifyUrl: _stringifyUrl,
38
- QueryBuilder: _QueryBuilder,
39
- builder: (options) => new _QueryBuilder(options),
40
- q: _q,
41
- schema: _schema,
42
- validate: _validate,
43
- isValid: _isValid,
44
- plugins: defaultPluginManager,
45
- createSecureParser: (options) => createSecureParser(_parse, options),
46
- version: '1.0.0',
47
- };
48
- export default querystring;
49
- //# sourceMappingURL=index.js.map
1
+ // src/utils/encoding.ts
2
+ var hexTable = (() => {
3
+ const array = [];
4
+ for (let i = 0; i < 256; ++i) {
5
+ array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase());
6
+ }
7
+ return array;
8
+ })();
9
+ function isUnreserved(c, allowBrackets) {
10
+ return c === 45 || // -
11
+ c === 46 || // .
12
+ c === 95 || // _
13
+ c === 126 || // ~
14
+ allowBrackets && (c === 91 || c === 93) || // [ ]
15
+ c >= 48 && c <= 57 || // 0-9
16
+ c >= 65 && c <= 90 || // A-Z
17
+ c >= 97 && c <= 122;
18
+ }
19
+ function encode(str, format = "RFC3986", allowBrackets = false, charset = "utf-8") {
20
+ const string = typeof str === "string" ? str : String(str);
21
+ if (string.length === 0) {
22
+ return string;
23
+ }
24
+ const out = [];
25
+ for (let i = 0; i < string.length; ++i) {
26
+ let c = string.charCodeAt(i);
27
+ if (isUnreserved(c, allowBrackets)) {
28
+ out.push(string[i]);
29
+ continue;
30
+ }
31
+ if (c === 32 && format === "RFC1738") {
32
+ out.push("+");
33
+ continue;
34
+ }
35
+ if (c < 128) {
36
+ out.push(hexTable[c]);
37
+ continue;
38
+ }
39
+ if (charset === "iso-8859-1") {
40
+ if (c <= 255) {
41
+ out.push(hexTable[c]);
42
+ continue;
43
+ }
44
+ const codePoint = string.codePointAt(i);
45
+ if (codePoint > 65535) {
46
+ i += 1;
47
+ }
48
+ out.push(`%26%23${codePoint}%3B`);
49
+ continue;
50
+ }
51
+ if (c < 2048) {
52
+ out.push(hexTable[192 | c >> 6] + hexTable[128 | c & 63]);
53
+ continue;
54
+ }
55
+ if (c >= 55296 && c <= 56319 && i + 1 < string.length) {
56
+ const next = string.charCodeAt(i + 1);
57
+ if (next >= 56320 && next <= 57343) {
58
+ i += 1;
59
+ c = 65536 + ((c & 1023) << 10 | next & 1023);
60
+ out.push(
61
+ hexTable[240 | c >> 18] + hexTable[128 | c >> 12 & 63] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]
62
+ );
63
+ continue;
64
+ }
65
+ }
66
+ if (c >= 55296 && c <= 57343) {
67
+ c = 65533;
68
+ }
69
+ out.push(
70
+ hexTable[224 | c >> 12] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]
71
+ );
72
+ }
73
+ return out.join("");
74
+ }
75
+ var PERCENT_RUN = /(?:%[0-9A-Fa-f]{2})+/g;
76
+ function decode(str, charset = "utf-8") {
77
+ if (!str || str.length === 0) {
78
+ return str;
79
+ }
80
+ const withSpaces = str.indexOf("+") === -1 ? str : str.replace(/\+/g, " ");
81
+ if (withSpaces.indexOf("%") === -1) {
82
+ return withSpaces;
83
+ }
84
+ if (charset === "iso-8859-1") {
85
+ return withSpaces.replace(/%[0-9A-Fa-f]{2}/g, (m) => String.fromCharCode(parseInt(m.slice(1), 16)));
86
+ }
87
+ try {
88
+ return decodeURIComponent(withSpaces);
89
+ } catch {
90
+ return withSpaces.replace(PERCENT_RUN, decodePercentRun);
91
+ }
92
+ }
93
+ function decodePercentRun(run) {
94
+ try {
95
+ return decodeURIComponent(run);
96
+ } catch {
97
+ return decodeUtf8Lenient(run);
98
+ }
99
+ }
100
+ function decodeUtf8Lenient(run) {
101
+ const count = run.length / 3;
102
+ const bytes = new Array(count);
103
+ for (let i2 = 0; i2 < count; i2++) {
104
+ bytes[i2] = parseInt(run.slice(i2 * 3 + 1, i2 * 3 + 3), 16);
105
+ }
106
+ let out = "";
107
+ let i = 0;
108
+ while (i < count) {
109
+ const b0 = bytes[i];
110
+ let needed = 0;
111
+ let min = 0;
112
+ let codePoint = 0;
113
+ if (b0 < 128) {
114
+ out += String.fromCharCode(b0);
115
+ i += 1;
116
+ continue;
117
+ } else if (b0 >= 194 && b0 <= 223) {
118
+ needed = 1;
119
+ min = 128;
120
+ codePoint = b0 & 31;
121
+ } else if (b0 >= 224 && b0 <= 239) {
122
+ needed = 2;
123
+ min = 2048;
124
+ codePoint = b0 & 15;
125
+ } else if (b0 >= 240 && b0 <= 244) {
126
+ needed = 3;
127
+ min = 65536;
128
+ codePoint = b0 & 7;
129
+ }
130
+ let valid = needed > 0 && i + needed < count;
131
+ if (valid) {
132
+ for (let k = 1; k <= needed; k++) {
133
+ const b = bytes[i + k];
134
+ if (b === void 0 || (b & 192) !== 128) {
135
+ valid = false;
136
+ break;
137
+ }
138
+ codePoint = codePoint << 6 | b & 63;
139
+ }
140
+ }
141
+ if (valid && (codePoint < min || codePoint > 1114111 || codePoint >= 55296 && codePoint <= 57343)) {
142
+ valid = false;
143
+ }
144
+ if (valid) {
145
+ out += String.fromCodePoint(codePoint);
146
+ i += needed + 1;
147
+ } else {
148
+ out += run.slice(i * 3, i * 3 + 3);
149
+ i += 1;
150
+ }
151
+ }
152
+ return out;
153
+ }
154
+ function interpretNumericEntities(str) {
155
+ return str.replace(/&#(\d{1,7});/g, (match, entity) => {
156
+ const code = parseInt(entity, 10);
157
+ return code <= 1114111 ? String.fromCodePoint(code) : match;
158
+ });
159
+ }
160
+ function parseArrayValue(val, options) {
161
+ if (options.parseNumbers) {
162
+ const numVal = Number(val);
163
+ if (!Number.isNaN(numVal) && val.trim() !== "") {
164
+ return numVal;
165
+ }
166
+ }
167
+ if (options.parseBooleans) {
168
+ if (val === "true") return true;
169
+ if (val === "false") return false;
170
+ }
171
+ return val;
172
+ }
173
+ function isValidDate(date) {
174
+ return date instanceof Date && !isNaN(date.getTime());
175
+ }
176
+ function tryParseDate(str) {
177
+ if (!/^\d{4}-\d{2}-\d{2}/.test(str)) {
178
+ return str;
179
+ }
180
+ const date = new Date(str);
181
+ return isValidDate(date) ? date : str;
182
+ }
183
+
184
+ // src/utils/object.ts
185
+ function isObject(obj) {
186
+ return obj !== null && typeof obj === "object" && !Array.isArray(obj);
187
+ }
188
+ function hasOwn(obj, key) {
189
+ return Object.prototype.hasOwnProperty.call(obj, key);
190
+ }
191
+ function setOwn(obj, key, value) {
192
+ if (key === "__proto__") {
193
+ Object.defineProperty(obj, key, { value, enumerable: true, writable: true, configurable: true });
194
+ } else {
195
+ obj[key] = value;
196
+ }
197
+ return obj;
198
+ }
199
+ function merge(target, source, options = {}) {
200
+ if (!source) {
201
+ return target;
202
+ }
203
+ if (!isObject(source)) {
204
+ if (Array.isArray(target)) {
205
+ target.push(source);
206
+ } else if (isObject(target)) {
207
+ if (options.allowPrototypes || hasOwn(source, "constructor") === false) {
208
+ target[Object.keys(source).length] = source;
209
+ }
210
+ } else {
211
+ return [target, source];
212
+ }
213
+ return target;
214
+ }
215
+ if (!isObject(target)) {
216
+ return Object.assign({}, { 0: target }, source);
217
+ }
218
+ const mergeTarget = {};
219
+ for (const key of Object.keys(target)) {
220
+ setOwn(mergeTarget, key, target[key]);
221
+ }
222
+ if (Array.isArray(source) && !Array.isArray(target)) {
223
+ return source;
224
+ }
225
+ Object.keys(source).forEach((key) => {
226
+ const value = source[key];
227
+ if (hasOwn(mergeTarget, key)) {
228
+ const targetValue = mergeTarget[key];
229
+ if (Array.isArray(targetValue) && Array.isArray(value)) {
230
+ mergeTarget[key] = targetValue.concat(value);
231
+ } else if (isObject(targetValue) && isObject(value)) {
232
+ mergeTarget[key] = merge(targetValue, value, options);
233
+ } else {
234
+ mergeTarget[key] = value;
235
+ }
236
+ } else {
237
+ setOwn(mergeTarget, key, value);
238
+ }
239
+ });
240
+ return mergeTarget;
241
+ }
242
+ function getDepth(obj, currentDepth = 0) {
243
+ if (!isObject(obj) && !Array.isArray(obj)) {
244
+ return currentDepth;
245
+ }
246
+ let maxDepth = currentDepth;
247
+ if (Array.isArray(obj)) {
248
+ for (const item of obj) {
249
+ const depth = getDepth(item, currentDepth + 1);
250
+ maxDepth = Math.max(maxDepth, depth);
251
+ }
252
+ } else {
253
+ for (const key in obj) {
254
+ if (hasOwn(obj, key)) {
255
+ const depth = getDepth(obj[key], currentDepth + 1);
256
+ maxDepth = Math.max(maxDepth, depth);
257
+ }
258
+ }
259
+ }
260
+ return maxDepth;
261
+ }
262
+
263
+ // src/utils/array.ts
264
+ function parseArrayFormat(_key, value, format, separator = ",") {
265
+ if (Array.isArray(value)) {
266
+ return value;
267
+ }
268
+ if (typeof value !== "string") {
269
+ return value;
270
+ }
271
+ switch (format) {
272
+ case "comma":
273
+ if (value.includes(",")) {
274
+ return value.split(",").map((v) => v.trim());
275
+ }
276
+ return value;
277
+ case "separator":
278
+ case "bracket-separator":
279
+ if (value.includes(separator)) {
280
+ return value.split(separator).map((v) => v.trim());
281
+ }
282
+ return value;
283
+ case "json":
284
+ try {
285
+ const parsed = JSON.parse(value);
286
+ return Array.isArray(parsed) ? parsed : value;
287
+ } catch {
288
+ return value;
289
+ }
290
+ default:
291
+ return value;
292
+ }
293
+ }
294
+ function combineArrayValues(existing, newValue) {
295
+ if (existing === void 0) {
296
+ return newValue;
297
+ }
298
+ if (Array.isArray(existing)) {
299
+ if (Array.isArray(newValue)) {
300
+ return existing.concat(newValue);
301
+ }
302
+ return existing.concat([newValue]);
303
+ }
304
+ if (Array.isArray(newValue)) {
305
+ return [existing].concat(newValue);
306
+ }
307
+ return [existing, newValue];
308
+ }
309
+
310
+ // src/parser.ts
311
+ var defaults = {
312
+ delimiter: "&",
313
+ depth: 5,
314
+ arrayFormat: "repeat",
315
+ arrayFormatSeparator: ",",
316
+ arrayLimit: 20,
317
+ decode: true,
318
+ decoder: (str, _defaultDecoder, charset) => decode(str, charset),
319
+ charset: "utf-8",
320
+ charsetSentinel: false,
321
+ interpretNumericEntities: false,
322
+ parameterLimit: 1e3,
323
+ parseArrays: true,
324
+ allowDots: false,
325
+ plainObjects: false,
326
+ allowPrototypes: false,
327
+ allowSparse: false,
328
+ strictNullHandling: false,
329
+ comma: false,
330
+ commaRoundTrip: false,
331
+ ignoreQueryPrefix: false,
332
+ duplicates: "combine",
333
+ parseNumbers: false,
334
+ parseBooleans: false,
335
+ parseDates: false,
336
+ typeCoercion: false
337
+ };
338
+ var UTF8_SENTINEL = "utf8=%E2%9C%93";
339
+ var ISO_SENTINEL = "utf8=%26%2310003%3B";
340
+ var SPLIT_FORMATS = /* @__PURE__ */ new Set(["comma", "separator", "bracket-separator"]);
341
+ function parse(input, options) {
342
+ const opts = { ...defaults };
343
+ if (options) {
344
+ for (const key of Object.keys(options)) {
345
+ if (options[key] !== void 0) {
346
+ opts[key] = options[key];
347
+ }
348
+ }
349
+ }
350
+ if (options?.arrayFormat === void 0 && opts.comma) {
351
+ opts.arrayFormat = "comma";
352
+ }
353
+ const {
354
+ delimiter,
355
+ depth,
356
+ arrayFormat,
357
+ arrayFormatSeparator,
358
+ decode: shouldDecode,
359
+ decoder,
360
+ charsetSentinel,
361
+ interpretNumericEntities: shouldInterpretNumericEntities,
362
+ parameterLimit,
363
+ parseArrays,
364
+ allowDots,
365
+ plainObjects,
366
+ allowSparse,
367
+ strictNullHandling,
368
+ ignoreQueryPrefix,
369
+ parseNumbers,
370
+ parseBooleans,
371
+ parseDates,
372
+ typeCoercion
373
+ } = opts;
374
+ const result = plainObjects ? /* @__PURE__ */ Object.create(null) : {};
375
+ if (!input || typeof input !== "string") {
376
+ return result;
377
+ }
378
+ let queryString = input;
379
+ if (ignoreQueryPrefix && queryString.charAt(0) === "?") {
380
+ queryString = queryString.slice(1);
381
+ }
382
+ const limit = Number.isFinite(parameterLimit) && parameterLimit >= 0 ? parameterLimit : Infinity;
383
+ const pairs = limit === Infinity ? queryString.split(delimiter) : queryString.split(delimiter, limit + 1);
384
+ if (pairs.length > limit) {
385
+ throw new Error(`Parameter limit exceeded. Maximum allowed: ${parameterLimit}`);
386
+ }
387
+ let charset = opts.charset;
388
+ let skipIndex = -1;
389
+ if (charsetSentinel) {
390
+ for (let i = 0; i < pairs.length; i++) {
391
+ if (pairs[i] === UTF8_SENTINEL) {
392
+ charset = "utf-8";
393
+ skipIndex = i;
394
+ break;
395
+ }
396
+ if (pairs[i] === ISO_SENTINEL) {
397
+ charset = "iso-8859-1";
398
+ skipIndex = i;
399
+ break;
400
+ }
401
+ }
402
+ }
403
+ const coercion = typeof typeCoercion === "object" && typeCoercion !== null ? typeCoercion : {
404
+ numbers: typeCoercion === true || parseNumbers,
405
+ booleans: typeCoercion === true || parseBooleans,
406
+ dates: typeCoercion === true || parseDates
407
+ };
408
+ const decodeComponent = (str) => shouldDecode ? decoder(str, (s) => decode(s, charset), charset) : str;
409
+ const assignOptions = {
410
+ arrayLimit: opts.arrayLimit,
411
+ parseArrays,
412
+ plainObjects,
413
+ allowPrototypes: opts.allowPrototypes,
414
+ duplicates: opts.duplicates
415
+ };
416
+ for (let i = 0; i < pairs.length; i++) {
417
+ const pair = pairs[i];
418
+ if (!pair || i === skipIndex) {
419
+ continue;
420
+ }
421
+ const equalIndex = pair.indexOf("=");
422
+ const rawKey = equalIndex === -1 ? pair : pair.slice(0, equalIndex);
423
+ const rawValue = equalIndex === -1 ? null : pair.slice(equalIndex + 1);
424
+ const key = decodeComponent(rawKey);
425
+ let value;
426
+ if (rawValue === null) {
427
+ value = strictNullHandling ? null : "";
428
+ } else if (parseArrays && SPLIT_FORMATS.has(arrayFormat)) {
429
+ const separator = arrayFormat === "comma" ? "," : arrayFormatSeparator;
430
+ const parts = separator && rawValue.includes(separator) ? rawValue.split(separator) : [rawValue];
431
+ const decoded = parts.map((part) => finishValue(decodeComponent(part)));
432
+ value = decoded.length === 1 ? decoded[0] : decoded;
433
+ } else {
434
+ const decoded = decodeComponent(rawValue);
435
+ if (parseArrays && arrayFormat === "json") {
436
+ const parsed = parseArrayFormat(key, decoded, "json");
437
+ if (Array.isArray(parsed)) {
438
+ value = parsed;
439
+ assign(result, splitKey(key, allowDots, depth), value, assignOptions);
440
+ continue;
441
+ }
442
+ }
443
+ value = finishValue(decoded);
444
+ }
445
+ assign(result, splitKey(key, allowDots, depth), value, assignOptions);
446
+ }
447
+ if (parseArrays && !allowSparse) {
448
+ compactSparseArrays(result);
449
+ }
450
+ return result;
451
+ function finishValue(val) {
452
+ let out = val;
453
+ if (shouldInterpretNumericEntities && charset === "iso-8859-1") {
454
+ out = interpretNumericEntities(out);
455
+ }
456
+ let parsed = out;
457
+ if (coercion.numbers || coercion.booleans) {
458
+ parsed = parseArrayValue(out, { parseNumbers: coercion.numbers, parseBooleans: coercion.booleans });
459
+ }
460
+ if (coercion.dates && typeof parsed === "string") {
461
+ const date = tryParseDate(parsed);
462
+ if (date instanceof Date) {
463
+ parsed = date;
464
+ }
465
+ }
466
+ return parsed;
467
+ }
468
+ }
469
+ function splitKey(key, allowDots, depth) {
470
+ const normalized = allowDots ? key.replace(/\.([^.[]+)/g, "[$1]") : key;
471
+ const maxDepth = Number.isFinite(depth) ? Math.max(0, Math.floor(depth)) : Infinity;
472
+ const first = maxDepth > 0 ? normalized.indexOf("[") : -1;
473
+ const closing = first === -1 ? -1 : normalized.indexOf("]", first);
474
+ if (first === -1 || closing === -1) {
475
+ return [normalized];
476
+ }
477
+ const segments = [];
478
+ const root = normalized.slice(0, first);
479
+ if (root) {
480
+ segments.push(root);
481
+ }
482
+ const child = /\[([^[\]]*)\]/g;
483
+ child.lastIndex = first;
484
+ let count = 0;
485
+ let match = null;
486
+ while (count < maxDepth && (match = child.exec(normalized)) !== null) {
487
+ segments.push(match[1]);
488
+ count++;
489
+ }
490
+ if (count >= maxDepth) {
491
+ const rest = child.exec(normalized);
492
+ if (rest !== null) {
493
+ segments.push(normalized.slice(rest.index));
494
+ }
495
+ }
496
+ return segments.filter((segment, index) => segment !== "" || index === segments.length - 1);
497
+ }
498
+ function isArrayIndex(segment, options) {
499
+ if (!options.parseArrays || !/^(?:0|[1-9]\d*)$/.test(segment)) {
500
+ return false;
501
+ }
502
+ return Number(segment) < options.arrayLimit;
503
+ }
504
+ function isSafeKey(segment, options) {
505
+ if (segment === "__proto__") {
506
+ return false;
507
+ }
508
+ return options.plainObjects || options.allowPrototypes || !hasOwn(Object.prototype, segment);
509
+ }
510
+ function createObject(plainObjects) {
511
+ return plainObjects ? /* @__PURE__ */ Object.create(null) : {};
512
+ }
513
+ function arrayToObject(array, plainObjects) {
514
+ const obj = createObject(plainObjects);
515
+ for (let i = 0; i < array.length; i++) {
516
+ if (i in array) {
517
+ obj[i] = array[i];
518
+ }
519
+ }
520
+ return obj;
521
+ }
522
+ function isContainer(value) {
523
+ return typeof value === "object" && value !== null && !(value instanceof Date);
524
+ }
525
+ function assign(result, segments, value, options) {
526
+ let keys = segments;
527
+ let append = false;
528
+ if (keys.length > 1 && keys[keys.length - 1] === "") {
529
+ keys = keys.slice(0, -1);
530
+ append = options.parseArrays;
531
+ }
532
+ for (const key of keys) {
533
+ if (!isSafeKey(key, options)) {
534
+ return;
535
+ }
536
+ }
537
+ let target = result;
538
+ for (let i = 0; i < keys.length; i++) {
539
+ const key = keys[i];
540
+ const isLast = i === keys.length - 1;
541
+ if (isLast) {
542
+ setValue(target, key, value, append, options);
543
+ return;
544
+ }
545
+ const nextKey = keys[i + 1];
546
+ const wantsArray = isArrayIndex(nextKey, options);
547
+ let child = hasOwn(target, key) ? target[key] : void 0;
548
+ if (!isContainer(child)) {
549
+ if (child !== void 0 && options.duplicates === "first") {
550
+ return;
551
+ }
552
+ child = wantsArray ? [] : createObject(options.plainObjects);
553
+ target[key] = child;
554
+ } else if (Array.isArray(child) && !wantsArray) {
555
+ child = arrayToObject(child, options.plainObjects);
556
+ target[key] = child;
557
+ }
558
+ target = child;
559
+ }
560
+ }
561
+ function setValue(target, key, value, append, options) {
562
+ const record = target;
563
+ const exists = hasOwn(target, key);
564
+ const existing = exists ? record[key] : void 0;
565
+ if (append) {
566
+ if (!exists) {
567
+ record[key] = Array.isArray(value) ? value : [value];
568
+ } else if (isContainer(existing) && !Array.isArray(existing)) {
569
+ let index = 0;
570
+ while (hasOwn(existing, String(index))) index++;
571
+ existing[index] = value;
572
+ } else {
573
+ record[key] = combineArrayValues(existing, value);
574
+ }
575
+ return;
576
+ }
577
+ if (!exists || options.duplicates === "last") {
578
+ record[key] = value;
579
+ return;
580
+ }
581
+ if (options.duplicates === "first") {
582
+ return;
583
+ }
584
+ if (isContainer(existing) && !Array.isArray(existing)) {
585
+ return;
586
+ }
587
+ record[key] = combineArrayValues(existing, value);
588
+ }
589
+ function compactSparseArrays(root) {
590
+ const stack = [root];
591
+ while (stack.length > 0) {
592
+ const record = stack.pop();
593
+ for (const key of Object.keys(record)) {
594
+ let child = record[key];
595
+ if (Array.isArray(child)) {
596
+ for (let i = 0; i < child.length; i++) {
597
+ if (!(i in child)) {
598
+ child = child.filter(() => true);
599
+ record[key] = child;
600
+ break;
601
+ }
602
+ }
603
+ }
604
+ if (isContainer(child)) {
605
+ stack.push(child);
606
+ }
607
+ }
608
+ }
609
+ }
610
+ function parseUrl(url, options) {
611
+ if (!url || typeof url !== "string") {
612
+ return { url: "", query: parse("", options) };
613
+ }
614
+ const queryIndex = url.indexOf("?");
615
+ const hashIndex = url.indexOf("#");
616
+ if (queryIndex === -1 || hashIndex !== -1 && hashIndex < queryIndex) {
617
+ return { url: hashIndex === -1 ? url : url.slice(0, hashIndex), query: parse("", options) };
618
+ }
619
+ const baseUrl = url.slice(0, queryIndex);
620
+ const queryString = hashIndex === -1 ? url.slice(queryIndex + 1) : url.slice(queryIndex + 1, hashIndex);
621
+ const query = parse(queryString, options);
622
+ return { url: baseUrl, query };
623
+ }
624
+
625
+ // src/stringifier.ts
626
+ var defaults2 = {
627
+ delimiter: "&",
628
+ strictNullHandling: false,
629
+ skipNulls: false,
630
+ encode: true,
631
+ encoder: void 0,
632
+ filter: void 0,
633
+ arrayFormat: "repeat",
634
+ arrayFormatSeparator: ",",
635
+ indices: false,
636
+ sort: void 0,
637
+ serializeDate: (date) => date.toISOString(),
638
+ format: "RFC3986",
639
+ encodeValuesOnly: false,
640
+ addQueryPrefix: false,
641
+ allowDots: false,
642
+ charset: "utf-8",
643
+ charsetSentinel: false,
644
+ comma: false,
645
+ commaRoundTrip: false
646
+ };
647
+ function stringify(obj, options) {
648
+ if (!obj || typeof obj !== "object") {
649
+ return "";
650
+ }
651
+ const opts = { ...defaults2 };
652
+ if (options) {
653
+ for (const key of Object.keys(options)) {
654
+ if (options[key] !== void 0) {
655
+ opts[key] = options[key];
656
+ }
657
+ }
658
+ }
659
+ const {
660
+ delimiter,
661
+ encode: shouldEncode,
662
+ encoder,
663
+ filter,
664
+ sort,
665
+ format,
666
+ encodeValuesOnly,
667
+ addQueryPrefix,
668
+ charsetSentinel
669
+ } = opts;
670
+ const charset = opts.charset === "iso-8859-1" ? "iso-8859-1" : "utf-8";
671
+ let arrayFormat = opts.arrayFormat;
672
+ if (options?.arrayFormat === void 0) {
673
+ if (options?.comma === true) arrayFormat = "comma";
674
+ else if (options?.indices === true) arrayFormat = "indices";
675
+ }
676
+ let objToStringify = obj;
677
+ if (typeof filter === "function") {
678
+ objToStringify = filter("", obj);
679
+ } else if (Array.isArray(filter)) {
680
+ const filtered = {};
681
+ for (const key of filter) {
682
+ if (hasOwn(obj, String(key))) {
683
+ filtered[String(key)] = obj[String(key)];
684
+ }
685
+ }
686
+ objToStringify = filtered;
687
+ }
688
+ const makeEncoder = (type) => {
689
+ if (!shouldEncode || type === "key" && encodeValuesOnly) {
690
+ return (str) => str;
691
+ }
692
+ const allowBrackets = type === "key";
693
+ const defaultEncoder = (s) => encode(s, format, allowBrackets, charset);
694
+ if (typeof encoder === "function") {
695
+ return (str) => encoder(str, defaultEncoder, charset, type);
696
+ }
697
+ return defaultEncoder;
698
+ };
699
+ const ctx = {
700
+ pairs: [],
701
+ seen: /* @__PURE__ */ new WeakSet(),
702
+ strictNullHandling: opts.strictNullHandling,
703
+ skipNulls: opts.skipNulls,
704
+ encodeKey: makeEncoder("key"),
705
+ encodeValue: makeEncoder("value"),
706
+ arrayFormat,
707
+ arrayFormatSeparator: opts.arrayFormatSeparator,
708
+ commaRoundTrip: opts.commaRoundTrip,
709
+ serializeDate: opts.serializeDate,
710
+ allowDots: opts.allowDots,
711
+ filter: typeof filter === "function" ? filter : void 0
712
+ };
713
+ if (objToStringify && typeof objToStringify === "object") {
714
+ ctx.seen.add(objToStringify);
715
+ stringifyObject(objToStringify, "", ctx);
716
+ }
717
+ const pairs = ctx.pairs;
718
+ if (sort) {
719
+ const sorter = typeof sort === "function" ? sort : (a, b) => a.localeCompare(b);
720
+ pairs.sort((a, b) => sorter(pairKey(a), pairKey(b)));
721
+ }
722
+ let result = pairs.join(delimiter);
723
+ if (charsetSentinel) {
724
+ const charsetPrefix = charset === "utf-8" ? "utf8=%E2%9C%93" : "utf8=%26%2310003%3B";
725
+ result = result ? `${charsetPrefix}${delimiter}${result}` : charsetPrefix;
726
+ }
727
+ if (addQueryPrefix) {
728
+ result = "?" + result;
729
+ }
730
+ return result;
731
+ }
732
+ function pairKey(pair) {
733
+ const index = pair.indexOf("=");
734
+ return index === -1 ? pair : pair.slice(0, index);
735
+ }
736
+ function childKey(prefix, key, allowDots) {
737
+ if (!prefix) {
738
+ return key;
739
+ }
740
+ return allowDots ? `${prefix}.${key}` : `${prefix}[${key}]`;
741
+ }
742
+ function stringifyObject(obj, prefix, ctx) {
743
+ for (const key of Object.keys(obj)) {
744
+ const fullKey = childKey(prefix, key, ctx.allowDots);
745
+ let value = obj[key];
746
+ if (ctx.filter) {
747
+ value = ctx.filter(fullKey, value);
748
+ if (value === void 0) {
749
+ continue;
750
+ }
751
+ }
752
+ stringifyEntry(fullKey, value, ctx);
753
+ }
754
+ }
755
+ function isNested(value) {
756
+ return Array.isArray(value) || typeof value === "object" && value !== null && !(value instanceof Date);
757
+ }
758
+ function stringifyEntry(fullKey, value, ctx) {
759
+ const { pairs } = ctx;
760
+ if (typeof value === "function" || typeof value === "symbol") {
761
+ return;
762
+ }
763
+ if (value === null || value === void 0) {
764
+ if (ctx.skipNulls) {
765
+ return;
766
+ }
767
+ pairs.push(ctx.strictNullHandling ? ctx.encodeKey(fullKey) : `${ctx.encodeKey(fullKey)}=`);
768
+ return;
769
+ }
770
+ if (value instanceof Date) {
771
+ if (isValidDate(value)) {
772
+ pairs.push(`${ctx.encodeKey(fullKey)}=${ctx.encodeValue(ctx.serializeDate(value))}`);
773
+ }
774
+ return;
775
+ }
776
+ if (Array.isArray(value)) {
777
+ stringifyArray(fullKey, value, ctx);
778
+ return;
779
+ }
780
+ if (isObject(value)) {
781
+ if (ctx.seen.has(value)) {
782
+ return;
783
+ }
784
+ ctx.seen.add(value);
785
+ stringifyObject(value, fullKey, ctx);
786
+ ctx.seen.delete(value);
787
+ return;
788
+ }
789
+ pairs.push(`${ctx.encodeKey(fullKey)}=${ctx.encodeValue(String(value))}`);
790
+ }
791
+ function stringifyArray(fullKey, values, ctx) {
792
+ const { pairs, arrayFormat } = ctx;
793
+ if (values.length === 0) {
794
+ return;
795
+ }
796
+ if (arrayFormat === "json") {
797
+ pairs.push(`${ctx.encodeKey(fullKey)}=${ctx.encodeValue(JSON.stringify(values))}`);
798
+ return;
799
+ }
800
+ if (ctx.seen.has(values)) {
801
+ return;
802
+ }
803
+ if (values.some(isNested)) {
804
+ ctx.seen.add(values);
805
+ values.forEach((item, index) => {
806
+ const key = `${fullKey}[${index}]`;
807
+ const filtered = ctx.filter ? ctx.filter(key, item) : item;
808
+ if (filtered !== void 0 || !ctx.filter) {
809
+ stringifyEntry(key, filtered, ctx);
810
+ }
811
+ });
812
+ ctx.seen.delete(values);
813
+ return;
814
+ }
815
+ const items = [];
816
+ values.forEach((item, index) => {
817
+ if (item === null || item === void 0) {
818
+ if (!ctx.skipNulls) {
819
+ items.push({ index, value: null });
820
+ }
821
+ return;
822
+ }
823
+ if (typeof item === "function" || typeof item === "symbol") {
824
+ return;
825
+ }
826
+ if (item instanceof Date) {
827
+ if (isValidDate(item)) {
828
+ items.push({ index, value: ctx.serializeDate(item) });
829
+ }
830
+ return;
831
+ }
832
+ items.push({ index, value: String(item) });
833
+ });
834
+ if (items.length === 0) {
835
+ return;
836
+ }
837
+ const single = (key, value) => {
838
+ if (value === null) {
839
+ return ctx.strictNullHandling ? ctx.encodeKey(key) : `${ctx.encodeKey(key)}=`;
840
+ }
841
+ return `${ctx.encodeKey(key)}=${ctx.encodeValue(value)}`;
842
+ };
843
+ const joined = (key, separator) => `${ctx.encodeKey(key)}=${items.map((item) => item.value === null ? "" : ctx.encodeValue(item.value)).join(separator)}`;
844
+ switch (arrayFormat) {
845
+ case "brackets":
846
+ for (const item of items) pairs.push(single(`${fullKey}[]`, item.value));
847
+ return;
848
+ case "indices":
849
+ for (const item of items) pairs.push(single(`${fullKey}[${item.index}]`, item.value));
850
+ return;
851
+ case "comma":
852
+ pairs.push(joined(ctx.commaRoundTrip && items.length === 1 ? `${fullKey}[]` : fullKey, ","));
853
+ return;
854
+ case "separator":
855
+ pairs.push(joined(fullKey, ctx.arrayFormatSeparator));
856
+ return;
857
+ case "bracket-separator":
858
+ pairs.push(joined(`${fullKey}[]`, ctx.arrayFormatSeparator));
859
+ return;
860
+ case "repeat":
861
+ default:
862
+ for (const item of items) pairs.push(single(fullKey, item.value));
863
+ return;
864
+ }
865
+ }
866
+ function stringifyUrl(url, query, options) {
867
+ if (!url || typeof url !== "string") {
868
+ return "";
869
+ }
870
+ const queryString = stringify(query, { ...options, addQueryPrefix: false });
871
+ if (!queryString) {
872
+ return url;
873
+ }
874
+ const hashIndex = url.indexOf("#");
875
+ const base = hashIndex === -1 ? url : url.slice(0, hashIndex);
876
+ const hash = hashIndex === -1 ? "" : url.slice(hashIndex);
877
+ let separator = "?";
878
+ if (base.indexOf("?") !== -1) {
879
+ separator = base.endsWith("?") || base.endsWith("&") ? "" : "&";
880
+ }
881
+ return `${base}${separator}${queryString}${hash}`;
882
+ }
883
+
884
+ // src/builder.ts
885
+ var QueryBuilder = class _QueryBuilder {
886
+ constructor(options = {}) {
887
+ this.query = {};
888
+ this.options = options;
889
+ if (options.baseUrl) {
890
+ const parsed = parseUrl(options.baseUrl);
891
+ this.query = parsed.query;
892
+ }
893
+ }
894
+ static from(input, options) {
895
+ const builder = new _QueryBuilder(options);
896
+ if (typeof input === "string") {
897
+ builder.query = parse(input, options);
898
+ } else if (input instanceof _QueryBuilder) {
899
+ builder.query = { ...input.query };
900
+ builder.options = { ...input.options, ...options };
901
+ } else if (isObject(input)) {
902
+ builder.query = { ...input };
903
+ }
904
+ return builder;
905
+ }
906
+ add(key, value) {
907
+ setOwn(this.query, key, value);
908
+ return this;
909
+ }
910
+ addMultiple(obj) {
911
+ for (const key of Object.keys(obj)) {
912
+ setOwn(this.query, key, obj[key]);
913
+ }
914
+ return this;
915
+ }
916
+ addArray(key, values) {
917
+ if (!Array.isArray(values)) {
918
+ throw new TypeError("Values must be an array");
919
+ }
920
+ setOwn(this.query, key, values);
921
+ return this;
922
+ }
923
+ addObject(key, obj) {
924
+ if (!isObject(obj)) {
925
+ throw new TypeError("Value must be an object");
926
+ }
927
+ setOwn(this.query, key, obj);
928
+ return this;
929
+ }
930
+ append(key, value) {
931
+ const existing = hasOwn(this.query, key) ? this.query[key] : void 0;
932
+ if (existing === void 0) {
933
+ setOwn(this.query, key, value);
934
+ } else if (Array.isArray(existing)) {
935
+ existing.push(value);
936
+ } else {
937
+ setOwn(this.query, key, [existing, value]);
938
+ }
939
+ return this;
940
+ }
941
+ set(key, value) {
942
+ return this.add(key, value);
943
+ }
944
+ get(key) {
945
+ return hasOwn(this.query, key) ? this.query[key] : void 0;
946
+ }
947
+ has(key) {
948
+ return hasOwn(this.query, key);
949
+ }
950
+ delete(key) {
951
+ delete this.query[key];
952
+ return this;
953
+ }
954
+ clear() {
955
+ this.query = {};
956
+ return this;
957
+ }
958
+ keys() {
959
+ return Object.keys(this.query);
960
+ }
961
+ values() {
962
+ return Object.values(this.query);
963
+ }
964
+ entries() {
965
+ return Object.entries(this.query);
966
+ }
967
+ forEach(callback) {
968
+ for (const [key, value] of this.entries()) {
969
+ callback(value, key, this);
970
+ }
971
+ return this;
972
+ }
973
+ map(callback) {
974
+ const results = [];
975
+ this.forEach((value, key) => {
976
+ results.push(callback(value, key, this));
977
+ });
978
+ return results;
979
+ }
980
+ filter(predicate) {
981
+ const filtered = new _QueryBuilder(this.options);
982
+ this.forEach((value, key) => {
983
+ if (predicate(value, key, this)) {
984
+ filtered.add(key, value);
985
+ }
986
+ });
987
+ return filtered;
988
+ }
989
+ merge(other) {
990
+ let otherQuery;
991
+ if (typeof other === "string") {
992
+ otherQuery = parse(other, this.options);
993
+ } else if (other instanceof _QueryBuilder) {
994
+ otherQuery = other.query;
995
+ } else {
996
+ otherQuery = other;
997
+ }
998
+ this.query = merge(this.query, otherQuery);
999
+ return this;
1000
+ }
1001
+ clone() {
1002
+ const cloned = new _QueryBuilder(this.options);
1003
+ cloned.query = JSON.parse(JSON.stringify(this.query));
1004
+ return cloned;
1005
+ }
1006
+ isEmpty() {
1007
+ return Object.keys(this.query).length === 0;
1008
+ }
1009
+ size() {
1010
+ return Object.keys(this.query).length;
1011
+ }
1012
+ toObject() {
1013
+ return { ...this.query };
1014
+ }
1015
+ toString(options) {
1016
+ return stringify(this.query, { ...this.options, ...options });
1017
+ }
1018
+ toUrl(url, options) {
1019
+ const baseUrl = url || this.options.baseUrl;
1020
+ if (!baseUrl) {
1021
+ throw new Error("No base URL provided");
1022
+ }
1023
+ return stringifyUrl(baseUrl, this.query, { ...this.options, ...options });
1024
+ }
1025
+ build(options) {
1026
+ return this.toString(options);
1027
+ }
1028
+ buildUrl(url, options) {
1029
+ return this.toUrl(url, options);
1030
+ }
1031
+ pick(...keys) {
1032
+ const picked = new _QueryBuilder(this.options);
1033
+ for (const key of keys) {
1034
+ if (this.has(key)) {
1035
+ picked.add(key, this.get(key));
1036
+ }
1037
+ }
1038
+ return picked;
1039
+ }
1040
+ omit(...keys) {
1041
+ const omitted = new _QueryBuilder(this.options);
1042
+ const keySet = new Set(keys);
1043
+ this.forEach((value, key) => {
1044
+ if (!keySet.has(key)) {
1045
+ omitted.add(key, value);
1046
+ }
1047
+ });
1048
+ return omitted;
1049
+ }
1050
+ transform(transformer) {
1051
+ this.query = transformer(this.query);
1052
+ return this;
1053
+ }
1054
+ validate(validator) {
1055
+ const result = validator(this.query);
1056
+ if (result === false) {
1057
+ throw new Error("Query validation failed");
1058
+ } else if (typeof result === "string") {
1059
+ throw new Error(`Query validation failed: ${result}`);
1060
+ }
1061
+ return this;
1062
+ }
1063
+ when(condition, callback) {
1064
+ const shouldExecute = typeof condition === "function" ? condition(this) : condition;
1065
+ if (shouldExecute) {
1066
+ callback(this);
1067
+ }
1068
+ return this;
1069
+ }
1070
+ unless(condition, callback) {
1071
+ return this.when(
1072
+ typeof condition === "function" ? (builder) => !condition(builder) : !condition,
1073
+ callback
1074
+ );
1075
+ }
1076
+ tap(callback) {
1077
+ callback(this);
1078
+ return this;
1079
+ }
1080
+ static parse(input, options) {
1081
+ return _QueryBuilder.from(input, options);
1082
+ }
1083
+ static create(query, options) {
1084
+ const builder = new _QueryBuilder(options);
1085
+ if (query) {
1086
+ builder.query = { ...query };
1087
+ }
1088
+ return builder;
1089
+ }
1090
+ };
1091
+
1092
+ // src/schema.ts
1093
+ var BaseSchemaImpl = class {
1094
+ constructor() {
1095
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1096
+ this._transforms = [];
1097
+ this._refinements = [];
1098
+ }
1099
+ safeParse(value) {
1100
+ try {
1101
+ const data = this.parse(value);
1102
+ return { success: true, data };
1103
+ } catch (error) {
1104
+ return {
1105
+ success: false,
1106
+ errors: [{
1107
+ path: "",
1108
+ message: error instanceof Error ? error.message : "Validation failed",
1109
+ value
1110
+ }]
1111
+ };
1112
+ }
1113
+ }
1114
+ optional() {
1115
+ return new OptionalSchemaImpl(this);
1116
+ }
1117
+ nullable() {
1118
+ return new NullableSchemaImpl(this);
1119
+ }
1120
+ default(value) {
1121
+ this._default = value;
1122
+ return this;
1123
+ }
1124
+ transform(fn) {
1125
+ const schema2 = this;
1126
+ schema2._transforms.push(fn);
1127
+ return schema2;
1128
+ }
1129
+ refine(fn, message = "Validation failed") {
1130
+ this._refinements.push({ fn, message });
1131
+ return this;
1132
+ }
1133
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1134
+ applyTransforms(value) {
1135
+ let result = value;
1136
+ for (const transform of this._transforms) {
1137
+ result = transform(result);
1138
+ }
1139
+ return result;
1140
+ }
1141
+ applyRefinements(value) {
1142
+ for (const { fn, message } of this._refinements) {
1143
+ if (!fn(value)) {
1144
+ throw new Error(message);
1145
+ }
1146
+ }
1147
+ }
1148
+ };
1149
+ var StringSchemaImpl = class extends BaseSchemaImpl {
1150
+ constructor() {
1151
+ super(...arguments);
1152
+ this.type = "string";
1153
+ this._trim = false;
1154
+ this._toLowerCase = false;
1155
+ this._toUpperCase = false;
1156
+ }
1157
+ parse(value) {
1158
+ if (value === void 0 && this._default !== void 0) {
1159
+ value = this._default;
1160
+ }
1161
+ if (typeof value !== "string") {
1162
+ throw new Error(`Expected string, got ${typeof value}`);
1163
+ }
1164
+ let str = value;
1165
+ if (this._trim) str = str.trim();
1166
+ if (this._toLowerCase) str = str.toLowerCase();
1167
+ if (this._toUpperCase) str = str.toUpperCase();
1168
+ if (this._length !== void 0 && str.length !== this._length) {
1169
+ throw new Error(`String must be exactly ${this._length} characters`);
1170
+ }
1171
+ if (this._min !== void 0 && str.length < this._min) {
1172
+ throw new Error(`String must be at least ${this._min} characters`);
1173
+ }
1174
+ if (this._max !== void 0 && str.length > this._max) {
1175
+ throw new Error(`String must be at most ${this._max} characters`);
1176
+ }
1177
+ if (this._regex && !this._regex.test(str)) {
1178
+ throw new Error(`String does not match pattern`);
1179
+ }
1180
+ if (this._startsWith && !str.startsWith(this._startsWith)) {
1181
+ throw new Error(`String must start with "${this._startsWith}"`);
1182
+ }
1183
+ if (this._endsWith && !str.endsWith(this._endsWith)) {
1184
+ throw new Error(`String must end with "${this._endsWith}"`);
1185
+ }
1186
+ if (this._includes && !str.includes(this._includes)) {
1187
+ throw new Error(`String must include "${this._includes}"`);
1188
+ }
1189
+ this.applyRefinements(str);
1190
+ return this.applyTransforms(str);
1191
+ }
1192
+ min(length) {
1193
+ this._min = length;
1194
+ return this;
1195
+ }
1196
+ max(length) {
1197
+ this._max = length;
1198
+ return this;
1199
+ }
1200
+ length(length) {
1201
+ this._length = length;
1202
+ return this;
1203
+ }
1204
+ email() {
1205
+ this._regex = /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/;
1206
+ return this;
1207
+ }
1208
+ url() {
1209
+ this._regex = /^https?:\/\/.+/;
1210
+ return this;
1211
+ }
1212
+ uuid() {
1213
+ this._regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1214
+ return this;
1215
+ }
1216
+ regex(pattern) {
1217
+ this._regex = pattern;
1218
+ return this;
1219
+ }
1220
+ startsWith(prefix) {
1221
+ this._startsWith = prefix;
1222
+ return this;
1223
+ }
1224
+ endsWith(suffix) {
1225
+ this._endsWith = suffix;
1226
+ return this;
1227
+ }
1228
+ includes(substring) {
1229
+ this._includes = substring;
1230
+ return this;
1231
+ }
1232
+ trim() {
1233
+ this._trim = true;
1234
+ return this;
1235
+ }
1236
+ toLowerCase() {
1237
+ this._toLowerCase = true;
1238
+ return this;
1239
+ }
1240
+ toUpperCase() {
1241
+ this._toUpperCase = true;
1242
+ return this;
1243
+ }
1244
+ };
1245
+ var NumberSchemaImpl = class extends BaseSchemaImpl {
1246
+ constructor() {
1247
+ super(...arguments);
1248
+ this.type = "number";
1249
+ this._int = false;
1250
+ this._positive = false;
1251
+ this._negative = false;
1252
+ this._nonpositive = false;
1253
+ this._nonnegative = false;
1254
+ this._finite = false;
1255
+ this._safe = false;
1256
+ }
1257
+ parse(value) {
1258
+ if (value === void 0 && this._default !== void 0) {
1259
+ value = this._default;
1260
+ }
1261
+ if (typeof value !== "number" && !(typeof value === "string" && value.trim() !== "")) {
1262
+ throw new Error(`Expected number, got ${value === null ? "null" : typeof value}`);
1263
+ }
1264
+ const num = Number(value);
1265
+ if (isNaN(num)) {
1266
+ throw new Error(`Expected number, got ${typeof value}`);
1267
+ }
1268
+ if (this._int && !Number.isInteger(num)) {
1269
+ throw new Error("Expected integer");
1270
+ }
1271
+ if (this._positive && num <= 0) {
1272
+ throw new Error("Expected positive number");
1273
+ }
1274
+ if (this._negative && num >= 0) {
1275
+ throw new Error("Expected negative number");
1276
+ }
1277
+ if (this._nonpositive && num > 0) {
1278
+ throw new Error("Expected non-positive number");
1279
+ }
1280
+ if (this._nonnegative && num < 0) {
1281
+ throw new Error("Expected non-negative number");
1282
+ }
1283
+ if (this._min !== void 0 && num < this._min) {
1284
+ throw new Error(`Number must be at least ${this._min}`);
1285
+ }
1286
+ if (this._max !== void 0 && num > this._max) {
1287
+ throw new Error(`Number must be at most ${this._max}`);
1288
+ }
1289
+ if (this._multipleOf !== void 0 && num % this._multipleOf !== 0) {
1290
+ throw new Error(`Number must be a multiple of ${this._multipleOf}`);
1291
+ }
1292
+ if (this._finite && !Number.isFinite(num)) {
1293
+ throw new Error("Expected finite number");
1294
+ }
1295
+ if (this._safe && !Number.isSafeInteger(num)) {
1296
+ throw new Error("Expected safe integer");
1297
+ }
1298
+ this.applyRefinements(num);
1299
+ return this.applyTransforms(num);
1300
+ }
1301
+ min(value) {
1302
+ this._min = value;
1303
+ return this;
1304
+ }
1305
+ max(value) {
1306
+ this._max = value;
1307
+ return this;
1308
+ }
1309
+ int() {
1310
+ this._int = true;
1311
+ return this;
1312
+ }
1313
+ positive() {
1314
+ this._positive = true;
1315
+ return this;
1316
+ }
1317
+ negative() {
1318
+ this._negative = true;
1319
+ return this;
1320
+ }
1321
+ nonpositive() {
1322
+ this._nonpositive = true;
1323
+ return this;
1324
+ }
1325
+ nonnegative() {
1326
+ this._nonnegative = true;
1327
+ return this;
1328
+ }
1329
+ multipleOf(value) {
1330
+ this._multipleOf = value;
1331
+ return this;
1332
+ }
1333
+ finite() {
1334
+ this._finite = true;
1335
+ return this;
1336
+ }
1337
+ safe() {
1338
+ this._safe = true;
1339
+ return this;
1340
+ }
1341
+ };
1342
+ var BooleanSchemaImpl = class extends BaseSchemaImpl {
1343
+ constructor() {
1344
+ super(...arguments);
1345
+ this.type = "boolean";
1346
+ }
1347
+ parse(value) {
1348
+ if (value === void 0 && this._default !== void 0) {
1349
+ value = this._default;
1350
+ }
1351
+ if (typeof value === "boolean") {
1352
+ this.applyRefinements(value);
1353
+ return this.applyTransforms(value);
1354
+ }
1355
+ if (value === "true" || value === 1 || value === "1") {
1356
+ this.applyRefinements(true);
1357
+ return this.applyTransforms(true);
1358
+ }
1359
+ if (value === "false" || value === 0 || value === "0") {
1360
+ this.applyRefinements(false);
1361
+ return this.applyTransforms(false);
1362
+ }
1363
+ throw new Error(`Expected boolean, got ${typeof value}`);
1364
+ }
1365
+ };
1366
+ var DateSchemaImpl = class extends BaseSchemaImpl {
1367
+ constructor() {
1368
+ super(...arguments);
1369
+ this.type = "date";
1370
+ }
1371
+ parse(value) {
1372
+ if (value === void 0 && this._default !== void 0) {
1373
+ value = this._default;
1374
+ }
1375
+ let date;
1376
+ if (value instanceof Date) {
1377
+ date = value;
1378
+ } else if (typeof value === "string" || typeof value === "number") {
1379
+ date = new Date(value);
1380
+ } else {
1381
+ throw new Error(`Expected date, got ${typeof value}`);
1382
+ }
1383
+ if (isNaN(date.getTime())) {
1384
+ throw new Error("Invalid date");
1385
+ }
1386
+ if (this._min && date < this._min) {
1387
+ throw new Error(`Date must be after ${this._min.toISOString()}`);
1388
+ }
1389
+ if (this._max && date > this._max) {
1390
+ throw new Error(`Date must be before ${this._max.toISOString()}`);
1391
+ }
1392
+ this.applyRefinements(date);
1393
+ return this.applyTransforms(date);
1394
+ }
1395
+ min(date) {
1396
+ this._min = date;
1397
+ return this;
1398
+ }
1399
+ max(date) {
1400
+ this._max = date;
1401
+ return this;
1402
+ }
1403
+ };
1404
+ var ArraySchemaImpl = class extends BaseSchemaImpl {
1405
+ constructor(itemSchema) {
1406
+ super();
1407
+ this.type = "array";
1408
+ this._nonempty = false;
1409
+ this._itemSchema = itemSchema;
1410
+ }
1411
+ parse(value) {
1412
+ if (value === void 0 && this._default !== void 0) {
1413
+ value = this._default;
1414
+ }
1415
+ if (!Array.isArray(value)) {
1416
+ throw new Error(`Expected array, got ${typeof value}`);
1417
+ }
1418
+ if (this._length !== void 0 && value.length !== this._length) {
1419
+ throw new Error(`Array must have exactly ${this._length} items`);
1420
+ }
1421
+ if (this._min !== void 0 && value.length < this._min) {
1422
+ throw new Error(`Array must have at least ${this._min} items`);
1423
+ }
1424
+ if (this._max !== void 0 && value.length > this._max) {
1425
+ throw new Error(`Array must have at most ${this._max} items`);
1426
+ }
1427
+ if (this._nonempty && value.length === 0) {
1428
+ throw new Error("Array must not be empty");
1429
+ }
1430
+ const parsed = this._itemSchema ? value.map((item, index) => {
1431
+ try {
1432
+ return this._itemSchema.parse(item);
1433
+ } catch (error) {
1434
+ throw new Error(`Invalid item at index ${index}: ${error instanceof Error ? error.message : "Unknown error"}`);
1435
+ }
1436
+ }) : value;
1437
+ this.applyRefinements(parsed);
1438
+ return this.applyTransforms(parsed);
1439
+ }
1440
+ min(length) {
1441
+ this._min = length;
1442
+ return this;
1443
+ }
1444
+ max(length) {
1445
+ this._max = length;
1446
+ return this;
1447
+ }
1448
+ length(length) {
1449
+ this._length = length;
1450
+ return this;
1451
+ }
1452
+ nonempty() {
1453
+ this._nonempty = true;
1454
+ return this;
1455
+ }
1456
+ };
1457
+ var ObjectSchemaImpl = class _ObjectSchemaImpl extends BaseSchemaImpl {
1458
+ constructor() {
1459
+ super(...arguments);
1460
+ this.type = "object";
1461
+ this._strict = false;
1462
+ this._passthrough = false;
1463
+ }
1464
+ parse(value) {
1465
+ if (value === void 0 && this._default !== void 0) {
1466
+ value = this._default;
1467
+ }
1468
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1469
+ throw new Error(`Expected object, got ${typeof value}`);
1470
+ }
1471
+ const result = {};
1472
+ const input = value;
1473
+ if (this._shape) {
1474
+ for (const [key, schema2] of Object.entries(this._shape)) {
1475
+ try {
1476
+ result[key] = schema2.parse(input[key]);
1477
+ } catch (error) {
1478
+ throw new Error(`Invalid value for key "${key}": ${error instanceof Error ? error.message : "Unknown error"}`);
1479
+ }
1480
+ }
1481
+ for (const key of Object.keys(input)) {
1482
+ if (!hasOwn(this._shape, key)) {
1483
+ if (this._strict) {
1484
+ throw new Error(`Unknown key "${key}"`);
1485
+ } else if (this._passthrough) {
1486
+ setOwn(result, key, input[key]);
1487
+ } else if (this._catchall) {
1488
+ try {
1489
+ setOwn(result, key, this._catchall.parse(input[key]));
1490
+ } catch (error) {
1491
+ throw new Error(`Invalid value for key "${key}": ${error instanceof Error ? error.message : "Unknown error"}`);
1492
+ }
1493
+ }
1494
+ }
1495
+ }
1496
+ } else {
1497
+ for (const key of Object.keys(input)) {
1498
+ setOwn(result, key, input[key]);
1499
+ }
1500
+ }
1501
+ this.applyRefinements(result);
1502
+ return this.applyTransforms(result);
1503
+ }
1504
+ shape(shape) {
1505
+ this._shape = shape;
1506
+ return this;
1507
+ }
1508
+ strict() {
1509
+ this._strict = true;
1510
+ this._passthrough = false;
1511
+ return this;
1512
+ }
1513
+ passthrough() {
1514
+ this._passthrough = true;
1515
+ this._strict = false;
1516
+ return this;
1517
+ }
1518
+ strip() {
1519
+ this._strict = false;
1520
+ this._passthrough = false;
1521
+ return this;
1522
+ }
1523
+ catchall(schema2) {
1524
+ this._catchall = schema2;
1525
+ return this;
1526
+ }
1527
+ pick(keys) {
1528
+ if (!this._shape) {
1529
+ throw new Error("Cannot pick from object without shape");
1530
+ }
1531
+ const newShape = {};
1532
+ for (const key of keys) {
1533
+ if (key in this._shape) {
1534
+ newShape[key] = this._shape[key];
1535
+ }
1536
+ }
1537
+ const schema2 = new _ObjectSchemaImpl();
1538
+ schema2._shape = newShape;
1539
+ return schema2;
1540
+ }
1541
+ omit(keys) {
1542
+ if (!this._shape) {
1543
+ throw new Error("Cannot omit from object without shape");
1544
+ }
1545
+ const keySet = new Set(keys);
1546
+ const newShape = {};
1547
+ for (const [key, value] of Object.entries(this._shape)) {
1548
+ if (!keySet.has(key)) {
1549
+ newShape[key] = value;
1550
+ }
1551
+ }
1552
+ const schema2 = new _ObjectSchemaImpl();
1553
+ schema2._shape = newShape;
1554
+ return schema2;
1555
+ }
1556
+ extend(extension) {
1557
+ const newShape = { ...this._shape || {}, ...extension };
1558
+ const schema2 = new _ObjectSchemaImpl();
1559
+ schema2._shape = newShape;
1560
+ return schema2;
1561
+ }
1562
+ merge(other) {
1563
+ const otherImpl = other;
1564
+ const newShape = { ...this._shape || {}, ...otherImpl._shape || {} };
1565
+ const schema2 = new _ObjectSchemaImpl();
1566
+ schema2._shape = newShape;
1567
+ return schema2;
1568
+ }
1569
+ partial() {
1570
+ if (!this._shape) {
1571
+ return this;
1572
+ }
1573
+ const newShape = {};
1574
+ for (const [key, value] of Object.entries(this._shape)) {
1575
+ newShape[key] = value.optional();
1576
+ }
1577
+ const schema2 = new _ObjectSchemaImpl();
1578
+ schema2._shape = newShape;
1579
+ return schema2;
1580
+ }
1581
+ deepPartial() {
1582
+ return this;
1583
+ }
1584
+ required() {
1585
+ return this;
1586
+ }
1587
+ };
1588
+ var EnumSchemaImpl = class extends BaseSchemaImpl {
1589
+ constructor(options) {
1590
+ super();
1591
+ this.type = "enum";
1592
+ this.options = options;
1593
+ }
1594
+ parse(value) {
1595
+ if (value === void 0 && this._default !== void 0) {
1596
+ value = this._default;
1597
+ }
1598
+ if (!this.options.includes(value)) {
1599
+ throw new Error(`Expected one of ${this.options.join(", ")}, got ${value}`);
1600
+ }
1601
+ this.applyRefinements(value);
1602
+ return this.applyTransforms(value);
1603
+ }
1604
+ };
1605
+ var UnionSchemaImpl = class extends BaseSchemaImpl {
1606
+ constructor(options) {
1607
+ super();
1608
+ this.type = "union";
1609
+ this.options = options;
1610
+ }
1611
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1612
+ parse(value) {
1613
+ if (value === void 0 && this._default !== void 0) {
1614
+ value = this._default;
1615
+ }
1616
+ const errors = [];
1617
+ for (const schema2 of this.options) {
1618
+ try {
1619
+ const result = schema2.parse(value);
1620
+ this.applyRefinements(result);
1621
+ return this.applyTransforms(result);
1622
+ } catch (error) {
1623
+ errors.push(error instanceof Error ? error.message : "Unknown error");
1624
+ }
1625
+ }
1626
+ throw new Error(`Union validation failed: ${errors.join("; ")}`);
1627
+ }
1628
+ };
1629
+ var OptionalSchemaImpl = class extends BaseSchemaImpl {
1630
+ constructor(innerType) {
1631
+ super();
1632
+ this.type = "optional";
1633
+ this.innerType = innerType;
1634
+ }
1635
+ parse(value) {
1636
+ if (value === void 0) {
1637
+ return void 0;
1638
+ }
1639
+ const result = this.innerType.parse(value);
1640
+ this.applyRefinements(result);
1641
+ return this.applyTransforms(result);
1642
+ }
1643
+ };
1644
+ var NullableSchemaImpl = class extends BaseSchemaImpl {
1645
+ constructor(innerType) {
1646
+ super();
1647
+ this.type = "nullable";
1648
+ this.innerType = innerType;
1649
+ }
1650
+ parse(value) {
1651
+ if (value === null) {
1652
+ return null;
1653
+ }
1654
+ const result = this.innerType.parse(value);
1655
+ this.applyRefinements(result);
1656
+ return this.applyTransforms(result);
1657
+ }
1658
+ };
1659
+ var q = {
1660
+ string: () => new StringSchemaImpl(),
1661
+ number: () => new NumberSchemaImpl(),
1662
+ boolean: () => new BooleanSchemaImpl(),
1663
+ date: () => new DateSchemaImpl(),
1664
+ array: (schema2) => new ArraySchemaImpl(schema2),
1665
+ object: () => new ObjectSchemaImpl(),
1666
+ enum: (...values) => new EnumSchemaImpl(values),
1667
+ union: (...schemas) => new UnionSchemaImpl(schemas),
1668
+ literal: (value) => {
1669
+ return new class extends BaseSchemaImpl {
1670
+ constructor() {
1671
+ super(...arguments);
1672
+ this.type = "literal";
1673
+ }
1674
+ parse(input) {
1675
+ if (input !== value) {
1676
+ throw new Error(`Expected ${value}, got ${input}`);
1677
+ }
1678
+ return value;
1679
+ }
1680
+ }();
1681
+ },
1682
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1683
+ any: () => {
1684
+ return new class extends BaseSchemaImpl {
1685
+ constructor() {
1686
+ super(...arguments);
1687
+ this.type = "any";
1688
+ }
1689
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1690
+ parse(value) {
1691
+ return value;
1692
+ }
1693
+ }();
1694
+ },
1695
+ unknown: () => {
1696
+ return new class extends BaseSchemaImpl {
1697
+ constructor() {
1698
+ super(...arguments);
1699
+ this.type = "unknown";
1700
+ }
1701
+ parse(value) {
1702
+ return value;
1703
+ }
1704
+ }();
1705
+ },
1706
+ null: () => {
1707
+ return new class extends BaseSchemaImpl {
1708
+ constructor() {
1709
+ super(...arguments);
1710
+ this.type = "null";
1711
+ }
1712
+ parse(value) {
1713
+ if (value !== null) {
1714
+ throw new Error(`Expected null, got ${typeof value}`);
1715
+ }
1716
+ return null;
1717
+ }
1718
+ }();
1719
+ },
1720
+ undefined: () => {
1721
+ return new class extends BaseSchemaImpl {
1722
+ constructor() {
1723
+ super(...arguments);
1724
+ this.type = "undefined";
1725
+ }
1726
+ parse(value) {
1727
+ if (value !== void 0) {
1728
+ throw new Error(`Expected undefined, got ${typeof value}`);
1729
+ }
1730
+ return void 0;
1731
+ }
1732
+ }();
1733
+ },
1734
+ void: () => {
1735
+ return new class extends BaseSchemaImpl {
1736
+ constructor() {
1737
+ super(...arguments);
1738
+ this.type = "void";
1739
+ }
1740
+ parse(value) {
1741
+ if (value !== void 0) {
1742
+ throw new Error(`Expected void, got ${typeof value}`);
1743
+ }
1744
+ return void 0;
1745
+ }
1746
+ }();
1747
+ }
1748
+ };
1749
+ function schema(shape) {
1750
+ return q.object().shape(shape);
1751
+ }
1752
+ function validate(schema2, value) {
1753
+ return schema2.parse(value);
1754
+ }
1755
+ function isValid(schema2, value) {
1756
+ return schema2.safeParse(value).success;
1757
+ }
1758
+
1759
+ // src/plugins.ts
1760
+ var PluginManager = class _PluginManager {
1761
+ constructor() {
1762
+ this.plugins = /* @__PURE__ */ new Map();
1763
+ }
1764
+ register(plugin) {
1765
+ if (!plugin.name) {
1766
+ throw new Error("Plugin must have a name");
1767
+ }
1768
+ if (this.plugins.has(plugin.name)) {
1769
+ throw new Error(`Plugin "${plugin.name}" is already registered`);
1770
+ }
1771
+ this.plugins.set(plugin.name, plugin);
1772
+ return this;
1773
+ }
1774
+ unregister(pluginName) {
1775
+ return this.plugins.delete(pluginName);
1776
+ }
1777
+ has(pluginName) {
1778
+ return this.plugins.has(pluginName);
1779
+ }
1780
+ get(pluginName) {
1781
+ return this.plugins.get(pluginName);
1782
+ }
1783
+ list() {
1784
+ return Array.from(this.plugins.keys());
1785
+ }
1786
+ clear() {
1787
+ this.plugins.clear();
1788
+ }
1789
+ applyBeforeParse(input, options) {
1790
+ let result = input;
1791
+ for (const plugin of this.plugins.values()) {
1792
+ if (plugin.beforeParse) {
1793
+ result = plugin.beforeParse(result, options);
1794
+ }
1795
+ }
1796
+ return result;
1797
+ }
1798
+ applyAfterParse(result, options) {
1799
+ let output = result;
1800
+ for (const plugin of this.plugins.values()) {
1801
+ if (plugin.afterParse) {
1802
+ output = plugin.afterParse(output, options);
1803
+ }
1804
+ }
1805
+ return output;
1806
+ }
1807
+ applyBeforeStringify(obj, options) {
1808
+ let result = obj;
1809
+ for (const plugin of this.plugins.values()) {
1810
+ if (plugin.beforeStringify) {
1811
+ result = plugin.beforeStringify(result, options);
1812
+ }
1813
+ }
1814
+ return result;
1815
+ }
1816
+ applyAfterStringify(result, options) {
1817
+ let output = result;
1818
+ for (const plugin of this.plugins.values()) {
1819
+ if (plugin.afterStringify) {
1820
+ output = plugin.afterStringify(output, options);
1821
+ }
1822
+ }
1823
+ return output;
1824
+ }
1825
+ static create(plugins) {
1826
+ const manager = new _PluginManager();
1827
+ if (plugins) {
1828
+ for (const plugin of plugins) {
1829
+ manager.register(plugin);
1830
+ }
1831
+ }
1832
+ return manager;
1833
+ }
1834
+ };
1835
+ var createPlugin = (plugin) => plugin;
1836
+ var timestampPlugin = createPlugin({
1837
+ name: "timestamp",
1838
+ beforeStringify: (obj) => {
1839
+ return {
1840
+ ...obj,
1841
+ _timestamp: Date.now()
1842
+ };
1843
+ }
1844
+ });
1845
+ var sortKeysPlugin = createPlugin({
1846
+ name: "sortKeys",
1847
+ beforeStringify: (obj) => {
1848
+ const sorted = {};
1849
+ const keys = Object.keys(obj).sort();
1850
+ for (const key of keys) {
1851
+ setOwn(sorted, key, obj[key]);
1852
+ }
1853
+ return sorted;
1854
+ }
1855
+ });
1856
+ var lowercaseKeysPlugin = createPlugin({
1857
+ name: "lowercaseKeys",
1858
+ afterParse: (result) => {
1859
+ const transformed = {};
1860
+ for (const [key, value] of Object.entries(result)) {
1861
+ const lower = key.toLowerCase();
1862
+ if (lower !== "__proto__") {
1863
+ transformed[lower] = value;
1864
+ }
1865
+ }
1866
+ return transformed;
1867
+ },
1868
+ beforeStringify: (obj) => {
1869
+ const transformed = {};
1870
+ for (const [key, value] of Object.entries(obj)) {
1871
+ const lower = key.toLowerCase();
1872
+ if (lower !== "__proto__") {
1873
+ transformed[lower] = value;
1874
+ }
1875
+ }
1876
+ return transformed;
1877
+ }
1878
+ });
1879
+ var filterEmptyPlugin = createPlugin({
1880
+ name: "filterEmpty",
1881
+ beforeStringify: (obj) => {
1882
+ const filtered = {};
1883
+ for (const [key, value] of Object.entries(obj)) {
1884
+ if (value !== "" && value !== null && value !== void 0) {
1885
+ if (Array.isArray(value) && value.length === 0) {
1886
+ continue;
1887
+ }
1888
+ filtered[key] = value;
1889
+ }
1890
+ }
1891
+ return filtered;
1892
+ }
1893
+ });
1894
+ var base64Plugin = createPlugin({
1895
+ name: "base64",
1896
+ afterStringify: (result) => {
1897
+ const globalObj = globalThis;
1898
+ if (typeof globalObj.btoa === "function") {
1899
+ return globalObj.btoa(result);
1900
+ }
1901
+ return globalObj.Buffer?.from(result).toString("base64") || result;
1902
+ },
1903
+ beforeParse: (input) => {
1904
+ try {
1905
+ const globalObj = globalThis;
1906
+ if (typeof globalObj.atob === "function") {
1907
+ const decoded = globalObj.atob(input);
1908
+ const reencoded = globalObj.btoa?.(decoded);
1909
+ if (reencoded && reencoded.replace(/=+$/, "") === input.replace(/=+$/, "")) {
1910
+ return decoded;
1911
+ }
1912
+ return input;
1913
+ }
1914
+ const Buffer = globalObj.Buffer;
1915
+ if (Buffer) {
1916
+ const decoded = Buffer.from(input, "base64").toString("utf-8");
1917
+ const reencoded = Buffer.from(decoded).toString("base64");
1918
+ if (reencoded.replace(/=+$/, "") === input.replace(/=+$/, "")) {
1919
+ return decoded;
1920
+ }
1921
+ }
1922
+ return input;
1923
+ } catch {
1924
+ return input;
1925
+ }
1926
+ }
1927
+ });
1928
+ var compressPlugin = createPlugin({
1929
+ name: "compress",
1930
+ afterStringify: (result) => {
1931
+ return result.replace(/%20/g, "+").replace(/%2F/gi, "/").replace(/%3A/gi, ":").replace(/%3F/gi, "?").replace(/%40/gi, "@");
1932
+ }
1933
+ });
1934
+ var normalizePlugin = createPlugin({
1935
+ name: "normalize",
1936
+ afterParse: (result) => {
1937
+ return normalizeValues(result);
1938
+ }
1939
+ });
1940
+ function normalizeValues(obj) {
1941
+ if (obj === null || obj === void 0) {
1942
+ return obj;
1943
+ }
1944
+ if (typeof obj === "string") {
1945
+ const trimmed = obj.trim();
1946
+ if (trimmed === "true") return true;
1947
+ if (trimmed === "false") return false;
1948
+ if (trimmed === "null") return null;
1949
+ if (trimmed === "undefined") return void 0;
1950
+ const num = Number(trimmed);
1951
+ if (!isNaN(num) && trimmed === String(num)) {
1952
+ return num;
1953
+ }
1954
+ return trimmed;
1955
+ }
1956
+ if (Array.isArray(obj)) {
1957
+ return obj.map(normalizeValues);
1958
+ }
1959
+ if (typeof obj === "object") {
1960
+ const normalized = {};
1961
+ for (const [key, value] of Object.entries(obj)) {
1962
+ setOwn(normalized, key, normalizeValues(value));
1963
+ }
1964
+ return normalized;
1965
+ }
1966
+ return obj;
1967
+ }
1968
+ var createCustomPlugin = (name, handlers) => {
1969
+ return {
1970
+ name,
1971
+ ...handlers
1972
+ };
1973
+ };
1974
+
1975
+ // src/security.ts
1976
+ var XSS_PATTERNS = [
1977
+ /<script\b/i,
1978
+ /<iframe\b/i,
1979
+ /javascript:/i,
1980
+ /\bon\w+\s*=/i,
1981
+ /<embed\b/i,
1982
+ /<object\b/i,
1983
+ /<link\b/i,
1984
+ /<style\b/i,
1985
+ /vbscript:/i,
1986
+ /data:[^,]{0,256},/i
1987
+ ];
1988
+ var SQL_INJECTION_PATTERNS = [
1989
+ /\b(union|select|insert|update|delete|drop|create|alter|exec|execute)\b/gi,
1990
+ /(-{2}|\/\*|\*\/)/g,
1991
+ /[';]/g
1992
+ // Remove quotes and semicolons
1993
+ ];
1994
+ function sanitizeInput(input, options = {}) {
1995
+ if (!input || typeof input !== "string") {
1996
+ return input;
1997
+ }
1998
+ let sanitized = input;
1999
+ sanitized = sanitized.replace(/<\/?script\b[^<>]*>/gi, "");
2000
+ sanitized = removeElements(sanitized, "iframe");
2001
+ sanitized = removeElements(sanitized, "style");
2002
+ sanitized = sanitized.replace(/<embed\b[^<>]*>/gi, "");
2003
+ sanitized = sanitized.replace(/<object\b[^<>]*>/gi, "");
2004
+ sanitized = sanitized.replace(/<link\b[^<>]*>/gi, "");
2005
+ sanitized = sanitized.replace(/javascript:/gi, "");
2006
+ sanitized = sanitized.replace(/vbscript:/gi, "");
2007
+ sanitized = sanitized.replace(/data:text\/html/gi, "");
2008
+ sanitized = sanitized.replace(/\bon\w+\s*=\s*[^>\s]*/gi, "");
2009
+ if (options.aggressive) {
2010
+ for (const pattern of SQL_INJECTION_PATTERNS) {
2011
+ sanitized = sanitized.replace(pattern, "");
2012
+ }
2013
+ }
2014
+ sanitized = sanitized.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;").replace(/\//g, "&#x2F;");
2015
+ return sanitized;
2016
+ }
2017
+ function removeElements(input, tag) {
2018
+ const lower = input.toLowerCase();
2019
+ const open = `<${tag}`;
2020
+ const close = `</${tag}>`;
2021
+ let out = "";
2022
+ let pos = 0;
2023
+ for (; ; ) {
2024
+ let start = lower.indexOf(open, pos);
2025
+ while (start !== -1 && /[a-z0-9]/.test(lower.charAt(start + open.length))) {
2026
+ start = lower.indexOf(open, start + 1);
2027
+ }
2028
+ if (start === -1) break;
2029
+ const openEnd = lower.indexOf(">", start);
2030
+ if (openEnd === -1) break;
2031
+ const end = lower.indexOf(close, openEnd);
2032
+ if (end === -1) break;
2033
+ out += input.slice(pos, start);
2034
+ pos = end + close.length;
2035
+ }
2036
+ return out + input.slice(pos);
2037
+ }
2038
+ function validateSecurity(obj, options = {}) {
2039
+ const {
2040
+ maxKeys = 1e3,
2041
+ maxDepth = 10,
2042
+ allowPrototypes = false,
2043
+ sanitize = true
2044
+ } = options;
2045
+ const errors = [];
2046
+ const keyCount = countKeys(obj);
2047
+ if (keyCount > maxKeys) {
2048
+ errors.push(`Too many keys: ${keyCount} (max: ${maxKeys})`);
2049
+ }
2050
+ const depth = getDepth(obj);
2051
+ if (depth > maxDepth) {
2052
+ errors.push(`Object too deep: ${depth} levels (max: ${maxDepth})`);
2053
+ }
2054
+ if (!allowPrototypes && hasPrototypePollution(obj)) {
2055
+ errors.push("Prototype pollution detected");
2056
+ }
2057
+ if (sanitize) {
2058
+ const xssVulnerabilities = detectXSS(obj);
2059
+ if (xssVulnerabilities.length > 0) {
2060
+ errors.push(`XSS vulnerabilities detected in keys: ${xssVulnerabilities.join(", ")}`);
2061
+ }
2062
+ }
2063
+ return {
2064
+ valid: errors.length === 0,
2065
+ errors
2066
+ };
2067
+ }
2068
+ function countKeys(obj, count = 0) {
2069
+ if (!obj || typeof obj !== "object") {
2070
+ return count;
2071
+ }
2072
+ if (Array.isArray(obj)) {
2073
+ for (const item of obj) {
2074
+ count = countKeys(item, count);
2075
+ }
2076
+ } else {
2077
+ for (const key in obj) {
2078
+ if (hasOwn(obj, key)) {
2079
+ count++;
2080
+ count = countKeys(obj[key], count);
2081
+ }
2082
+ }
2083
+ }
2084
+ return count;
2085
+ }
2086
+ function hasPrototypePollution(obj) {
2087
+ if (!obj || typeof obj !== "object") {
2088
+ return false;
2089
+ }
2090
+ const dangerousKeys = ["__proto__", "constructor", "prototype"];
2091
+ if (Array.isArray(obj)) {
2092
+ for (const item of obj) {
2093
+ if (hasPrototypePollution(item)) {
2094
+ return true;
2095
+ }
2096
+ }
2097
+ } else {
2098
+ const proto = Object.getPrototypeOf(obj);
2099
+ if (proto && proto !== Object.prototype) {
2100
+ const protoProps = Object.getOwnPropertyNames(proto);
2101
+ for (const prop of protoProps) {
2102
+ if (prop !== "constructor" && typeof proto[prop] !== "function") {
2103
+ return true;
2104
+ }
2105
+ }
2106
+ }
2107
+ const allKeys = Object.getOwnPropertyNames(obj);
2108
+ for (const key of allKeys) {
2109
+ if (dangerousKeys.includes(key)) {
2110
+ return true;
2111
+ }
2112
+ if (hasPrototypePollution(obj[key])) {
2113
+ return true;
2114
+ }
2115
+ }
2116
+ }
2117
+ return false;
2118
+ }
2119
+ function detectXSS(obj, path = "") {
2120
+ const vulnerabilities = [];
2121
+ if (!obj || typeof obj !== "object") {
2122
+ if (typeof obj === "string" && containsXSS(obj)) {
2123
+ vulnerabilities.push(path);
2124
+ }
2125
+ return vulnerabilities;
2126
+ }
2127
+ if (Array.isArray(obj)) {
2128
+ for (let i = 0; i < obj.length; i++) {
2129
+ vulnerabilities.push(...detectXSS(obj[i], `${path}[${i}]`));
2130
+ }
2131
+ } else {
2132
+ for (const key in obj) {
2133
+ if (hasOwn(obj, key)) {
2134
+ const newPath = path ? `${path}.${key}` : key;
2135
+ if (containsXSS(key)) {
2136
+ vulnerabilities.push(`${newPath} (key)`);
2137
+ }
2138
+ vulnerabilities.push(...detectXSS(obj[key], newPath));
2139
+ }
2140
+ }
2141
+ }
2142
+ return vulnerabilities;
2143
+ }
2144
+ function containsXSS(str) {
2145
+ if (typeof str !== "string") {
2146
+ return false;
2147
+ }
2148
+ for (const pattern of XSS_PATTERNS) {
2149
+ if (pattern.test(str)) {
2150
+ return true;
2151
+ }
2152
+ }
2153
+ return false;
2154
+ }
2155
+ function secureStringify(obj, options = {}) {
2156
+ let processedObj = obj;
2157
+ if (options.sanitize) {
2158
+ processedObj = sanitizeObjectData(obj);
2159
+ }
2160
+ const validation = validateSecurity(processedObj, options);
2161
+ if (!validation.valid) {
2162
+ throw new Error(`Security validation failed: ${validation.errors.join(", ")}`);
2163
+ }
2164
+ return JSON.stringify(processedObj);
2165
+ }
2166
+ function sanitizeObjectData(obj) {
2167
+ if (!obj || typeof obj !== "object") {
2168
+ return typeof obj === "string" ? sanitizeInput(obj) : String(obj);
2169
+ }
2170
+ if (Array.isArray(obj)) {
2171
+ return obj.map((item) => sanitizeObjectData(item));
2172
+ }
2173
+ const sanitized = {};
2174
+ for (const key in obj) {
2175
+ if (hasOwn(obj, key)) {
2176
+ const sanitizedKey = sanitizeInput(key);
2177
+ sanitized[sanitizedKey] = sanitizeObjectData(obj[key]);
2178
+ }
2179
+ }
2180
+ return sanitized;
2181
+ }
2182
+ function createSecureParser(parserOrOptions, maybeOptions = {}) {
2183
+ const baseParser = typeof parserOrOptions === "function" ? parserOrOptions : parse;
2184
+ const securityOptions = typeof parserOrOptions === "function" ? maybeOptions : parserOrOptions ?? {};
2185
+ return function secureParser(input, options) {
2186
+ if (!securityOptions.allowPrototypes && !securityOptions.sanitize && typeof input === "string" && hasDangerousKey(input, options)) {
2187
+ throw new Error("Security validation failed: Prototype pollution detected");
2188
+ }
2189
+ let result = baseParser(input, options);
2190
+ if (securityOptions.sanitize) {
2191
+ result = sanitizeObjectData(result);
2192
+ }
2193
+ const validation = validateSecurity(result, securityOptions);
2194
+ if (!validation.valid) {
2195
+ throw new Error(`Security validation failed: ${validation.errors.join(", ")}`);
2196
+ }
2197
+ return result;
2198
+ };
2199
+ }
2200
+ var DANGEROUS_SEGMENT = /(?:^|[[\].])(?:__proto__|constructor|prototype)(?:$|[[\].])/;
2201
+ function hasDangerousKey(input, options) {
2202
+ const delimiter = options?.delimiter ?? "&";
2203
+ for (const pair of input.split(delimiter)) {
2204
+ const equalIndex = pair.indexOf("=");
2205
+ const rawKey = equalIndex === -1 ? pair : pair.slice(0, equalIndex);
2206
+ let key = rawKey;
2207
+ try {
2208
+ key = decodeURIComponent(rawKey.replace(/\+/g, " "));
2209
+ } catch {
2210
+ }
2211
+ if (DANGEROUS_SEGMENT.test(key)) {
2212
+ return true;
2213
+ }
2214
+ }
2215
+ return false;
2216
+ }
2217
+
2218
+ // src/index.ts
2219
+ var defaultPluginManager = new PluginManager();
2220
+ var querystring = {
2221
+ parse: (input, options) => {
2222
+ const { plugins, ...parseOptions } = options || {};
2223
+ const pluginManager = plugins === true ? defaultPluginManager : plugins instanceof PluginManager ? plugins : null;
2224
+ if (pluginManager) {
2225
+ const processedInput = pluginManager.applyBeforeParse(input, parseOptions);
2226
+ const result = parse(processedInput, parseOptions);
2227
+ return pluginManager.applyAfterParse(result, parseOptions);
2228
+ }
2229
+ return parse(input, parseOptions);
2230
+ },
2231
+ stringify: (obj, options) => {
2232
+ const { plugins, ...stringifyOptions } = options || {};
2233
+ const pluginManager = plugins === true ? defaultPluginManager : plugins instanceof PluginManager ? plugins : null;
2234
+ if (pluginManager) {
2235
+ const processedObj = pluginManager.applyBeforeStringify(obj, stringifyOptions);
2236
+ const result = stringify(processedObj, stringifyOptions);
2237
+ return pluginManager.applyAfterStringify(result, stringifyOptions);
2238
+ }
2239
+ return stringify(obj, stringifyOptions);
2240
+ },
2241
+ parseUrl,
2242
+ stringifyUrl,
2243
+ QueryBuilder,
2244
+ builder: (options) => new QueryBuilder(options),
2245
+ q,
2246
+ schema,
2247
+ validate,
2248
+ isValid,
2249
+ plugins: defaultPluginManager,
2250
+ createSecureParser: (options) => createSecureParser(parse, options),
2251
+ version: "1.1.0"
2252
+ };
2253
+ var index_default = querystring;
2254
+ export {
2255
+ PluginManager,
2256
+ QueryBuilder,
2257
+ base64Plugin,
2258
+ compressPlugin,
2259
+ countKeys,
2260
+ createCustomPlugin,
2261
+ createPlugin,
2262
+ createSecureParser,
2263
+ index_default as default,
2264
+ detectXSS,
2265
+ filterEmptyPlugin,
2266
+ hasPrototypePollution,
2267
+ isValid,
2268
+ lowercaseKeysPlugin,
2269
+ normalizePlugin,
2270
+ parse,
2271
+ parseUrl,
2272
+ q,
2273
+ querystring,
2274
+ sanitizeInput,
2275
+ schema,
2276
+ secureStringify,
2277
+ sortKeysPlugin,
2278
+ stringify,
2279
+ stringifyUrl,
2280
+ timestampPlugin,
2281
+ validate,
2282
+ validateSecurity
2283
+ };
2284
+ //# sourceMappingURL=index.mjs.map