@ultimat3/schema 24.0.0 → 25.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -15,8 +15,9 @@ Tier 0. **Imports no `@ultimat3/*` package — not even `@ultimat3/core`.**
15
15
  | Re-exports | `action`, `query`, `jobs`, `entity` re-export `t` verbatim so an authoring file imports one package — never let them wrap or copy it |
16
16
 
17
17
  Module order (no cycles):
18
- `char-count → describe-value → node → builder → money-value → validators → discriminated-union →
19
- provider → t`. `char-count.ts` is imported by BOTH `validators.ts` (which rejects on length) and
18
+ `char-count → describe-value → node → builder → money-value → json-value → validators →
19
+ discriminated-union → provider → t` (`node-fits` and `json-schema` read `json-value` too).
20
+ `char-count.ts` is imported by BOTH `validators.ts` (which rejects on length) and
20
21
  `describe-value.ts` (which renders the length in the same message), because they disagreed: the
21
22
  rule counted code points and the message counted UTF-16 units, so `t.string.min(3)` refused `'👍a'`
22
23
  with "at least 3 chars, received a string of 3 characters".
@@ -59,8 +60,8 @@ is the whole edit `As of 2026-08-27`** — the title and its `terminal` retry cl
59
60
  derived from this set, where they used to be a hand-kept duplicate in core plus a hand-written
60
61
  retry list a fifth code would have been silently missing from.
61
62
 
62
- `ERROR_DOCS_URL` in `errors.ts` is the third deliberate tier-0 duplicate, beside `singleLine` and
63
- `ULTIMATE_ERROR_BRAND` — one URL, spelled out, because `SchemaError` cannot import
63
+ `ERROR_DOCS_URL` in `errors.ts` is the second deliberate tier-0 duplicate, beside `singleLine` —
64
+ one URL, spelled out, because `SchemaError` cannot import
64
65
  `@ultimat3/core`'s constant. There is no per-code URL anywhere in the framework: codes live in
65
66
  `wiki/Error-Codes.md` as table ROWS and a table row has no anchor, so
66
67
  `https://ultimate.dev/errors/<code>` was a 404 on every error and was deleted `As of 2026-08-23`. Change it
@@ -69,9 +70,11 @@ here and in `packages/core/src/error-codes.ts` in the same edit. **It is pinned
69
70
  `UltimateError`'s, which was the one copy with no mechanical check at all and the one that decides
70
71
  where every schema refusal sends its reader.
71
72
 
72
- **These three are the whole of the duplication that remains, and the edge does not reach them.**
73
- `core -> schema` was declared 2026-08-27 and collapsed five copies on the CORE side; `singleLine`,
74
- `ERROR_DOCS_URL` and `ULTIMATE_ERROR_BRAND` go the other way, and `schema -> core` stays forbidden
73
+ **These two are the whole of the duplication that remains, and the edge does not reach them.**
74
+ `core -> schema` was declared 2026-08-27 and collapsed five copies on the CORE side, and
75
+ `ULTIMATE_ERROR_BRAND` in 25.0.0 — declared HERE once, imported by core's `errors.ts`, because one
76
+ value name has one declaring package (`scripts/factory-names.ts`). `singleLine` and
77
+ `ERROR_DOCS_URL` go the other way, and `schema -> core` stays forbidden
75
78
  on its merits — `t` is in every bundle graph an app has, so a dependency here is a dependency
76
79
  everywhere.
77
80
 
@@ -165,9 +168,9 @@ Gotchas:
165
168
  decimal only (`DECIMAL`); `Number()` also reads `0x10`.
166
169
  - Adding a `SchemaKind` means updating `json-schema.ts`, `coerce.ts` and `node-fits.ts` in the same commit.
167
170
  - **`wire-schema.ts` is the one MCP tool-schema narrowing** (`toWireSchema`, `toWireOutputSchema`,
168
- `WireJsonSchema`): `@ultimat3/mcp`'s `tools/list` and `@ultimat3/action`'s `.tool()` both publish
169
- through it, so one declaration has one tool document. It lived in `mcp` (tier 4), out of
170
- `action`'s reach, and the two documents differed (`format`, output bounds).
171
+ `WireJsonSchema`): `@ultimat3/mcp`'s `tools/list` (`toolFrom`, the one tool projection
172
+ since 25.0.0 deleted `.tool()`) publishes through it. It lived in `mcp` (tier 4) while
173
+ `action` carried a second projection, and the two documents differed (`format`, output bounds).
171
174
  - **`ToJsonSchemaOptions.dialect` is a closed vocabulary read with `Object.hasOwn`** (`As of
172
175
  2026-09-06`). `DIALECTS[dialect]` on an object literal answered the `Object` FUNCTION for
173
176
  `dialect: 'constructor'` — measured: `$schema` held it, `JSON.stringify` dropped the key in
@@ -185,6 +188,13 @@ Gotchas:
185
188
  a schema change is not allowed to edit. `refinements` and `discriminant` are both fields for that
186
189
  reason: a refined string still reads as a string, and a discriminated union still reads as a
187
190
  union, everywhere. `lazy` and `tuple` cannot be — which is why neither has shipped.
