@lunora/values 0.0.0 → 1.0.0-alpha.10

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.
@@ -0,0 +1,508 @@
1
+ import { LunoraError } from '@lunora/errors';
2
+ import { StandardSchemaV1 } from '@standard-schema/spec';
3
+ type ValidationPath = ReadonlyArray<number | string>;
4
+ /**
5
+ * Thrown by `validator.parse` (or returned inside `safeParse`) when input does
6
+ * not match the validator's shape. `path` walks from the root to the offending
7
+ * value, e.g. `["users", 0, "email"]`.
8
+ *
9
+ * A `LunoraError` subclass: carries `code: "VALIDATION_ERROR"` and `status: 400`
10
+ * so the runtime/DO transport mappers surface it structurally (a request that
11
+ * fails validation is a 400), while keeping the `name: "ValidationError"` and the
12
+ * `path`/`expected`/`received` diagnostics.
13
+ */
14
+ declare class ValidationError extends LunoraError {
15
+ readonly path: ValidationPath;
16
+ readonly expected: string;
17
+ readonly received: string;
18
+ constructor(message: string, options: {
19
+ expected: string;
20
+ path: ValidationPath;
21
+ received: string;
22
+ });
23
+ }
24
+ /**
25
+ * Render a short, diagnostic description of a runtime value for the `received`
26
+ * field of a {@link ValidationError}. Primitives carry their concrete (length-
27
+ * capped) literal so messages distinguish `string "7"` from `number 7`;
28
+ * non-plain objects carry their constructor name (e.g. `Date`) so a class
29
+ * instance is not flattened to a bare `"object"`.
30
+ *
31
+ * Pass `{ literal: false }` to suppress the concrete primitive literal and
32
+ * return only the type tag (`"string"`, `"number"`, `"bigint"`, …). This is used
33
+ * on `.check()` refinement failures — where the value already passed its type
34
+ * check — so a secret-bearing field (password, token) never surfaces its value
35
+ * in the `ValidationError.message`/`received` that goes to the wire and logs.
36
+ */
37
+ declare const describeValue: (value: unknown, options?: {
38
+ literal?: boolean;
39
+ }) => string;
40
+ declare const formatPath: (path: ValidationPath) => string;
41
+ /** Branded id type, e.g. `Id&lt;"users">`. */
42
+ type Id<TableName extends string> = string & {
43
+ readonly __table: TableName;
44
+ };
45
+ /**
46
+ * A JSON Schema fragment (Draft 2020-12 / OpenAPI 3.1 compatible). Intentionally
47
+ * a loose bag — a `.check()`/`.meta()` caller contributes keywords like
48
+ * `minLength`/`pattern`/`minimum` that `toJsonSchema` shallow-merges onto the
49
+ * node for the enclosing validator. Mirrors the `JsonSchema` shape exported by
50
+ * `./to-json-schema`; kept structurally identical and local so `v.ts` never
51
+ * imports the converter and the two files stay decoupled.
52
+ */
53
+ interface JsonSchemaFragment {
54
+ [keyword: string]: unknown;
55
+ }
56
+ /**
57
+ * Options for a {@link Validator.check} refinement. Lets a predicate carry both
58
+ * a human-facing `message` and an introspectable JSON Schema `schema` fragment
59
+ * (e.g. `{ minLength: 1 }`) so the constraint flows into `toJsonSchema`. The
60
+ * legacy `.check(pred, "message")` string form remains supported.
61
+ */
62
+ interface CheckOptions {
63
+ /** Failure message thrown on the `ValidationError` (default `"value matching refinement"`). */
64
+ message?: string;
65
+ /** JSON Schema fragment merged onto this validator's node by `toJsonSchema`. */
66
+ schema?: JsonSchemaFragment;
67
+ }
68
+ /**
69
+ * Options for {@link Validator.meta} — pure metadata with no runtime parsing
70
+ * effect, used to enrich the emitted JSON Schema node (description + constraint
71
+ * keywords) without attaching a predicate.
72
+ */
73
+ interface MetaOptions {
74
+ /** A human description merged onto this validator's JSON Schema node. */
75
+ description?: string;
76
+ /** JSON Schema fragment merged onto this validator's node by `toJsonSchema`. */
77
+ schema?: JsonSchemaFragment;
78
+ }
79
+ /**
80
+ * Runtime "kind" tag attached to every validator. Codegen and reflective tools
81
+ * use this to inspect the shape without crawling the closure.
82
+ */
83
+ type ValidatorKind = "any" | "array" | "bigint" | "boolean" | "bytes" | "date" | "from" | "geoPoint" | "id" | "literal" | "null" | "number" | "object" | "optional" | "record" | "storage" | "string" | "timestamp" | "union";
84
+ interface Validator<T = unknown> extends StandardSchemaV1<T, T> {
85
+ readonly __type: T;
86
+ /**
87
+ * Attach a refinement predicate. The returned validator parses with the
88
+ * original rules first; if the result satisfies `predicate` it passes
89
+ * through, otherwise it throws a {@link ValidationError} carrying
90
+ * `message` (default: `"value matching refinement"`). Multiple `.check()`
91
+ * calls chain — every predicate must return true.
92
+ *
93
+ * The second argument may be a plain message string (legacy form) or a
94
+ * {@link CheckOptions} object that additionally carries a JSON Schema
95
+ * `schema` fragment (e.g. `{ minLength: 1 }`) reflected by `toJsonSchema`.
96
+ *
97
+ * Works in any context — argument validators, column validators, or
98
+ * standalone — so it can encode invariants like
99
+ * `v.number().check(n => n >= 0)` or
100
+ * `v.string().check(s => s.length > 0, { message: "non-empty", schema: { minLength: 1 } })`.
101
+ */
102
+ check: (predicate: (value: T) => boolean, options?: CheckOptions | string) => Validator<T>;
103
+ readonly kind: ValidatorKind;
104
+ /**
105
+ * Attach pure metadata (description + JSON Schema constraint fragment) with
106
+ * no effect on runtime parsing. The fragment is shallow-merged onto this
107
+ * validator's emitted JSON Schema node, composing with any `.check()`
108
+ * `schema` fragments (later wins on conflicting keys).
109
+ */
110
+ meta: (options: MetaOptions) => Validator<T>;
111
+ parse: (value: unknown) => T;
112
+ safeParse: (value: unknown) => {
113
+ error: ValidationError;
114
+ ok: false;
115
+ } | {
116
+ ok: true;
117
+ value: T;
118
+ };
119
+ }
120
+ /** Extract the TS type a validator describes (the **select** type). */
121
+ type Infer<V> = V extends Validator<infer T> ? T : never;
122
+ /**
123
+ * Column constraints/defaults collected from the `v.*` modifier chain used
124
+ * inside `defineTable`. Inert in argument position. Persisted on the
125
+ * validator's internal `_meta.column` and mirrored into codegen IR.
126
+ */
127
+ interface ColumnMeta {
128
+ /** `.$defaultFn(fn)` — default factory; field is optional on insert. */
129
+ defaultFn?: () => unknown;
130
+ /** `.default(value)` — literal default; field is optional on insert. */
131
+ defaultValue?: unknown;
132
+ /** Default `true`; `.nullable()` flips it to `false`. */
133
+ notNull: boolean;
134
+ /** `.$onUpdateFn(fn)` — recomputed on every patch/replace. */
135
+ onUpdateFn?: () => unknown;
136
+ /**
137
+ * `.serverDefault(fn)` — a SERVER-trusted value factory. Unlike
138
+ * `.$defaultFn` (which only fills an absent field), this runs on every
139
+ * insert/update and SILENTLY OVERWRITES any client-supplied value with
140
+ * `fn({ auth })`, so the column is never client-controllable (e.g.
141
+ * `ownerId`/`tenantId` stamped from `auth.userId`). Field is optional on
142
+ * insert. The factory runs server-side with the resolved request auth.
143
+ */
144
+ serverDefault?: (context: ServerDefaultContext) => unknown;
145
+ /** `.unique()` — synthesizes a UNIQUE index. */
146
+ unique?: boolean;
147
+ }
148
+ /**
149
+ * Context handed to a `.serverDefault(fn)` factory at write time. Carries the
150
+ * resolved request identity so a column can be stamped from the caller
151
+ * (`auth.userId`) rather than trusted from the client. Structurally mirrors the
152
+ * `auth` slice of the server's procedure context without depending on
153
+ * `@lunora/server`.
154
+ */
155
+ interface ServerDefaultContext {
156
+ readonly auth: {
157
+ /** The raw identity claims, or `null` for the anonymous/no-resolver case. */
158
+ readonly identity: Record<string, unknown> | null;
159
+ /** The resolved caller id, or `null` when unauthenticated. */
160
+ readonly userId: null | string;
161
+ };
162
+ }
163
+ /**
164
+ * Phantom carrier of a column's select/insert types. Never present at runtime;
165
+ * `defineTable` reads it to derive `$inferSelect` / `$inferInsert`.
166
+ */
167
+ interface Column<TSelect, TInsert> {
168
+ /** Phantom carrier — type-only, never present at runtime. */
169
+ readonly __column: {
170
+ insert: TInsert;
171
+ select: TSelect;
172
+ };
173
+ }
174
+ /**
175
+ * A {@link Validator} carrying the chainable column-modifier API. The factories
176
+ * (`v.string()`, …) return this so modifiers are available inside `defineTable`.
177
+ * `TSelect` is the read type; `TInsert` is the write type (modifiers may make it
178
+ * `| undefined`, marking the field optional on insert).
179
+ */
180
+ interface ColumnValidator<TSelect, TInsert> extends Column<TSelect, TInsert>, Validator<TSelect> {
181
+ /** Default factory applied in the write layer; field becomes optional on insert. */
182
+ $defaultFn: (function_: () => TSelect) => ColumnValidator<TSelect, TInsert | undefined>;
183
+ /** Recompute the field on every patch/replace when not explicitly provided. */
184
+ $onUpdateFn: (function_: () => TSelect) => ColumnValidator<TSelect, TInsert>;
185
+ /** Override the inferred select/insert type without changing runtime parsing (e.g. `v.string().$type&lt;Id&lt;"users">>()`). */
186
+ $type: <TOverride>() => ColumnValidator<TOverride, TOverride>;
187
+ /** Refinement predicate run after parsing — see {@link Validator.check}. Chainable; preserves column modifiers. */
188
+ check: (predicate: (value: TSelect) => boolean, options?: CheckOptions | string) => ColumnValidator<TSelect, TInsert>;
189
+ /** Literal default applied in the write layer; field becomes optional on insert. */
190
+ default: (value: TSelect) => ColumnValidator<TSelect, TInsert | undefined>;
191
+ /** Attach JSON Schema metadata — see {@link Validator.meta}. Chainable; preserves column modifiers. */
192
+ meta: (options: MetaOptions) => ColumnValidator<TSelect, TInsert>;
193
+ /** Allow SQL NULL — widens the select type to `T | null`. */
194
+ nullable: () => ColumnValidator<null | TSelect, null | TInsert>;
195
+ /**
196
+ * Stamp this column SERVER-side from the request auth on every write,
197
+ * overwriting any client-supplied value. The field becomes optional on
198
+ * insert (the server fills it). Use for owner/tenant columns that must never
199
+ * be client-controllable — e.g. `v.string().serverDefault(({ auth }) => auth.userId)`.
200
+ */
201
+ serverDefault: (function_: (context: ServerDefaultContext) => TSelect) => ColumnValidator<TSelect, TInsert | undefined>;
202
+ /** Enforce a UNIQUE constraint (synthesizes a unique index). */
203
+ unique: () => ColumnValidator<TSelect, TInsert>;
204
+ }
205
+ /**
206
+ * A time-valued {@link ColumnValidator} (epoch milliseconds). Adds
207
+ * {@link TimestampColumnValidator.defaultNow} so the field can default to the
208
+ * insert-time clock.
209
+ */
210
+ interface TimestampColumnValidator extends ColumnValidator<number, number> {
211
+ /** Default to the current epoch-ms (`Date.now()`) at insert time; field becomes optional on insert. */
212
+ defaultNow: () => ColumnValidator<number, number | undefined>;
213
+ }
214
+ /** The type a validator/column presents on **select** (reads). */
215
+ type InferSelect<V> = V extends Validator<infer T> ? T : never;
216
+ /** The type a validator/column accepts on **insert** (writes). */
217
+ type InferInsert<V> = V extends Column<unknown, infer I> ? I : V extends Validator<infer T> ? T : never;
218
+ /** Derive the read shape of a table's column map. */
219
+ type SelectShape<S extends Record<string, Validator>> = { [K in keyof S]: InferSelect<S[K]>; };
220
+ /**
221
+ * Derive the write shape of a table's column map. Columns whose insert type
222
+ * includes `undefined` (via `.default()` / `.$defaultFn()` / `v.optional`)
223
+ * become optional keys.
224
+ */
225
+ type InsertShape<S extends Record<string, Validator>> = { [K in keyof S as undefined extends InferInsert<S[K]> ? K : never]?: Exclude<InferInsert<S[K]>, undefined>; } & { [K in keyof S as undefined extends InferInsert<S[K]> ? never : K]: InferInsert<S[K]>; };
226
+ declare const string: () => ColumnValidator<string, string>;
227
+ declare const number: () => ColumnValidator<number, number>;
228
+ /** Epoch-millisecond timestamp (`number`). Pair with `.defaultNow()` for an insert-time clock. */
229
+ declare const timestamp: () => TimestampColumnValidator;
230
+ /** Calendar date stored as an epoch-millisecond `number`. Pair with `.defaultNow()` for an insert-time clock. */
231
+ declare const date: () => TimestampColumnValidator;
232
+ declare const boolean: () => ColumnValidator<boolean, boolean>;
233
+ declare const bigintValidator: () => ColumnValidator<bigint, bigint>;
234
+ declare const nullValidator: () => ColumnValidator<null, null>;
235
+ declare const bytes: () => ColumnValidator<ArrayBuffer, ArrayBuffer>;
236
+ declare const id: <TableName extends string>(tableName: TableName) => ColumnValidator<Id<TableName>, Id<TableName>>;
237
+ /**
238
+ * A reference to a stored R2 object: the column holds the object's **key** (a
239
+ * string), the same key `@lunora/storage` puts/gets by. Functionally it parses
240
+ * like `v.string()`, but the distinct `"storage"` kind lets codegen and the
241
+ * studio join the data model to R2 — the file browser uses it to show which
242
+ * record owns a file and to flag orphaned objects no row references. The
243
+ * optional `bucket` names the typed bucket the key lives in (for app-context
244
+ * signed URLs); omit it for the app's default bucket.
245
+ */
246
+ declare const storage: (bucket?: string) => ColumnValidator<string, string>;
247
+ /**
248
+ * A geographic point — latitude/longitude in decimal degrees (WGS84). The value
249
+ * a `v.geoPoint()` column reads/writes. Stored as a JSON object alongside the
250
+ * row; a `.geoIndex(name, { field })` on the table maintains a geohash companion
251
+ * so `withGeoIndex(name, q => q.near(point, radius) | q.within(bbox))` can answer
252
+ * proximity/bounding-box reads.
253
+ */
254
+ interface GeoPoint {
255
+ /** Latitude in decimal degrees, `-90 … 90`. */
256
+ lat: number;
257
+ /** Longitude in decimal degrees, `-180 … 180`. */
258
+ lng: number;
259
+ }
260
+ /**
261
+ * A latitude/longitude point (WGS84 decimal degrees). Parses an object with
262
+ * finite `lat` ∈ `[-90, 90]` and `lng` ∈ `[-180, 180]`; any other shape or an
263
+ * out-of-range coordinate throws a {@link ValidationError}. Pair with a table's
264
+ * `.geoIndex(name, { field })` to enable `near` / `within` reads.
265
+ */
266
+ declare const geoPoint: () => ColumnValidator<GeoPoint, GeoPoint>;
267
+ declare const literal: <T extends bigint | boolean | number | string | null>(literalValue: T) => ColumnValidator<T, T>;
268
+ declare const array: <V extends Validator>(inner: V) => ColumnValidator<Infer<V>[], Infer<V>[]>;
269
+ /**
270
+ * Split a value-type map into optional + required keys: any member whose value
271
+ * type includes `undefined` becomes an optional key. The single optionality rule
272
+ * shared by object-shape inference ({@link ObjectShapeType}) and args-map
273
+ * inference (`InferValidatorMap` in `./validator-map`), so the two can never
274
+ * drift. (`InsertShape` stays separate — it additionally `Exclude`s `undefined`
275
+ * from the optional value, a deliberate insert-type difference.)
276
+ */
277
+ type OptionalizeShape<M> = { [K in keyof M as undefined extends M[K] ? K : never]?: M[K]; } & { [K in keyof M as undefined extends M[K] ? never : K]: M[K]; };
278
+ type ObjectShape = Record<string, Validator>;
279
+ type ObjectShapeType<S extends ObjectShape> = OptionalizeShape<{ [K in keyof S]: Infer<S[K]>; }>;
280
+ declare const objectValidator: <S extends ObjectShape>(shape: S) => ColumnValidator<ObjectShapeType<S>, ObjectShapeType<S>>;
281
+ declare const record: <K extends Validator<string>, V extends Validator>(keyValidator: K, valueValidator: V) => ColumnValidator<Record<Infer<K>, Infer<V>>, Record<Infer<K>, Infer<V>>>;
282
+ declare const union: <Vs extends ReadonlyArray<Validator>>(...members: Vs) => ColumnValidator<Infer<Vs[number]>, Infer<Vs[number]>>;
283
+ declare const optional: <V extends Validator>(inner: V) => ColumnValidator<Infer<V> | undefined, Infer<V> | undefined>;
284
+ declare const any: () => ColumnValidator<unknown, unknown>;
285
+ /**
286
+ * Infer the output type of a Standard Schema v1 object. When the schema omits
287
+ * `~standard.types` (it is optional in the spec), falls back to `unknown` so
288
+ * callers always get a usable type rather than `never`.
289
+ */
290
+ type InferStandardOutput<S extends StandardSchemaV1> = S["~standard"]["types"] extends {
291
+ output: infer O;
292
+ } ? O : unknown;
293
+ /**
294
+ * Wrap any Standard Schema v1 validator (`zod`, `valibot`, `arktype`, …) so it
295
+ * can be used as an **args** validator in `query`/`mutation`/`action`. The
296
+ * wrapped validator's output type is inferred from `~standard.types.output`
297
+ * when declared; falls back to `unknown` when the schema omits the types field.
298
+ *
299
+ * **Args-only.** `v.from(...)` validators must not be used as table columns —
300
+ * `defineTable` checks the `kind` and throws a clear error if you try.
301
+ *
302
+ * **Sync-only.** Standard Schema allows async `validate`; Lunora args
303
+ * validation is synchronous and throws when a Promise is returned.
304
+ */
305
+ declare const from: <S extends StandardSchemaV1>(schema: S) => ColumnValidator<InferStandardOutput<S>, InferStandardOutput<S>>;
306
+ /**
307
+ * True when `validator` is `v.from(...)` or structurally wraps one through
308
+ * `v.optional` / `v.array` / `v.object` / `v.record` / `v.union`. `defineTable`
309
+ * uses it to reject Standard-Schema-backed validators anywhere in a column —
310
+ * not just at the top level — since they are args-only and have no SQL column
311
+ * type. The nested children live on the validator's `_meta` (`inner`, `shape`,
312
+ * `members`, `keyValidator`/`valueValidator`) and are themselves validators.
313
+ */
314
+ declare const isOrWrapsFromValidator: (validator: Validator) => boolean;
315
+ /**
316
+ * The inner validator wrapped by `v.optional(inner)`, or `undefined` for any
317
+ * other validator. The nested child lives on the validator's internal `_meta`
318
+ * bag; this accessor keeps that knowledge inside `@lunora/values` (the package
319
+ * that owns validator internals) so consumers don't reach into `_meta`
320
+ * themselves. Used by `@lunora/server`'s `defineEnv` to coerce through a leading
321
+ * `v.optional(...)`.
322
+ * @returns The inner validator if `v.optional(...)`, otherwise `undefined`.
323
+ */
324
+ declare const optionalInner: (validator: Validator) => Validator | undefined;
325
+ /**
326
+ * Validator/codec namespace. Each factory returns a {@link Validator} with a
327
+ * runtime `parse`/`safeParse` plus a phantom `__type` field for inference.
328
+ */
329
+ declare const v: {
330
+ any: typeof any;
331
+ array: typeof array;
332
+ bigint: typeof bigintValidator;
333
+ boolean: typeof boolean;
334
+ bytes: typeof bytes;
335
+ date: typeof date;
336
+ from: typeof from;
337
+ geoPoint: typeof geoPoint;
338
+ id: typeof id;
339
+ literal: typeof literal;
340
+ null: typeof nullValidator;
341
+ number: typeof number;
342
+ object: typeof objectValidator;
343
+ optional: typeof optional;
344
+ record: typeof record;
345
+ storage: typeof storage;
346
+ string: typeof string;
347
+ timestamp: typeof timestamp;
348
+ union: typeof union;
349
+ };
350
+ /**
351
+ * A JSON Schema node (Draft 2020-12 / OpenAPI 3.1 compatible). Intentionally a
352
+ * loose bag — Lunora only emits a known subset, but consumers (OpenAPI/OpenRPC
353
+ * builders, Swagger UI, form generators) treat it as an opaque schema object.
354
+ */
355
+ interface JsonSchema {
356
+ [keyword: string]: unknown;
357
+ }
358
+ /**
359
+ * Structural reader over a validator-like node. The shared mapping algorithm
360
+ * ({@link jsonSchemaFromNode}) is parameterized by this interface so the same
361
+ * switch/recursion serves both inputs Lunora maps to JSON Schema: the runtime
362
+ * `@lunora/values` validator (children + metadata live on `_meta`), and the
363
+ * build-time validator IR consumed by codegen (children are plain fields, with
364
+ * no runtime metadata — so `constraints`/`isNullable` may be inert there).
365
+ *
366
+ * A reader normalizes a `TNode` to the small set of children/leaves the mapper
367
+ * recurses over. Composite accessors (`inner`/`shape`/`members`/`valueChild`)
368
+ * return the same `TNode` type so the mapper can recurse uniformly; leaf concerns
369
+ * that differ between the two sources — how a literal's `const` is computed,
370
+ * whether a `.check()`/`.meta()` constraint fragment exists, whether `.nullable()`
371
+ * was applied — are delegated wholesale to the reader.
372
+ */
373
+ interface SchemaNodeReader<TNode> {
374
+ /**
375
+ * The `.check()`/`.meta()` JSON Schema fragment to shallow-merge onto the
376
+ * node, or `undefined` when none (the IR side never carries one). Constraint
377
+ * keys win over the base on conflict so a refinement can tighten — never
378
+ * silently weaken — the schema.
379
+ */
380
+ constraints: (node: TNode) => JsonSchema | undefined;
381
+ /** Inner child of an `array`/`optional` node. May be absent on the IR side. */
382
+ inner: (node: TNode) => TNode | undefined;
383
+ /** Whether `.nullable()` was applied (runtime: `_meta.column.notNull === false`). */
384
+ isNullable: (node: TNode) => boolean;
385
+ /** Discriminating validator kind. */
386
+ kind: (node: TNode) => ValidatorKind;
387
+ /**
388
+ * The JSON Schema `const` fragment for a `literal` node. Computed differently
389
+ * per source — runtime reads the live `_meta.value`; the IR parses verbatim
390
+ * source text — so the reader owns it entirely.
391
+ */
392
+ literalSchema: (node: TNode) => JsonSchema;
393
+ /** Member nodes of a `union`. */
394
+ members: (node: TNode) => ReadonlyArray<TNode>;
395
+ /** Property nodes of an `object`, keyed by property name. */
396
+ shape: (node: TNode) => Record<string, TNode>;
397
+ /** Target table name of an `id` node. */
398
+ tableName: (node: TNode) => unknown;
399
+ /** Value-child of a `record` node. May be absent on the IR side. */
400
+ valueChild: (node: TNode) => TNode | undefined;
401
+ }
402
+ /**
403
+ * The single validator→JSON-Schema mapping algorithm, shared by the runtime
404
+ * `toJsonSchema` (over `@lunora/values` validators) and codegen's IR-backed
405
+ * mapper. It walks a node recursively via the supplied {@link SchemaNodeReader},
406
+ * so nested objects/arrays/unions/records are fully expanded (never collapsed to
407
+ * one level).
408
+ *
409
+ * `date`/`timestamp` are epoch-millisecond numbers in Lunora (not ISO strings),
410
+ * so they schema as integers; `bigint` schemas as an int64 (JSON has no bigint
411
+ * type, so `format: int64` is the conventional OpenAPI carrier); `bytes` is an
412
+ * `ArrayBuffer`, surfaced as base64 per JSON Schema 2020-12 content encoding.
413
+ *
414
+ * A `.check()`/`.meta()` JSON Schema fragment (when the reader exposes one) is
415
+ * shallow-merged onto the node — constraint keys win on conflict. A `.nullable()`
416
+ * node widens to also accept `null`; constraints describe the underlying value,
417
+ * so they ride inside the non-null branch rather than on the wrapping `anyOf`.
418
+ */
419
+ declare const jsonSchemaFromNode: <TNode>(node: TNode, reader: SchemaNodeReader<TNode>) => JsonSchema;
420
+ /**
421
+ * Build `{ type: "object", properties, required, additionalProperties: false }`
422
+ * from a node shape. A `v.optional(...)` property is the only thing that drops
423
+ * out of `required`; every other property is required.
424
+ */
425
+ declare const objectSchemaFromNodes: <TNode>(shape: Record<string, TNode>, reader: SchemaNodeReader<TNode>) => JsonSchema;
426
+ /**
427
+ * Convert a single `@lunora/values` validator to a JSON Schema node (Draft
428
+ * 2020-12 / OpenAPI 3.1). A thin wrapper over the shared {@link jsonSchemaFromNode}
429
+ * core with the runtime {@link validatorReader}; see that core for the full
430
+ * kind→schema mapping (date/timestamp → epoch-ms integer, bigint → int64, bytes →
431
+ * base64, id → annotated string, literal → `const`, optionality via the parent
432
+ * `required` list, `.nullable()` widening, `.check()`/`.meta()` constraint merge).
433
+ */
434
+ declare const toJsonSchema: (validator: Validator) => JsonSchema;
435
+ /**
436
+ * Convert a function's argument validators (a name-to-validator map) into a
437
+ * single JSON Schema object. Non-`optional` arguments are `required`; the result
438
+ * is the request `params`/`args` schema an OpenAPI operation or OpenRPC method
439
+ * advertises. An empty arg map yields an empty (but valid) object schema.
440
+ */
441
+ declare const argsToJsonSchema: (args: Record<string, Validator>) => JsonSchema;
442
+ /** Map of validators describing a record of named fields (a function's args, a step's args, an HTTP query/body/params). */
443
+ type ValidatorMap = Record<string, Validator>;
444
+ /**
445
+ * Infer the object type from a {@link ValidatorMap} — optional validators
446
+ * (`v.optional`) become optional keys. Shares the single optionality rule with
447
+ * `ObjectShapeType` via {@link OptionalizeShape}, so args-map and object-shape
448
+ * inference can never drift.
449
+ */
450
+ type InferValidatorMap<A extends ValidatorMap> = OptionalizeShape<{ [K in keyof A]: Infer<A[K]>; }>;
451
+ /**
452
+ * A precompiled fast-path parser for one {@link ValidatorMap}. Returns the fully
453
+ * built, validated record on a confident success, or the {@link DEFER_VALIDATION}
454
+ * sentinel to hand the input back to the interpreted parser.
455
+ *
456
+ * The contract is soundness, not completeness: a compiled parser may return
457
+ * {@link DEFER_VALIDATION} for any input it is not certain about (the interpreted
458
+ * path then runs and either succeeds or throws the canonical error), but it must
459
+ * NEVER return a built record for input the interpreted parser would reject, and
460
+ * the record it returns must be byte-for-byte what the interpreted parser would
461
+ * have produced. This lets `@lunora/codegen` emit zero-allocation structural
462
+ * checks (the common case) while every error message and every tricky validator
463
+ * still flows through the single interpreted implementation below — so error
464
+ * contracts can never drift.
465
+ *
466
+ * The `source` parameter is intentionally `any`: the codegen-emitted body is
467
+ * plain JavaScript (no type annotations — it must also be loadable via
468
+ * `new Function` in the compiler's differential tests) that index-walks the input
469
+ * to arbitrary depth, which strict TypeScript forbids on `unknown`/`object`. An
470
+ * `any` input lets the emitted structural checks type-check cleanly while the
471
+ * RESULT stays strongly typed; soundness is enforced by the differential test
472
+ * harness, not the input type.
473
+ */
474
+ type CompiledValidatorMap = (source: any) => Record<string, unknown> | typeof DEFER_VALIDATION;
475
+ /**
476
+ * Sentinel a {@link CompiledValidatorMap} returns to defer to the interpreted
477
+ * parser. A unique symbol (never a valid parse result — {@link parseValidatorMap}
478
+ * always yields a record) so the seam can distinguish "compiled handled it" from
479
+ * "compiled bailed" with a single identity check and no per-call allocation.
480
+ */
481
+ declare const DEFER_VALIDATION: unique symbol;
482
+ /**
483
+ * Install a compiled fast-path parser for `validators`. Idempotent-ish: a second
484
+ * install overwrites the first (codegen emits each map once, so this only matters
485
+ * if a host installs by hand). See {@link CompiledValidatorMap} for the contract
486
+ * the parser must honour.
487
+ */
488
+ declare const installCompiledValidatorMap: (validators: object, compiled: CompiledValidatorMap) => void;
489
+ /**
490
+ * Validate each declared field of `source` through its validator, re-wrapping
491
+ * any {@link ValidationError} with a `label.&lt;key>:` prefix and the rebuilt path
492
+ * `[key, ...error.path]` so the failure points at the offending field. Optional
493
+ * fields absent from the source are skipped (so `v.optional` passes and a
494
+ * required validator fails on `undefined`).
495
+ *
496
+ * The single arg-/field-parsing implementation shared across the framework — the
497
+ * procedure builder (label `args`), the HTTP route builder (`searchParams` /
498
+ * `body` / `params`), and `@lunora/workflow`'s reusable steps (`step args`) — so
499
+ * the error-prefixing and optional-skip semantics can't drift apart. The `label`
500
+ * is the only thing each caller varies.
501
+ *
502
+ * When a codegen-emitted {@link CompiledValidatorMap} is installed for this exact
503
+ * `validators` object, the fast path runs first; it either returns the finished
504
+ * record (a confident success — the common case) or {@link DEFER_VALIDATION}, in
505
+ * which case the interpreted loop below runs and owns the result (and any error).
506
+ */
507
+ declare const parseValidatorMap: (validators: ValidatorMap, source: Record<string, unknown>, label: string) => Record<string, unknown>;
508
+ export { type CheckOptions, type Column, type ColumnMeta, type ColumnValidator, type CompiledValidatorMap, DEFER_VALIDATION, type GeoPoint, type Id, type Infer, type InferInsert, type InferSelect, type InferStandardOutput, type InferValidatorMap, type InsertShape, type JsonSchema, type JsonSchemaFragment, type MetaOptions, type SchemaNodeReader, type SelectShape, type ServerDefaultContext, type TimestampColumnValidator, ValidationError, type ValidationPath, type Validator, type ValidatorKind, type ValidatorMap, argsToJsonSchema, describeValue, formatPath, installCompiledValidatorMap, isOrWrapsFromValidator, jsonSchemaFromNode, objectSchemaFromNodes, optionalInner, parseValidatorMap, toJsonSchema, v };
package/dist/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ export { ValidationError, describeValue, formatPath } from './packem_shared/ValidationError-CoyFtkxj.mjs';
2
+ export { jsonSchemaFromNode, objectSchemaFromNodes } from './packem_shared/jsonSchemaFromNode-e81rO5qr.mjs';
3
+ export { argsToJsonSchema, toJsonSchema } from './packem_shared/argsToJsonSchema-DSAZmlYY.mjs';
4
+ export { isOrWrapsFromValidator, optionalInner, v } from './packem_shared/isOrWrapsFromValidator-Cxpmyfut.mjs';
5
+ export { DEFER_VALIDATION, installCompiledValidatorMap, parseValidatorMap } from './packem_shared/DEFER_VALIDATION-CIKr17sW.mjs';
@@ -0,0 +1,42 @@
1
+ import { ValidationError } from './ValidationError-CoyFtkxj.mjs';
2
+
3
+ const DEFER_VALIDATION = /* @__PURE__ */ Symbol("lunora.deferValidation");
4
+ const COMPILED_PARSERS = /* @__PURE__ */ new WeakMap();
5
+ const installCompiledValidatorMap = (validators, compiled) => {
6
+ COMPILED_PARSERS.set(validators, compiled);
7
+ };
8
+ const parseValidatorMap = (validators, source, label) => {
9
+ const compiled = COMPILED_PARSERS.get(validators);
10
+ if (compiled !== void 0) {
11
+ const fast = compiled(source);
12
+ if (fast !== DEFER_VALIDATION) {
13
+ return fast;
14
+ }
15
+ }
16
+ const out = {};
17
+ for (const key of Object.keys(validators)) {
18
+ const validator = validators[key];
19
+ if (!validator) {
20
+ continue;
21
+ }
22
+ const candidate = Object.hasOwn(source, key) ? source[key] : void 0;
23
+ if (candidate === void 0 && validator.kind === "optional") {
24
+ continue;
25
+ }
26
+ try {
27
+ out[key] = validator.parse(candidate);
28
+ } catch (error) {
29
+ if (error instanceof ValidationError) {
30
+ throw new ValidationError(`${label}.${key}: ${error.message}`, {
31
+ expected: error.expected,
32
+ path: [key, ...error.path],
33
+ received: error.received
34
+ });
35
+ }
36
+ throw error;
37
+ }
38
+ }
39
+ return out;
40
+ };
41
+
42
+ export { DEFER_VALIDATION, installCompiledValidatorMap, parseValidatorMap };
@@ -0,0 +1,65 @@
1
+ import { LunoraError } from '@lunora/errors';
2
+
3
+ const MAX_DESCRIBED_LENGTH = 80;
4
+ const truncate = (text) => text.length > MAX_DESCRIBED_LENGTH ? `${text.slice(0, MAX_DESCRIBED_LENGTH)}…` : text;
5
+ const describeObject = (value) => {
6
+ try {
7
+ const { constructor } = value;
8
+ const constructorName = constructor?.name;
9
+ if (constructorName !== void 0 && constructorName !== "Object") {
10
+ return `object ${constructorName}`;
11
+ }
12
+ } catch {
13
+ return "object";
14
+ }
15
+ return "object";
16
+ };
17
+ class ValidationError extends LunoraError {
18
+ path;
19
+ expected;
20
+ received;
21
+ constructor(message, options) {
22
+ super("VALIDATION_ERROR", message, { name: "ValidationError" });
23
+ this.path = options.path;
24
+ this.expected = options.expected;
25
+ this.received = options.received;
26
+ }
27
+ }
28
+ const describeValue = (value, options) => {
29
+ const literal = options?.literal ?? true;
30
+ if (value === null) {
31
+ return "null";
32
+ }
33
+ if (Array.isArray(value)) {
34
+ return "array";
35
+ }
36
+ if (value instanceof ArrayBuffer) {
37
+ return "ArrayBuffer";
38
+ }
39
+ if (typeof value === "string") {
40
+ return literal ? `string ${truncate(JSON.stringify(value))}` : "string";
41
+ }
42
+ if (typeof value === "number" || typeof value === "boolean") {
43
+ return literal ? `${typeof value} ${String(value)}` : typeof value;
44
+ }
45
+ if (typeof value === "bigint") {
46
+ return literal ? `bigint ${value.toString()}n` : "bigint";
47
+ }
48
+ if (typeof value === "object") {
49
+ return describeObject(value);
50
+ }
51
+ return typeof value;
52
+ };
53
+ const formatPath = (path) => {
54
+ if (path.length === 0) {
55
+ return "<root>";
56
+ }
57
+ return path.map((segment, index) => {
58
+ if (typeof segment === "number") {
59
+ return `[${String(segment)}]`;
60
+ }
61
+ return index === 0 ? segment : `.${segment}`;
62
+ }).join("");
63
+ };
64
+
65
+ export { ValidationError, describeValue, formatPath };
@@ -0,0 +1,22 @@
1
+ import { objectSchemaFromNodes, jsonSchemaFromNode } from './jsonSchemaFromNode-e81rO5qr.mjs';
2
+
3
+ const introspect = (validator) => validator;
4
+ const metaOf = (validator) => introspect(validator)._meta ?? {};
5
+ const validatorReader = {
6
+ constraints: (validator) => metaOf(validator).constraints,
7
+ inner: (validator) => metaOf(validator).inner,
8
+ isNullable: (validator) => metaOf(validator).column?.notNull === false,
9
+ kind: (validator) => validator.kind,
10
+ literalSchema: (validator) => {
11
+ const { value } = metaOf(validator);
12
+ return typeof value === "bigint" ? { const: value.toString(), type: "string" } : { const: value };
13
+ },
14
+ members: (validator) => metaOf(validator).members,
15
+ shape: (validator) => metaOf(validator).shape,
16
+ tableName: (validator) => metaOf(validator).tableName,
17
+ valueChild: (validator) => metaOf(validator).valueValidator
18
+ };
19
+ const toJsonSchema = (validator) => jsonSchemaFromNode(validator, validatorReader);
20
+ const argsToJsonSchema = (args) => objectSchemaFromNodes(args, validatorReader);
21
+
22
+ export { argsToJsonSchema, toJsonSchema };