Skip to content

Commit d3af6f5

Browse files
committed
fix(router-core): format Standard Schema issues instead of JSON.stringify
An issue can carry a value that JSON.stringify refuses, such as a bigint, or a circular reference, so serializing it threw and hid the validation failure it was meant to report. The blob also buried the messages. Server-function validation and router search validation now share one formatter that reports each issue as `path: message`. Keys that are not plain identifiers are bracket-quoted, so the two-key path ['a', 'b'] and the single key ['a.b'] stay distinct, and only the message and path are read, each defensively. Fixes #7779
1 parent 6faf2bf commit d3af6f5

7 files changed

Lines changed: 263 additions & 3 deletions

File tree

‎.changeset/olive-donkeys-repeat.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@tanstack/router-core': patch
3+
'@tanstack/start-client-core': patch
4+
---
5+
6+
Format Standard Schema validation issues instead of running them through `JSON.stringify`. An issue can carry a value that cannot be serialized, such as a bigint or a circular reference, which threw and hid the real failure, and the resulting blob buried the messages. Server-function validation and router search validation now share one formatter that reports each issue as `path: message`, quoting any key that is not a plain identifier so `['a', 'b']` and `['a.b']` stay distinct.
7+
8+
Fixes #7779

‎packages/router-core/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,10 @@ export type {
390390
ResolveValidatorOutput,
391391
} from './validators'
392392

