@timber-js/app 0.2.0-alpha.188 → 0.2.0-alpha.189

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 (42) hide show
  1. package/dist/_chunks/{resolve-schema-5ma5pp1b.js → resolve-schema-CBR6Lm4i.js} +2 -2
  2. package/dist/_chunks/{resolve-schema-5ma5pp1b.js.map → resolve-schema-CBR6Lm4i.js.map} +1 -1
  3. package/dist/_chunks/{schema-bridge-Cc2Gngu1.js → schema-bridge-C83xa9lT.js} +2 -2
  4. package/dist/_chunks/{schema-bridge-Cc2Gngu1.js.map → schema-bridge-C83xa9lT.js.map} +1 -1
  5. package/dist/_chunks/{use-query-states-BbU5Ge1V.js → use-query-states-I3JMng6J.js} +29 -5
  6. package/dist/_chunks/use-query-states-I3JMng6J.js.map +1 -0
  7. package/dist/client/index.js +1 -1
  8. package/dist/client/internal.js +1 -1
  9. package/dist/client/use-query-states.d.ts.map +1 -1
  10. package/dist/codec.js +1 -1
  11. package/dist/cookies/index.js +1 -1
  12. package/dist/params/index.js +1 -1
  13. package/dist/schema-bridge.d.ts +4 -1
  14. package/dist/schema-bridge.d.ts.map +1 -1
  15. package/dist/search-params/define.d.ts +30 -4
  16. package/dist/search-params/define.d.ts.map +1 -1
  17. package/dist/search-params/index.d.ts +1 -1
  18. package/dist/search-params/index.d.ts.map +1 -1
  19. package/dist/search-params/index.js +20 -5
  20. package/dist/search-params/index.js.map +1 -1
  21. package/dist/search-params/parse-total.d.ts +14 -3
  22. package/dist/search-params/parse-total.d.ts.map +1 -1
  23. package/dist/search-params/serialize-equal.d.ts +9 -0
  24. package/dist/search-params/serialize-equal.d.ts.map +1 -0
  25. package/dist/server/internal.js +1 -1
  26. package/dist/server/internal.js.map +1 -1
  27. package/dist/server/route-element-builder.d.ts.map +1 -1
  28. package/dist/server/slot-resolver.d.ts +12 -0
  29. package/dist/server/slot-resolver.d.ts.map +1 -1
  30. package/docs/api/33-api-search-params.mdx +3 -3
  31. package/docs/learn/05-typed-params.mdx +1 -1
  32. package/package.json +1 -1
  33. package/src/client/use-query-states.ts +23 -14
  34. package/src/schema-bridge.ts +8 -3
  35. package/src/search-params/define.ts +73 -14
  36. package/src/search-params/index.ts +1 -0
  37. package/src/search-params/parse-total.ts +17 -4
  38. package/src/search-params/serialize-equal.ts +14 -0
  39. package/src/search-params/wrappers.ts +1 -1
  40. package/src/server/route-element-builder.ts +11 -1
  41. package/src/server/slot-resolver.ts +82 -0
  42. package/dist/_chunks/use-query-states-BbU5Ge1V.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { a as resolveCodecOrSchema, r as isCodec } from "./schema-bridge-Cc2Gngu1.js";
1
+ import { a as resolveCodecOrSchema, r as isCodec } from "./schema-bridge-C83xa9lT.js";
2
2
  //#region src/params/resolve-schema.ts
3
3
  /**
4
4
  * Reconstruct the bracket key for a segment from its type and param name.
@@ -47,4 +47,4 @@ function resolveSchemaCodecs(segmentParams) {
47
47
  //#endregion
48
48
  export { toBracketKey as n, resolveSchemaCodecs as t };
49
49
 
50
- //# sourceMappingURL=resolve-schema-5ma5pp1b.js.map
50
+ //# sourceMappingURL=resolve-schema-CBR6Lm4i.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-schema-5ma5pp1b.js","names":[],"sources":["../../src/params/resolve-schema.ts"],"sourcesContent":["/**\n * Schema resolution — resolves the global schema's segmentParams into\n * a runtime-ready codec map keyed by bracket name (e.g. '[id]').\n *\n * Bracket keys are preserved so that `[id]`, `[...id]`, and `[[...id]]`\n * remain distinct entries. The coercion layer reconstructs bracket keys\n * from matched segment metadata to look up the correct codec.\n *\n * Design doc: design/41-global-params.md §Pipeline Integration\n */\n\nimport type { Codec } from '../codec.js';\nimport { isCodec, resolveCodecOrSchema } from '../schema-bridge.js';\n\n/**\n * Reconstruct the bracket key for a segment from its type and param name.\n * Used by the coercion layer to look up codecs in the bracket-keyed map.\n *\n * 'dynamic' + 'id' → '[id]'\n * 'catch-all' + 'slug' → '[...slug]'\n * 'optional-catch-all' + 'slug' → '[[...slug]]'\n */\nexport function toBracketKey(segmentType: string, paramName: string): string {\n switch (segmentType) {\n case 'catch-all':\n return `[...${paramName}]`;\n case 'optional-catch-all':\n return `[[...${paramName}]]`;\n default:\n return `[${paramName}]`;\n }\n}\n\nconst CATCH_ALL_RE = /^\\[\\.\\.\\..+\\]$/;\nconst OPTIONAL_CATCH_ALL_RE = /^\\[\\[\\.\\.\\..+\\]\\]$/;\n\nfunction isCatchAllKey(key: string): boolean {\n return CATCH_ALL_RE.test(key) || OPTIONAL_CATCH_ALL_RE.test(key);\n}\n\nfunction isOptionalCatchAllKey(key: string): boolean {\n return OPTIONAL_CATCH_ALL_RE.test(key);\n}\n\n/**\n * Resolve the global schema's segmentParams into a map of bracket-keyed\n * param name → resolved Codec.\n *\n * Keys are preserved exactly as written in `app/schema.ts` so that\n * `[id]`, `[...id]`, and `[[...id]]` remain distinct entries.\n * The coercion layer in `param-coercion.ts` reconstructs bracket keys\n * from matched segment metadata to look up the correct codec.\n *\n * Input: { '[id]': z.coerce.number(), '[...slug]': codec.string }\n * Output: { '[id]': Codec<number>, '[...slug]': Codec<string> }\n */\nexport function resolveSchemaCodecs(\n segmentParams: Record<string, unknown>\n): Record<string, Codec<unknown>> {\n const resolved: Record<string, Codec<unknown>> = Object.create(null);\n\n for (const [bracketName, value] of Object.entries(segmentParams)) {\n if (isCatchAllKey(bracketName) && isCodec(value) && !('__catchAll' in value)) {\n throw new Error(\n `[timber] Schema error: '${bracketName}' is a catch-all segment and requires an array codec ` +\n `(e.g. codec.catchAll(codec.string)). Got a scalar codec.`\n );\n }\n if (\n isOptionalCatchAllKey(bracketName) &&\n isCodec(value) &&\n '__catchAll' in value &&\n !('__optional' in value)\n ) {\n throw new Error(\n `[timber] Schema error: '${bracketName}' is an optional catch-all segment and requires codec.optionalCatchAll() ` +\n `(e.g. codec.optionalCatchAll(codec.string)). Got a non-optional catch-all codec.`\n );\n }\n resolved[bracketName] = resolveCodecOrSchema(bracketName, value, 'param');\n }\n\n return resolved;\n}\n"],"mappings":";;;;;;;;;;AAsBA,SAAgB,aAAa,aAAqB,WAA2B;CAC3E,QAAQ,aAAR;EACE,KAAK,aACH,OAAO,OAAO,UAAU;EAC1B,KAAK,sBACH,OAAO,QAAQ,UAAU;EAC3B,SACE,OAAO,IAAI,UAAU;CACzB;AACF;AAEA,IAAM,eAAe;AACrB,IAAM,wBAAwB;AAE9B,SAAS,cAAc,KAAsB;CAC3C,OAAO,aAAa,KAAK,GAAG,KAAK,sBAAsB,KAAK,GAAG;AACjE;AAEA,SAAS,sBAAsB,KAAsB;CACnD,OAAO,sBAAsB,KAAK,GAAG;AACvC;;;;;;;;;;;;;AAcA,SAAgB,oBACd,eACgC;CAChC,MAAM,WAA2C,OAAO,OAAO,IAAI;CAEnE,KAAK,MAAM,CAAC,aAAa,UAAU,OAAO,QAAQ,aAAa,GAAG;EAChE,IAAI,cAAc,WAAW,KAAK,QAAQ,KAAK,KAAK,EAAE,gBAAgB,QACpE,MAAM,IAAI,MACR,2BAA2B,YAAY,8GAEzC;EAEF,IACE,sBAAsB,WAAW,KACjC,QAAQ,KAAK,KACb,gBAAgB,SAChB,EAAE,gBAAgB,QAElB,MAAM,IAAI,MACR,2BAA2B,YAAY,0JAEzC;EAEF,SAAS,eAAe,qBAAqB,aAAa,OAAO,OAAO;CAC1E;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"resolve-schema-CBR6Lm4i.js","names":[],"sources":["../../src/params/resolve-schema.ts"],"sourcesContent":["/**\n * Schema resolution — resolves the global schema's segmentParams into\n * a runtime-ready codec map keyed by bracket name (e.g. '[id]').\n *\n * Bracket keys are preserved so that `[id]`, `[...id]`, and `[[...id]]`\n * remain distinct entries. The coercion layer reconstructs bracket keys\n * from matched segment metadata to look up the correct codec.\n *\n * Design doc: design/41-global-params.md §Pipeline Integration\n */\n\nimport type { Codec } from '../codec.js';\nimport { isCodec, resolveCodecOrSchema } from '../schema-bridge.js';\n\n/**\n * Reconstruct the bracket key for a segment from its type and param name.\n * Used by the coercion layer to look up codecs in the bracket-keyed map.\n *\n * 'dynamic' + 'id' → '[id]'\n * 'catch-all' + 'slug' → '[...slug]'\n * 'optional-catch-all' + 'slug' → '[[...slug]]'\n */\nexport function toBracketKey(segmentType: string, paramName: string): string {\n switch (segmentType) {\n case 'catch-all':\n return `[...${paramName}]`;\n case 'optional-catch-all':\n return `[[...${paramName}]]`;\n default:\n return `[${paramName}]`;\n }\n}\n\nconst CATCH_ALL_RE = /^\\[\\.\\.\\..+\\]$/;\nconst OPTIONAL_CATCH_ALL_RE = /^\\[\\[\\.\\.\\..+\\]\\]$/;\n\nfunction isCatchAllKey(key: string): boolean {\n return CATCH_ALL_RE.test(key) || OPTIONAL_CATCH_ALL_RE.test(key);\n}\n\nfunction isOptionalCatchAllKey(key: string): boolean {\n return OPTIONAL_CATCH_ALL_RE.test(key);\n}\n\n/**\n * Resolve the global schema's segmentParams into a map of bracket-keyed\n * param name → resolved Codec.\n *\n * Keys are preserved exactly as written in `app/schema.ts` so that\n * `[id]`, `[...id]`, and `[[...id]]` remain distinct entries.\n * The coercion layer in `param-coercion.ts` reconstructs bracket keys\n * from matched segment metadata to look up the correct codec.\n *\n * Input: { '[id]': z.coerce.number(), '[...slug]': codec.string }\n * Output: { '[id]': Codec<number>, '[...slug]': Codec<string> }\n */\nexport function resolveSchemaCodecs(\n segmentParams: Record<string, unknown>\n): Record<string, Codec<unknown>> {\n const resolved: Record<string, Codec<unknown>> = Object.create(null);\n\n for (const [bracketName, value] of Object.entries(segmentParams)) {\n if (isCatchAllKey(bracketName) && isCodec(value) && !('__catchAll' in value)) {\n throw new Error(\n `[timber] Schema error: '${bracketName}' is a catch-all segment and requires an array codec ` +\n `(e.g. codec.catchAll(codec.string)). Got a scalar codec.`\n );\n }\n if (\n isOptionalCatchAllKey(bracketName) &&\n isCodec(value) &&\n '__catchAll' in value &&\n !('__optional' in value)\n ) {\n throw new Error(\n `[timber] Schema error: '${bracketName}' is an optional catch-all segment and requires codec.optionalCatchAll() ` +\n `(e.g. codec.optionalCatchAll(codec.string)). Got a non-optional catch-all codec.`\n );\n }\n resolved[bracketName] = resolveCodecOrSchema(bracketName, value, 'param');\n }\n\n return resolved;\n}\n"],"mappings":";;;;;;;;;;AAsBA,SAAgB,aAAa,aAAqB,WAA2B;CAC3E,QAAQ,aAAR;EACE,KAAK,aACH,OAAO,OAAO,UAAU;EAC1B,KAAK,sBACH,OAAO,QAAQ,UAAU;EAC3B,SACE,OAAO,IAAI,UAAU;CACzB;AACF;AAEA,IAAM,eAAe;AACrB,IAAM,wBAAwB;AAE9B,SAAS,cAAc,KAAsB;CAC3C,OAAO,aAAa,KAAK,GAAG,KAAK,sBAAsB,KAAK,GAAG;AACjE;AAEA,SAAS,sBAAsB,KAAsB;CACnD,OAAO,sBAAsB,KAAK,GAAG;AACvC;;;;;;;;;;;;;AAcA,SAAgB,oBACd,eACgC;CAChC,MAAM,WAA2C,OAAO,OAAO,IAAI;CAEnE,KAAK,MAAM,CAAC,aAAa,UAAU,OAAO,QAAQ,aAAa,GAAG;EAChE,IAAI,cAAc,WAAW,KAAK,QAAQ,KAAK,KAAK,EAAE,gBAAgB,QACpE,MAAM,IAAI,MACR,2BAA2B,YAAY,8GAEzC;EAEF,IACE,sBAAsB,WAAW,KACjC,QAAQ,KAAK,KACb,gBAAgB,SAChB,EAAE,gBAAgB,QAElB,MAAM,IAAI,MACR,2BAA2B,YAAY,0JAEzC;EAEF,SAAS,eAAe,qBAAqB,aAAa,OAAO,OAAO;CAC1E;CAEA,OAAO;AACT"}
@@ -188,7 +188,7 @@ function fromArraySchema(schema) {
188
188
  parse: (value) => parseThroughSchema(schema, arrayFirst, value),
189
189
  serialize(value) {
190
190
  if (value === null || value === void 0) return null;
191
- if (Array.isArray(value)) return value.length === 0 ? null : value.join(",");
191
+ if (Array.isArray(value)) return value.length === 0 ? null : value.map(String);
192
192
  return String(value);
193
193
  }
194
194
  };