191
+ - **`t.json()` is a `SchemaKind`, the one exception to the line above** (`As of 2026-10`):
192
+ `unknown` means the IR cannot describe a value, `json` that it can — and every foreign
193
+ `default:` already projects it correctly (`{}`, raw pass-through, a `null` sample, admin's JSON
194
+ textarea). `JsonValue` in `json-value.ts` is the framework's one declaration; `cli`, `render`,
195
+ `manifest` and `realtime` still restate it. Its path segments are POSITIONS (the `t.record`
196
+ rule), shared values are memoised by height so a DAG is linear, and `JSON_MAX_DEPTH` is fixed:
197
+ a caller-set bound needs a declaration-time refusal code this package does not have yet.
188
198
  - A refinement is carried as a **declaration** (`name`, `message`, `path`), never a closure: a
189
199
  predicate cannot cross into OpenAPI or an MCP tool schema, and `refine`'s `message` is rendered
190
200
  verbatim on both — so it states the rule and never interpolates a value.
package/README.md CHANGED
@@ -11,6 +11,7 @@ type, a JSON Schema, an OpenAPI body, an MCP tool `inputSchema` and HTTP query c
11
11
  | the introspectable IR every generator walks | `node.ts` |
12
12
  | `Schema` factory, `Infer` machinery, `.refine()` | `builder.ts` |
13
13
  | how a rejected value is described — its shape, never its content | `describe-value.ts` |
14
+ | `JsonValue`, `t.json()` / `jsonSchema()`, `JSON_MAX_DEPTH` | `json-value.ts` |
14
15
  | a union routed by one literal key | `discriminated-union.ts` |
15
16
  | `configureSchemaProvider()` — the swap point | `provider.ts` |
16
17
  | schema → JSON Schema (OpenAPI + MCP) | `json-schema.ts` |
@@ -39,7 +40,7 @@ type PublishPost = Infer<typeof publishPost>;
39
40
  | Value schemas | Factories | Methods |
40
41
  |---|---|---|
41
42
  | `string` `number` `boolean` `date` `uuid` `email` `url` | `object` `array` `enum` `literal` `union` `discriminatedUnion` `record` `optional` `nullable` `refine` | `.default(v)` `.optional()` `.nullable()` `.describe(s)` `.refine(r)` |
42
- | `money` `timezone` `locale` `slug` `cursor` | `object(...).extend/.pick/.omit` | `string.min/.max/.pattern`, `number.min/.max/.int` |
43
+ | `money` `timezone` `locale` `slug` `cursor` `json()` | `object(...).extend/.pick/.omit` | `string.min/.max/.pattern`, `number.min/.max/.int` |
43
44
 
44
45
  `nullable` is a value the row holds; `optional` is the caller omitting the key. Both ship as a
45
46
  namespace member (`t.nullable`) and a free function (`nullableSchema`) — symmetrically.
@@ -55,10 +56,33 @@ Refused at the boundary rather than guessed at (`As of 2026-10`):
55
56
  | `t.object` `t.record` `t.money` | anything whose prototype is not `Object.prototype` or `null` — a `Map`, a `Date`, a class instance | none has the own keys the schema declared, so it parsed to `{}` |
56
57
  | `.default(v)` | a `v` the schema itself rejects — `X_SCHEMA_DEFAULT_INVALID`, thrown where it is declared | an omitted field parsed to a value the same schema refuses when sent |
57
58
 
59
+ ### `t.json()` — a payload whose shape is somebody else's
60
+
61
+ ```ts
62
+ import { t, type Infer, type JsonValue } from '@ultimat3/schema';
63
+
64
+ export const hook = t.object({ event: t.slug, payload: t.json() });
65
+ export const payload: JsonValue = ({} as Infer<typeof hook>).payload;
66
+ // entity column: json(t.json()) — a jsonb that stores what it was sent
67
+ ```
68
+
69
+ | Accepts | Refuses (with the issue's path) |
70
+ |---|---|
71
+ | `null`, booleans, finite numbers, strings, arrays and plain / null-prototype objects of them, recursively | `undefined` (an array hole too), functions, symbols, bigints, `NaN` / `±Infinity`, a `Date`, a `Map` / `Set` / class instance / typed array, a cycle |
72
+ | every key, `__proto__` and `constructor` included — answered on a null-prototype copy | a NUL or a lone UTF-16 surrogate in a string or a key — Postgres `jsonb` refuses both (measured, PG 17) |
73
+ | at most `JSON_MAX_DEPTH` (256) nested containers | one more: the walk recurses per level, and an unbounded one was a `RangeError` |
74
+
75
+ A path into a JSON object is the entry's **position** (`payload[2][0]`), never its key — the
76
+ `t.record` rule. A value shared twice is walked once, so a DAG is linear, not exponential. The
77
+ JSON Schema is `{}` with the depth bound in `description`; the bound is fixed — narrow it with
78
+ `.refine()`. Node `kind: 'json'`, distinct from `unknown` ("the IR cannot say").
79
+
58
80
  Every string-backed schema (`string` `uuid` `email` `url` `timezone` `locale` `slug` `cursor`, with
59
- any `.min/.max/.pattern`) and every `t.record` key **refuses U+0000** — the one character Postgres
60
- `text` and `jsonb` cannot store, so a NUL that passed reached the row write as a 500. Tabs, newlines
61
- and the other C0 controls stay legal text. The issue names the fact, never the value:
81
+ any `.min/.max/.pattern`) and every `t.record` key **refuses U+0000 and a lone UTF-16 surrogate** —
82
+ the rule `t.json()` applies, one predicate (`unstorable-text.ts`). Postgres `text` and `jsonb` cannot
83
+ store a NUL, `jsonb` refuses a lone surrogate, and into `text` Bun's sql writes U+FFFD in its place,
84
+ so either reached the row write as a 500 or a silent rewrite. A well-formed pair (an emoji), tabs,
85
+ newlines and the other C0 controls stay legal text. The issue names the fact, never the value:
62
86
  `title: expected a non-empty string, received a string of 3 characters that contains a NUL
63
87
  character (U+0000)`. Not published in the JSON Schema — it is a storage fact, not a format.
