@octanejs/nuqs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/parsers.ts ADDED
@@ -0,0 +1,581 @@
1
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import type { Options } from './defs';
3
+ import { safeParse } from './lib/safe-parse';
4
+
5
+ type Require<T, Keys extends keyof T> = Pick<Required<T>, Keys> & Omit<T, Keys>;
6
+
7
+ export type SingleParser<T> = {
8
+ type?: 'single';
9
+ /**
10
+ * Convert a query string value into a state value.
11
+ *
12
+ * If the string value does not represent a valid state value,
13
+ * the parser should return `null`. Throwing an error is also supported.
14
+ */
15
+ parse: (value: string) => T | null;
16
+
17
+ /**
18
+ * Render the state value into a query string value.
19
+ */
20
+ serialize?: (value: T) => string;
21
+
22
+ /**
23
+ * Check if two state values are equal.
24
+ *
25
+ * This is used when using the `clearOnDefault` value, to compare the default
26
+ * value with the set value.
27
+ *
28
+ * It makes sense to provide this function when the state value is an object
29
+ * or an array, as the default referential equality check will not work.
30
+ */
31
+ eq?: (a: T, b: T) => boolean;
32
+ };
33
+
34
+ export type MultiParser<T> = {
35
+ type: 'multi';
36
+ parse: (value: ReadonlyArray<string>) => T | null;
37
+ serialize?: (value: T) => Array<string>;
38
+ eq?: (a: T, b: T) => boolean;
39
+ };
40
+
41
+ export type GenericParser<T> = SingleParser<T> | MultiParser<T>;
42
+ export type GenericParserBuilder<T> = SingleParserBuilder<T> | MultiParserBuilder<T>;
43
+
44
+ /* type aliases for backwards compatibility */
45
+ /** @deprecated use SingleParser instead */
46
+ export type Parser<T> = SingleParser<T>;
47
+ /** @deprecated use SingleParserBuilder instead */
48
+ export type ParserBuilder<T> = SingleParserBuilder<T>;
49
+
50
+ export type SingleParserBuilder<T> = Required<SingleParser<T>> &
51
+ Options & {
52
+ /**
53
+ * Set history type, shallow routing and scroll restoration options
54
+ * at the hook declaration level.
55
+ *
56
+ * Note that you can override those options in individual calls to the
57
+ * state updater function.
58
+ */
59
+ withOptions<This>(this: This, options: Options): This;
60
+
61
+ /**
62
+ * Specifying a default value makes the hook state non-nullable when the
63
+ * query is missing from the URL: the default value is returned instead
64
+ * of `null`.
65
+ *
66
+ * Setting the state to the default value¹ will clear the query string key
67
+ * from the URL, unless `clearOnDefault` is set to `false`.
68
+ *
69
+ * Setting the state to `null` will always clear the query string key
70
+ * from the URL, and return the default value.
71
+ *
72
+ * ¹: Equality is checked with the parser's `eq` function, or referential
73
+ * equality if not provided.
74
+ *
75
+ * @param defaultValue
76
+ */
77
+ withDefault(
78
+ this: SingleParserBuilder<T>,
79
+ defaultValue: NonNullable<T>,
80
+ ): Omit<SingleParserBuilder<T>, 'parseServerSide'> & {
81
+ readonly defaultValue: NonNullable<T>;
82
+
83
+ /**
84
+ * Use the parser in Server Components
85
+ *
86
+ * `parse` is intended to be used only by the hook, but you can use this
87
+ * method to hydrate query values on server-side rendered pages.
88
+ * See the `server-side-parsing` demo for an example.
89
+ *
90
+ * Note that when multiple queries are presented to the parser
91
+ * (eg: `/?a=1&a=2`), only the **first** will be parsed, to mimic the
92
+ * behaviour of URLSearchParams:
93
+ * https://url.spec.whatwg.org/#dom-urlsearchparams-get
94
+ *
95
+ * @param value as coming from page props
96
+ *
97
+ * @deprecated prefer using loaders instead, as they enforce a strong
98
+ * bond between the data type and the search param key.
99
+ */
100
+ parseServerSide(value: string | string[] | undefined): NonNullable<T>;
101
+ };
102
+
103
+ /**
104
+ * Use the parser in Server Components
105
+ *
106
+ * `parse` is intended to be used only by the hook, but you can use this
107
+ * method to hydrate query values on server-side rendered pages.
108
+ * See the `server-side-parsing` demo for an example.
109
+ *
110
+ * Note that when multiple queries are presented to the parser
111
+ * (eg: `/?a=1&a=2`), only the **first** will be parsed, to mimic the
112
+ * behaviour of URLSearchParams:
113
+ * https://url.spec.whatwg.org/#dom-urlsearchparams-get
114
+ *
115
+ * @param value as coming from page props
116
+ *
117
+ * @deprecated prefer using loaders instead, as they enforce a strong
118
+ * bond between the data type and the search param key.
119
+ */
120
+ parseServerSide(value: string | string[] | undefined): T | null;
121
+ };
122
+
123
+ export type MultiParserBuilder<T> = Required<MultiParser<T>> &
124
+ Options & {
125
+ withOptions<This>(this: This, options: Options): This;
126
+ withDefault(
127
+ this: MultiParserBuilder<T>,
128
+ defaultValue: NonNullable<T>,
129
+ ): Omit<MultiParserBuilder<T>, 'parseServerSide'> & {
130
+ readonly defaultValue: NonNullable<T>;
131
+ /**
132
+ * @deprecated exposed for symmetry with SingleParserBuilder only,
133
+ * prefer using loaders instead.
134
+ */
135
+ parseServerSide(value: string | string[] | undefined): NonNullable<T>;
136
+ };
137
+ /**
138
+ * @deprecated exposed for symmetry with SingleParserBuilder only,
139
+ * prefer using loaders instead.
140
+ */
141
+ parseServerSide(value: string | string[] | undefined): T | null;
142
+ };
143
+
144
+ /**
145
+ * Wrap a set of parse/serialize functions into a builder pattern parser
146
+ * you can pass to one of the hooks, making its default value type safe.
147
+ */
148
+ export function createParser<T>(
149
+ parser: Require<SingleParser<T>, 'parse' | 'serialize'>,
150
+ ): SingleParserBuilder<T> {
151
+ function parseServerSideNullable(value: string | string[] | undefined) {
152
+ if (typeof value === 'undefined') {
153
+ return null;
154
+ }
155
+ let str = '';
156
+ if (Array.isArray(value)) {
157
+ // Follow the spec:
158
+ // https://url.spec.whatwg.org/#dom-urlsearchparams-get
159
+ if (value[0] === undefined) {
160
+ return null;
161
+ }
162
+ str = value[0];
163
+ }
164
+ if (typeof value === 'string') {
165
+ str = value;
166
+ }
167
+ return safeParse(parser.parse, str);
168
+ }
169
+
170
+ return {
171
+ type: 'single',
172
+ eq: (a, b) => a === b,
173
+ ...parser,
174
+ parseServerSide: parseServerSideNullable,
175
+ withDefault(defaultValue) {
176
+ return {
177
+ ...this,
178
+ defaultValue,
179
+ parseServerSide(value) {
180
+ return parseServerSideNullable(value) ?? defaultValue;
181
+ },
182
+ };
183
+ },
184
+ withOptions(options: Options) {
185
+ return {
186
+ ...this,
187
+ ...options,
188
+ };
189
+ },
190
+ };
191
+ }
192
+
193
+ export function createMultiParser<T>(
194
+ parser: Omit<Require<MultiParser<T>, 'parse' | 'serialize'>, 'type'>,
195
+ ): MultiParserBuilder<T> {
196
+ function parseServerSideNullable(value: string | string[] | undefined) {
197
+ if (typeof value === 'undefined') {
198
+ return null;
199
+ }
200
+ return safeParse(parser.parse, Array.isArray(value) ? value : [value]);
201
+ }
202
+
203
+ return {
204
+ type: 'multi',
205
+ eq: (a, b) => a === b,
206
+ ...parser,
207
+ parseServerSide: parseServerSideNullable,
208
+ withDefault(defaultValue) {
209
+ return {
210
+ ...this,
211
+ defaultValue,
212
+ parseServerSide(value) {
213
+ return parseServerSideNullable(value) ?? defaultValue;
214
+ },
215
+ };
216
+ },
217
+ withOptions(options: Options) {
218
+ return {
219
+ ...this,
220
+ ...options,
221
+ };
222
+ },
223
+ };
224
+ }
225
+
226
+ // Parsers implementations -----------------------------------------------------
227
+
228
+ export const parseAsString: SingleParserBuilder<string> = createParser({
229
+ parse: (v) => v,
230
+ serialize: String,
231
+ });
232
+
233
+ export const parseAsInteger: SingleParserBuilder<number> = createParser({
234
+ parse: (v) => {
235
+ const int = parseInt(v);
236
+ return int == int ? int : null; // NaN check at low bundle size cost
237
+ },
238
+ serialize: (v) => '' + Math.round(v),
239
+ });
240
+
241
+ export const parseAsIndex: SingleParserBuilder<number> = createParser({
242
+ parse: (v) => {
243
+ const int = parseInt(v);
244
+ return int == int ? int - 1 : null; // NaN check at low bundle size cost
245
+ },
246
+ serialize: (v) => '' + Math.round(v + 1),
247
+ });
248
+
249
+ export const parseAsHex: SingleParserBuilder<number> = createParser({
250
+ parse: (v) => {
251
+ const int = parseInt(v, 16);
252
+ return int == int ? int : null; // NaN check at low bundle size cost
253
+ },
254
+ serialize: (v) => {
255
+ const hex = Math.round(v).toString(16);
256
+ return (hex.length & 1 ? '0' : '') + hex;
257
+ },
258
+ });
259
+
260
+ export const parseAsFloat: SingleParserBuilder<number> = createParser({
261
+ parse: (v) => {
262
+ const float = parseFloat(v);
263
+ return float == float ? float : null; // NaN check at low bundle size cost
264
+ },
265
+ serialize: String,
266
+ });
267
+
268
+ export const parseAsBoolean: SingleParserBuilder<boolean> = createParser({
269
+ parse: (v) => v.toLowerCase() === 'true',
270
+ serialize: String,
271
+ });
272
+
273
+ function compareDates(a: Date, b: Date) {
274
+ return a.valueOf() === b.valueOf();
275
+ }
276
+
277
+ /**
278
+ * Querystring encoded as the number of milliseconds since epoch,
279
+ * and returned as a Date object.
280
+ */
281
+ export const parseAsTimestamp: SingleParserBuilder<Date> = createParser({
282
+ parse: (v) => {
283
+ const ms = parseInt(v);
284
+ return ms == ms ? new Date(ms) : null; // NaN check at low bundle size cost
285
+ },
286
+ serialize: (v: Date) => '' + v.valueOf(),
287
+ eq: compareDates,
288
+ });
289
+
290
+ /**
291
+ * Querystring encoded as an ISO-8601 string (UTC),
292
+ * and returned as a Date object.
293
+ */
294
+ export const parseAsIsoDateTime: SingleParserBuilder<Date> = createParser({
295
+ parse: (v) => {
296
+ const date = new Date(v);
297
+ // NaN check at low bundle size cost
298
+ return date.valueOf() == date.valueOf() ? date : null;
299
+ },
300
+ serialize: (v: Date) => v.toISOString(),
301
+ eq: compareDates,
302
+ });
303
+
304
+ /**
305
+ * Querystring encoded as an ISO-8601 string (UTC)
306
+ * without the time zone offset, and returned as
307
+ * a Date object.
308
+ *
309
+ * The Date is parsed without the time zone offset,
310
+ * making it at 00:00:00 UTC.
311
+ */
312
+ export const parseAsIsoDate: SingleParserBuilder<Date> = createParser({
313
+ parse: (v) => {
314
+ const date = new Date(v.slice(0, 10));
315
+ // NaN check at low bundle size cost
316
+ return date.valueOf() == date.valueOf() ? date : null;
317
+ },
318
+ serialize: (v: Date) => v.toISOString().slice(0, 10),
319
+ eq: compareDates,
320
+ });
321
+
322
+ /**
323
+ * String-based enums provide better type-safety for known sets of values.
324
+ * You will need to pass the parseAsStringEnum function a list of your enum values
325
+ * in order to validate the query string. Anything else will return `null`,
326
+ * or your default value if specified.
327
+ *
328
+ * Example:
329
+ * ```ts
330
+ * enum Direction {
331
+ * up = 'UP',
332
+ * down = 'DOWN',
333
+ * left = 'LEFT',
334
+ * right = 'RIGHT'
335
+ * }
336
+ *
337
+ * const [direction, setDirection] = useQueryState(
338
+ * 'direction',
339
+ * parseAsStringEnum<Direction>(Object.values(Direction)) // pass a list of allowed values
340
+ * .withDefault(Direction.up)
341
+ * )
342
+ * ```
343
+ *
344
+ * Note: the query string value will be the value of the enum, not its name
345
+ * (example above: `direction=UP`).
346
+ *
347
+ * @param validValues The values you want to accept
348
+ */
349
+ export function parseAsStringEnum<Enum extends string>(
350
+ validValues: Enum[],
351
+ ): SingleParserBuilder<Enum> {
352
+ // Delegate implementation to parseAsStringLiteral to avoid duplication.
353
+ return parseAsStringLiteral(validValues as readonly Enum[]);
354
+ }
355
+
356
+ /**
357
+ * String-based literals provide better type-safety for known sets of values.
358
+ * You will need to pass the parseAsStringLiteral function a list of your string values
359
+ * in order to validate the query string. Anything else will return `null`,
360
+ * or your default value if specified.
361
+ *
362
+ * Example:
363
+ * ```ts
364
+ * const colors = ["red", "green", "blue"] as const
365
+ *
366
+ * const [color, setColor] = useQueryState(
367
+ * 'color',
368
+ * parseAsStringLiteral(colors) // pass a readonly list of allowed values
369
+ * .withDefault("red")
370
+ * )
371
+ * ```
372
+ *
373
+ * @param validValues The values you want to accept
374
+ */
375
+ export function parseAsStringLiteral<const Literal extends string>(
376
+ validValues: readonly Literal[],
377
+ ): SingleParserBuilder<Literal> {
378
+ return createParser({
379
+ parse: (query: string) => {
380
+ const asConst = query as unknown as Literal;
381
+ return validValues.includes(asConst) ? asConst : null;
382
+ },
383
+ serialize: String,
384
+ });
385
+ }
386
+
387
+ /**
388
+ * Number-based literals provide better type-safety for known sets of values.
389
+ * You will need to pass the parseAsNumberLiteral function a list of your number values
390
+ * in order to validate the query string. Anything else will return `null`,
391
+ * or your default value if specified.
392
+ *
393
+ * Example:
394
+ * ```ts
395
+ * const diceSides = [1, 2, 3, 4, 5, 6] as const
396
+ *
397
+ * const [side, setSide] = useQueryState(
398
+ * 'side',
399
+ * parseAsNumberLiteral(diceSides) // pass a readonly list of allowed values
400
+ * .withDefault(4)
401
+ * )
402
+ * ```
403
+ *
404
+ * @param validValues The values you want to accept
405
+ */
406
+ export function parseAsNumberLiteral<const Literal extends number>(
407
+ validValues: readonly Literal[],
408
+ ): SingleParserBuilder<Literal> {
409
+ return createParser({
410
+ parse: (query: string) => {
411
+ const asConst = parseFloat(query) as unknown as Literal;
412
+ if (validValues.includes(asConst)) {
413
+ return asConst;
414
+ }
415
+ return null;
416
+ },
417
+ serialize: String,
418
+ });
419
+ }
420
+
421
+ /**
422
+ * Encode any object shape into the querystring value as JSON.
423
+ * Note: you may want to use `useQueryStates` for finer control over
424
+ * multiple related query keys.
425
+ *
426
+ * @param runtimeParser Runtime parser (eg: Zod schema or Standard Schema) to validate after JSON.parse
427
+ */
428
+ export function parseAsJson<T>(
429
+ validator: ((value: unknown) => T | null) | StandardSchemaV1<T>,
430
+ ): SingleParserBuilder<T> {
431
+ return createParser({
432
+ parse: (query) => {
433
+ try {
434
+ const obj = JSON.parse(query);
435
+ if ('~standard' in validator) {
436
+ const result = validator['~standard'].validate(obj);
437
+ if (result instanceof Promise) {
438
+ throw new Error(
439
+ '[nuqs] Only synchronous Standard Schemas are supported in parseAsJson.',
440
+ );
441
+ }
442
+ return result.issues ? null : result.value;
443
+ }
444
+ return validator(obj);
445
+ } catch {
446
+ return null;
447
+ }
448
+ },
449
+ serialize: (value) => JSON.stringify(value),
450
+ eq(a, b) {
451
+ // Check for referential equality first
452
+ return a === b || JSON.stringify(a) === JSON.stringify(b);
453
+ },
454
+ });
455
+ }
456
+
457
+ /**
458
+ * A comma-separated list of items.
459
+ * Items are URI-encoded for safety, so they may not look nice in the URL.
460
+ *
461
+ * @param itemParser Parser for each individual item in the array
462
+ * @param separator The character to use to separate items (default ',')
463
+ */
464
+ export function parseAsArrayOf<ItemType>(
465
+ itemParser: SingleParser<ItemType>,
466
+ separator = ',',
467
+ ): SingleParserBuilder<ItemType[]> {
468
+ const itemEq = itemParser.eq ?? ((a: ItemType, b: ItemType) => a === b);
469
+ const encodedSeparator = encodeURIComponent(separator);
470
+ // todo: Handle default item values and make return type non-nullable
471
+ return createParser({
472
+ parse: (query) => {
473
+ if (query === '') {
474
+ // Empty query should not go through the split/map/filter logic,
475
+ // see https://github.com/47ng/nuqs/issues/329
476
+ return [] as ItemType[];
477
+ }
478
+ return query
479
+ .split(separator)
480
+ .map((item, index) =>
481
+ safeParse(itemParser.parse, item.replaceAll(encodedSeparator, separator), `[${index}]`),
482
+ )
483
+ .filter((value) => value !== null && value !== undefined) as ItemType[];
484
+ },
485
+ serialize: (values) =>
486
+ values
487
+ .map<string>((value) => {
488
+ const str = itemParser.serialize ? itemParser.serialize(value) : String(value);
489
+ return str.replaceAll(separator, encodedSeparator);
490
+ })
491
+ .join(separator),
492
+ eq(a, b) {
493
+ if (a === b) {
494
+ return true; // Referentially stable
495
+ }
496
+ if (a.length !== b.length) {
497
+ return false;
498
+ }
499
+ return a.every((value, index) => itemEq(value, b[index]!));
500
+ },
501
+ });
502
+ }
503
+
504
+ export function parseAsNativeArrayOf<ItemType>(
505
+ itemParser: SingleParser<ItemType>,
506
+ ): ReturnType<MultiParserBuilder<ItemType[]>['withDefault']> {
507
+ const itemEq = itemParser.eq ?? ((a: ItemType, b: ItemType) => a === b);
508
+ return createMultiParser({
509
+ parse: (query) => {
510
+ const parsed = query
511
+ .map((item, index) => safeParse(itemParser.parse, item, `[${index}]`))
512
+ .filter((value) => value !== null && value !== undefined) as ItemType[];
513
+ return parsed.length === 0 ? null : parsed;
514
+ },
515
+ serialize: (values) => {
516
+ // defensive check because we potentially get a single value passed from a standard schema
517
+ const safeValues = Array.isArray(values) ? values : [values];
518
+ return safeValues.flatMap((value) => {
519
+ const serialized = itemParser.serialize?.(value) ?? String(value);
520
+ return typeof serialized === 'string' ? [serialized] : [...serialized];
521
+ });
522
+ },
523
+ eq(a, b) {
524
+ if (a === b) {
525
+ return true; // Referentially stable
526
+ }
527
+ if (a.length !== b.length) {
528
+ return false;
529
+ }
530
+ return a.every((value, index) => itemEq(value, b[index]!));
531
+ },
532
+ }).withDefault([]);
533
+ }
534
+
535
+ type inferSingleParserType<Parser> = Parser extends GenericParserBuilder<infer Value> & {
536
+ defaultValue: infer Value;
537
+ }
538
+ ? Value
539
+ : Parser extends GenericParserBuilder<infer Value>
540
+ ? Value | null
541
+ : never;
542
+
543
+ type inferParserRecordType<Map extends Record<string, GenericParserBuilder<any>>> = {
544
+ [Key in keyof Map]: inferSingleParserType<Map[Key]>;
545
+ } & {};
546
+
547
+ /**
548
+ * Type helper to extract the underlying returned data type of a parser
549
+ * or of an object describing multiple parsers and their associated keys.
550
+ *
551
+ * Usage:
552
+ *
553
+ * ```ts
554
+ * import { type inferParserType } from 'nuqs' // or 'nuqs/server'
555
+ *
556
+ * const intNullable = parseAsInteger
557
+ * const intNonNull = parseAsInteger.withDefault(0)
558
+ *
559
+ * inferParserType<typeof intNullable> // number | null
560
+ * inferParserType<typeof intNonNull> // number
561
+ *
562
+ * const parsers = {
563
+ * a: parseAsInteger,
564
+ * b: parseAsBoolean.withDefault(false)
565
+ * }
566
+ *
567
+ * inferParserType<typeof parsers>
568
+ * // { a: number | null, b: boolean }
569
+ * ```
570
+ */
571
+ export type inferParserType<Input> =
572
+ Input extends GenericParserBuilder<any>
573
+ ? inferSingleParserType<Input>
574
+ : Input extends Record<string, GenericParserBuilder<any>>
575
+ ? inferParserRecordType<Input>
576
+ : never;
577
+
578
+ export type ParserWithOptionalDefault<T> = GenericParserBuilder<T> & {
579
+ defaultValue?: T;
580
+ };
581
+ export type ParserMap = Record<string, ParserWithOptionalDefault<any>>;
@@ -0,0 +1,120 @@
1
+ import type { Nullable, Options, UrlKeys } from './defs';
2
+ import { write } from './lib/search-params';
3
+ import { renderQueryString } from './lib/url-encoding';
4
+ import type { inferParserType, ParserMap } from './parsers';
5
+
6
+ type Base = string | URLSearchParams | URL;
7
+
8
+ export type CreateSerializerOptions<Parsers extends ParserMap> = Pick<Options, 'clearOnDefault'> & {
9
+ urlKeys?: UrlKeys<Parsers>;
10
+ processUrlSearchParams?: (searchParams: URLSearchParams) => URLSearchParams;
11
+ };
12
+
13
+ type SerializeFunction<Parsers extends ParserMap, BaseType extends Base = Base, Return = string> = {
14
+ /**
15
+ * Generate a query string for the given values.
16
+ */
17
+ (values: Partial<Nullable<inferParserType<Parsers>>>): Return;
18
+ /**
19
+ * Append/amend the query string of the given base with the given values.
20
+ *
21
+ * Existing search param values will kept, unless:
22
+ * - the value is null, in which case the search param will be deleted
23
+ * - another value is given for an existing key, in which case the
24
+ * search param will be updated
25
+ */
26
+ (base: BaseType, values: Partial<Nullable<inferParserType<Parsers>>> | null): Return;
27
+ };
28
+
29
+ export function createSerializer<
30
+ Parsers extends ParserMap,
31
+ BaseType extends Base = Base,
32
+ Return = string,
33
+ >(
34
+ parsers: Parsers,
35
+ {
36
+ clearOnDefault = true,
37
+ urlKeys = {},
38
+ processUrlSearchParams,
39
+ }: CreateSerializerOptions<Parsers> = {},
40
+ ): SerializeFunction<Parsers, BaseType, Return> {
41
+ type Values = Partial<Nullable<inferParserType<Parsers>>>;
42
+
43
+ /**
44
+ * Generate a query string for the given values.
45
+ */
46
+ function serialize(values: Values): Return;
47
+ /**
48
+ * Append/amend the query string of the given base with the given values.
49
+ *
50
+ * Existing search param values will kept, unless:
51
+ * - the value is null, in which case the search param will be deleted
52
+ * - another value is given for an existing key, in which case the
53
+ * search param will be updated
54
+ */
55
+ function serialize(base: BaseType, values: Values | null): Return;
56
+ function serialize(arg1BaseOrValues: BaseType | Values, arg2values: Values | null = {}) {
57
+ let [base, search, hash] = isBase<BaseType>(arg1BaseOrValues)
58
+ ? splitBase(arg1BaseOrValues)
59
+ : ['', new URLSearchParams(), ''];
60
+ const values = isBase(arg1BaseOrValues) ? arg2values : arg1BaseOrValues;
61
+ if (values === null) {
62
+ for (const key in parsers) {
63
+ const urlKey = urlKeys[key] ?? key;
64
+ search.delete(urlKey);
65
+ }
66
+ if (processUrlSearchParams) {
67
+ search = processUrlSearchParams(search);
68
+ }
69
+ return (base + renderQueryString(search) + hash) as Return;
70
+ }
71
+ for (const key in parsers) {
72
+ const parser = parsers[key];
73
+ const value = values[key];
74
+ if (!parser || value === undefined) {
75
+ continue;
76
+ }
77
+ const urlKey = urlKeys[key] ?? key;
78
+ const isMatchingDefault =
79
+ parser.defaultValue !== undefined &&
80
+ value !== null &&
81
+ (parser.eq ?? ((a, b) => a === b))(value, parser.defaultValue);
82
+
83
+ if (
84
+ value === null ||
85
+ ((parser.clearOnDefault ?? clearOnDefault ?? true) && isMatchingDefault)
86
+ ) {
87
+ search.delete(urlKey);
88
+ } else {
89
+ const serialized = parser.serialize(value);
90
+ search = write(search, urlKey, serialized);
91
+ }
92
+ }
93
+ if (processUrlSearchParams) {
94
+ search = processUrlSearchParams(search);
95
+ }
96
+ return base + renderQueryString(search) + hash;
97
+ }
98
+ return serialize;
99
+ }
100
+
101
+ function isBase<BaseType>(base: any): base is BaseType {
102
+ return typeof base === 'string' || base instanceof URLSearchParams || base instanceof URL;
103
+ }
104
+
105
+ function splitBase<BaseType extends Base>(base: BaseType) {
106
+ if (typeof base === 'string') {
107
+ const [pathAndSearch = '', ...hashParts] = base.split('#');
108
+ const hash = hashParts.length ? '#' + hashParts.join('#') : '';
109
+ const [path = '', ...search] = pathAndSearch.split('?');
110
+ return [path, new URLSearchParams(search.join('?')), hash] as const;
111
+ } else if (base instanceof URLSearchParams) {
112
+ return ['', new URLSearchParams(base), ''] as const; // Operate on a copy of URLSearchParams, as derived classes may restrict its allowed methods
113
+ } else {
114
+ return [
115
+ base.origin + base.pathname,
116
+ new URLSearchParams(base.searchParams),
117
+ base.hash,
118
+ ] as const;
119
+ }
120
+ }