@@ -196,4 +196,4 @@ function fromArraySchema(schema) {
196
196
  //#endregion
197
197
  export { resolveCodecOrSchema as a, isStandardSchema as i, fromSchema as n, isCodec as r, fromArraySchema as t };
198
198
 
199
- //# sourceMappingURL=schema-bridge-Cc2Gngu1.js.map
199
+ //# sourceMappingURL=schema-bridge-C83xa9lT.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema-bridge-Cc2Gngu1.js","names":[],"sources":["../../src/schema-bridge.ts"],"sourcesContent":["/**\n * Standard Schema bridge — shared helpers for bridging Standard Schema-compatible\n * validation libraries (Zod, Valibot, ArkType) to the Codec<T> protocol.\n *\n * This module is the single source of truth for:\n * - StandardSchemaV1 interface (subset of the Standard Schema spec)\n * - validateSync() helper\n * - fromSchema() — search-param bridge; scalar shape first, array second\n * - fromArraySchema() — same loop, array shape first\n * - fromCookieSchema() — scalar shape only; a cookie has no array shape\n * - fromParamSchema() — route params; throws on failure (invalid param → 404)\n *\n * One parse loop, four candidate orders. Which shapes a bridge offers, and\n * in what order, is the ONLY thing that differs — see §\"Shape tolerance\"\n * below and in design/23-search-params.md. `serialize` is deliberately NOT\n * shared: `null` means \"omit the key\" for a search param and \"delete the\n * cookie\" for a cookie, so unifying it silently changed what\n * `cookie.set([])` did (TIM-1352).\n *\n * These are re-exported from @timber-js/app/search-params, @timber-js/app/segment-params,\n * and @timber-js/app/cookies for convenience. The canonical import is\n * @timber-js/app/codec.\n *\n * Design doc: design/23a-search-params-triage.md §\"Unify Codec<T> type\"\n */\n\nimport type { Codec } from './codec.js';\n\n// ---------------------------------------------------------------------------\n// Standard Schema interface (subset)\n//\n// Standard Schema (https://github.com/standard-schema/standard-schema) defines\n// a minimal interface that Zod ≥3.24, Valibot ≥1.0, and ArkType all implement.\n// We depend only on `~standard.validate` to avoid coupling to any specific lib.\n// ---------------------------------------------------------------------------\n\n/** Minimal Standard Schema interface for auto-detection. */\nexport interface StandardSchemaV1<Output = unknown> {\n '~standard': {\n validate(value: unknown): StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;\n };\n}\n\nexport type StandardSchemaResult<Output> =\n | { value: Output; issues?: undefined }\n | { value?: undefined; issues: ReadonlyArray<{ message: string }> };\n\n// ---------------------------------------------------------------------------\n// Sync validate helper\n// ---------------------------------------------------------------------------\n\n/**\n * Run a Standard Schema's `~standard.validate()` synchronously.\n *\n * Zod v4's signature includes `Promise` in the return union to satisfy the\n * Standard Schema spec, but in practice Zod always validates synchronously\n * for the schema types we use. We assert the result is sync and throw if\n * it isn't — codec parsing must be synchronous.\n */\nexport function validateSync<Output>(\n schema: StandardSchemaV1<Output>,\n value: unknown\n): StandardSchemaResult<Output> {\n const result = schema['~standard'].validate(value);\n if (result instanceof Promise) {\n throw new Error(\n '[timber] fromSchema: schema returned a Promise — only sync schemas are supported.'\n );\n }\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Type guards\n// ---------------------------------------------------------------------------\n\n/** Check if a value is a Standard Schema object. */\nexport function isStandardSchema(value: unknown): value is StandardSchemaV1 {\n return (\n typeof value === 'object' &&\n value !== null &&\n '~standard' in value &&\n typeof (value as StandardSchemaV1)['~standard']?.validate === 'function'\n );\n}\n\n/** Check if a value is a Codec (has parse + serialize methods). */\nexport function isCodec(value: unknown): value is Codec<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Codec<unknown>).parse === 'function' &&\n typeof (value as Codec<unknown>).serialize === 'function'\n );\n}\n\n// ---------------------------------------------------------------------------\n// fromParamSchema — bridge from Standard Schema to Codec<T> for route params\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema to a Codec for route params.\n * Parse throws on failure (invalid param → 404). Serialize returns string.\n */\nexport function fromParamSchema<T>(fieldName: string, schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse(value: string | string[] | undefined): T {\n const result = validateSync(schema, value);\n if (!result.issues) {\n return result.value;\n }\n const messages = result.issues.map((i) => i.message).join(', ');\n throw new Error(`[timber] Param '${fieldName}' coercion failed: ${messages}`);\n },\n serialize(value: T): string | null {\n if (value === null || value === undefined) return null;\n if (Array.isArray(value)) return value.join('/');\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// resolveCodecOrSchema — generic resolver for any codec-or-schema field\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a field value to a Codec. Accepts Codec<T>, StandardSchemaV1<T>,\n * or (for route params) auto-wraps via fromParamSchema.\n *\n * @param fieldName - used in error messages\n * @param value - the codec or schema to resolve\n * @param mode - 'param' uses fromParamSchema (throws on parse failure),\n * 'search' uses fromSchema (falls back to default on failure,\n * tolerant of the repeated-key array shape),\n * 'cookie' uses fromCookieSchema (same, minus the array shape,\n * which a cookie value cannot have)\n */\nexport function resolveCodecOrSchema(\n fieldName: string,\n value: unknown,\n mode: 'param' | 'search' | 'cookie' = 'search'\n): Codec<unknown> {\n if (isCodec(value)) return value;\n if (isStandardSchema(value)) {\n if (mode === 'param') return fromParamSchema(fieldName, value);\n if (mode === 'cookie') return fromCookieSchema(value) as Codec<unknown>;\n return fromSchema(value) as Codec<unknown>;\n }\n throw new Error(\n `[timber] Field '${fieldName}' is not a valid codec or Standard Schema. ` +\n `Expected an object with { parse, serialize } methods, or a Standard Schema object ` +\n `(Zod, Valibot, ArkType).`\n );\n}\n\n// ---------------------------------------------------------------------------\n// fromSchema — bridge from Standard Schema to Codec<T>\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Shape tolerance — the shared parse loop for both bridges\n//\n// A URL value is `string | string[] | undefined`, but a schema is written\n// against ONE of those: `z.string()` wants `'a'`, `z.array(z.string())`\n// wants `['a']`. Nothing in Standard Schema says which — `~standard.types`\n// exists at the type level only, and probing at runtime is not reliable\n// (design/23-search-params.md §\"Shape tolerance\"). So a bridge tries BOTH\n// shapes rather than committing to one and discarding the value when it\n// guessed wrong.\n//\n// Each bridge only chooses WHICH candidates, and in what order. The first\n// candidate is always the shape that bridge already passed, so nothing that\n// parses today changes meaning; a later one is reached only where the old\n// code fell through to the default. `fromCookieSchema` offers ONE candidate,\n// because a cookie has no array shape at all.\n// ---------------------------------------------------------------------------\n\n/**\n * The scalar shape, and only it. A value that cannot be repeated — a cookie —\n * has no array shape to tolerate, so its bridge stays exactly where it was.\n */\nfunction scalarOnly(value: string | string[] | undefined): unknown[] {\n return [Array.isArray(value) ? value[0] : value];\n}\n\n/** Candidate inputs for the scalar bridge: scalar first, array second. */\nfunction scalarFirst(value: string | string[] | undefined): unknown[] {\n if (value === undefined) return [undefined];\n if (typeof value === 'string') return [value, [value]];\n // Repeated keys: `value[0]` matches URLSearchParams.get().\n //\n // A raw `[]` carries no value at all. `value[0]` is `undefined`, which is\n // the shape the scalar bridge has always passed for it, so `undefined`\n // stays FIRST — an empty array must keep meaning \"absent\" and land on the\n // schema's default. Only `defineSearchParams().parse({ tags: [] })`, the\n // record form, can produce one: URLSearchParams never yields an empty list.\n return value.length > 0 ? [value[0], value] : [undefined, value];\n}\n\n/** Candidate inputs for the array bridge: array first, scalar second. */\nfunction arrayFirst(value: string | string[] | undefined): unknown[] {\n if (value === undefined) return [undefined];\n if (typeof value === 'string') return [[value], value];\n // `[]` first here for the same reason, inverted: the array bridge has\n // always passed the empty array straight through.\n return value.length > 0 ? [value, value[0]] : [value, undefined];\n}\n\n/**\n * Validate `value` against `schema` in each candidate shape, then fall back\n * to the schema's default. Shared by every bridge — they differ only in\n * which candidates they offer, and in what order.\n */\nfunction parseThroughSchema<T>(\n schema: StandardSchemaV1<T>,\n candidates: (value: string | string[] | undefined) => unknown[],\n value: string | string[] | undefined\n): T {\n const inputs = candidates(value);\n for (let i = 0; i < inputs.length; i++) {\n // A throw from the FIRST candidate propagates, unchanged: that is the\n // shape the schema was written against, and a throw from it is the\n // deliberate signal design/23 protects — an app schema may `redirect()`\n // or `notFound()` on a value it refuses, and `validateSync` throws on\n // an async schema.\n //\n // A throw from a LATER candidate is ours, not the app's. We invented\n // that shape; the schema never agreed to receive it. A scalar-only\n // hand-written validator doing `value.toUpperCase()`, or a schema that\n // is async for the array shape only, would turn a field that used to\n // fall back to its default into a render-phase 500. Treat it as \"this\n // shape does not fit\" and keep going.\n let result: StandardSchemaResult<T>;\n try {\n result = validateSync(schema, inputs[i]);\n } catch (error) {\n if (i === 0) throw error;\n continue;\n }\n if (!result.issues) {\n return result.value;\n }\n }\n\n // No shape validated — try parsing undefined to get the default.\n // Re-validate each time so factory defaults (e.g. .default(() => []))\n // produce fresh values.\n const defaultResult = validateSync(schema, undefined);\n if (!defaultResult.issues) {\n return defaultResult.value;\n }\n\n // No default available — the field is implicitly optional. Return\n // undefined; defineSearchParams widens the field's inferred type to\n // T | undefined via InferField so this doesn't lie.\n // design/23-search-params.md §\"Implicit Optionality\"\n return undefined as T;\n}\n\n/**\n * Bridge a Standard Schema-compatible schema (Zod, Valibot, ArkType) to a\n * Codec<T>.\n *\n * Parse: coerces the raw URL value through the schema, trying the scalar\n * shape and then the array shape (see `scalarFirst`), so an array schema\n * works bare: `z.array(z.string()).default([])` yields `[]` when absent,\n * `['a']` for `?tags=a`, and `['a','b']` for `?tags=a&tags=b`. When no\n * shape validates, parses `undefined` to get the schema's default (the\n * schema should have a `.default()` call). If that also fails, returns\n * `undefined`.\n *\n * Serialize: `String()` for primitives, `null` for null/undefined. Note\n * that `String(['a','b'])` is `'a,b'` — the same string `fromArraySchema`\n * writes — so a bare array schema round-trips exactly as design/09\n * §\"Array params\" describes.\n *\n * This is the SEARCH-PARAM bridge. Cookies use `fromCookieSchema`; a\n * cookie has no array shape (see below).\n *\n * ```ts\n * import { z } from 'zod/v4'\n *\n * const pageCodec = fromSchema(z.coerce.number().int().min(1).default(1))\n * const tagsCodec = fromSchema(z.array(z.string()).default([]))\n * ```\n */\nexport function fromSchema<T>(schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, scalarFirst, value),\n serialize(value: T): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// fromCookieSchema — bridge for cookie values\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema for a COOKIE value.\n *\n * Identical to `fromSchema` minus the array shape, because a cookie cannot\n * carry one: `Cookie:` headers and `document.cookie` yield a single string\n * per name, and there is no repeated-key concept to be tolerant of. Sharing\n * the search-param bridge here meant a cookie written by this very codec —\n * `serialize(['a','b'])` → `a,b` — read back as the one-element array\n * `['a,b']` instead of failing to its default: no repeated key in sight,\n * just a delimiter reinterpreted as data.\n *\n * The `serialize` contract also differs by domain and must not be unified:\n * for a search param `null` means \"omit the key\", for a cookie it means\n * **delete the cookie** (design/29-cookies.md).\n */\nexport function fromCookieSchema<T>(schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, scalarOnly, value),\n serialize(value: T): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// fromArraySchema — bridge for array-valued codecs\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema for array values. Handles both single strings\n * and repeated query keys (`?tag=a&tag=b`).\n *\n * ```ts\n * import { fromArraySchema } from '@timber-js/app/codec'\n * import { z } from 'zod/v4'\n *\n * const tagsCodec = fromArraySchema(z.array(z.string()).default([]))\n * ```\n *\n * Since TIM-1352 a bare array schema works through `fromSchema` too, so\n * this is no longer required to make an array field parse. Two cases still\n * want it, both listed in design/23 §\"Shape tolerance\":\n *\n * 1. A **permissive** schema meant as an array — one that accepts a string\n * as readily as an array (`z.any()`, a hand-written coercing validator)\n * — where scalar-first ordering would settle on the scalar shape.\n * 2. An array schema wrapped in `.catch([])`, which swallows the failure\n * that would otherwise trigger the array attempt.\n *\n * It also serializes an empty array to `null` (omitting the key) where\n * `fromSchema` writes `''`.\n */\nexport function fromArraySchema<T>(schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, arrayFirst, value),\n serialize(value: T): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (Array.isArray(value)) {\n return value.length === 0 ? null : value.join(',');\n }\n return String(value);\n },\n };\n}\n"],"mappings":";;;;;;;;;AA2DA,SAAgB,aACd,QACA,OAC8B;CAC9B,MAAM,SAAS,OAAO,YAAY,CAAC,SAAS,KAAK;CACjD,IAAI,kBAAkB,SACpB,MAAM,IAAI,MACR,mFACF;CAEF,OAAO;AACT;;AAOA,SAAgB,iBAAiB,OAA2C;CAC1E,OACE,OAAO,UAAU,YACjB,UAAU,QACV,eAAe,SACf,OAAQ,MAA2B,YAAY,EAAE,aAAa;AAElE;;AAGA,SAAgB,QAAQ,OAAyC;CAC/D,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAyB,UAAU,cAC3C,OAAQ,MAAyB,cAAc;AAEnD;;;;;AAUA,SAAgB,gBAAmB,WAAmB,QAAuC;CAC3F,OAAO;EACL,MAAM,OAAyC;GAC7C,MAAM,SAAS,aAAa,QAAQ,KAAK;GACzC,IAAI,CAAC,OAAO,QACV,OAAO,OAAO;GAEhB,MAAM,WAAW,OAAO,OAAO,KAAK,MAAM,EAAE,OAAO,CAAC,CAAC,KAAK,IAAI;GAC9D,MAAM,IAAI,MAAM,mBAAmB,UAAU,qBAAqB,UAAU;EAC9E;EACA,UAAU,OAAyB;GACjC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;GAClD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,KAAK,GAAG;GAC/C,OAAO,OAAO,KAAK;EACrB;CACF;AACF;;;;;;;;;;;;;AAkBA,SAAgB,qBACd,WACA,OACA,OAAsC,UACtB;CAChB,IAAI,QAAQ,KAAK,GAAG,OAAO;CAC3B,IAAI,iBAAiB,KAAK,GAAG;EAC3B,IAAI,SAAS,SAAS,OAAO,gBAAgB,WAAW,KAAK;EAC7D,IAAI,SAAS,UAAU,OAAO,iBAAiB,KAAK;EACpD,OAAO,WAAW,K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ACrB;CACF;AACF;;;;;;;;;;;;;;;;AAqBA,SAAgB,iBAAoB,QAAuC;CACzE,OAAO;EACL,QAAQ,UACN,mBAAmB,QAAQ,YAAY,KAAK;EAC9C,UAAU,OAAyB;GACjC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,OAAO;GAET,OAAO,OAAO,KAAK;EACrB;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,gBAAmB,QAAuC;CACxE,OAAO;EACL,QAAQ,UACN,mBAAmB,QAAQ,YAAY,KAAK;EAC9C,UAAU,OAAyB;GACjC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,OAAO;GAET,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,WAAW,IAAI,OAAO,MAAM,KAAK,GAAG;GAEnD,OAAO,OAAO,KAAK;EACrB;CACF;AACF"}
1
+ {"version":3,"file":"schema-bridge-C83xa9lT.js","names":[],"sources":["../../src/schema-bridge.ts"],"sourcesContent":["/**\n * Standard Schema bridge — shared helpers for bridging Standard Schema-compatible\n * validation libraries (Zod, Valibot, ArkType) to the Codec<T> protocol.\n *\n * This module is the single source of truth for:\n * - StandardSchemaV1 interface (subset of the Standard Schema spec)\n * - validateSync() helper\n * - fromSchema() — search-param bridge; scalar shape first, array second\n * - fromArraySchema() — same loop, array shape first\n * - fromCookieSchema() — scalar shape only; a cookie has no array shape\n * - fromParamSchema() — route params; throws on failure (invalid param → 404)\n *\n * One parse loop, four candidate orders. Which shapes a bridge offers, and\n * in what order, is the ONLY thing that differs — see §\"Shape tolerance\"\n * below and in design/23-search-params.md. `serialize` is deliberately NOT\n * shared: `null` means \"omit the key\" for a search param and \"delete the\n * cookie\" for a cookie, so unifying it silently changed what\n * `cookie.set([])` did (TIM-1352).\n *\n * These are re-exported from @timber-js/app/search-params, @timber-js/app/segment-params,\n * and @timber-js/app/cookies for convenience. The canonical import is\n * @timber-js/app/codec.\n *\n * Design doc: design/23a-search-params-triage.md §\"Unify Codec<T> type\"\n */\n\nimport type { Codec } from './codec.js';\n\n// ---------------------------------------------------------------------------\n// Standard Schema interface (subset)\n//\n// Standard Schema (https://github.com/standard-schema/standard-schema) defines\n// a minimal interface that Zod ≥3.24, Valibot ≥1.0, and ArkType all implement.\n// We depend only on `~standard.validate` to avoid coupling to any specific lib.\n// ---------------------------------------------------------------------------\n\n/** Minimal Standard Schema interface for auto-detection. */\nexport interface StandardSchemaV1<Output = unknown> {\n '~standard': {\n validate(value: unknown): StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;\n };\n}\n\nexport type StandardSchemaResult<Output> =\n | { value: Output; issues?: undefined }\n | { value?: undefined; issues: ReadonlyArray<{ message: string }> };\n\n// ---------------------------------------------------------------------------\n// Sync validate helper\n// ---------------------------------------------------------------------------\n\n/**\n * Run a Standard Schema's `~standard.validate()` synchronously.\n *\n * Zod v4's signature includes `Promise` in the return union to satisfy the\n * Standard Schema spec, but in practice Zod always validates synchronously\n * for the schema types we use. We assert the result is sync and throw if\n * it isn't — codec parsing must be synchronous.\n */\nexport function validateSync<Output>(\n schema: StandardSchemaV1<Output>,\n value: unknown\n): StandardSchemaResult<Output> {\n const result = schema['~standard'].validate(value);\n if (result instanceof Promise) {\n throw new Error(\n '[timber] fromSchema: schema returned a Promise — only sync schemas are supported.'\n );\n }\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Type guards\n// ---------------------------------------------------------------------------\n\n/** Check if a value is a Standard Schema object. */\nexport function isStandardSchema(value: unknown): value is StandardSchemaV1 {\n return (\n typeof value === 'object' &&\n value !== null &&\n '~standard' in value &&\n typeof (value as StandardSchemaV1)['~standard']?.validate === 'function'\n );\n}\n\n/** Check if a value is a Codec (has parse + serialize methods). */\nexport function isCodec(value: unknown): value is Codec<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Codec<unknown>).parse === 'function' &&\n typeof (value as Codec<unknown>).serialize === 'function'\n );\n}\n\n// ---------------------------------------------------------------------------\n// fromParamSchema — bridge from Standard Schema to Codec<T> for route params\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema to a Codec for route params.\n * Parse throws on failure (invalid param → 404). Serialize returns string.\n */\nexport function fromParamSchema<T>(fieldName: string, schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse(value: string | string[] | undefined): T {\n const result = validateSync(schema, value);\n if (!result.issues) {\n return result.value;\n }\n const messages = result.issues.map((i) => i.message).join(', ');\n throw new Error(`[timber] Param '${fieldName}' coercion failed: ${messages}`);\n },\n serialize(value: T): string | null {\n if (value === null || value === undefined) return null;\n if (Array.isArray(value)) return value.join('/');\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// resolveCodecOrSchema — generic resolver for any codec-or-schema field\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a field value to a Codec. Accepts Codec<T>, StandardSchemaV1<T>,\n * or (for route params) auto-wraps via fromParamSchema.\n *\n * @param fieldName - used in error messages\n * @param value - the codec or schema to resolve\n * @param mode - 'param' uses fromParamSchema (throws on parse failure),\n * 'search' uses fromSchema (falls back to default on failure,\n * tolerant of the repeated-key array shape),\n * 'cookie' uses fromCookieSchema (same, minus the array shape,\n * which a cookie value cannot have)\n */\nexport function resolveCodecOrSchema(\n fieldName: string,\n value: unknown,\n mode: 'param' | 'search' | 'cookie' = 'search'\n): Codec<unknown> {\n if (isCodec(value)) return value;\n if (isStandardSchema(value)) {\n if (mode === 'param') return fromParamSchema(fieldName, value);\n if (mode === 'cookie') return fromCookieSchema(value) as Codec<unknown>;\n return fromSchema(value) as Codec<unknown>;\n }\n throw new Error(\n `[timber] Field '${fieldName}' is not a valid codec or Standard Schema. ` +\n `Expected an object with { parse, serialize } methods, or a Standard Schema object ` +\n `(Zod, Valibot, ArkType).`\n );\n}\n\n// ---------------------------------------------------------------------------\n// fromSchema — bridge from Standard Schema to Codec<T>\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Shape tolerance — the shared parse loop for both bridges\n//\n// A URL value is `string | string[] | undefined`, but a schema is written\n// against ONE of those: `z.string()` wants `'a'`, `z.array(z.string())`\n// wants `['a']`. Nothing in Standard Schema says which — `~standard.types`\n// exists at the type level only, and probing at runtime is not reliable\n// (design/23-search-params.md §\"Shape tolerance\"). So a bridge tries BOTH\n// shapes rather than committing to one and discarding the value when it\n// guessed wrong.\n//\n// Each bridge only chooses WHICH candidates, and in what order. The first\n// candidate is always the shape that bridge already passed, so nothing that\n// parses today changes meaning; a later one is reached only where the old\n// code fell through to the default. `fromCookieSchema` offers ONE candidate,\n// because a cookie has no array shape at all.\n// ---------------------------------------------------------------------------\n\n/**\n * The scalar shape, and only it. A value that cannot be repeated — a cookie —\n * has no array shape to tolerate, so its bridge stays exactly where it was.\n */\nfunction scalarOnly(value: string | string[] | undefined): unknown[] {\n return [Array.isArray(value) ? value[0] : value];\n}\n\n/** Candidate inputs for the scalar bridge: scalar first, array second. */\nfunction scalarFirst(value: string | string[] | undefined): unknown[] {\n if (value === undefined) return [undefined];\n if (typeof value === 'string') return [value, [value]];\n // Repeated keys: `value[0]` matches URLSearchParams.get().\n //\n // A raw `[]` carries no value at all. `value[0]` is `undefined`, which is\n // the shape the scalar bridge has always passed for it, so `undefined`\n // stays FIRST — an empty array must keep meaning \"absent\" and land on the\n // schema's default. Only `defineSearchParams().parse({ tags: [] })`, the\n // record form, can produce one: URLSearchParams never yields an empty list.\n return value.length > 0 ? [value[0], value] : [undefined, value];\n}\n\n/** Candidate inputs for the array bridge: array first, scalar second. */\nfunction arrayFirst(value: string | string[] | undefined): unknown[] {\n if (value === undefined) return [undefined];\n if (typeof value === 'string') return [[value], value];\n // `[]` first here for the same reason, inverted: the array bridge has\n // always passed the empty array straight through.\n return value.length > 0 ? [value, value[0]] : [value, undefined];\n}\n\n/**\n * Validate `value` against `schema` in each candidate shape, then fall back\n * to the schema's default. Shared by every bridge — they differ only in\n * which candidates they offer, and in what order.\n */\nfunction parseThroughSchema<T>(\n schema: StandardSchemaV1<T>,\n candidates: (value: string | string[] | undefined) => unknown[],\n value: string | string[] | undefined\n): T {\n const inputs = candidates(value);\n for (let i = 0; i < inputs.length; i++) {\n // A throw from the FIRST candidate propagates, unchanged: that is the\n // shape the schema was written against, and a throw from it is the\n // deliberate signal design/23 protects — an app schema may `redirect()`\n // or `notFound()` on a value it refuses, and `validateSync` throws on\n // an async schema.\n //\n // A throw from a LATER candidate is ours, not the app's. We invented\n // that shape; the schema never agreed to receive it. A scalar-only\n // hand-written validator doing `value.toUpperCase()`, or a schema that\n // is async for the array shape only, would turn a field that used to\n // fall back to its default into a render-phase 500. Treat it as \"this\n // shape does not fit\" and keep going.\n let result: StandardSchemaResult<T>;\n try {\n result = validateSync(schema, inputs[i]);\n } catch (error) {\n if (i === 0) throw error;\n continue;\n }\n if (!result.issues) {\n return result.value;\n }\n }\n\n // No shape validated — try parsing undefined to get the default.\n // Re-validate each time so factory defaults (e.g. .default(() => []))\n // produce fresh values.\n const defaultResult = validateSync(schema, undefined);\n if (!defaultResult.issues) {\n return defaultResult.value;\n }\n\n // No default available — the field is implicitly optional. Return\n // undefined; defineSearchParams widens the field's inferred type to\n // T | undefined via InferField so this doesn't lie.\n // design/23-search-params.md §\"Implicit Optionality\"\n return undefined as T;\n}\n\n/**\n * Bridge a Standard Schema-compatible schema (Zod, Valibot, ArkType) to a\n * Codec<T>.\n *\n * Parse: coerces the raw URL value through the schema, trying the scalar\n * shape and then the array shape (see `scalarFirst`), so an array schema\n * works bare: `z.array(z.string()).default([])` yields `[]` when absent,\n * `['a']` for `?tags=a`, and `['a','b']` for `?tags=a&tags=b`. When no\n * shape validates, parses `undefined` to get the schema's default (the\n * schema should have a `.default()` call). If that also fails, returns\n * `undefined`.\n *\n * Serialize: `String()` for primitives, `null` for null/undefined. Note\n * that `String(['a','b'])` is `'a,b'` — the same string `fromArraySchema`\n * writes — so a bare array schema round-trips exactly as design/09\n * §\"Array params\" describes.\n *\n * This is the SEARCH-PARAM bridge. Cookies use `fromCookieSchema`; a\n * cookie has no array shape (see below).\n *\n * ```ts\n * import { z } from 'zod/v4'\n *\n * const pageCodec = fromSchema(z.coerce.number().int().min(1).default(1))\n * const tagsCodec = fromSchema(z.array(z.string()).default([]))\n * ```\n */\nexport function fromSchema<T>(schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, scalarFirst, value),\n serialize(value: T): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// fromCookieSchema — bridge for cookie values\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema for a COOKIE value.\n *\n * Identical to `fromSchema` minus the array shape, because a cookie cannot\n * carry one: `Cookie:` headers and `document.cookie` yield a single string\n * per name, and there is no repeated-key concept to be tolerant of. Sharing\n * the search-param bridge here meant a cookie written by this very codec —\n * `serialize(['a','b'])` → `a,b` — read back as the one-element array\n * `['a,b']` instead of failing to its default: no repeated key in sight,\n * just a delimiter reinterpreted as data.\n *\n * The `serialize` contract also differs by domain and must not be unified:\n * for a search param `null` means \"omit the key\", for a cookie it means\n * **delete the cookie** (design/29-cookies.md).\n */\nexport function fromCookieSchema<T>(schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, scalarOnly, value),\n serialize(value: T): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// fromArraySchema — bridge for array-valued codecs\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema for array values. Handles both single strings\n * and repeated query keys (`?tag=a&tag=b`).\n *\n * ```ts\n * import { fromArraySchema } from '@timber-js/app/codec'\n * import { z } from 'zod/v4'\n *\n * const tagsCodec = fromArraySchema(z.array(z.string()).default([]))\n * ```\n *\n * Since TIM-1352 a bare array schema works through `fromSchema` too, so\n * this is no longer required to make an array field parse. Two cases still\n * want it, both listed in design/23 §\"Shape tolerance\":\n *\n * 1. A **permissive** schema meant as an array — one that accepts a string\n * as readily as an array (`z.any()`, a hand-written coercing validator)\n * — where scalar-first ordering would settle on the scalar shape.\n * 2. An array schema wrapped in `.catch([])`, which swallows the failure\n * that would otherwise trigger the array attempt.\n *\n * It also serializes an empty array to `null` (omitting the key) where\n * `fromSchema` writes `''`.\n */\nexport function fromArraySchema<T>(schema: StandardSchemaV1<T>): {\n parse(value: string | string[] | undefined): T;\n serialize(value: T): string | string[] | null;\n} {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, arrayFirst, value),\n serialize(value: T): string | string[] | null {\n if (value === null || value === undefined) {\n return null;\n }\n // TIM-1353: return string[] so buildSearchParams emits repeated keys\n // (?tag=a&tag=b) instead of comma-joining into one key (?tag=a%2Cb).\n if (Array.isArray(value)) {\n return value.length === 0 ? null : value.map(String);\n }\n return String(value);\n },\n };\n}\n"],"mappings":";;;;;;;;;AA2DA,SAAgB,aACd,QACA,OAC8B;CAC9B,MAAM,SAAS,OAAO,YAAY,CAAC,SAAS,KAAK;CACjD,IAAI,kBAAkB,SACpB,MAAM,IAAI,MACR,mFACF;CAEF,OAAO;AACT;;AAOA,SAAgB,iBAAiB,OAA2C;CAC1E,OACE,OAAO,UAAU,YACjB,UAAU,QACV,eAAe,SACf,OAAQ,MAA2B,YAAY,EAAE,aAAa;AAElE;;AAGA,SAAgB,QAAQ,OAAyC;CAC/D,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAyB,UAAU,cAC3C,OAAQ,MAAyB,cAAc;AAEnD;;;;;AAUA,SAAgB,gBAAmB,WAAmB,QAAuC;CAC3F,OAAO;EACL,MAAM,OAAyC;GAC7C,MAAM,SAAS,aAAa,QAAQ,KAAK;GACzC,IAAI,CAAC,OAAO,QACV,OAAO,OAAO;GAEhB,MAAM,WAAW,OAAO,OAAO,KAAK,MAAM,EAAE,OAAO,CAAC,CAAC,KAAK,IAAI;GAC9D,MAAM,IAAI,MAAM,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AAI;GACF,SAAS,aAAa,QAAQ,OAAO,EAAE;EACzC,SAAS,OAAO;GACd,IAAI,MAAM,GAAG,MAAM;GACnB;EACF;EACA,IAAI,CAAC,OAAO,QACV,OAAO,OAAO;CAElB;CAKA,MAAM,gBAAgB,aAAa,QAAQ,KAAA,CAAS;CACpD,IAAI,CAAC,cAAc,QACjB,OAAO,cAAc;AAQzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,WAAc,QAAuC;CACnE,OAAO;EACL,QAAQ,UACN,mBAAmB,QAAQ,aAAa,KAAK;EAC/C,UAAU,OAAyB;GACjC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,OAAO;GAET,OAAO,OAAO,KAAK;EACrB;CACF;AACF;;;;;;;;;;;;;;;;AAqBA,SAAgB,iBAAoB,QAAuC;CACzE,OAAO;EACL,QAAQ,UACN,mBAAmB,QAAQ,YAAY,KAAK;EAC9C,UAAU,OAAyB;GACjC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,OAAO;GAET,OAAO,OAAO,KAAK;EACrB;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,gBAAmB,QAGjC;CACA,OAAO;EACL,QAAQ,UACN,mBAAmB,QAAQ,YAAY,KAAK;EAC9C,UAAU,OAAoC;GAC5C,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,OAAO;GAIT,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,WAAW,IAAI,OAAO,MAAM,IAAI,MAAM;GAErD,OAAO,OAAO,KAAK;EACrB;CACF;AACF"}
@@ -16,6 +16,20 @@ function parseTotal(codec, raw) {
16
16
  return hasParseServerSide(codec) ? codec.parseServerSide(raw) : codec.parse(raw);
17
17
  }
18
18
  //#endregion
19
+ //#region src/search-params/serialize-equal.ts
20
+ /**
21
+ * Compare two serialize results for equality. Needed because `string[]`
22
+ * from repeated-key codecs does not compare by reference.
23
+ *
24
+ * Shared between define.ts (buildSearchParams default-omission) and
25
+ * use-query-states.ts (bridgeCodec eq). One source of truth.
26
+ */
27
+ function serializedEqual(a, b) {
28
+ if (a === b) return true;
29
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((v, i) => v === b[i]);
30
+ return false;
31
+ }
32
+ //#endregion
19
33
  //#region src/client/use-query-states.ts
20
34
  /**
21
35
  * useQueryStates — client-side hook for URL-synced search params.
@@ -74,12 +88,21 @@ function bridgeCodec(codec) {
74
88
  parse: (v) => wrapNuqsValue(parseTotal(codec, v.length === 1 ? v[0] : [...v])),
75
89
  serialize: (v) => {
76
90
  const value = unwrapNuqsValue(v);
77
- return [value === void 0 ? "" : codec.serialize(value) ?? ""];
91
+ if (value === void 0) return [""];
92
+ let result;
93
+ try {
94
+ result = codec.serialize(value);
95
+ } catch (error) {
96
+ if (error instanceof TypeError) return [""];
97
+ throw error;
98
+ }
99
+ if (Array.isArray(result)) return result;
100
+ return [result ?? ""];
78
101
  },
79
102
  eq: (a, b) => {
80
103
  if (a === b) return true;
81
104
  try {
82
- return codec.serialize(unwrapNuqsValue(a)) === codec.serialize(unwrapNuqsValue(b));
105
+ return serializedEqual(codec.serialize(unwrapNuqsValue(a)), codec.serialize(unwrapNuqsValue(b)));
83
106
  } catch {
84
107
  return false;
85
108
  }
@@ -175,7 +198,8 @@ function useQueryStates$1(codecs, _options, urlKeys) {
175
198
  } else if (value === null) {
176
199
  let encoded = null;
177
200
  try {
178
- encoded = codecs[key]?.serialize(null) ?? null;
201
+ const raw = codecs[key]?.serialize(null);
202
+ encoded = raw === null ? null : Array.isArray(raw) ? raw.length > 0 ? raw : null : raw;
179
203
  } catch {}
180
204
  if (encoded !== null) {
181
205
  if (forwarded === partial) forwarded = { ...partial };
@@ -197,6 +221,6 @@ function bindUseQueryStates(definition) {
197
221
  };
198
222
  }
199
223
  //#endregion
200
- export { useQueryStates$1 as n, parseTotal as r, bindUseQueryStates as t };
224
+ export { parseTotal as i, useQueryStates$1 as n, serializedEqual as r, bindUseQueryStates as t };
201
225
 
202
- //# sourceMappingURL=use-query-states-BbU5Ge1V.js.map
226
+ //# sourceMappingURL=use-query-states-I3JMng6J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-query-states-I3JMng6J.js","names":[],"sources":["../../src/search-params/parse-total.ts","../../src/search-params/serialize-equal.ts","../../src/client/use-query-states.ts"],"sourcesContent":["/**\n * parseTotal — invoke a codec over the FULL raw domain.\n *\n * `SearchParamCodec.parse` is documented to be total over\n * `string | string[] | undefined`, because that is exactly what a URL\n * hands it: a param can be absent (`undefined`) or repeated (`string[]`).\n * Timber's own codecs and the Standard Schema bridges honour that.\n *\n * nuqs parsers do not. Their `parse` expects a **present scalar string** —\n * nuqs checks presence itself before ever calling it — so `parseAsBoolean`\n * and `parseAsIsoDate` threw a render-phase 500 on an absent param and\n * `parseAsString` returned an array on a repeated one (TIM-1350).\n *\n * nuqs ships the missing adapter: every parser builder exposes\n * `parseServerSide(value: string | string[] | undefined)`, which maps\n * absent → `null` (or the parser's `withDefault` value), takes the FIRST\n * entry of a repeated param (matching `URLSearchParams.get()`), and wraps\n * the inner `parse` so a throw becomes `null`. That is precisely timber's\n * domain, so we call it in preference to `parse` rather than hand-rolling\n * a second normalization that could disagree with the client hook.\n *\n * Feature detection, not an instanceof check: any codec MAY publish\n * `parseServerSide` to declare \"this is my total entry point\" — it is an\n * optional member of `SearchParamCodec` — and a codec that does not is\n * assumed already total and called through `parse`. Timber codecs and\n * schema bridges take the second branch untouched; several of them rely on\n * `parse(undefined)` to produce their default.\n *\n * **Search params only.** Segment params (`server/param-coercion.ts`) call\n * `codec.parse` directly and must keep doing so: their domain is a value\n * the router matched, never absent, and a codec that REJECTS one is how a\n * route produces a 404. Routing a rejection through nuqs's `safeParse`\n * would turn that 404 into a silent `null` param. The two domains differ\n * in what \"no value\" means, not just in plumbing. Cookies are a third\n * domain (`cookies/define-cookie.ts`) and are likewise untouched.\n *\n * `parseServerSide` carries a `@deprecated` tag in nuqs (it steers users to\n * loaders, which timber does not use). It remains public, typed and\n * exercised; `tests/nuqs-codec-boundary.test.ts` asserts totality for every\n * parser through timber's own API, so a nuqs release that drops it fails\n * loudly rather than silently reinstating the 500s.\n *\n * Design doc: design/23-search-params.md §\"nuqs parsers, made total\"\n */\n\n/**\n * Minimal interface for anything `parseTotal` can dispatch. Only `parse` is\n * required; `parseServerSide` is the optional total entry point. `serialize`\n * is deliberately absent — `parseTotal` never calls it, and requiring it\n * would prevent `SearchParamCodec<T>` (whose serialize returns `string |\n * string[] | null`) from being passed where `Codec<T>` (whose serialize\n * returns `string | null`) is expected.\n */\nexport interface ParseableCodec<T> {\n parse(value: string | string[] | undefined): T;\n parseServerSide?(value: string | string[] | undefined): T;\n}\n\n/**\n * A codec that publishes a total entry point over the raw URL domain.\n *\n * The return is `T`, not `T | null`. This is the entry point timber calls,\n * so whatever it answers IS the field's type. A `null` for an absent param\n * belongs in `T` — a bare nuqs parser is a codec of `string | null`, and\n * `parseAsInteger.withDefault(1)` is a codec of `number`, because nuqs\n * narrows its own `parseServerSide` return to `NonNullable<T>`. Declaring\n * `T | null` here would let a codec annotated `SearchParamCodec<string>`\n * hand back `null` under a non-nullable type (TIM-1350 review).\n */\nexport interface TotalCodec<T> {\n parseServerSide(value: string | string[] | undefined): T;\n}\n\nfunction hasParseServerSide<T>(\n codec: ParseableCodec<T>\n): codec is ParseableCodec<T> & TotalCodec<T> {\n return typeof (codec as Partial<TotalCodec<T>>).parseServerSide === 'function';\n}\n\n/**\n * Parse a raw URL value through a codec, using the codec's total entry\n * point when it publishes one.\n *\n * Returns `T`, from both branches. A `null` for an absent param is part of\n * the codec's own `T` — see TotalCodec above — so this signature does not\n * widen it, and a caller that must handle \"no value\" (`withDefault`) sees\n * it because `T` carries it.\n */\nexport function parseTotal<T>(codec: ParseableCodec<T>, raw: string | string[] | undefined): T {\n return hasParseServerSide(codec) ? codec.parseServerSide(raw) : codec.parse(raw);\n}\n","/**\n * Compare two serialize results for equality. Needed because `string[]`\n * from repeated-key codecs does not compare by reference.\n *\n * Shared between define.ts (buildSearchParams default-omission) and\n * use-query-states.ts (bridgeCodec eq). One source of truth.\n */\nexport function serializedEqual(a: string | string[] | null, b: string | string[] | null): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n }\n return false;\n}\n","/**\n * useQueryStates — client-side hook for URL-synced search params.\n *\n * Delegates to nuqs for URL synchronization, batching, React 19 transitions,\n * and throttled URL writes. Bridges timber's SearchParamCodec protocol to\n * nuqs-compatible parsers.\n *\n * Design doc: design/23-search-params.md §\"Codec Bridge\"\n */\n\n'use client';\n\nimport { useQueryStates as nuqsUseQueryStates } from 'nuqs';\nimport type { MultiParser } from 'nuqs';\nimport type {\n SearchParamCodec,\n SearchParamsDefinition,\n SetParams,\n QueryStatesOptions,\n} from '../search-params/define.js';\nimport { parseTotal } from '../search-params/parse-total.js';\nimport { serializedEqual } from '../search-params/serialize-equal.js';\n\n// ─── Codec Bridge ─────────────────────────────────────────────────\n\n// nuqs's parser contract conflates values timber codecs distinguish:\n// parse() returning null means \"unparseable, substitute defaultValue\",\n// and undefined entries are skipped entirely. Timber codecs can\n// legitimately produce both — bare z.string() yields undefined for absent\n// params (implicit optionality), and a codec may map a present value to\n// null. Wrap those two values in sentinels across the nuqs boundary and\n// unwrap them before handing values back to the caller, so the client\n// hook returns exactly what server-side parse() returns.\n// Unique object references compared by identity — a codec can never\n// produce these from URL input, so user-controlled strings cannot collide\n// with them (unlike string sentinels), and unlike Symbols they survive\n// nuqs's internal string coercion without throwing.\nconst NULL_SENTINEL: object = { timberSentinel: 'null' };\nconst UNDEFINED_SENTINEL: object = { timberSentinel: 'undefined' };\n\nfunction wrapNuqsValue(value: unknown): unknown {\n if (value === null) return NULL_SENTINEL;\n if (value === undefined) return UNDEFINED_SENTINEL;\n return value;\n}\n\nfunction unwrapNuqsValue(value: unknown): unknown {\n if (value === NULL_SENTINEL) return null;\n if (value === UNDEFINED_SENTINEL) return undefined;\n return value;\n}\n\n/**\n * Bridge a timber SearchParamCodec to a nuqs-compatible MultiParser.\n *\n * nuqs parsers: { parse(string) → T|null, serialize?(T) → string, eq?, defaultValue? }\n * timber codecs: { parse(string|string[]|undefined) → T, serialize(T) → string|null }\n *\n * The defaultValue is computed eagerly, through `parseTotal` — the same\n * entry point server-side `parse()` uses, so the hook and the server agree\n * on what an absent param means (a bare nuqs parser answers `null`, not\n * `undefined`; TIM-1350). Codecs are documented to return a default rather\n * than throw, but a throwing codec must not crash every component that\n * mounts the hook — treat its default as undefined and let its error\n * surface from server-side parse() instead.\n *\n * A `null` absent-value is NOT registered as the nuqs default. nuqs\n * already represents an absent key as `null`, so the hook reads the same\n * value either way — but registering it makes `clearOnDefault` fire on\n * `setParams({ q: null })` and delete the key before the bridged\n * `serialize` runs. For a codec that encodes `null` as a real query value\n * (`serialize(null) === 'none'`), that silently disagrees with\n * `buildSearchParams({ q: null })`, which writes it. Same reasoning as\n * `getDefaultSerialized` on the server: a codec with no value for an\n * absent param has no default to register.\n */\nfunction bridgeCodec<T>(codec: SearchParamCodec<T>): MultiParser<T> & { defaultValue: T } {\n let absent: unknown;\n try {\n absent = parseTotal(codec, undefined);\n } catch {\n absent = undefined;\n }\n\n const parser = {\n // `multi`, so nuqs reads the key with `searchParams.getAll()` and hands\n // us EVERY value. A single parser reads `.get()` — the first value only\n // — which is not the domain a timber codec is defined over. The server\n // parses `?tags=a&tags=b` as `['a','b']`; a single parser made the hook\n // answer `['a']` for the same URL, under a declared `string[]` that\n // admitted no such disagreement (TIM-1352). Scalar codecs are unaffected:\n // they receive the array and take `value[0]`, exactly as they do on the\n // server, so first-value-wins is preserved through the same code path\n // rather than through nuqs's reader.\n //\n // nuqs never calls this with an empty array — `isAbsentFromUrl` treats\n // `[]` as absent and answers `defaultValue` directly — which is what\n // keeps the absent case agreeing with the server's `undefined`.\n //\n // Reading every value is only half of it: the values must arrive in the\n // SAME SHAPE the server would have produced, or the divergence just\n // moves. `normalizeRaw` (search-params/define.ts) collapses a\n // single-valued key to a bare string and keeps an array only for a\n // repeated one, so this mirrors that rule exactly. Handing a codec\n // `['3']` where the server hands it `'3'` breaks every codec whose\n // `parse` is written for the scalar case — which is most hand-written\n // ones, contract or no contract.\n type: 'multi' as const,\n // Through parseTotal, not codec.parse. nuqs's own `.withDefault(d)`\n // overrides ONLY `parseServerSide`, so `parseAsInteger.withDefault(1)`\n // on `?page=abc` returned 1 from the server and null from the hook —\n // a divergence the declared non-nullable `number` did not admit.\n parse: (v: readonly string[]) =>\n wrapNuqsValue(parseTotal(codec, v.length === 1 ? v[0] : [...v])),\n serialize: (v: unknown) => {\n const value = unwrapNuqsValue(v);\n if (value === undefined) return [''];\n // TIM-1354: catch TypeError from codecs whose serialize is not total\n // over null (e.g. parseAsIsoDate.serialize(null) → null.toISOString()).\n // Only TypeError — deliberate signals must not be swallowed.\n let result: string | string[] | null;\n try {\n result = codec.serialize(value as T);\n } catch (error) {\n if (error instanceof TypeError) return [''];\n throw error;\n }\n // TIM-1353: pass through string[] from codecs that emit repeated\n // keys. nuqs multi parsers append one key=value per array element.\n if (Array.isArray(result)) return result;\n return [result ?? ''];\n },\n eq: (a: unknown, b: unknown) => {\n if (a === b) return true;\n try {\n return serializedEqual(\n codec.serialize(unwrapNuqsValue(a) as T),\n codec.serialize(unwrapNuqsValue(b) as T)\n );\n } catch {\n return false;\n }\n },\n } as MultiParser<T> & { defaultValue: T };\n\n if (absent !== null) parser.defaultValue = wrapNuqsValue(absent) as T;\n return parser;\n}\n\n/**\n * Collect `withUrlKey` aliases off a codec map.\n *\n * `withUrlKey(codec, 'q')` returns a codec carrying `urlKey: 'q'`, so the map\n * alone is enough to reconstruct the aliases — `defineSearchParams` builds its\n * own `urlKeys` from exactly this property.\n */\nfunction deriveUrlKeys(codecs: Record<string, SearchParamCodec<unknown>>): Record<string, string> {\n const result: Record<string, string> = {};\n for (const key of Object.keys(codecs)) {\n const alias = codecs[key]?.urlKey;\n if (alias) result[key] = alias;\n }\n return result;\n}\n\n/**\n * Bridge an entire codec map to nuqs-compatible parsers.\n */\nfunction bridgeCodecs<T extends Record<string, unknown>>(codecs: {\n [K in keyof T]: SearchParamCodec<T[K]>;\n}) {\n const result: Record<string, MultiParser<unknown> & { defaultValue: unknown }> = {};\n for (const key of Object.keys(codecs)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n result[key] = bridgeCodec(codecs[key as keyof T]) as any;\n }\n return result as { [K in keyof T]: MultiParser<T[K]> & { defaultValue: T[K] } };\n}\n\n// ─── Hook ─────────────────────────────────────────────────────────\n\n/**\n * Read and write typed search params from/to the URL.\n *\n * Delegates to nuqs internally. The timber nuqs adapter (auto-injected in\n * browser-entry.ts) handles RSC navigation on non-shallow updates.\n *\n * Usage:\n * ```ts\n * // Via a SearchParamsDefinition imported from the route's params.ts\n * const [params, setParams] = definition.useQueryStates()\n *\n * // Standalone with inline codecs\n * const [params, setParams] = useQueryStates({\n * page: fromSchema(z.coerce.number().int().min(1).default(1)),\n * })\n * ```\n *\n * There is deliberately no route-string form (`useQueryStates('/products')`).\n * Importing the definition from `params.ts` is the documented way to reach\n * another route's codecs — it needs no runtime registry lookup and so has no\n * \"not registered yet\" failure mode. See design/23-search-params.md\n * §\"Client Access\".\n */\nexport function useQueryStates<T extends Record<string, unknown>>(\n codecs: { [K in keyof T]: SearchParamCodec<T[K]> },\n _options?: QueryStatesOptions,\n urlKeys?: Readonly<Record<string, string>>\n): [T, SetParams<T>] {\n const bridged = bridgeCodecs(codecs);\n\n // Forward hook-level options (shallow, scroll, history) to nuqs.\n // These become the default for all setter calls from this hook instance.\n // Per-call options in setParams(values, opts) override these defaults.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const nuqsOptions: any = {};\n if (_options?.shallow !== undefined) nuqsOptions.shallow = _options.shallow;\n if (_options?.scroll !== undefined) nuqsOptions.scroll = _options.scroll;\n if (_options?.history !== undefined) nuqsOptions.history = _options.history;\n // `withUrlKey` attaches the alias to the codec itself — that is the design's\n // \"URL keys travel with codecs\" principle — so the aliases are derivable\n // here and must be, for the inline codec-map form: nobody passes `urlKeys`\n // on that path, and without this an aliased bundle silently read and wrote\n // the property name instead of the alias. `bindUseQueryStates` still passes\n // the definition's precomputed map, which wins on conflict; it is built from\n // these same codecs, so the two agree by construction rather than by luck.\n const resolvedUrlKeys = { ...deriveUrlKeys(codecs), ...urlKeys };\n if (Object.keys(resolvedUrlKeys).length > 0) {\n nuqsOptions.urlKeys = resolvedUrlKeys;\n }\n\n let values: Record<string, unknown>;\n let setValues: Function;\n try {\n [values, setValues] = nuqsUseQueryStates(bridged, nuqsOptions);\n } catch (err) {\n if (\n err instanceof Error &&\n /Invalid hook call|cannot be called|Cannot read properties of null/i.test(err.message)\n ) {\n throw new Error(\n 'useQueryStates is a client component hook and cannot be called outside a React component. ' +\n 'Use definition.parse(searchParams) in server components instead.'\n );\n }\n throw err;\n }\n\n // Unwrap the null/undefined sentinels the bridge injected (see Codec\n // Bridge above) so callers see exactly what server-side parse() returns.\n // Copy-on-write preserves the identity of nuqs's memoized values object\n // when nothing needs unwrapping.\n let normalized = values;\n for (const key of Object.keys(bridged)) {\n const value = normalized[key];\n if (value === NULL_SENTINEL || value === UNDEFINED_SENTINEL) {\n if (normalized === values) normalized = { ...values };\n normalized[key] = unwrapNuqsValue(value);\n }\n }\n\n // Wrap the nuqs setter to match timber's SetParams<T> signature.\n // nuqs's setter accepts Partial<Nullable<Values>> | UpdaterFn | null.\n // timber's setter accepts Partial<T> with optional SetParamsOptions.\n const setParams: SetParams<T> = (partial, setOptions?) => {\n const nuqsSetOptions: Record<string, unknown> = {};\n if (setOptions?.shallow !== undefined) nuqsSetOptions.shallow = setOptions.shallow;\n if (setOptions?.scroll !== undefined) nuqsSetOptions.scroll = setOptions.scroll;\n if (setOptions?.history !== undefined) nuqsSetOptions.history = setOptions.history;\n // nuqs's update loop skips undefined entries and treats null as a\n // key deletion before serialize runs. Timber semantics:\n // - setParams({ q: undefined }) must clear ?q= (absent = undefined),\n // so explicit undefined maps to a null deletion.\n // - setParams({ q: null }) clears the key only when the codec encodes\n // null as \"omit\" (serialize(null) === null). If the codec encodes\n // null as a real query value, forward the sentinel so the bridged\n // serialize writes it — matching definition.serialize({ q: null }).\n let forwarded: Record<string, unknown> = partial;\n for (const key of Object.keys(partial)) {\n const value = partial[key as keyof T];\n if (value === undefined) {\n if (forwarded === partial) forwarded = { ...partial };\n forwarded[key] = null;\n } else if (value === null) {\n let encoded: string | string[] | null = null;\n try {\n const raw = codecs[key as keyof T]?.serialize(null as T[keyof T]);\n // string[] is non-null, but an empty array carries no value\n encoded = raw === null ? null : Array.isArray(raw) ? (raw.length > 0 ? raw : null) : raw;\n } catch {\n // Codec can't serialize null — treat as a deletion.\n }\n if (encoded !== null) {\n if (forwarded === partial) forwarded = { ...partial };\n forwarded[key] = NULL_SENTINEL;\n }\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n void setValues(forwarded as any, nuqsSetOptions);\n };\n\n return [normalized as T, setParams];\n}\n\n// ─── Definition binding ───────────────────────────────────────────\n\n/**\n * Create a useQueryStates binding for a SearchParamsDefinition.\n * This is used internally by SearchParamsDefinition.useQueryStates().\n */\nexport function bindUseQueryStates<T extends Record<string, unknown>>(\n definition: SearchParamsDefinition<T>\n): (options?: QueryStatesOptions) => [T, SetParams<T>] {\n return (options?: QueryStatesOptions) => {\n return useQueryStates<T>(definition.codecs, options, definition.urlKeys);\n };\n}\n"],"mappings":";;AAyEA,SAAS,mBACP,OAC4C;CAC5C,OAAO,OAAQ,MAAiC,oBAAoB;AACtE;;;;;;;;;;AAWA,SAAgB,WAAc,OAA0B,KAAuC;CAC7F,OAAO,mBAAmB,KAAK,IAAI,MAAM,gBAAgB,GAAG,IAAI,MAAM,MAAM,GAAG;AACjF;;;;;;;;;;ACnFA,SAAgB,gBAAgB,GAA6B,GAAsC;CACjG,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,MAAM,QAAQ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AAgB,KAAK;EACzC;CACF;CAKA,MAAM,aAA2B,SAAS,eAAgB;EACxD,MAAM,iBAA0C,CAAC;EACjD,IAAI,YAAY,YAAY,KAAA,GAAW,eAAe,UAAU,WAAW;EAC3E,IAAI,YAAY,WAAW,KAAA,GAAW,eAAe,SAAS,WAAW;EACzE,IAAI,YAAY,YAAY,KAAA,GAAW,eAAe,UAAU,WAAW;EAS3E,IAAI,YAAqC;EACzC,KAAK,MAAM,OAAO,OAAO,KAAK,OAAO,GAAG;GACtC,MAAM,QAAQ,QAAQ;GACtB,IAAI,UAAU,KAAA,GAAW;IACvB,IAAI,cAAc,SAAS,YAAY,EAAE,GAAG,QAAQ;IACpD,UAAU,OAAO;GACnB,OAAO,IAAI,UAAU,MAAM;IACzB,IAAI,UAAoC;IACxC,IAAI;KACF,MAAM,MAAM,OAAO,IAAe,EAAE,UAAU,IAAkB;KAEhE,UAAU,QAAQ,OAAO,OAAO,MAAM,QAAQ,GAAG,IAAK,IAAI,SAAS,IAAI,MAAM,OAAQ;IACvF,QAAQ,CAER;IACA,IAAI,YAAY,MAAM;KACpB,IAAI,cAAc,SAAS,YAAY,EAAE,GAAG,QAAQ;KACpD,UAAU,OAAO;IACnB;GACF;EACF;EAEA,UAAe,WAAkB,cAAc;CACjD;CAEA,OAAO,CAAC,YAAiB,SAAS;AACpC;;;;;AAQA,SAAgB,mBACd,YACqD;CACrD,QAAQ,YAAiC;EACvC,OAAO,iBAAkB,WAAW,QAAQ,SAAS,WAAW,OAAO;CACzE;AACF"}
@@ -6,7 +6,7 @@ import { n as getRouterOrNull } from "../_chunks/router-ref-DuYuV_0Q.js";
6
6
  import { n as useSegmentContext } from "../_chunks/segment-context-CjOlyB8Y.js";