64
88
 
@@ -188,16 +212,18 @@ swap. `introspect()` is what OpenAPI/MCP generation needs; a provider without it
188
212
 
189
213
  ```ts
190
214
  toJsonSchema(publishPost); // OpenAPI 3.1 (2020-12)
191
- toWireSchema(publishPost); // an MCP tool's inputSchema: what tools/list serves and .tool() returns
215
+ toWireSchema(publishPost); // an MCP tool's inputSchema: what tools/list serves
192
216
  toWireOutputSchema(publishPost); // its outputSchema: structure only; undefined for a non-object root
193
217
  toJsonSchema(publishPost, { dialect: 'x' }); // X_SCHEMA_UNSUPPORTED — the two spellings are closed
194
218
  parse(publishPost, coerceQuery(publishPost, url.searchParams));
219
+ numeric(' 12 '); // 12 — numeric('0x10'), numeric(' '): undefined
195
220
  ```
196
221
 
197
222
  Coercion is separate from validation on purpose: only the HTTP layer has strings that mean
198
223
  numbers. `coerceQuery` promotes repeated params to arrays and leaves anything ambiguous
199
224
  untouched so validation still produces the real error. It never invents data: only a **decimal**
200
- numeral becomes a number (`0x10` stays text), only a plain object is read as one (an array is never
225
+ numeral becomes a number (`0x10` stays text; `numeric` is that one reader, for a boundary that
226
+ holds a string and no schema node — admin's form decode), only a plain object is read as one (an array is never
201
227
  spread into `{ 0: … }`), and a union tries **every** member in declaration order — a string some
202
228
  member already accepts is left alone, and a union of objects coerces through the member whose
203
229
  literal fields the value carries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/schema",
3
- "version": "24.0.0",
3
+ "version": "25.0.0",
4
4
  "description": "Ultimate's validation seam: Standard Schema interface, the t namespace, JSON Schema output",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -26,7 +26,7 @@
26
26
  "LICENSE"
27
27
  ],
28
28
  "engines": {
29
- "bun": ">=1.4.0"
29
+ "bun": ">=1.4.2"
30
30
  },
31
31
  "scripts": {
32
32
  "typecheck": "tsc --noEmit -p tsconfig.json",
package/src/coerce.ts CHANGED
@@ -18,8 +18,12 @@ const FALSE_VALUES = new Set(['0', 'false', 'no', 'off', '']);
18
18
  */
19
19
  const DECIMAL = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
20
20
 
21
- /** A numeric string as a number, or `undefined` for anything that is not confidently one. */
22
- function numeric(raw: unknown): number | undefined {
21
+ /**
22
+ * A numeric string as a number, or `undefined` for anything that is not confidently one. Exported
23
+ * for the other string-to-number boundary, admin's form decode: two readers of one posted numeral
24
+ * would disagree about `0x10`, which is the drift this rule exists to end.
25
+ */
26
+ export function numeric(raw: unknown): number | undefined {
23
27
  if (typeof raw !== 'string' || !DECIMAL.test(raw.trim())) return undefined;
24
28
  const value = Number(raw);
25
29
  return Number.isFinite(value) ? value : undefined;
@@ -133,6 +137,10 @@ export function coerceNode(node: SchemaNode, raw: unknown): unknown {
133
137
  }
134
138
  return raw;
135
139
  }
140
+ // Named rather than left to `default`: a query parameter is TEXT, and text is already a JSON
141
+ // value. Parsing it would make `?q=12` a number for one caller and a string for the next.
142
+ case 'json':
143
+ return raw;
136
144
  default:
137
145
  return raw;
138
146
  }
@@ -0,0 +1,10 @@
1
+ // Single responsibility: the ONE brand every framework error carries — `SchemaError` here,
2
+ // `UltimateError` in `@ultimat3/core`, which imports this declaration over the `core -> schema`
3
+ // edge. A leaf of its own for `error-codes.ts`'s reason: core's error contract is in every browser
4
+ // bundle, and importing the brand from `errors.ts` would drag `SchemaError` and its table in too.
5
+
6
+ /**
7
+ * Never renamed: the `Symbol.for` key is what a duplicated module instance recognises, so
8
+ * `isUltimateError()` stays true across two copies of a package in one process.
9
+ */
10
+ export const ULTIMATE_ERROR_BRAND: unique symbol = Symbol.for('ultimate.error');
package/src/errors.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  // Single responsibility: this package's error codes. `@ultimat3/schema` is tier 0 and may not
2
2
  // import `@ultimat3/core`, so `SchemaError` reproduces the `UltimateError` shape structurally
3
- // and carries the same `Symbol.for('ultimate.error')` brand — `isUltimateError()` still matches.
3
+ // and carries the one brand both classes share (`error-brand.ts`) — `isUltimateError()` matches.
4
4
 
5
+ import { ULTIMATE_ERROR_BRAND } from './error-brand';
5
6
  import { SCHEMA_ERROR_CODES } from './error-codes';
6
7
  import { renderMetaRecord } from './render-meta';
7
8
  import { formatIssues } from './standard';
@@ -11,8 +12,8 @@ import { formatIssues } from './standard';
11
12
  * there — briefly: the 3-line format is line-oriented, and a `cause` may hold a value the caller
12
13
  * chose, so a newline in one writes a line an operator reads as a genuine framework message.
13
14
  *
14
- * Copied rather than imported for the same reason the brand symbol above is: `schema` and `core`
15
- * are both tier 0, so `schema` may not import `core` (imports go DOWN, never sideways). A schema
15
+ * Copied rather than imported: `schema` and `core` are both tier 0, and only `core -> schema` is a
16
+ * declared edge, so `schema` may not import `core`. A schema
16
17
  * cause is the one most likely to carry a hostile string — it describes the value that failed
17
18
  * validation, which is the request body.
18
19
  */
@@ -35,9 +36,6 @@ const singleLine = (text: string): string =>
35
36
  (char) => ESCAPES[char] ?? `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`,
36
37
  );