393+
// Exported so `start-client-core` can share one formatter. Not part of the
394+
// documented public API.
395+
export { formatStandardSchemaIssues } from './standardSchemaIssues'
396+
393397
export type {
394398
UseRouteContextBaseOptions,
395399
UseRouteContextOptions,

‎packages/router-core/src/router.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ import type {
117117
} from './RouterProvider'
118118
import type { Manifest, ManifestRouteAssets } from './manifest'
119119
import type { AnySchema, AnyValidator } from './validators'
120+
import { formatStandardSchemaIssues } from './standardSchemaIssues'
120121
import type { NavigateOptions, ResolveRelativePath, ToOptions } from './link'
121122
import type {
122123
AnySerializationAdapter,
@@ -2848,7 +2849,7 @@ function validateSearch(validateSearch: AnyValidator, input: unknown): unknown {
28482849
throw new SearchParamError('Async validation not supported')
28492850

28502851
if (result.issues)
2851-
throw new SearchParamError(JSON.stringify(result.issues, undefined, 2), {
2852+
throw new SearchParamError(formatStandardSchemaIssues(result.issues), {
28522853
cause: result,
28532854
})
28542855

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import type { AnyStandardSchemaValidateIssue } from './validators'
2+
3+
/**
4+
* Keys that can appear in a Standard Schema issue path. The spec allows a bare
5+
* key or an object carrying one, and the key itself may be a symbol.
6+
*/
7+
type IssuePathKey = string | number | symbol
8+
9+
const SAFE_KEY_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/
10+
11+
/**
12+
* Reads the key out of a path segment. The segment is either the key itself or
13+
* an object with a `key` property. Anything else is not a key we can render.
14+
*/
15+
function readSegmentKey(segment: unknown): IssuePathKey | undefined {
16+
if (
17+
typeof segment === 'string' ||
18+
typeof segment === 'number' ||
19+
typeof segment === 'symbol'
20+
) {
21+
return segment
22+
}
23+
if (segment !== null && typeof segment === 'object') {
24+
try {
25+
const key = (segment as { key?: unknown }).key
26+
if (
27+
typeof key === 'string' ||
28+
typeof key === 'number' ||
29+
typeof key === 'symbol'
30+
) {
31+
return key
32+
}
33+
} catch {
34+
// a getter that throws is not a key we can use
35+
}
36+
}
37+
return undefined
38+
}
39+
40+
/**
41+
* Renders one key. Bracket-quoting anything that is not a plain identifier is
42+
* what keeps paths unambiguous: the two-key path `['a', 'b']` renders `a.b`,
43+
* while the single key `'a.b'` renders `["a.b"]`, so they can never collide.
44+
* A numeric key renders as an index, and the string `'0'` renders as `["0"]`,
45+
* keeping those distinct too.
46+
*/
47+
function renderKey(key: IssuePathKey, isFirst: boolean): string {
48+
if (typeof key === 'number') {
49+
return `[${key}]`
50+
}
51+
const text = typeof key === 'symbol' ? key.toString() : key
52+
if (typeof key === 'string' && SAFE_KEY_RE.test(key)) {
53+
return isFirst ? text : `.${text}`
54+
}
55+
return `[${JSON.stringify(text)}]`
56+
}
57+
58+
function formatIssuePath(path: ReadonlyArray<unknown>): string {
59+
let rendered = ''
60+
let isFirst = true
61+
for (const segment of path) {
62+
const key = readSegmentKey(segment)
63+
if (key === undefined) continue
64+
rendered += renderKey(key, isFirst)
65+
isFirst = false
66+
}
67+
return rendered
68+
}
69+
70+
function formatIssue(issue: unknown): string {
71+
let message = ''
72+
try {
73+
const raw = (issue as { message?: unknown } | null | undefined)?.message
74+
if (raw !== undefined && raw !== null) message = String(raw)
75+
} catch {
76+
// fall through to the generic message below
77+
}
78+
if (!message) message = 'Invalid value'
79+
80+
let path = ''
81+
try {
82+
const raw = (issue as { path?: unknown } | null | undefined)?.path
83+
if (Array.isArray(raw) && raw.length > 0) path = formatIssuePath(raw)
84+
} catch {
85+
// an unreadable path is reported as a root issue
86+
}
87+
88+
return path ? `${path}: ${message}` : message
89+
}
90+
91+
/**
92+
* Turns Standard Schema issues into a readable message.
93+
*
94+
* `JSON.stringify` cannot be used here: an issue may carry values it refuses to
95+
* serialize, such as a bigint, which throws, or a circular reference, and the
96+
* resulting blob hid the messages that explain the failure. Only the message
97+
* and the path are read, each defensively, so a hostile or exotic issue object
98+
* still produces a usable error.
99+
*/
100+
export function formatStandardSchemaIssues(
101+
issues: ReadonlyArray<AnyStandardSchemaValidateIssue> | undefined,
102+
): string {
103+
if (!issues || issues.length === 0) return 'Validation failed'
104+
const lines: Array<string> = []
105+
for (const issue of issues) {
106+
lines.push(formatIssue(issue))
107+
}
108+
return lines.join('\n')
109+
}

‎packages/router-core/src/validators.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ export interface AnyStandardSchemaValidateFailure {
2727

2828
export interface AnyStandardSchemaValidateIssue {
2929
readonly message: string
30+
/**
31+
* Where the issue occurred. Absent for a root issue. A segment is either the
32+
* key itself or an object carrying one, and the key may be a symbol.
33+
*/
34+
readonly path?:
35+
| ReadonlyArray<PropertyKey | { readonly key: PropertyKey }>
36+
| undefined
3037
}
3138

3239
export interface AnyStandardSchemaValidateInput {
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { formatStandardSchemaIssues } from '../src/standardSchemaIssues'
3+
4+
describe('formatStandardSchemaIssues', () => {
5+
it('reports a root issue as the bare message', () => {
6+
expect(formatStandardSchemaIssues([{ message: 'Required' }])).toBe(
7+
'Required',
8+
)
9+
})
10+
11+
it('falls back when there are no issues', () => {
12+
expect(formatStandardSchemaIssues([])).toBe('Validation failed')
13+
expect(formatStandardSchemaIssues(undefined)).toBe('Validation failed')
14+
})
15+
16+
it('prefixes a nested path', () => {
17+
expect(
18+
formatStandardSchemaIssues([
19+
{ message: 'Expected string', path: ['user', 'name'] },
20+
]),
21+
).toBe('user.name: Expected string')
22+
})
23+
24+
it('accepts the object form of a path segment', () => {
25+
expect(
26+
formatStandardSchemaIssues([
27+
{ message: 'Expected string', path: [{ key: 'user' }, { key: 'name' }] },
28+
]),
29+
).toBe('user.name: Expected string')
30+
})
31+
32+
it('renders a numeric key as an index', () => {
33+
expect(
34+
formatStandardSchemaIssues([{ message: 'Too small', path: ['items', 0] }]),
35+
).toBe('items[0]: Too small')
36+
})
37+
38+
it('keeps a numeric string distinct from a numeric index', () => {
39+
const numeric = formatStandardSchemaIssues([{ message: 'x', path: [0] }])
40+
const stringy = formatStandardSchemaIssues([{ message: 'x', path: ['0'] }])
41+
expect(numeric).toBe('[0]: x')
42+
expect(stringy).toBe('["0"]: x')
43+
expect(numeric).not.toBe(stringy)
44+
})
45+
46+
it('does not let a dotted key collide with two keys', () => {
47+
const twoKeys = formatStandardSchemaIssues([
48+
{ message: 'x', path: ['a', 'b'] },
49+
])
50+
const dottedKey = formatStandardSchemaIssues([
51+
{ message: 'x', path: ['a.b'] },
52+
])
53+
expect(twoKeys).toBe('a.b: x')
54+
expect(dottedKey).toBe('["a.b"]: x')
55+
expect(twoKeys).not.toBe(dottedKey)
56+
})
57+
58+
it('quotes keys that are not plain identifiers', () => {
59+
expect(
60+
formatStandardSchemaIssues([
61+
{ message: 'x', path: ['with space', 'quote"key', ''] },
62+
]),
63+
).toBe('["with space"]["quote\\"key"][""]: x')
64+
})
65+
66+
it('handles prototype-named keys without touching the prototype', () => {
67+
expect(
68+
formatStandardSchemaIssues([
69+
{ message: 'x', path: ['__proto__', 'constructor'] },
70+
]),
71+
).toBe('__proto__.constructor: x')
72+
expect(({} as Record<string, unknown>).polluted).toBeUndefined()
73+
})
74+
75+
it('renders a symbol key', () => {
76+
const key = Symbol('secret')
77+
expect(
78+
formatStandardSchemaIssues([{ message: 'x', path: [key] }]),
79+
).toBe('["Symbol(secret)"]: x')
80+
})
81+
82+
it('joins several issues one per line', () => {
83+
expect(
84+
formatStandardSchemaIssues([
85+
{ message: 'Required', path: ['a'] },
86+
{ message: 'Too long', path: ['b', 1] },
87+
]),
88+
).toBe('a: Required\nb[1]: Too long')
89+
})
90+
91+
it('survives an issue that cannot be serialized', () => {
92+
const circular: any = { message: 'Bad input', path: ['a'] }
93+
circular.self = circular
94+
expect(() => JSON.stringify(circular)).toThrow()
95+
expect(formatStandardSchemaIssues([circular])).toBe('a: Bad input')
96+
})
97+
98+
it('survives a bigint in the issue, which JSON.stringify refuses', () => {
99+
const issue: any = { message: 'Bad input', received: 1n }
100+
expect(() => JSON.stringify(issue)).toThrow()
101+
expect(formatStandardSchemaIssues([issue])).toBe('Bad input')
102+
})
103+
104+
it('survives getters that throw', () => {
105+
const issue: any = {
106+
get message() {
107+
throw new Error('nope')
108+
},
109+
get path() {
110+
throw new Error('nope')
111+
},
112+
}
113+
expect(formatStandardSchemaIssues([issue])).toBe('Invalid value')
114+
})
115+
116+
it('coerces a non-string message', () => {
117+
expect(formatStandardSchemaIssues([{ message: 42 } as any])).toBe('42')
118+
})
119+
120+
it('skips path segments that carry no usable key', () => {
121+
expect(
122+
formatStandardSchemaIssues([
123+
{ message: 'x', path: ['a', null, undefined, {}, 'b'] as any },
124+
]),
125+
).toBe('a.b: x')
126+
})
127+
})

‎packages/start-client-core/src/createServerFn.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import { mergeHeaders } from '@tanstack/router-core/ssr/client'
22

3-
import { isRedirect, parseRedirect } from '@tanstack/router-core'
3+
import {
4+
formatStandardSchemaIssues,
5+
isRedirect,
6+
parseRedirect,
7+
} from '@tanstack/router-core'
48
import { TSS_SERVER_FUNCTION_FACTORY } from './constants'
59
import { getStartOptions } from './getStartOptions'
610
import { getStartContextServerOnly } from './getStartContextServerOnly'
@@ -898,7 +902,7 @@ export async function execValidator(
898902
const result = await validator['~standard'].validate(input)
899903

900904
if (result.issues)
901-
throw new Error(JSON.stringify(result.issues, undefined, 2))
905+
throw new Error(formatStandardSchemaIssues(result.issues))
902906

903907
return result.value
904908
}

0 commit comments

Comments
 (0)