7
7
  import { t as getLinkCodec } from "../_chunks/codec-registry-oOUxugz3.js";
8
8
  import { l as useNavigationContext, r as useSegmentParams, u as usePendingNavigation } from "../_chunks/use-segment-params-C4r4BD9T.js";
9
- import { n as useQueryStates } from "../_chunks/use-query-states-BbU5Ge1V.js";
9
+ import { n as useQueryStates } from "../_chunks/use-query-states-I3JMng6J.js";
10
10
  import { createContext, useActionState as useActionState$1, useContext, useRef, useState, useTransition } from "react";
11
11
  import { jsx } from "react/jsx-runtime";
12
12
  //#region src/client/use-link-status.ts
@@ -8,7 +8,7 @@ import { i as markStaleFromError, n as isClientStale, r as markClientStale, t as
8
8
  import { n as useSegmentContext, t as SegmentProvider } from "../_chunks/segment-context-CjOlyB8Y.js";
9
9
  import "../_chunks/rsc-error-envelope-tT5PJs4q.js";
10
10
  import { a as supersedeNavigationTransitions, c as setNavigationState, i as setHardNavigating, l as useNavigationContext, n as setCurrentSlotParams, o as NavigationProvider, s as getNavigationState, t as setCurrentParams } from "../_chunks/use-segment-params-C4r4BD9T.js";
11
- import { t as bindUseQueryStates } from "../_chunks/use-query-states-BbU5Ge1V.js";
11
+ import { t as bindUseQueryStates } from "../_chunks/use-query-states-I3JMng6J.js";
12
12
  //#region src/shared/payload-root.ts
13
13
  /**
14
14
  * What a reader gets when the value it was handed is not a payload root.
@@ -1 +1 @@
1
- {"version":3,"file":"use-query-states.d.ts","sourceRoot":"","sources":["../../src/client/use-query-states.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAMH,OAAO,KAAK,EACV,gBAAgB,EAChB,sBAAsB,EACtB,SAAS,EACT,kBAAkB,EACnB,MAAM,4BAA4B,CAAC;AA2JpC;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9D,MAAM,EAAE;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,EAClD,QAAQ,CAAC,EAAE,kBAAkB,EAC7B,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GACzC,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CA6FnB;AAID;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClE,UAAU,EAAE,sBAAsB,CAAC,CAAC,CAAC,GACpC,CAAC,OAAO,CAAC,EAAE,kBAAkB,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAIrD"}
1
+ {"version":3,"file":"use-query-states.d.ts","sourceRoot":"","sources":["../../src/client/use-query-states.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAMH,OAAO,KAAK,EACV,gBAAgB,EAChB,sBAAsB,EACtB,SAAS,EACT,kBAAkB,EACnB,MAAM,4BAA4B,CAAC;AAkKpC;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9D,MAAM,EAAE;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,EAClD,QAAQ,CAAC,EAAE,kBAAkB,EAC7B,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GACzC,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CA+FnB;AAID;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClE,UAAU,EAAE,sBAAsB,CAAC,CAAC,CAAC,GACpC,CAAC,OAAO,CAAC,EAAE,kBAAkB,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAIrD"}
package/dist/codec.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as fromArraySchema } from "./_chunks/schema-bridge-Cc2Gngu1.js";
1
+ import { t as fromArraySchema } from "./_chunks/schema-bridge-C83xa9lT.js";
2
2
  //#region src/codec.ts
3
3
  var codec = {
4
4
  string: {
@@ -1,6 +1,6 @@
1
1
  import { n as assertValidCookieName, t as require_dist } from "../_chunks/dist-BA3u1z3W.js";
2
2
  import { n as getSsrData } from "../_chunks/ssr-data-14MXm7Pj.js";
3
- import { a as resolveCodecOrSchema } from "../_chunks/schema-bridge-Cc2Gngu1.js";
3
+ import { a as resolveCodecOrSchema } from "../_chunks/schema-bridge-C83xa9lT.js";
4
4
  import * as React$1 from "react";
5
5
  import { getCookieJar } from "@timber-js/app/server";
6
6
  //#region src/client/use-cookie.ts
@@ -1,4 +1,4 @@
1
- import { n as toBracketKey, t as resolveSchemaCodecs } from "../_chunks/resolve-schema-5ma5pp1b.js";
1
+ import { n as toBracketKey, t as resolveSchemaCodecs } from "../_chunks/resolve-schema-CBR6Lm4i.js";
2
2
  import { n as setLinkCodecs, t as getLinkCodec } from "../_chunks/codec-registry-oOUxugz3.js";
3
3
  //#region src/params/define-schema.ts
4
4
  /**
@@ -138,5 +138,8 @@ export declare function fromCookieSchema<T>(schema: StandardSchemaV1<T>): Codec<
138
138
  * It also serializes an empty array to `null` (omitting the key) where
139
139
  * `fromSchema` writes `''`.
140
140
  */
141
- export declare function fromArraySchema<T>(schema: StandardSchemaV1<T>): Codec<T>;
141
+ export declare function fromArraySchema<T>(schema: StandardSchemaV1<T>): {
142
+ parse(value: string | string[] | undefined): T;
143
+ serialize(value: T): string | string[] | null;
144
+ };
142
145
  //# sourceMappingURL=schema-bridge.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema-bridge.d.ts","sourceRoot":"","sources":["../src/schema-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAUxC,4DAA4D;AAC5D,MAAM,WAAW,gBAAgB,CAAC,MAAM,GAAG,OAAO;IAChD,WAAW,EAAE;QACX,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG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AG,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,CAO/D;AAMD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAgB3F;AAMD;;;;;;;;;;;GAWG;AACH,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,OAAO,EACd,IAAI,GAAE,OAAO,GAAG,QAAQ,GAAG,QAAmB,GAC7C,KAAK,CAAC,OAAO,CAAC,CAYhB;AA0GD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAWnE;AAMD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAWzE;AAMD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG;IAC/D,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,GAAG,CAAC,CAAC;IAC/C,SAAS,CAAC,KAAK,EAAE,CAAC,GAAG,MAAM,GAAG,MAAM,EAAE,GAAG,IAAI,CAAC;CAC/C,CAgBA"}
@@ -30,7 +30,19 @@ import type { Codec } from '../codec.js';
30
30
  * by defineSearchParams and wrapped via fromSchema; those ARE total
31
31
  * through `parse` and are called that way.
32
32
  */
33
- export interface SearchParamCodec<T> extends Codec<T> {
33
+ export interface SearchParamCodec<T> extends Omit<Codec<T>, 'serialize'> {
34
+ /**
35
+ * Typed value → URL string(s). Return `null` to omit/clear.
36
+ *
37
+ * A codec MAY return `string[]` to emit repeated keys (`?tag=a&tag=b`).
38
+ * `buildSearchParams` appends one `key=value` entry per array element;
39
+ * the nuqs bridge forwards the array to nuqs, which does the same.
40
+ * Codecs that always produce a single value return a plain string.
41
+ *
42
+ * Wider than `Codec<T>.serialize` (`string | null`) because search params
43
+ * have a repeated-key concept that cookies and segment params do not.
44
+ */
45
+ serialize(value: T): string | string[] | null;
34
46
  /** Optional URL key alias, set by withUrlKey(). */
35
47
  urlKey?: string;
36
48
  /**
@@ -111,7 +123,7 @@ export interface SearchParamsDefinition<T extends Record<string, unknown>> {
111
123
  /** Client hook — reads current URL params and returns typed values + setter. */
112
124
  useQueryStates(options?: QueryStatesOptions): [T, SetParams<T>];
113
125
  /** Extend with additional codecs or Standard Schema objects. */
114
- extend<U extends Record<string, SearchParamCodec<unknown> | StandardSchemaV1<unknown>>>(codecs: U): SearchParamsDefinition<T & {
126
+ extend<U extends Record<string, SearchParamField>>(codecs: U): SearchParamsDefinition<T & {
115
127
  [K in keyof U]: InferField<U[K]>;
116
128
  }>;
117
129
  /** Pick a subset of keys. Preserves codecs and aliases. */
@@ -190,8 +202,22 @@ type InferSchemaInput<V> = V extends {
190
202
  export type InferField<V> = V extends {
191
203
  parseServerSide(value: string | string[] | undefined): infer R;
192
204
  } ? R : V extends SearchParamCodec<infer T> ? T : V extends StandardSchemaV1<infer T> ? undefined extends InferSchemaInput<V> ? T : T | undefined : never;
193
- /** Acceptable field value for defineSearchParams: a codec or a Standard Schema. */
194
- export type SearchParamField<T = unknown> = SearchParamCodec<T> | StandardSchemaV1<T>;
205
+ /**
206
+ * A codec whose total entry point is `parseServerSide`, even when `parse`
207
+ * has a narrower signature. nuqs multi parsers (`parseAsNativeArrayOf`) have
208
+ * `parse(value: readonly string[])` — too narrow for `SearchParamCodec`'s
209
+ * `parse(string | string[] | undefined)` — but their `parseServerSide`
210
+ * covers the full domain. Timber never calls `parse` directly on these;
211
+ * `parseTotal` always reaches `parseServerSide` first (TIM-1355).
212
+ */
213
+ export interface TotalSearchParamCodec<T> {
214
+ parseServerSide(value: string | string[] | undefined): T;
215
+ parse(...args: any[]): any;
216
+ serialize(value: T): string | string[] | null;
217
+ urlKey?: string;
218
+ }
219
+ /** Acceptable field value for defineSearchParams: a codec, a total codec, or a Standard Schema. */
220
+ export type SearchParamField<T = unknown> = SearchParamCodec<T> | TotalSearchParamCodec<T> | StandardSchemaV1<T>;
195
221
  /**
196
222
  * Create a SearchParamsDefinition from a map of codecs and/or Standard Schema
197
223
  * objects. Accepts both SearchParamCodec values and raw Zod/Valibot/ArkType
@@ -1 +1 @@
1
- {"version":3,"file":"define.d.ts","sourceRoot":"","sources":["../../src/search-params/define.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAazC;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,WAAW,gBAAgB,CAAC,CAAC,CAAE,SAAQ,KAAK,CAAC,CAAC,CAAC;IACnD,mDAAmD;IACnD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;;;;;;;;;;;;OAgBG;IACH,eAAe,CAAC,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,GAAG,CAAC,CAAC;CAC3D;AAED,8DAA8D;AAC9D,MAAM,WAAW,0BAA0B,CAAC,CAAC,CAAE,SAAQ,gBAAgB,CAAC,CAAC,CAAC;IACxE,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,wCAAwC;AACxC,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI,CAAC,SAAS,gBAAgB,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAE5E,uCAAuC;AACvC,MAAM,MAAM,QAAQ,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI;KAC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,CAAC,CAAC,CAAC;CAAE,CAAC,CAAC;AAE3F;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,EAC3E,MAAM,EAAE,CAAC,GACR,sBAAsB,CAAC;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,CAAC,CAAC"}
@@ -1,4 +1,4 @@
1
- export type { SearchParamCodec, SearchParamCodecWithUrlKey, InferCodec, InferField, CodecMap, SearchParamsDefinition, SetParams, SetParamsOptions, QueryStatesOptions, StandardSchemaV1, } from './define.js';
1
+ export type { SearchParamCodec, SearchParamCodecWithUrlKey, TotalSearchParamCodec, InferCodec, InferField, CodecMap, SearchParamsDefinition, SetParams, SetParamsOptions, QueryStatesOptions, StandardSchemaV1, } from './define.js';
2
2
  export { defineSearchParams } from './define.js';
3
3
  export { withDefault, withUrlKey } from './wrappers.js';
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/search-params/index.ts"],"names":[],"mappings":"AAMA,YAAY,EACV,gBAAgB,EAChB,0BAA0B,EAC1B,UAAU,EACV,UAAU,EACV,QAAQ,EACR,sBAAsB,EACtB,SAAS,EACT,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAMjD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/search-params/index.ts"],"names":[],"mappings":"AAMA,YAAY,EACV,gBAAgB,EAChB,0BAA0B,EAC1B,qBAAqB,EACrB,UAAU,EACV,UAAU,EACV,QAAQ,EACR,sBAAsB,EACtB,SAAS,EACT,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAMjD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import { r as getSearchParamsFromAls } from "../_chunks/als-slots-BEEIPKYm.js";
2
- import { i as isStandardSchema, n as fromSchema, r as isCodec } from "../_chunks/schema-bridge-Cc2Gngu1.js";
3
- import { n as useQueryStates, r as parseTotal } from "../_chunks/use-query-states-BbU5Ge1V.js";
2
+ import { i as isStandardSchema, n as fromSchema, r as isCodec } from "../_chunks/schema-bridge-C83xa9lT.js";
3
+ import { i as parseTotal, n as useQueryStates, r as serializedEqual } from "../_chunks/use-query-states-I3JMng6J.js";
4
4
  //#region src/search-params/define.ts
5
5
  /**
6
6
  * defineSearchParams — factory for SearchParamsDefinition<T>.
@@ -70,6 +70,12 @@ function getDefaultSerialized(codec) {
70
70
  /**
71
71
  * Resolve a field value to a SearchParamCodec. Auto-detects Standard Schema
72
72
  * objects and wraps them with fromSchema. Reads .urlKey from codecs.
73
+ *
74
+ * The returned codec is typed as `SearchParamCodec<unknown>` because the
75
+ * codec map uses that type. At runtime, the value may be a `Codec<T>` from
76
+ * `fromSchema` (whose serialize returns `string | null`) or a nuqs parser
77
+ * (whose serialize returns `string | string[] | null`). Both are safe
78
+ * because `buildSearchParams` handles the union.
73
79
  */
74
80
  function resolveField(fieldName, value) {
75
81
  if (isCodec(value)) return {
@@ -128,10 +134,19 @@ function buildDefinition(codecMap, urlKeys) {
128
134
  const parts = [];
129
135
  for (const prop of Object.keys(codecMap)) {
130
136
  if (!(prop in values)) continue;
131
- const serialized = codecMap[prop].serialize(values[prop]);
132
- if (serialized === defaultSerialized[prop]) continue;
137
+ const codec = codecMap[prop];
138
+ let serialized;
139
+ try {
140
+ serialized = codec.serialize(values[prop]);
141
+ } catch (error) {
142
+ if (error instanceof TypeError) continue;
143
+ throw error;
144
+ }
133
145
  if (serialized === null) continue;
134
- parts.push(`${encodeURIComponent(getUrlKey(prop))}=${encodeURIComponent(serialized)}`);
146
+ if (serializedEqual(serialized, defaultSerialized[prop])) continue;
147
+ const urlKey = encodeURIComponent(getUrlKey(prop));
148
+ if (Array.isArray(serialized)) for (const entry of serialized) parts.push(`${urlKey}=${encodeURIComponent(entry)}`);
149
+ else parts.push(`${urlKey}=${encodeURIComponent(serialized)}`);
135
150
  }
136
151
  return parts.join("&");
137
152
  }