37
38
 
38
- /** Same well-known symbol `@ultimat3/core` brands with. Keep in sync, never rename. */
39
- export const ULTIMATE_ERROR_BRAND: unique symbol = Symbol.for('ultimate.error');
40
-
41
39
  /**
42
40
  * The same one URL `@ultimat3/core`'s `ERROR_DOCS_URL` holds. **Keep in sync**, and read the
43
41
  * reason there — briefly: `wiki/` is the only public documentation surface, codes live on that
package/src/index.ts CHANGED
@@ -22,9 +22,10 @@ export { checkOf, fail, failWith, makeSchema, pass, VENDOR } from './builder';
22
22
  // not import this package — but `mcp` is tier 4 and can, so a copy there would have no excuse.
23
23
  export { charCount } from './char-count';
24
24
  export type { QuerySource } from './coerce';
25
- export { coerceInput, coerceNode, coerceQuery } from './coerce';
25
+ export { coerceInput, coerceNode, coerceQuery, numeric } from './coerce';
26
26
  export { describeValue, expected } from './describe-value';
27
27
  export { discriminatedUnionSchema } from './discriminated-union';
28
+ export { ULTIMATE_ERROR_BRAND } from './error-brand';
28
29
  export type { SchemaErrorCodeDeclaration } from './error-codes';
29
30
  export { SCHEMA_ERROR_CODES } from './error-codes';
30
31
  export type {
@@ -39,7 +40,6 @@ export {
39
40
  isSchemaError,
40
41
  SchemaError,
41
42
  SchemaUnsupportedError,
42
- ULTIMATE_ERROR_BRAND,
43
43
  ValidationFailedError,
44
44
  } from './errors';
45
45
  // Exported for `@ultimat3/time`'s `fromIso`: one ISO-shape rule, whichever door a date comes in by.
@@ -52,6 +52,8 @@ export type {
52
52
  ToJsonSchemaOptions,
53
53
  } from './json-schema';
54
54
  export { nodeToJsonSchema, toJsonSchema } from './json-schema';
55
+ export type { JsonValue } from './json-value';
56
+ export { JSON_MAX_DEPTH, jsonSchema } from './json-value';
55
57
  export type { MoneyValue } from './money-value';
56
58
  export {
57
59
  CURRENCY_CODE_PATTERN,
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { describeValue } from './describe-value';
7
7
  import { SchemaUnsupportedError } from './errors';
8
+ import { JSON_MAX_DEPTH } from './json-value';
8
9
  import { CURRENCY_CODE_PATTERN, MAX_MONEY_SCALE } from './money-value';
9
10
  import { requiredKeys, type SchemaNode, type SchemaRefinement } from './node';
10
11
  import { PROTOTYPE_KEYS } from './prototype-keys';
@@ -158,10 +159,22 @@ function patternNote(node: SchemaNode): string | undefined {
158
159
  : `pattern is applied with RegExp flags "${flags}"`;
159
160
  }
160
161
 
162
+ /**
163
+ * JSON Schema has no keyword for nesting depth, so `t.json()`'s bound is stated in prose — the
164
+ * narrower-of-the-two rule this file's header states: `{}` alone promised a document 300 levels
165
+ * deep that the parser refuses.
166
+ */
167
+ function jsonNote(node: SchemaNode): string | undefined {
168
+ return node.kind === 'json'
169
+ ? `any JSON value, nested at most ${JSON_MAX_DEPTH} levels deep`
170
+ : undefined;
171
+ }
172
+
161
173
  function convert(node: SchemaNode): JsonSchema {
162
174
  const refinements = node.refinements ?? [];
163
175
  const notes = [
164
176
  node.description,
177
+ jsonNote(node),
165
178
  patternNote(node),
166
179
  ...refinements.map((refinement) => refinement.message),
167
180
  ].filter((part): part is string => part !== undefined);
@@ -282,6 +295,10 @@ function convert(node: SchemaNode): JsonSchema {
282
295
  additionalProperties: false,
283
296
  });
284
297
  }
298
+ // No `type`: an empty schema is JSON Schema's own spelling of "any JSON value", and every
299
+ // instance it validates is JSON already. The depth bound rides in `description` (`jsonNote`).
300
+ case 'json':
301
+ return annotate({});
285
302
  default:
286
303
  return annotate({});
287
304
  }
@@ -0,0 +1,205 @@
1
+ // Single responsibility: the framework's ONE `JsonValue` declaration and `t.json()`, the validator
2
+ // that admits exactly the values `JSON.stringify` and a Postgres `jsonb` round-trip unchanged.
3
+ // Its own file for `money-value.ts`'s reason: it is a builtin whose SHAPE other packages alias.
4
+
5
+ import {
6
+ type Check,
7
+ fail,
8
+ failWith,
9
+ isPlainObject,
10
+ makeSchema,
11
+ pass,
12
+ type Schema,
13
+ } from './builder';
14
+ import { expected } from './describe-value';
15
+ import type { SchemaNode } from './node';
16
+ import type { StandardIssue } from './standard';
17
+ import { unstorable } from './unstorable-text';
18
+
19
+ /**
20
+ * Any value JSON can carry. Readonly, because a parsed payload is data the handler reads; the copy
21
+ * `t.json()` answers is its own, so nothing it holds is shared with the caller's input.
22
+ */
23
+ export type JsonValue =
24
+ | string
25
+ | number
26
+ | boolean
27
+ | null
28
+ | readonly JsonValue[]
29
+ | { readonly [key: string]: JsonValue };
30
+
31
+ /**
32
+ * How many containers `t.json()` lets nest. A FIXED bound, not an option: the walk recurses once
33
+ * per level and `JSON.parse` builds 100 000 levels from 200 KB of brackets, so an unbounded walk
34
+ * was a `RangeError` — a 500 — for any caller who sent one. 256 holds a rich-text document (each
35
+ * list level is an array and an object) with room to spare. Narrower is `.refine()`'s job.
36
+ */
37
+ export const JSON_MAX_DEPTH = 256;
38
+
39
+ /** A path segment chain, materialised only for an issue: a copy per node is O(n × depth). */
40
+ interface At {
41
+ readonly parent: At | readonly PropertyKey[];
42
+ readonly segment: number;
43
+ }
44
+
45
+ function pathOf(at: At | readonly PropertyKey[]): PropertyKey[] {
46
+ const segments: number[] = [];
47
+ let cursor = at;
48
+ while (!Array.isArray(cursor)) {
49
+ const link = cursor as At;
50
+ segments.push(link.segment);
51
+ cursor = link.parent;
52
+ }
53
+ return [...(cursor as readonly PropertyKey[]), ...segments.reverse()];
54
+ }
55
+
56
+ interface Walk {
57
+ readonly issues: StandardIssue[];
58
+ /** The containers enclosing the current one: meeting one again is a cycle. */
59
+ readonly open: Set<object>;
60
+ /** A container already accepted, with its height, so a shared one is walked ONCE. */
61
+ readonly done: Map<object, { readonly value: JsonValue; readonly height: number }>;
62
+ /** A container already refused: its issues are reported, at the first position it was met. */
63
+ readonly refused: Set<object>;
64
+ }
65
+
66
+ type Step = { readonly ok: true; readonly value: JsonValue; readonly height: number } | null;
67
+
68
+ const CYCLE = 'expected a JSON value, received a cycle (a reference back to an enclosing value)';
69
+ const NOT_PLAIN = 'expected a JSON value, received an object that is not a plain object or array';
70
+
71
+ function refuse(state: Walk, at: At | readonly PropertyKey[], message: string): null {
72
+ state.issues.push({ message, path: pathOf(at) });
73
+ return null;
74
+ }
75
+
76
+ function scalar(value: unknown, at: At | readonly PropertyKey[], state: Walk): Step {
77
+ if (value === null || typeof value === 'boolean') return { ok: true, value, height: 0 };
78
+ if (typeof value === 'number') {
79
+ return Number.isFinite(value)
80
+ ? { ok: true, value, height: 0 }
81
+ : refuse(state, at, expected('a JSON value', value));
82
+ }
83
+ if (typeof value === 'string') {
84
+ const reason = unstorable(value);
85
+ return reason === undefined
86
+ ? { ok: true, value, height: 0 }
87
+ : refuse(state, at, `${expected('a JSON value', value)} ${reason}`);
88
+ }
89
+ return refuse(state, at, expected('a JSON value', value));
90
+ }
91
+
92
+ function walk(value: unknown, at: At | readonly PropertyKey[], depth: number, state: Walk): Step {
93
+ if (typeof value !== 'object' || value === null) return scalar(value, at, state);
94
+ const array = Array.isArray(value);
95
+ if (!array && !isPlainObject(value)) {
96
+ // A Date names itself (`describeValue`); a Map, a Set or a class instance is "an object" there.
97
+ return refuse(state, at, value instanceof Date ? expected('a JSON value', value) : NOT_PLAIN);
98
+ }
99
+ if (state.open.has(value)) return refuse(state, at, CYCLE);
100
+ if (state.refused.has(value)) return null;
101
+ const seen = state.done.get(value);
102
+ const tooDeep = expected(`JSON nested at most ${JSON_MAX_DEPTH} levels deep`, value);
103
+ if (seen !== undefined) {
104
+ return depth + seen.height <= JSON_MAX_DEPTH
105
+ ? { ok: true, ...seen }
106
+ : refuse(state, at, tooDeep);
107
+ }
108
+ if (depth >= JSON_MAX_DEPTH) return refuse(state, at, tooDeep);
109
+
110
+ state.open.add(value);
111
+ const built = array ? walkArray(value, at, depth, state) : walkObject(value, at, depth, state);
112
+ state.open.delete(value);
113
+ if (built === null) {
114
+ state.refused.add(value);
115
+ return null;
116
+ }
117
+ state.done.set(value, built);
118
+ return { ok: true, ...built };
119
+ }
120
+
121
+ type Built = { readonly value: JsonValue; readonly height: number } | null;
122
+
123
+ function walkArray(
124
+ items: readonly unknown[],
125
+ at: At | readonly PropertyKey[],
126
+ depth: number,
127
+ state: Walk,
128
+ ): Built {
129
+ const out: JsonValue[] = [];
130
+ let height = 0;
131
+ let ok = true;
132
+ // An index loop, never `entries()` on a sparse array alone: a hole reads `undefined` and is
133
+ // refused at its index, where `JSON.stringify` would have written `null` in silence.
134
+ for (let index = 0; index < items.length; index += 1) {
135
+ const step = walk(items[index], { parent: at, segment: index }, depth + 1, state);
136
+ if (step === null) ok = false;
137
+ else {
138
+ out.push(step.value);
139
+ height = Math.max(height, step.height);
140
+ }
141
+ }
142
+ return ok ? { value: out, height: height + 1 } : null;
143
+ }
144
+
145
+ function walkObject(
146
+ source: Record<string, unknown>,
147
+ at: At | readonly PropertyKey[],
148
+ depth: number,
149
+ state: Walk,
150
+ ): Built {
151
+ // Null-prototype, for `recordSchema`'s reason: every key here is the caller's, and on a `{}`
152
+ // literal `out['__proto__'] = …` re-prototypes the output instead of storing the key.
153
+ const out: Record<string, JsonValue> = Object.create(null) as Record<string, JsonValue>;
154
+ let height = 0;
155
+ let ok = true;
156
+ // The entry's POSITION is its path segment, never its key — the rule `recordSchema` states:
157
+ // a key is caller data, and an issue path reaches the problem document and the log line.
158
+ for (const [index, key] of Object.keys(source).entries()) {
159
+ const link: At = { parent: at, segment: index };
160
+ const reason = unstorable(key);
161
+ if (reason !== undefined) {
162
+ refuse(state, link, `expected an object key, received one ${reason}`);
163
+ ok = false;
164
+ continue;
165
+ }
166
+ const step = walk(source[key], link, depth + 1, state);
167
+ if (step === null) ok = false;
168
+ else {
169
+ out[key] = step.value;
170
+ height = Math.max(height, step.height);
171
+ }
172
+ }
173
+ return ok ? { value: out, height: height + 1 } : null;
174
+ }
175
+
176
+ const checkJson: Check<JsonValue> = (value, path) => {
177
+ const state: Walk = { issues: [], open: new Set(), done: new Map(), refused: new Set() };
178
+ const step = walk(value, path, 0, state);
179
+ if (step !== null) return pass(step.value);
180
+ // Every refusal pushes its issue; the fallback only keeps a refusal from ever reading as success.
181
+ return state.issues.length > 0
182
+ ? failWith(state.issues)
183
+ : fail(path, expected('a JSON value', value));
184
+ };
185
+
186
+ /**
187
+ * Whether a value has a JSON SHAPE, one level deep — `node-fits.ts`'s question for a union
188
+ * member. Not validation: a nested `undefined` still fits, and is refused by the parse after.
189
+ */
190
+ export function isJsonShape(value: unknown): boolean {
191
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') return true;
192
+ if (typeof value === 'number') return Number.isFinite(value);
193
+ return Array.isArray(value) || isPlainObject(value);
194
+ }
195
+
196
+ const JSON_NODE: SchemaNode = Object.freeze({ kind: 'json' });
197
+
198
+ /**
199
+ * `t.json()` as a free function, shipped beside the namespace member as `nullableSchema` is.
200
+ * Every key is kept, `__proto__` and `constructor` included — a webhook body is somebody else's
201
+ * document — and answered on a null-prototype copy, so no key reaches a prototype.
202
+ */
203
+ export function jsonSchema(): Schema<JsonValue, JsonValue> {
204
+ return makeSchema<JsonValue, JsonValue>(JSON_NODE, checkJson);
205
+ }
@@ -106,7 +106,7 @@ export const moneySchema: Schema<MoneyValue, MoneyValue> = makeSchema<MoneyValue
106
106
  const currency = value['currency'];
107
107
  const scale = value['scale'];
108
108
  const issues: StandardIssue[] = [];
109
- // Safe, not merely whole: `money()` and `entity`'s `parseMinor` both demand a safe integer, so
109
+ // Safe, not merely whole: `fromMinor()` and `entity`'s `parseMinor` both demand a safe integer, so
110
110
  // `Number.isInteger` here let 2^53 through the boundary as a 200 and failed at the row write
111
111
  // as a 500 — the same value refused twice, once with a field path and once without.
112
112
  if (typeof minor !== 'number' || !Number.isSafeInteger(minor)) {
package/src/node-fits.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // `coerce.ts` asks to pick the union member a raw HTTP value was written for.
3
3
 
4
4
  import { isPlainObject } from './builder';
5
+ import { isJsonShape } from './json-value';
5
6
  import type { SchemaNode } from './node';
6
7
 
7
8
  /**
@@ -42,6 +43,8 @@ export function fits(node: SchemaNode, value: unknown): boolean {
42
43
  }
43
44
  case 'union':
44
45
  return (node.anyOf ?? []).some((member) => fits(member, value));
46
+ case 'json':
47
+ return isJsonShape(value);
45
48
  default:
46
49
  return false;
47
50
  }
package/src/node.ts CHANGED
@@ -14,6 +14,14 @@ export type SchemaKind =
14
14
  | 'union'
15
15
  | 'record'
16
16
  | 'money'
17
+ /**
18
+ * Any JSON value — `t.json()`. A kind and not a field on `unknown`, because they are different
19
+ * facts: `unknown` is the IR saying it CANNOT describe a value (`@ultimat3/entity`'s view of a
20
+ * column it has no node for), `json` is the IR saying exactly what it holds. Every foreign
21
+ * `default:` already degrades to the right projection — `{}`, a raw pass-through, a `null`
22
+ * sample, admin's JSON textarea — so a consumer that has never heard of it is still correct.
23
+ */
24
+ | 'json'
17
25
  | 'unknown';
18
26
 
19
27
  /** JSON Schema `format`, plus the framework's own semantic formats. */
package/src/t.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  // even for modules that captured `t` at import time.
4
4
 
5
5
  import type { AnySchema, Refinement, Schema, Shape } from './builder';
6
+ import type { JsonValue } from './json-value';
6
7
  import type { MoneyValue } from './money-value';
7
8
  import { schemaProvider } from './provider';
8
9
  import type { InferInput, InferOutput, StandardSchemaV1 } from './standard';
@@ -49,6 +50,14 @@ export const t: TNamespace = {
49
50
  get cursor(): StringSchema {
50
51
  return provider().cursor;
51
52
  },
53
+ /**
54
+ * `t.json()` — any JSON value: null, a boolean, a finite number, a string, and arrays and plain
55
+ * objects of them, at most `JSON_MAX_DEPTH` deep. The column it pairs with is entity's
56
+ * `json(t.json())`, a `jsonb` that stores what it was sent.
57
+ */
58
+ json(): Schema<JsonValue, JsonValue> {
59
+ return provider().json();
60
+ },
52
61
  object<S extends Shape>(shape: S): ObjectSchema<S> {
53
62
  return provider().object(shape);
54
63
  },
@@ -1,7 +1,7 @@
1
1
  // Single responsibility: is a string an IANA zone NAME? TIER 0'S ONE STATEMENT of the rule
2
2
  // `@ultimat3/time` enforces everywhere above it — a zone is `Area/Location`, and `UTC` is the one
3
- // exception. `@ultimat3/core` imported its own copy of this predicate until 2026-08-27 and now
4
- // re-exports this one, over the declared `core -> schema` edge.
3
+ // exception. `@ultimat3/core` carried its own copy until 2026-08-27, then a re-export for the
4
+ // `defaultTimeZone` validator, deleted with that key in 25.0.0.
5
5
  //
6
6
  // `@ultimat3/time`'s `canonicalTimeZone` is NOT a fourth copy and is deliberately left alone: it
7
7
  // answers a different question (the canonical SPELLING, memoised over ~445 listed zones plus a
@@ -14,9 +14,8 @@
14
14
  * Unobservable on ICU 78 — `+01:00` resolves to itself, so the slash rule below already refuses it,
15
15
  * and deleting this line changes no answer this package can currently produce. It stays because it
16
16
  * guards the runtime that folds an offset into `Etc/GMT-1`, which WOULD carry a slash, and because
17
- * `packages/core/src/time-zone-name.ts` and `packages/time/src/zone-canonical.ts` both carry the
18
- * same line: three statements of one rule may not differ, least of all in the half that is hard to
19
- * test.
17
+ * `packages/time/src/zone-canonical.ts` carries the same line: two statements of one rule may not
18
+ * differ, least of all in the half that is hard to test.
20
19
  */
21
20
  const NUMERIC_OFFSET = /^[+-]/;
22
21
 
@@ -0,0 +1,20 @@
1
+ // Single responsibility: the ONE predicate naming a string Postgres cannot store as written — the
2
+ // rule every string-backed validator (`t.string` and its kin, a `t.record` key, `t.json()`) shares,
3
+ // so the three can never disagree about which input reaches the row write.
4
+
5
+ const NUL = '\u0000';
6
+ /** A lone UTF-16 surrogate. `String#isWellFormed` is ES2024 and the lib is ES2023. */
7
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
8
+
9
+ /**
10
+ * Why a string cannot be stored, or `undefined`. Both MEASURED against Postgres 17: a NUL is
11
+ * refused by `text` and `jsonb` alike (22021 / 22P05), a lone surrogate by `jsonb` (22P02) — and
12
+ * into `text`, Bun's sql encodes it as U+FFFD, so the row holds a different string than the
13
+ * caller sent while a memory store holds the original. Passing either moved the failure to the
14
+ * row write, as a 500 with no field path. Names the fact, never the content (`describe-value.ts`).
15
+ */
16
+ export function unstorable(text: string): string | undefined {
17
+ if (text.includes(NUL)) return 'that contains a NUL character (U+0000)';
18
+ if (LONE_SURROGATE.test(text)) return 'that contains a lone UTF-16 surrogate';
19
+ return undefined;
20
+ }
package/src/validators.ts CHANGED
@@ -22,19 +22,17 @@ import { charCount } from './char-count';
22
22
  import { expected } from './describe-value';
23
23
  import { discriminatedUnionSchema } from './discriminated-union';
24
24
  import { isIsoDateTime, isZonelessDateTime } from './iso-date';
25
+ import { type JsonValue, jsonSchema } from './json-value';
25
26
  import { type MoneyValue, moneySchema } from './money-value';
26
27
  import type { SchemaNode } from './node';
27
28
  import { isPrototypeKey, PROTOTYPE_KEYS } from './prototype-keys';
28
29
  import type { InferInput, InferOutput, StandardIssue } from './standard';
29
30
  import { isIanaZoneName } from './time-zone-name';
31
+ import { unstorable } from './unstorable-text';
30
32
 
31
33
  const EMAIL_RE = /^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/;
32
34
  const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
33
35
  const CURSOR_RE = /^[A-Za-z0-9_-]+$/;
34
- /** The one code point no Postgres `text` or `jsonb` value can hold — see `stringLike`. */
35
- const NUL = '\u0000';
36
- /** Names the fact, never the content: the issue-message rule in `describe-value.ts`. */
37
- const NUL_REFUSAL = 'that contains a NUL character (U+0000)';
38
36
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
39
37
 
40
38
  export interface StringSchema extends Schema<string, string> {
@@ -89,11 +87,11 @@ function stringLike(node: SchemaNode, what: string, test?: (value: string) => bo
89
87
  const matchesPattern = patternTester(node);
90
88
  const check: Check<string> = (value, path) => {
91
89
  if (typeof value !== 'string') return fail(path, expected(what, value));
92
- // U+0000 is the one character Postgres cannot store: `text` and `jsonb` both refuse it
93
- // (SQLSTATE 22021 / 22P05), so a NUL that passed here reached the row write — or a `where`
94
- // bind — as `X_DB_STATEMENT_FAILED`, a 500 blaming the server for a byte the caller sent.
95
- // Only NUL: a tab, a newline or any other C0 control is legal text Postgres stores unchanged.
96
- if (value.includes(NUL)) return fail(path, `${expected(what, value)} ${NUL_REFUSAL}`);
90
+ // A NUL or a lone surrogate passed here reached the row write — or a `where` bind — as
91
+ // `X_DB_STATEMENT_FAILED`, a 500 blaming the server for what the caller sent (`unstorable`).
92
+ // Only those: a tab, a newline or any other C0 control is legal text Postgres stores unchanged.
93
+ const unfit = unstorable(value);
94
+ if (unfit !== undefined) return fail(path, `${expected(what, value)} ${unfit}`);
97
95
  if (node.minLength !== undefined && charCount(value) < node.minLength) {
98
96
  return fail(path, expected(`${what} of at least ${node.minLength} chars`, value));
99
97
  }
@@ -313,10 +311,11 @@ export function recordSchema<S extends AnySchema>(
313
311
  // new spelling to learn. It is `Object.entries` order — integer-like keys sort ahead of
314
312
  // string ones — so it names an entry that exists rather than a byte offset in the body.
315
313
  const at = [...path, index];
316
- // A record is stored as `jsonb` far more often than not, and jsonb refuses a NUL in a KEY
317
- // exactly as it does in a value — so the key is refused here, by position, not quoted.
318
- if (key.includes(NUL)) {
319
- issues.push({ message: `expected a record key, received one ${NUL_REFUSAL}`, path: at });
314
+ // A record is stored as `jsonb` far more often than not, and jsonb refuses an unstorable
315
+ // KEY exactly as it does a value — so the key is refused here, by position, not quoted.
316
+ const unfitKey = unstorable(key);
317
+ if (unfitKey !== undefined) {
318
+ issues.push({ message: `expected a record key, received one ${unfitKey}`, path: at });
320
319
  continue;
321
320
  }
322
321
  if (isPrototypeKey(key)) {
@@ -414,6 +413,8 @@ export interface TNamespace {
414
413
  readonly locale: StringSchema;
415
414
  readonly slug: StringSchema;
416
415
  readonly cursor: StringSchema;
416
+ /** Any JSON value, bounded in depth — a payload whose shape is somebody else's. */
417
+ json(): Schema<JsonValue, JsonValue>;
417
418
  object<S extends Shape>(shape: S): ObjectSchema<S>;
418
419
  array<S extends AnySchema>(items: S): Schema<readonly InferInput<S>[], InferOutput<S>[]>;
419
420
  enum<const V extends readonly [string, ...string[]]>(values: V): Schema<V[number], V[number]>;
@@ -468,6 +469,7 @@ export const builtinT: TNamespace = Object.freeze({
468
469
  { kind: 'string', format: 'cursor', pattern: CURSOR_RE.source },
469
470
  'an opaque base64url cursor',
470
471
  ),
472
+ json: jsonSchema,
471
473
  object: objectSchema,
472
474
  array: arraySchema,
473
475
  enum: enumSchema,
@@ -1,6 +1,6 @@
1
1
  // Single responsibility: the JSON Schema subset an MCP tool publishes, and the two narrowings onto
2
- // it — an input's and an output's. One home, tier 0, so `@ultimat3/action`'s `.tool()` and
3
- // `@ultimat3/mcp`'s `tools/list` publish ONE document for one declaration rather than two.
2
+ // it — an input's and an output's. One home, tier 0: `@ultimat3/mcp`'s `tools/list` is the one
3
+ // tool projection, and no second one may publish a different document for the same declaration.
4
4
 
5
5
  import type { JsonSchema } from './json-schema';
6
6
  import { toMcpInputSchema } from './json-schema';