@vielzeug/spell 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -0
- package/dist/_dev.cjs +2 -0
- package/dist/_dev.cjs.map +1 -0
- package/dist/_dev.d.ts +2 -0
- package/dist/_dev.d.ts.map +1 -0
- package/dist/_dev.js +2 -0
- package/dist/_dev.js.map +1 -0
- package/dist/core.cjs +2 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.d.ts +108 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +2 -0
- package/dist/core.js.map +1 -0
- package/dist/errors.cjs +3 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.ts +53 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +3 -0
- package/dist/errors.js.map +1 -0
- package/dist/formats.cjs +2 -0
- package/dist/formats.cjs.map +1 -0
- package/dist/formats.d.ts +41 -0
- package/dist/formats.d.ts.map +1 -0
- package/dist/formats.js +2 -0
- package/dist/formats.js.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1 -0
- package/dist/json-schema.cjs +2 -0
- package/dist/json-schema.cjs.map +1 -0
- package/dist/json-schema.d.ts +15 -0
- package/dist/json-schema.d.ts.map +1 -0
- package/dist/json-schema.js +2 -0
- package/dist/json-schema.js.map +1 -0
- package/dist/messages.cjs +2 -0
- package/dist/messages.cjs.map +1 -0
- package/dist/messages.d.ts +228 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +2 -0
- package/dist/messages.js.map +1 -0
- package/dist/s.cjs +2 -0
- package/dist/s.cjs.map +1 -0
- package/dist/s.d.ts +65 -0
- package/dist/s.d.ts.map +1 -0
- package/dist/s.js +2 -0
- package/dist/s.js.map +1 -0
- package/dist/safe-object.cjs +2 -0
- package/dist/safe-object.cjs.map +1 -0
- package/dist/safe-object.d.ts +6 -0
- package/dist/safe-object.d.ts.map +1 -0
- package/dist/safe-object.js +2 -0
- package/dist/safe-object.js.map +1 -0
- package/dist/schemas/array.cjs +2 -0
- package/dist/schemas/array.cjs.map +1 -0
- package/dist/schemas/array.d.ts +49 -0
- package/dist/schemas/array.d.ts.map +1 -0
- package/dist/schemas/array.js +2 -0
- package/dist/schemas/array.js.map +1 -0
- package/dist/schemas/bigint.cjs +2 -0
- package/dist/schemas/bigint.cjs.map +1 -0
- package/dist/schemas/bigint.d.ts +42 -0
- package/dist/schemas/bigint.d.ts.map +1 -0
- package/dist/schemas/bigint.js +2 -0
- package/dist/schemas/bigint.js.map +1 -0
- package/dist/schemas/boolean.cjs +2 -0
- package/dist/schemas/boolean.cjs.map +1 -0
- package/dist/schemas/boolean.d.ts +18 -0
- package/dist/schemas/boolean.d.ts.map +1 -0
- package/dist/schemas/boolean.js +2 -0
- package/dist/schemas/boolean.js.map +1 -0
- package/dist/schemas/date.cjs +2 -0
- package/dist/schemas/date.cjs.map +1 -0
- package/dist/schemas/date.d.ts +25 -0
- package/dist/schemas/date.d.ts.map +1 -0
- package/dist/schemas/date.js +2 -0
- package/dist/schemas/date.js.map +1 -0
- package/dist/schemas/enum.cjs +2 -0
- package/dist/schemas/enum.cjs.map +1 -0
- package/dist/schemas/enum.d.ts +14 -0
- package/dist/schemas/enum.d.ts.map +1 -0
- package/dist/schemas/enum.js +2 -0
- package/dist/schemas/enum.js.map +1 -0
- package/dist/schemas/instanceof.cjs +2 -0
- package/dist/schemas/instanceof.cjs.map +1 -0
- package/dist/schemas/instanceof.d.ts +11 -0
- package/dist/schemas/instanceof.d.ts.map +1 -0
- package/dist/schemas/instanceof.js +2 -0
- package/dist/schemas/instanceof.js.map +1 -0
- package/dist/schemas/intersect.cjs +2 -0
- package/dist/schemas/intersect.cjs.map +1 -0
- package/dist/schemas/intersect.d.ts +16 -0
- package/dist/schemas/intersect.d.ts.map +1 -0
- package/dist/schemas/intersect.js +2 -0
- package/dist/schemas/intersect.js.map +1 -0
- package/dist/schemas/lazy.cjs +2 -0
- package/dist/schemas/lazy.cjs.map +1 -0
- package/dist/schemas/lazy.d.ts +16 -0
- package/dist/schemas/lazy.d.ts.map +1 -0
- package/dist/schemas/lazy.js +2 -0
- package/dist/schemas/lazy.js.map +1 -0
- package/dist/schemas/literal.cjs +2 -0
- package/dist/schemas/literal.cjs.map +1 -0
- package/dist/schemas/literal.d.ts +11 -0
- package/dist/schemas/literal.d.ts.map +1 -0
- package/dist/schemas/literal.js +2 -0
- package/dist/schemas/literal.js.map +1 -0
- package/dist/schemas/map.cjs +2 -0
- package/dist/schemas/map.cjs.map +1 -0
- package/dist/schemas/map.d.ts +29 -0
- package/dist/schemas/map.d.ts.map +1 -0
- package/dist/schemas/map.js +2 -0
- package/dist/schemas/map.js.map +1 -0
- package/dist/schemas/never.cjs +2 -0
- package/dist/schemas/never.cjs.map +1 -0
- package/dist/schemas/never.d.ts +10 -0
- package/dist/schemas/never.d.ts.map +1 -0
- package/dist/schemas/never.js +2 -0
- package/dist/schemas/never.js.map +1 -0
- package/dist/schemas/number.cjs +2 -0
- package/dist/schemas/number.cjs.map +1 -0
- package/dist/schemas/number.d.ts +50 -0
- package/dist/schemas/number.d.ts.map +1 -0
- package/dist/schemas/number.js +2 -0
- package/dist/schemas/number.js.map +1 -0
- package/dist/schemas/object.cjs +2 -0
- package/dist/schemas/object.cjs.map +1 -0
- package/dist/schemas/object.d.ts +95 -0
- package/dist/schemas/object.d.ts.map +1 -0
- package/dist/schemas/object.js +2 -0
- package/dist/schemas/object.js.map +1 -0
- package/dist/schemas/pipe.d.ts +2 -0
- package/dist/schemas/pipe.d.ts.map +1 -0
- package/dist/schemas/raw-or.cjs +2 -0
- package/dist/schemas/raw-or.cjs.map +1 -0
- package/dist/schemas/raw-or.d.ts +17 -0
- package/dist/schemas/raw-or.d.ts.map +1 -0
- package/dist/schemas/raw-or.js +2 -0
- package/dist/schemas/raw-or.js.map +1 -0
- package/dist/schemas/record.cjs +2 -0
- package/dist/schemas/record.cjs.map +1 -0
- package/dist/schemas/record.d.ts +16 -0
- package/dist/schemas/record.d.ts.map +1 -0
- package/dist/schemas/record.js +2 -0
- package/dist/schemas/record.js.map +1 -0
- package/dist/schemas/set.cjs +2 -0
- package/dist/schemas/set.cjs.map +1 -0
- package/dist/schemas/set.d.ts +28 -0
- package/dist/schemas/set.d.ts.map +1 -0
- package/dist/schemas/set.js +2 -0
- package/dist/schemas/set.js.map +1 -0
- package/dist/schemas/string.cjs +2 -0
- package/dist/schemas/string.cjs.map +1 -0
- package/dist/schemas/string.d.ts +155 -0
- package/dist/schemas/string.d.ts.map +1 -0
- package/dist/schemas/string.js +2 -0
- package/dist/schemas/string.js.map +1 -0
- package/dist/schemas/tuple.cjs +2 -0
- package/dist/schemas/tuple.cjs.map +1 -0
- package/dist/schemas/tuple.d.ts +22 -0
- package/dist/schemas/tuple.d.ts.map +1 -0
- package/dist/schemas/tuple.js +2 -0
- package/dist/schemas/tuple.js.map +1 -0
- package/dist/schemas/union.cjs +2 -0
- package/dist/schemas/union.cjs.map +1 -0
- package/dist/schemas/union.d.ts +13 -0
- package/dist/schemas/union.d.ts.map +1 -0
- package/dist/schemas/union.js +2 -0
- package/dist/schemas/union.js.map +1 -0
- package/dist/schemas/variant.cjs +2 -0
- package/dist/schemas/variant.cjs.map +1 -0
- package/dist/schemas/variant.d.ts +26 -0
- package/dist/schemas/variant.d.ts.map +1 -0
- package/dist/schemas/variant.js +2 -0
- package/dist/schemas/variant.js.map +1 -0
- package/dist/spell.cjs +3 -0
- package/dist/spell.cjs.map +1 -0
- package/dist/spell.iife.js +3 -0
- package/dist/spell.iife.js.map +1 -0
- package/dist/spell.js +3 -0
- package/dist/spell.js.map +1 -0
- package/dist/types.cjs +2 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.ts +326 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/validators.cjs +2 -0
- package/dist/validators.cjs.map +1 -0
- package/dist/validators.d.ts +20 -0
- package/dist/validators.d.ts.map +1 -0
- package/dist/validators.js +2 -0
- package/dist/validators.js.map +1 -0
- package/package.json +43 -0
package/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# @vielzeug/spell
|
|
2
|
+
|
|
3
|
+
> Zero-dependency schema validation library with strict-by-default objects, unified sync/async `validate()`, coercion, flexible schema composition, and full TypeScript inference.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@vielzeug/spell) [](https://opensource.org/licenses/MIT)
|
|
6
|
+
|
|
7
|
+
<details>
|
|
8
|
+
<summary>Quick Reference</summary>
|
|
9
|
+
|
|
10
|
+
**Package:** `@vielzeug/spell` · **Category:** Validation
|
|
11
|
+
|
|
12
|
+
**Key exports:** `s`, `SpellValidationError`, `setMessages`, `setLogger`, `resetMessages`, `ErrorCode`, `errorsAt`, `descriptorToJsonSchema`
|
|
13
|
+
|
|
14
|
+
**When to use:** Zero-dependency schema validation library with strict-by-default objects, async refinements, coercion, flexible schema composition, and full TypeScript inference.
|
|
15
|
+
|
|
16
|
+
**Related:** [@vielzeug/forge](https://vielzeug.dev/forge/) · [@vielzeug/courier](https://vielzeug.dev/courier/) · [@vielzeug/vault](https://vielzeug.dev/vault/)
|
|
17
|
+
|
|
18
|
+
</details>
|
|
19
|
+
|
|
20
|
+
`@vielzeug/spell` is part of Vielzeug and ships as a zero-dependency TypeScript package with ESM+CJS output.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
pnpm add @vielzeug/spell
|
|
26
|
+
npm install @vielzeug/spell
|
|
27
|
+
yarn add @vielzeug/spell
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Quick Start
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { s, type Infer } from '@vielzeug/spell';
|
|
34
|
+
|
|
35
|
+
const UserSchema = s.object({
|
|
36
|
+
id: s.coerce.number().int().positive(),
|
|
37
|
+
name: s.string().trim().min(1),
|
|
38
|
+
email: s.string().trim().email(),
|
|
39
|
+
role: s.union('admin', 'editor', 'viewer').default('viewer'),
|
|
40
|
+
tags: s.array(s.string()).unique().default([]),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
type User = Infer<typeof UserSchema>;
|
|
44
|
+
|
|
45
|
+
const result = UserSchema.safeParse({ id: '42', name: 'Ada', email: 'ada@example.com' });
|
|
46
|
+
|
|
47
|
+
if (result.success) {
|
|
48
|
+
const user: User = result.data;
|
|
49
|
+
console.log(user.id); // 42
|
|
50
|
+
|
|
51
|
+
// Assertion form — narrows type, throws SpellValidationError on failure
|
|
52
|
+
UserSchema.assert(result.data, 'user');
|
|
53
|
+
} else {
|
|
54
|
+
const { fieldErrors, formErrors } = result.error.flattenFirst();
|
|
55
|
+
console.log(fieldErrors, formErrors);
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Documentation
|
|
60
|
+
|
|
61
|
+
- [Overview](https://vielzeug.dev/spell/)
|
|
62
|
+
- [Usage Guide](https://vielzeug.dev/spell/usage)
|
|
63
|
+
- [API Reference](https://vielzeug.dev/spell/api)
|
|
64
|
+
- [Examples](https://vielzeug.dev/spell/examples)
|
|
65
|
+
|
|
66
|
+
## License
|
|
67
|
+
|
|
68
|
+
MIT © [Helmuth Saatkamp](https://github.com/helmuthdu) — part of the [Vielzeug](https://github.com/helmuthdu/vielzeug) monorepo.
|
package/dist/_dev.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_dev.cjs","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __SPELL_PROD__?: boolean }).__SPELL_PROD__;\n\n/** @internal */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/spell] ${msg}`);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":"AAAA,IAAM,EAAQ,CAAE,WAA4C,eAG5D,SAAgB,EAAK,EAAmB,CAClC,GAAO,QAAQ,KAAK,qBAAqB,GAAK,CACpD"}
|
package/dist/_dev.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_dev.d.ts","sourceRoot":"","sources":["../src/_dev.ts"],"names":[],"mappings":""}
|
package/dist/_dev.js
ADDED
package/dist/_dev.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_dev.js","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __SPELL_PROD__?: boolean }).__SPELL_PROD__;\n\n/** @internal */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/spell] ${msg}`);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":"AAAA,IAAM,EAAQ,CAAE,WAA4C,eAG5D,SAAgB,EAAK,EAAmB,CAClC,GAAO,QAAQ,KAAK,qBAAqB,GAAK,CACpD"}
|
package/dist/core.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./types.cjs"),t=require("./errors.cjs"),n=require("./safe-object.cjs"),r=require("./json-schema.cjs"),i=require("./messages.cjs");let a=require("@vielzeug/arsenal");function o(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>o(e));if(e instanceof Date)return new Date(e.getTime());if(e instanceof Map){let t=new Map;for(let[n,r]of e.entries())t.set(o(n),o(r));return t}if(e instanceof Set)return new Set([...e.values()].map(e=>o(e)));if((0,a.isPlainObject)(e)){let t={};for(let[r,i]of Object.entries(e))n.defineOwnProperty(t,r,o(i));return t}return e}function s(){return{isNullable:!1,isOptional:!1,postprocessors:[],preprocessors:[],validators:[]}}function c(e){return{catch:e.catch,defaultValue:e.defaultValue,description:e.description,isNullable:e.isNullable,isOptional:e.isOptional,postprocessors:[...e.postprocessors],preprocessors:[...e.preprocessors],validators:[...e.validators]}}function l(e){return{messages:e??i._messages()}}function u(t,n){let r=[...n];return typeof t==`string`?r.push({code:e.ErrorCode.custom,message:t,path:[]}):t===!1&&r.length===0&&r.push({code:e.ErrorCode.custom,message:i._messages().check.default(),path:[]}),r.length?r:null}var d=class{state;_annotations={};_typeValidator=null;constructor(e){this.state=s(),this._typeValidator=e??null}parse(n,r){let i=r??l();return this._withCatch(()=>{let r=this._prepareInput(n);if(r.skip)return r.value;let a=this._parse(r.value,i);if(a instanceof Promise)throw new t.SpellValidationError([{code:e.ErrorCode.custom,message:`parse() received an async schema. Use parseAsync() instead.`,path:[]}]);let o=a,s=o.typeOk?this._runValidatorsSync(o.data,i):[],c=[...o.issues,...s];if(c.length)throw new t.SpellValidationError(c);return this._runPostprocessors(o.data)})}safeParse(e,n){try{return{data:this.parse(e,n),success:!0}}catch(e){if(t.SpellValidationError.is(e))return{error:e,success:!1};throw e}}async parseAsync(e,n){let r=n??l();return this._withCatchAsync(async()=>{let n=this._prepareInput(e);if(n.skip)return n.value;let i=await this._parse(n.value,r),a=i.typeOk?await this._runValidatorsAsync(i.data,r):[],o=[...i.issues,...a];if(o.length)throw new t.SpellValidationError(o);return this._runPostprocessors(i.data)})}async safeParseAsync(e,n){try{return{data:await this.parseAsync(e,n),success:!0}}catch(e){if(t.SpellValidationError.is(e))return{error:e,success:!1};throw e}}_parseFullSync(n,r){let i=r??l(),a=this._prepareInput(n);if(a.skip)return{data:a.value,issues:[]};let o=this._parse(a.value,i);if(o instanceof Promise)throw new t.SpellValidationError([{code:e.ErrorCode.custom,message:`Sync parse path received an async schema. Use parseAsync() instead.`,path:[]}]);let s=o,c=s.typeOk?this._runValidatorsSync(s.data,i):[],u=[...s.issues,...c];return u.length>0?this.state.catch?{data:this.state.catch(),issues:[]}:{data:s.data,issues:u}:{data:this._runPostprocessors(s.data),issues:[]}}async _parseFullAsync(e,t){let n=t??l(),r=this._prepareInput(e);if(r.skip)return{data:r.value,issues:[]};let i=await this._parse(r.value,n),a=i.typeOk?await this._runValidatorsAsync(i.data,n):[],o=[...i.issues,...a];return o.length>0?this.state.catch?{data:this.state.catch(),issues:[]}:{data:i.data,issues:o}:{data:this._runPostprocessors(i.data),issues:[]}}validate(e){return this._addConstraint((t,n)=>{let r=[],i=e(t,{addIssue:e=>r.push({...e,path:e.path??[]})});return i instanceof Promise?i.then(e=>u(e,r)):u(i,r)})}refine(n,r){return this._addConstraint((i,a)=>{if(n(i))return null;let o=r?t.resolveMessage(r,{value:i}):a.messages.check.default();return t.fail(e.ErrorCode.custom,o)})}optional(){let e=this._clone();return e.state.isOptional=!0,e}nullable(){let e=this._clone();return e.state.isNullable=!0,e}nullish(){let e=this._clone();return e.state.isOptional=!0,e.state.isNullable=!0,e}required(){let e=this._clone();return e.state.isOptional=!1,e}default(e){let t=this._clone();return t.state.defaultValue=typeof e==`function`?e:()=>o(e),t}catch(e){let t=this._clone();return t.state.catch=typeof e==`function`?e:()=>o(e),t}transform(e){let t=this._clone();return t.state.postprocessors.push(e),t}preprocess(e){let t=this._clone();return t.state.preprocessors.push(e),t}pipe(e){return new f(this,e)}label(e){let t=this._clone();return t.state.description=e,t}toDescriptor(){return this.state.preprocessors.length>0&&i._dev(`toDescriptor(): this schema has preprocessors (e.g. trim(), lowercase(), coerce()). Preprocessors are not serializable and will not appear in the descriptor output.`),this._toDescriptorImpl()}get description(){return this.state.description}get isOptional(){return this.state.isOptional}get isNullable(){return this.state.isNullable}is(e){return this.safeParse(e).success}toJsonSchema(){return r.schemaToJsonSchema(this)}assert(e,n){let r=this._parseFullSync(e);if(r.issues.length!==0)throw new t.SpellValidationError(n?r.issues.map(e=>({...e,message:e.path.length===0?`${n}: ${e.message}`:e.message})):r.issues)}walk(e){return this._walk(e)}equals(e){return e===this?!0:Object.getPrototypeOf(e)!==Object.getPrototypeOf(this)||e.isOptional!==this.isOptional||e.isNullable!==this.isNullable||e.description!==this.description?!1:this._equalsImpl(e)}get kind(){return this._kind}get _kind(){return`any`}_describeBase(){return{...this.state.description===void 0?{}:{description:this.state.description},...this.state.isNullable?{isNullable:!0}:{},...this.state.isOptional?{isOptional:!0}:{}}}_annotationsEqual(e){let t=this._annotations,n=e._annotations,r=Object.keys(t),i=Object.keys(n);return r.length===i.length?r.every(e=>t[e]===n[e]):!1}_addConstraint(e,t){let n=this._clone();return n.state.validators.push(e),t&&(n._annotations=t({...n._annotations})),n}_construct(e){let t=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{state:e});return t._annotations={...this._annotations},t}_clone(){return this._construct(c(this.state))}_copyStateTo(e){return e.state=c(this.state),e}_walk(e){return e.unknown?e.unknown(this):null}_toDescriptorImpl(){return{...this._describeBase(),kind:`any`}}_equalsImpl(e){return!0}_withCatch(e){if(!this.state.catch)return e();try{return e()}catch(e){if(t.SpellValidationError.is(e))return this.state.catch();throw e}}async _withCatchAsync(e){if(!this.state.catch)return e();try{return await e()}catch(e){if(t.SpellValidationError.is(e))return this.state.catch();throw e}}_prepareInput(e){let t=this._runPreprocessors(e),n=t===void 0&&this.state.defaultValue?this.state.defaultValue():t;return this.state.isOptional&&n===void 0||this.state.isNullable&&n===null?{skip:!0,value:n}:{skip:!1,value:n}}_runPreprocessors(e){let t=e;for(let e of this.state.preprocessors)t=e(t);return t}_runPostprocessors(e){let t=e;for(let e of this.state.postprocessors)t=e(t);return t}_runValidatorsSync(n,r){if(this._typeValidator){let i=this._typeValidator(n,r);if(i instanceof Promise)throw new t.SpellValidationError([{code:e.ErrorCode.custom,message:`Type validator returned a Promise. Use parseAsync() for async validation.`,path:[]}]);if(i&&i.length>0)return i}let a=[];for(let e of this.state.validators){let t=e(n,r);if(t instanceof Promise){i._dev(`An async validate() callback was skipped because parse()/safeParse() cannot await it. The value passed this check unvalidated — use parseAsync()/safeParseAsync() instead.`);continue}t&&a.push(...t)}return a}async _runValidatorsAsync(e,t){if(this._typeValidator){let n=await this._typeValidator(e,t);if(n&&n.length>0)return n}let n=[];for(let r of this.state.validators){let i=await r(e,t);i&&n.push(...i)}return n}_parse(e,t){return{data:e,issues:[],typeOk:!0}}},f=class e extends d{from;to;get _kind(){return`pipe`}constructor(e,t){super(),this.from=e,this.to=t}_parse(e,t){let n=this.from._parseFullSync(e,t);if(n instanceof Promise)return n.then(n=>n.issues.length>0?{data:e,issues:n.issues,typeOk:!1}:this.to._parseFullAsync(n.data,t).then(e=>e.issues.length>0?{data:n.data,issues:e.issues,typeOk:!1}:{data:e.data,issues:[],typeOk:!0}));if(n.issues.length>0)return{data:e,issues:n.issues,typeOk:!1};let r=this.to._parseFullSync(n.data,t);return r instanceof Promise?r.then(e=>e.issues.length>0?{data:n.data,issues:e.issues,typeOk:!1}:{data:e.data,issues:[],typeOk:!0}):r.issues.length>0?{data:n.data,issues:r.issues,typeOk:!1}:{data:r.data,issues:[],typeOk:!0}}_walk(e){let t=this.from.walk(e),n=this.to.walk(e);return e.pipe?e.pipe(this,t,n):super._walk(e)}_toDescriptorImpl(){return{...this._describeBase(),from:this.from.toDescriptor(),kind:`pipe`,to:this.to.toDescriptor()}}_equalsImpl(t){return t instanceof e?this.from.equals(t.from)&&this.to.equals(t.to):!1}};exports.ErrorCode=e.ErrorCode,exports.PipeSchema=f,exports.Schema=d,exports.SpellError=t.SpellError,exports.SpellValidationError=t.SpellValidationError,exports._makeCtx=l,exports.errorsAt=t.errorsAt,exports.fail=t.fail,exports.prependIssuePath=t.prependIssuePath,exports.resolveMessage=t.resolveMessage;
|
|
2
|
+
//# sourceMappingURL=core.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core.cjs","names":[],"sources":["../src/core.ts"],"sourcesContent":["import { isPlainObject } from '@vielzeug/arsenal';\n\nimport { fail, resolveMessage, SpellValidationError } from './errors';\nimport { schemaToJsonSchema } from './json-schema';\nimport { _messages, _dev } from './messages';\nimport { defineOwnProperty } from './safe-object';\nimport {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type FlatError,\n type FlatErrorFirst,\n type FormattedErrors,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type JsonSchema,\n type MessageFn,\n type Messages,\n type ParseContext,\n type ParseResult,\n type SchemaDescriptor,\n type SchemaWalker,\n type ValidateFn,\n type ValidateResult,\n} from './types';\n\nexport {\n ErrorCode,\n type AnySchema,\n type CheckContext,\n type FlatError,\n type FlatErrorFirst,\n type FormattedErrors,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type JsonSchema,\n type MessageFn,\n type Messages,\n type ParseContext,\n type ParseResult,\n type SchemaDescriptor,\n type SchemaWalker,\n type ValidateFn,\n type ValidateResult,\n};\n\nexport { SpellError, SpellValidationError, errorsAt, fail, prependIssuePath, resolveMessage } from './errors';\n\nfunction materializeValue<T>(value: T): T {\n if (value == null || typeof value !== 'object') return value;\n\n if (Array.isArray(value)) return value.map((item) => materializeValue(item)) as T;\n\n if (value instanceof Date) return new Date(value.getTime()) as T;\n\n if (value instanceof Map) {\n const out = new Map<unknown, unknown>();\n\n for (const [key, mapValue] of value.entries()) out.set(materializeValue(key), materializeValue(mapValue));\n\n return out as T;\n }\n\n if (value instanceof Set) return new Set([...value.values()].map((item) => materializeValue(item))) as T;\n\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n\n for (const [key, entry] of Object.entries(value)) defineOwnProperty(out, key, materializeValue(entry));\n\n return out as T;\n }\n\n return value;\n}\n\n/* -------------------- Schema State -------------------- */\n\ntype Preprocessor = (value: unknown) => unknown;\ntype Postprocessor = (value: unknown) => unknown;\n\nexport interface SchemaState<Output = unknown> {\n catch?: () => Output;\n defaultValue?: () => Output;\n description?: string;\n isNullable: boolean;\n isOptional: boolean;\n postprocessors: Postprocessor[];\n preprocessors: Preprocessor[];\n validators: ValidateFn[];\n}\n\nfunction defaultState<Output>(): SchemaState<Output> {\n return { isNullable: false, isOptional: false, postprocessors: [], preprocessors: [], validators: [] };\n}\n\nfunction cloneState<Output>(state: SchemaState<Output>): SchemaState<Output> {\n return {\n catch: state.catch,\n defaultValue: state.defaultValue,\n description: state.description,\n isNullable: state.isNullable,\n isOptional: state.isOptional,\n postprocessors: [...state.postprocessors],\n preprocessors: [...state.preprocessors],\n validators: [...state.validators],\n };\n}\n\n/* -------------------- Internal parse-value return type -------------------- */\n\n/** @internal */\nexport type ParseValue = { data: unknown; issues: Issue[]; typeOk: boolean };\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/* -------------------- ParseContext default -------------------- */\n\n/** @internal */\nexport function _makeCtx(messages?: Messages): ParseContext {\n return { messages: messages ?? _messages() };\n}\n\n/* -------------------- ValidateResult normalizer -------------------- */\n\nfunction normalizeValidateResult(result: ValidateResult, ctxIssues: Issue[]): Issue[] | null {\n const issues = [...ctxIssues];\n\n if (typeof result === 'string') {\n issues.push({ code: ErrorCode.custom, message: result, path: [] });\n } else if (result === false && issues.length === 0) {\n issues.push({ code: ErrorCode.custom, message: _messages().check.default(), path: [] });\n }\n\n return issues.length ? issues : null;\n}\n\n/* -------------------- Base Schema -------------------- */\n\nexport class Schema<Output = unknown, Input = Output> {\n protected state: SchemaState<Output>;\n\n protected _annotations: Record<string, unknown> = {};\n\n private _typeValidator: ValidateFn | null = null;\n\n constructor(typeValidator?: ValidateFn) {\n this.state = defaultState<Output>();\n this._typeValidator = typeValidator ?? null;\n }\n\n /* -------------------- Parse -------------------- */\n\n parse(value: unknown, ctx?: ParseContext): Output {\n const c = ctx ?? _makeCtx();\n\n return this._withCatch(() => {\n const prepared = this._prepareInput(value);\n\n if (prepared.skip) return prepared.value as Output;\n\n const coreOrPromise = this._parse(prepared.value, c);\n\n if (coreOrPromise instanceof Promise) {\n throw new SpellValidationError([\n {\n code: ErrorCode.custom,\n message: 'parse() received an async schema. Use parseAsync() instead.',\n path: [],\n },\n ]);\n }\n\n const core = coreOrPromise;\n const validationIssues = core.typeOk ? this._runValidatorsSync(core.data, c) : [];\n const allIssues = [...core.issues, ...validationIssues];\n\n if (allIssues.length) throw new SpellValidationError(allIssues);\n\n return this._runPostprocessors(core.data) as Output;\n });\n }\n\n safeParse(value: unknown, ctx?: ParseContext): ParseResult<Output> {\n try {\n return { data: this.parse(value, ctx), success: true };\n } catch (error) {\n if (SpellValidationError.is(error)) return { error, success: false };\n\n throw error;\n }\n }\n\n async parseAsync(value: unknown, ctx?: ParseContext): Promise<Output> {\n const c = ctx ?? _makeCtx();\n\n return this._withCatchAsync(async () => {\n const prepared = this._prepareInput(value);\n\n if (prepared.skip) return prepared.value as Output;\n\n const core = await this._parse(prepared.value, c);\n const validationIssues = core.typeOk ? await this._runValidatorsAsync(core.data, c) : [];\n const allIssues = [...core.issues, ...validationIssues];\n\n if (allIssues.length) throw new SpellValidationError(allIssues);\n\n return this._runPostprocessors(core.data) as Output;\n });\n }\n\n async safeParseAsync(value: unknown, ctx?: ParseContext): Promise<ParseResult<Output>> {\n try {\n return { data: await this.parseAsync(value, ctx), success: true };\n } catch (error) {\n if (SpellValidationError.is(error)) return { error, success: false };\n\n throw error;\n }\n }\n\n /**\n * Internal full parse without throwing. Returns { data, issues }.\n * Used by composite schemas (array, object, union, etc.) to avoid\n * the try/catch + object allocation overhead of safeParse().\n * @internal\n */\n _parseFullSync(value: unknown, ctx?: ParseContext): { data: unknown; issues: Issue[] } {\n const c = ctx ?? _makeCtx();\n const prepared = this._prepareInput(value);\n\n if (prepared.skip) return { data: prepared.value, issues: [] };\n\n const coreOrPromise = this._parse(prepared.value, c);\n\n if (coreOrPromise instanceof Promise) {\n throw new SpellValidationError([\n {\n code: ErrorCode.custom,\n message: 'Sync parse path received an async schema. Use parseAsync() instead.',\n path: [],\n },\n ]);\n }\n\n const core = coreOrPromise;\n const validationIssues = core.typeOk ? this._runValidatorsSync(core.data, c) : [];\n const allIssues = [...core.issues, ...validationIssues];\n\n if (allIssues.length > 0) {\n if (this.state.catch) return { data: this.state.catch(), issues: [] };\n\n return { data: core.data, issues: allIssues };\n }\n\n return { data: this._runPostprocessors(core.data), issues: [] };\n }\n\n /**\n * Async version of _parseFullSync.\n * @internal\n */\n async _parseFullAsync(value: unknown, ctx?: ParseContext): Promise<{ data: unknown; issues: Issue[] }> {\n const c = ctx ?? _makeCtx();\n const prepared = this._prepareInput(value);\n\n if (prepared.skip) return { data: prepared.value, issues: [] };\n\n const core = await this._parse(prepared.value, c);\n const validationIssues = core.typeOk ? await this._runValidatorsAsync(core.data, c) : [];\n const allIssues = [...core.issues, ...validationIssues];\n\n if (allIssues.length > 0) {\n if (this.state.catch) return { data: this.state.catch(), issues: [] };\n\n return { data: core.data, issues: allIssues };\n }\n\n return { data: this._runPostprocessors(core.data), issues: [] };\n }\n\n /* -------------------- Validators -------------------- */\n\n /**\n * Add a custom validation rule. The callback receives the typed value and an optional\n * `{ addIssue }` context for reporting multiple issues in one pass.\n *\n * **Return values:**\n * - `string` — fail with that message\n * - `false` — fail silently (use `addIssue` to report)\n * - `true` / `null` / `void` — pass\n *\n * The `|| 'message'` shorthand works naturally:\n * ```ts\n * s.string().validate(v => v.length > 0 || 'Cannot be empty')\n * ```\n *\n * For async validation, return a Promise:\n * ```ts\n * s.string().validate(async v => (await db.exists(v)) ? 'Already taken' : null)\n * ```\n */\n validate(\n fn:\n | ((value: Output, ctx: CheckContext) => ValidateResult)\n | ((value: Output, ctx: CheckContext) => Promise<ValidateResult>),\n ): this {\n const validator: ValidateFn = (value, _ctx) => {\n const ctxIssues: Issue[] = [];\n const checkCtx: CheckContext = {\n addIssue: (issue) => ctxIssues.push({ ...issue, path: issue.path ?? [] } as Issue),\n };\n const result = fn(value as Output, checkCtx);\n\n if (result instanceof Promise) {\n return result.then((r) => normalizeValidateResult(r, ctxIssues));\n }\n\n return normalizeValidateResult(result, ctxIssues);\n };\n\n return this._addConstraint(validator);\n }\n\n refine(predicate: (value: Output) => boolean, message?: MessageFn<{ value: Output }>): this {\n return this._addConstraint((value, ctx) => {\n if ((predicate as (v: unknown) => boolean)(value)) return null;\n\n const msg = message ? resolveMessage(message, { value: value as Output }) : ctx!.messages.check.default();\n\n return fail(ErrorCode.custom, msg);\n });\n }\n\n /* -------------------- Nullability / Optionality -------------------- */\n\n optional(): Schema<Output | undefined, Input | undefined> {\n const cloned = this._clone() as unknown as Schema<Output | undefined, Input | undefined>;\n\n cloned.state.isOptional = true;\n\n return cloned;\n }\n\n nullable(): Schema<Output | null, Input | null> {\n const cloned = this._clone() as unknown as Schema<Output | null, Input | null>;\n\n cloned.state.isNullable = true;\n\n return cloned;\n }\n\n nullish(): Schema<Output | null | undefined, Input | null | undefined> {\n const cloned = this._clone() as unknown as Schema<Output | null | undefined, Input | null | undefined>;\n\n cloned.state.isOptional = true;\n cloned.state.isNullable = true;\n\n return cloned;\n }\n\n required(): Schema<Exclude<Output, undefined>, Exclude<Input, undefined>> {\n const cloned = this._clone() as unknown as Schema<Exclude<Output, undefined>, Exclude<Input, undefined>>;\n\n cloned.state.isOptional = false;\n\n return cloned;\n }\n\n /* -------------------- Transforms -------------------- */\n\n default(defaultValue: Output | (() => Output)): this {\n const cloned = this._clone();\n\n cloned.state.defaultValue =\n typeof defaultValue === 'function' ? (defaultValue as () => Output) : () => materializeValue(defaultValue);\n\n return cloned;\n }\n\n catch(fallback: Output | (() => Output)): this {\n const cloned = this._clone();\n\n cloned.state.catch = typeof fallback === 'function' ? (fallback as () => Output) : () => materializeValue(fallback);\n\n return cloned;\n }\n\n transform<NewOutput>(fn: (value: Output) => NewOutput): Schema<NewOutput, Input> {\n const next = this._clone() as unknown as Schema<NewOutput, Input>;\n\n next.state.postprocessors.push(fn as (v: unknown) => unknown);\n\n return next;\n }\n\n preprocess(fn: (value: unknown) => unknown): this {\n const cloned = this._clone();\n\n cloned.state.preprocessors.push(fn);\n\n return cloned;\n }\n\n pipe<B>(next: Schema<B, NoInfer<Output>>): Schema<B, Input> {\n return new PipeSchema<B, Input>(this, next);\n }\n\n /* -------------------- Introspection -------------------- */\n\n label(description: string): this {\n const cloned = this._clone();\n\n cloned.state.description = description;\n\n return cloned;\n }\n\n toDescriptor(): SchemaDescriptor {\n if (this.state.preprocessors.length > 0) {\n _dev(\n 'toDescriptor(): this schema has preprocessors (e.g. trim(), lowercase(), coerce()). ' +\n 'Preprocessors are not serializable and will not appear in the descriptor output.',\n );\n }\n\n return this._toDescriptorImpl();\n }\n\n get description(): string | undefined {\n return this.state.description;\n }\n\n get isOptional(): boolean {\n return this.state.isOptional;\n }\n\n get isNullable(): boolean {\n return this.state.isNullable;\n }\n\n is(value: unknown): value is Output {\n return this.safeParse(value).success;\n }\n\n toJsonSchema(): JsonSchema {\n return schemaToJsonSchema(this);\n }\n\n assert(value: unknown, label?: string): asserts value is Output {\n const result = this._parseFullSync(value);\n\n if (result.issues.length === 0) return;\n\n const issues = label\n ? result.issues.map((issue) => ({\n ...issue,\n message: issue.path.length === 0 ? `${label}: ${issue.message}` : issue.message,\n }))\n : result.issues;\n\n throw new SpellValidationError(issues);\n }\n\n walk<R>(visitor: SchemaWalker<R>): R | null {\n return this._walk(visitor);\n }\n\n equals(other: AnySchema): boolean {\n if (other === this) return true;\n\n if (Object.getPrototypeOf(other) !== Object.getPrototypeOf(this)) return false;\n\n if (other.isOptional !== this.isOptional) return false;\n\n if (other.isNullable !== this.isNullable) return false;\n\n if (other.description !== this.description) return false;\n\n return this._equalsImpl(other);\n }\n\n get kind(): string {\n return this._kind;\n }\n\n protected get _kind(): string {\n return 'any';\n }\n\n /* -------------------- Protected helpers -------------------- */\n\n protected _describeBase(): { description?: string; isNullable?: true; isOptional?: true } {\n return {\n ...(this.state.description !== undefined ? { description: this.state.description } : {}),\n ...(this.state.isNullable ? { isNullable: true as const } : {}),\n ...(this.state.isOptional ? { isOptional: true as const } : {}),\n };\n }\n\n protected _annotationsEqual(other: AnySchema): boolean {\n const a = this._annotations;\n const b = (other as Schema)._annotations;\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n return keysA.every((k) => a[k] === b[k]);\n }\n\n protected _addConstraint(\n validator: ValidateFn,\n mergeAnnotations?: (current: Record<string, unknown>) => Record<string, unknown>,\n ): this {\n const next = this._clone();\n\n next.state.validators.push(validator);\n\n if (mergeAnnotations) {\n next._annotations = mergeAnnotations({ ...next._annotations });\n }\n\n return next;\n }\n\n protected _construct(state: SchemaState<any>): this {\n const next = Object.assign(Object.create(Object.getPrototypeOf(this)), this, { state }) as this;\n\n next._annotations = { ...this._annotations };\n\n return next;\n }\n\n protected _clone(): this {\n return this._construct(cloneState(this.state));\n }\n\n protected _copyStateTo<T extends Schema<any, any>>(target: T): T {\n target.state = cloneState(this.state);\n\n return target;\n }\n\n protected _walk<R>(visitor: SchemaWalker<R>): R | null {\n if (visitor.unknown) return visitor.unknown(this);\n\n return null;\n }\n\n protected _toDescriptorImpl(): SchemaDescriptor {\n return { ...this._describeBase(), kind: 'any' };\n }\n\n protected _equalsImpl(_other: AnySchema): boolean {\n return true;\n }\n\n /* -------------------- Private -------------------- */\n\n private _withCatch<T>(fn: () => T): T {\n if (!this.state.catch) return fn();\n\n try {\n return fn();\n } catch (error) {\n if (SpellValidationError.is(error)) return this.state.catch() as unknown as T;\n\n throw error;\n }\n }\n\n protected async _withCatchAsync<T>(fn: () => Promise<T>): Promise<T> {\n if (!this.state.catch) return fn();\n\n try {\n return await fn();\n } catch (error) {\n if (SpellValidationError.is(error)) return this.state.catch() as unknown as T;\n\n throw error;\n }\n }\n\n protected _prepareInput(value: unknown): { skip: true; value: null | undefined } | { skip: false; value: unknown } {\n const processed = this._runPreprocessors(value);\n const withDefault = processed === undefined && this.state.defaultValue ? this.state.defaultValue() : processed;\n\n if ((this.state.isOptional && withDefault === undefined) || (this.state.isNullable && withDefault === null)) {\n return { skip: true, value: withDefault };\n }\n\n return { skip: false, value: withDefault };\n }\n\n protected _runPreprocessors(value: unknown): unknown {\n let current = value;\n\n for (const preprocess of this.state.preprocessors) current = preprocess(current);\n\n return current;\n }\n\n protected _runPostprocessors(value: unknown): unknown {\n let current = value;\n\n for (const postprocess of this.state.postprocessors) current = postprocess(current);\n\n return current;\n }\n\n private _runValidatorsSync(value: unknown, ctx: ParseContext): Issue[] {\n if (this._typeValidator) {\n const typeResult = this._typeValidator(value, ctx);\n\n if (typeResult instanceof Promise) {\n throw new SpellValidationError([\n {\n code: ErrorCode.custom,\n message: 'Type validator returned a Promise. Use parseAsync() for async validation.',\n path: [],\n },\n ]);\n }\n\n if (typeResult && typeResult.length > 0) return typeResult;\n }\n\n const issues: Issue[] = [];\n\n for (const validate of this.state.validators) {\n const result = validate(value, ctx);\n\n if (result instanceof Promise) {\n _dev(\n 'An async validate() callback was skipped because parse()/safeParse() cannot await it. ' +\n 'The value passed this check unvalidated — use parseAsync()/safeParseAsync() instead.',\n );\n continue;\n }\n\n if (result) issues.push(...result);\n }\n\n return issues;\n }\n\n protected async _runValidatorsAsync(value: unknown, ctx: ParseContext): Promise<Issue[]> {\n if (this._typeValidator) {\n const typeResult = await this._typeValidator(value, ctx);\n\n if (typeResult && typeResult.length > 0) return typeResult;\n }\n\n const issues: Issue[] = [];\n\n for (const validate of this.state.validators) {\n const result = await validate(value, ctx);\n\n if (result) issues.push(...result);\n }\n\n return issues;\n }\n\n protected _parse(_value: unknown, _ctx: ParseContext): MaybePromise<ParseValue> {\n return { data: _value, issues: [], typeOk: true };\n }\n}\n\n/* -------------------- PipeSchema -------------------- */\n\nexport class PipeSchema<Output, Input = unknown> extends Schema<Output, Input> {\n readonly from: Schema<any, Input>;\n readonly to: Schema<Output, any>;\n\n protected override get _kind(): string {\n return 'pipe';\n }\n\n constructor(from: Schema<any, Input>, to: Schema<Output, any>) {\n super();\n this.from = from;\n this.to = to;\n }\n\n protected override _parse(value: unknown, ctx: ParseContext): MaybePromise<ParseValue> {\n const r1OrPromise = this.from._parseFullSync(value, ctx);\n\n if (r1OrPromise instanceof Promise) {\n return (r1OrPromise as Promise<{ data: unknown; issues: Issue[] }>).then((r1) => {\n if (r1.issues.length > 0) return { data: value, issues: r1.issues, typeOk: false };\n\n return this.to\n ._parseFullAsync(r1.data, ctx)\n .then((r2) =>\n r2.issues.length > 0\n ? { data: r1.data, issues: r2.issues, typeOk: false }\n : { data: r2.data, issues: [], typeOk: true },\n );\n });\n }\n\n if (r1OrPromise.issues.length > 0) return { data: value, issues: r1OrPromise.issues, typeOk: false };\n\n const r2OrPromise = this.to._parseFullSync(r1OrPromise.data, ctx);\n\n if (r2OrPromise instanceof Promise) {\n return r2OrPromise.then((r2) =>\n r2.issues.length > 0\n ? { data: r1OrPromise.data, issues: r2.issues, typeOk: false }\n : { data: r2.data, issues: [], typeOk: true },\n );\n }\n\n return r2OrPromise.issues.length > 0\n ? { data: r1OrPromise.data, issues: r2OrPromise.issues, typeOk: false }\n : { data: r2OrPromise.data, issues: [], typeOk: true };\n }\n\n protected override _walk<R>(visitor: SchemaWalker<R>): R | null {\n const fromR = this.from.walk(visitor);\n const toR = this.to.walk(visitor);\n\n if (visitor.pipe) return visitor.pipe(this, fromR, toR);\n\n return super._walk(visitor);\n }\n\n protected override _toDescriptorImpl(): SchemaDescriptor {\n return {\n ...this._describeBase(),\n from: this.from.toDescriptor(),\n kind: 'pipe',\n to: this.to.toDescriptor(),\n };\n }\n\n protected override _equalsImpl(other: AnySchema): boolean {\n if (!(other instanceof PipeSchema)) return false;\n\n return this.from.equals(other.from) && this.to.equals(other.to);\n }\n}\n"],"mappings":"sLAoDA,SAAS,EAAoB,EAAa,CACxC,GAAqB,OAAO,GAAU,WAAlC,EAA4C,OAAO,EAEvD,GAAI,MAAM,QAAQ,CAAK,EAAG,OAAO,EAAM,IAAK,GAAS,EAAiB,CAAI,CAAC,EAE3E,GAAI,aAAiB,KAAM,OAAO,IAAI,KAAK,EAAM,QAAQ,CAAC,EAE1D,GAAI,aAAiB,IAAK,CACxB,IAAM,EAAM,IAAI,IAEhB,IAAK,GAAM,CAAC,EAAK,KAAa,EAAM,QAAQ,EAAG,EAAI,IAAI,EAAiB,CAAG,EAAG,EAAiB,CAAQ,CAAC,EAExG,OAAO,CACT,CAEA,GAAI,aA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,GAAI,KAAK,GAAG,aAAa,CAC3B,CACF,CAEA,YAA+B,EAA2B,CAGxD,OAFM,aAAiB,EAEhB,KAAK,KAAK,OAAO,EAAM,IAAI,GAAK,KAAK,GAAG,OAAO,EAAM,EAAE,EAFnB,EAG7C,CACF"}
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { type AnySchema, type CheckContext, ErrorCode, type FlatError, type FlatErrorFirst, type FormattedErrors, type Infer, type InferInput, type InferOutput, type Issue, type JsonSchema, type MessageFn, type Messages, type ParseContext, type ParseResult, type SchemaDescriptor, type SchemaWalker, type ValidateFn, type ValidateResult } from './types';
|
|
2
|
+
export { ErrorCode, type AnySchema, type CheckContext, type FlatError, type FlatErrorFirst, type FormattedErrors, type Infer, type InferInput, type InferOutput, type Issue, type JsonSchema, type MessageFn, type Messages, type ParseContext, type ParseResult, type SchemaDescriptor, type SchemaWalker, type ValidateFn, type ValidateResult, };
|
|
3
|
+
export { SpellError, SpellValidationError, errorsAt, fail, prependIssuePath, resolveMessage } from './errors';
|
|
4
|
+
type Preprocessor = (value: unknown) => unknown;
|
|
5
|
+
type Postprocessor = (value: unknown) => unknown;
|
|
6
|
+
export interface SchemaState<Output = unknown> {
|
|
7
|
+
catch?: () => Output;
|
|
8
|
+
defaultValue?: () => Output;
|
|
9
|
+
description?: string;
|
|
10
|
+
isNullable: boolean;
|
|
11
|
+
isOptional: boolean;
|
|
12
|
+
postprocessors: Postprocessor[];
|
|
13
|
+
preprocessors: Preprocessor[];
|
|
14
|
+
validators: ValidateFn[];
|
|
15
|
+
}
|
|
16
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
17
|
+
export declare class Schema<Output = unknown, Input = Output> {
|
|
18
|
+
protected state: SchemaState<Output>;
|
|
19
|
+
protected _annotations: Record<string, unknown>;
|
|
20
|
+
private _typeValidator;
|
|
21
|
+
constructor(typeValidator?: ValidateFn);
|
|
22
|
+
parse(value: unknown, ctx?: ParseContext): Output;
|
|
23
|
+
safeParse(value: unknown, ctx?: ParseContext): ParseResult<Output>;
|
|
24
|
+
parseAsync(value: unknown, ctx?: ParseContext): Promise<Output>;
|
|
25
|
+
safeParseAsync(value: unknown, ctx?: ParseContext): Promise<ParseResult<Output>>;
|
|
26
|
+
/**
|
|
27
|
+
* Add a custom validation rule. The callback receives the typed value and an optional
|
|
28
|
+
* `{ addIssue }` context for reporting multiple issues in one pass.
|
|
29
|
+
*
|
|
30
|
+
* **Return values:**
|
|
31
|
+
* - `string` — fail with that message
|
|
32
|
+
* - `false` — fail silently (use `addIssue` to report)
|
|
33
|
+
* - `true` / `null` / `void` — pass
|
|
34
|
+
*
|
|
35
|
+
* The `|| 'message'` shorthand works naturally:
|
|
36
|
+
* ```ts
|
|
37
|
+
* s.string().validate(v => v.length > 0 || 'Cannot be empty')
|
|
38
|
+
* ```
|
|
39
|
+
*
|
|
40
|
+
* For async validation, return a Promise:
|
|
41
|
+
* ```ts
|
|
42
|
+
* s.string().validate(async v => (await db.exists(v)) ? 'Already taken' : null)
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
validate(fn: ((value: Output, ctx: CheckContext) => ValidateResult) | ((value: Output, ctx: CheckContext) => Promise<ValidateResult>)): this;
|
|
46
|
+
refine(predicate: (value: Output) => boolean, message?: MessageFn<{
|
|
47
|
+
value: Output;
|
|
48
|
+
}>): this;
|
|
49
|
+
optional(): Schema<Output | undefined, Input | undefined>;
|
|
50
|
+
nullable(): Schema<Output | null, Input | null>;
|
|
51
|
+
nullish(): Schema<Output | null | undefined, Input | null | undefined>;
|
|
52
|
+
required(): Schema<Exclude<Output, undefined>, Exclude<Input, undefined>>;
|
|
53
|
+
default(defaultValue: Output | (() => Output)): this;
|
|
54
|
+
catch(fallback: Output | (() => Output)): this;
|
|
55
|
+
transform<NewOutput>(fn: (value: Output) => NewOutput): Schema<NewOutput, Input>;
|
|
56
|
+
preprocess(fn: (value: unknown) => unknown): this;
|
|
57
|
+
pipe<B>(next: Schema<B, NoInfer<Output>>): Schema<B, Input>;
|
|
58
|
+
label(description: string): this;
|
|
59
|
+
toDescriptor(): SchemaDescriptor;
|
|
60
|
+
get description(): string | undefined;
|
|
61
|
+
get isOptional(): boolean;
|
|
62
|
+
get isNullable(): boolean;
|
|
63
|
+
is(value: unknown): value is Output;
|
|
64
|
+
toJsonSchema(): JsonSchema;
|
|
65
|
+
assert(value: unknown, label?: string): asserts value is Output;
|
|
66
|
+
walk<R>(visitor: SchemaWalker<R>): R | null;
|
|
67
|
+
equals(other: AnySchema): boolean;
|
|
68
|
+
get kind(): string;
|
|
69
|
+
protected get _kind(): string;
|
|
70
|
+
protected _describeBase(): {
|
|
71
|
+
description?: string;
|
|
72
|
+
isNullable?: true;
|
|
73
|
+
isOptional?: true;
|
|
74
|
+
};
|
|
75
|
+
protected _annotationsEqual(other: AnySchema): boolean;
|
|
76
|
+
protected _addConstraint(validator: ValidateFn, mergeAnnotations?: (current: Record<string, unknown>) => Record<string, unknown>): this;
|
|
77
|
+
protected _construct(state: SchemaState<any>): this;
|
|
78
|
+
protected _clone(): this;
|
|
79
|
+
protected _copyStateTo<T extends Schema<any, any>>(target: T): T;
|
|
80
|
+
protected _walk<R>(visitor: SchemaWalker<R>): R | null;
|
|
81
|
+
protected _toDescriptorImpl(): SchemaDescriptor;
|
|
82
|
+
protected _equalsImpl(_other: AnySchema): boolean;
|
|
83
|
+
private _withCatch;
|
|
84
|
+
protected _withCatchAsync<T>(fn: () => Promise<T>): Promise<T>;
|
|
85
|
+
protected _prepareInput(value: unknown): {
|
|
86
|
+
skip: true;
|
|
87
|
+
value: null | undefined;
|
|
88
|
+
} | {
|
|
89
|
+
skip: false;
|
|
90
|
+
value: unknown;
|
|
91
|
+
};
|
|
92
|
+
protected _runPreprocessors(value: unknown): unknown;
|
|
93
|
+
protected _runPostprocessors(value: unknown): unknown;
|
|
94
|
+
private _runValidatorsSync;
|
|
95
|
+
protected _runValidatorsAsync(value: unknown, ctx: ParseContext): Promise<Issue[]>;
|
|
96
|
+
protected _parse(_value: unknown, _ctx: ParseContext): MaybePromise<ParseValue>;
|
|
97
|
+
}
|
|
98
|
+
export declare class PipeSchema<Output, Input = unknown> extends Schema<Output, Input> {
|
|
99
|
+
readonly from: Schema<any, Input>;
|
|
100
|
+
readonly to: Schema<Output, any>;
|
|
101
|
+
protected get _kind(): string;
|
|
102
|
+
constructor(from: Schema<any, Input>, to: Schema<Output, any>);
|
|
103
|
+
protected _parse(value: unknown, ctx: ParseContext): MaybePromise<ParseValue>;
|
|
104
|
+
protected _walk<R>(visitor: SchemaWalker<R>): R | null;
|
|
105
|
+
protected _toDescriptorImpl(): SchemaDescriptor;
|
|
106
|
+
protected _equalsImpl(other: AnySchema): boolean;
|
|
107
|
+
}
|
|
108
|
+
//# sourceMappingURL=core.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,SAAS,EACT,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,KAAK,EACV,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,KAAK,EACV,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,gBAAgB,EACrB,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,cAAc,EACpB,MAAM,SAAS,CAAC;AAEjB,OAAO,EACL,SAAS,EACT,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,KAAK,EACV,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,KAAK,EACV,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,KAAK,YAAY,EACjB,KAAK,WAAW,EA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KAAK,CAAC;IAC5E,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IAClC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAEjC,cAAuB,KAAK,IAAI,MAAM,CAErC;gBAEW,IAAI,EAAE,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;cAM1C,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,YAAY,GAAG,YAAY,CAAC,UAAU,CAAC;cAkCnE,KAAK,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI;cAS5C,iBAAiB,IAAI,gBAAgB;cASrC,WAAW,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO;CAK1D"}
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ErrorCode as e}from"./types.js";import{SpellError as t,SpellValidationError as n,errorsAt as r,fail as i,prependIssuePath as a,resolveMessage as o}from"./errors.js";import{defineOwnProperty as s}from"./safe-object.js";import{schemaToJsonSchema as c}from"./json-schema.js";import{_dev as l,_messages as u}from"./messages.js";import{isPlainObject as d}from"@vielzeug/arsenal";function f(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>f(e));if(e instanceof Date)return new Date(e.getTime());if(e instanceof Map){let t=new Map;for(let[n,r]of e.entries())t.set(f(n),f(r));return t}if(e instanceof Set)return new Set([...e.values()].map(e=>f(e)));if(d(e)){let t={};for(let[n,r]of Object.entries(e))s(t,n,f(r));return t}return e}function p(){return{isNullable:!1,isOptional:!1,postprocessors:[],preprocessors:[],validators:[]}}function m(e){return{catch:e.catch,defaultValue:e.defaultValue,description:e.description,isNullable:e.isNullable,isOptional:e.isOptional,postprocessors:[...e.postprocessors],preprocessors:[...e.preprocessors],validators:[...e.validators]}}function h(e){return{messages:e??u()}}function g(t,n){let r=[...n];return typeof t==`string`?r.push({code:e.custom,message:t,path:[]}):t===!1&&r.length===0&&r.push({code:e.custom,message:u().check.default(),path:[]}),r.length?r:null}var _=class{state;_annotations={};_typeValidator=null;constructor(e){this.state=p(),this._typeValidator=e??null}parse(t,r){let i=r??h();return this._withCatch(()=>{let r=this._prepareInput(t);if(r.skip)return r.value;let a=this._parse(r.value,i);if(a instanceof Promise)throw new n([{code:e.custom,message:`parse() received an async schema. Use parseAsync() instead.`,path:[]}]);let o=a,s=o.typeOk?this._runValidatorsSync(o.data,i):[],c=[...o.issues,...s];if(c.length)throw new n(c);return this._runPostprocessors(o.data)})}safeParse(e,t){try{return{data:this.parse(e,t),success:!0}}catch(e){if(n.is(e))return{error:e,success:!1};throw e}}async parseAsync(e,t){let r=t??h();return this._withCatchAsync(async()=>{let t=this._prepareInput(e);if(t.skip)return t.value;let i=await this._parse(t.value,r),a=i.typeOk?await this._runValidatorsAsync(i.data,r):[],o=[...i.issues,...a];if(o.length)throw new n(o);return this._runPostprocessors(i.data)})}async safeParseAsync(e,t){try{return{data:await this.parseAsync(e,t),success:!0}}catch(e){if(n.is(e))return{error:e,success:!1};throw e}}_parseFullSync(t,r){let i=r??h(),a=this._prepareInput(t);if(a.skip)return{data:a.value,issues:[]};let o=this._parse(a.value,i);if(o instanceof Promise)throw new n([{code:e.custom,message:`Sync parse path received an async schema. Use parseAsync() instead.`,path:[]}]);let s=o,c=s.typeOk?this._runValidatorsSync(s.data,i):[],l=[...s.issues,...c];return l.length>0?this.state.catch?{data:this.state.catch(),issues:[]}:{data:s.data,issues:l}:{data:this._runPostprocessors(s.data),issues:[]}}async _parseFullAsync(e,t){let n=t??h(),r=this._prepareInput(e);if(r.skip)return{data:r.value,issues:[]};let i=await this._parse(r.value,n),a=i.typeOk?await this._runValidatorsAsync(i.data,n):[],o=[...i.issues,...a];return o.length>0?this.state.catch?{data:this.state.catch(),issues:[]}:{data:i.data,issues:o}:{data:this._runPostprocessors(i.data),issues:[]}}validate(e){return this._addConstraint((t,n)=>{let r=[],i=e(t,{addIssue:e=>r.push({...e,path:e.path??[]})});return i instanceof Promise?i.then(e=>g(e,r)):g(i,r)})}refine(t,n){return this._addConstraint((r,a)=>{if(t(r))return null;let s=n?o(n,{value:r}):a.messages.check.default();return i(e.custom,s)})}optional(){let e=this._clone();return e.state.isOptional=!0,e}nullable(){let e=this._clone();return e.state.isNullable=!0,e}nullish(){let e=this._clone();return e.state.isOptional=!0,e.state.isNullable=!0,e}required(){let e=this._clone();return e.state.isOptional=!1,e}default(e){let t=this._clone();return t.state.defaultValue=typeof e==`function`?e:()=>f(e),t}catch(e){let t=this._clone();return t.state.catch=typeof e==`function`?e:()=>f(e),t}transform(e){let t=this._clone();return t.state.postprocessors.push(e),t}preprocess(e){let t=this._clone();return t.state.preprocessors.push(e),t}pipe(e){return new v(this,e)}label(e){let t=this._clone();return t.state.description=e,t}toDescriptor(){return this.state.preprocessors.length>0&&l(`toDescriptor(): this schema has preprocessors (e.g. trim(), lowercase(), coerce()). Preprocessors are not serializable and will not appear in the descriptor output.`),this._toDescriptorImpl()}get description(){return this.state.description}get isOptional(){return this.state.isOptional}get isNullable(){return this.state.isNullable}is(e){return this.safeParse(e).success}toJsonSchema(){return c(this)}assert(e,t){let r=this._parseFullSync(e);if(r.issues.length!==0)throw new n(t?r.issues.map(e=>({...e,message:e.path.length===0?`${t}: ${e.message}`:e.message})):r.issues)}walk(e){return this._walk(e)}equals(e){return e===this?!0:Object.getPrototypeOf(e)!==Object.getPrototypeOf(this)||e.isOptional!==this.isOptional||e.isNullable!==this.isNullable||e.description!==this.description?!1:this._equalsImpl(e)}get kind(){return this._kind}get _kind(){return`any`}_describeBase(){return{...this.state.description===void 0?{}:{description:this.state.description},...this.state.isNullable?{isNullable:!0}:{},...this.state.isOptional?{isOptional:!0}:{}}}_annotationsEqual(e){let t=this._annotations,n=e._annotations,r=Object.keys(t),i=Object.keys(n);return r.length===i.length?r.every(e=>t[e]===n[e]):!1}_addConstraint(e,t){let n=this._clone();return n.state.validators.push(e),t&&(n._annotations=t({...n._annotations})),n}_construct(e){let t=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{state:e});return t._annotations={...this._annotations},t}_clone(){return this._construct(m(this.state))}_copyStateTo(e){return e.state=m(this.state),e}_walk(e){return e.unknown?e.unknown(this):null}_toDescriptorImpl(){return{...this._describeBase(),kind:`any`}}_equalsImpl(e){return!0}_withCatch(e){if(!this.state.catch)return e();try{return e()}catch(e){if(n.is(e))return this.state.catch();throw e}}async _withCatchAsync(e){if(!this.state.catch)return e();try{return await e()}catch(e){if(n.is(e))return this.state.catch();throw e}}_prepareInput(e){let t=this._runPreprocessors(e),n=t===void 0&&this.state.defaultValue?this.state.defaultValue():t;return this.state.isOptional&&n===void 0||this.state.isNullable&&n===null?{skip:!0,value:n}:{skip:!1,value:n}}_runPreprocessors(e){let t=e;for(let e of this.state.preprocessors)t=e(t);return t}_runPostprocessors(e){let t=e;for(let e of this.state.postprocessors)t=e(t);return t}_runValidatorsSync(t,r){if(this._typeValidator){let i=this._typeValidator(t,r);if(i instanceof Promise)throw new n([{code:e.custom,message:`Type validator returned a Promise. Use parseAsync() for async validation.`,path:[]}]);if(i&&i.length>0)return i}let i=[];for(let e of this.state.validators){let n=e(t,r);if(n instanceof Promise){l(`An async validate() callback was skipped because parse()/safeParse() cannot await it. The value passed this check unvalidated — use parseAsync()/safeParseAsync() instead.`);continue}n&&i.push(...n)}return i}async _runValidatorsAsync(e,t){if(this._typeValidator){let n=await this._typeValidator(e,t);if(n&&n.length>0)return n}let n=[];for(let r of this.state.validators){let i=await r(e,t);i&&n.push(...i)}return n}_parse(e,t){return{data:e,issues:[],typeOk:!0}}},v=class e extends _{from;to;get _kind(){return`pipe`}constructor(e,t){super(),this.from=e,this.to=t}_parse(e,t){let n=this.from._parseFullSync(e,t);if(n instanceof Promise)return n.then(n=>n.issues.length>0?{data:e,issues:n.issues,typeOk:!1}:this.to._parseFullAsync(n.data,t).then(e=>e.issues.length>0?{data:n.data,issues:e.issues,typeOk:!1}:{data:e.data,issues:[],typeOk:!0}));if(n.issues.length>0)return{data:e,issues:n.issues,typeOk:!1};let r=this.to._parseFullSync(n.data,t);return r instanceof Promise?r.then(e=>e.issues.length>0?{data:n.data,issues:e.issues,typeOk:!1}:{data:e.data,issues:[],typeOk:!0}):r.issues.length>0?{data:n.data,issues:r.issues,typeOk:!1}:{data:r.data,issues:[],typeOk:!0}}_walk(e){let t=this.from.walk(e),n=this.to.walk(e);return e.pipe?e.pipe(this,t,n):super._walk(e)}_toDescriptorImpl(){return{...this._describeBase(),from:this.from.toDescriptor(),kind:`pipe`,to:this.to.toDescriptor()}}_equalsImpl(t){return t instanceof e?this.from.equals(t.from)&&this.to.equals(t.to):!1}};export{e as ErrorCode,v as PipeSchema,_ as Schema,t as SpellError,n as SpellValidationError,h as _makeCtx,r as errorsAt,i as fail,a as prependIssuePath,o as resolveMessage};
|
|
2
|
+
//# sourceMappingURL=core.js.map
|
package/dist/core.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core.js","names":[],"sources":["../src/core.ts"],"sourcesContent":["import { isPlainObject } from '@vielzeug/arsenal';\n\nimport { fail, resolveMessage, SpellValidationError } from './errors';\nimport { schemaToJsonSchema } from './json-schema';\nimport { _messages, _dev } from './messages';\nimport { defineOwnProperty } from './safe-object';\nimport {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type FlatError,\n type FlatErrorFirst,\n type FormattedErrors,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type JsonSchema,\n type MessageFn,\n type Messages,\n type ParseContext,\n type ParseResult,\n type SchemaDescriptor,\n type SchemaWalker,\n type ValidateFn,\n type ValidateResult,\n} from './types';\n\nexport {\n ErrorCode,\n type AnySchema,\n type CheckContext,\n type FlatError,\n type FlatErrorFirst,\n type FormattedErrors,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type JsonSchema,\n type MessageFn,\n type Messages,\n type ParseContext,\n type ParseResult,\n type SchemaDescriptor,\n type SchemaWalker,\n type ValidateFn,\n type ValidateResult,\n};\n\nexport { SpellError, SpellValidationError, errorsAt, fail, prependIssuePath, resolveMessage } from './errors';\n\nfunction materializeValue<T>(value: T): T {\n if (value == null || typeof value !== 'object') return value;\n\n if (Array.isArray(value)) return value.map((item) => materializeValue(item)) as T;\n\n if (value instanceof Date) return new Date(value.getTime()) as T;\n\n if (value instanceof Map) {\n const out = new Map<unknown, unknown>();\n\n for (const [key, mapValue] of value.entries()) out.set(materializeValue(key), materializeValue(mapValue));\n\n return out as T;\n }\n\n if (value instanceof Set) return new Set([...value.values()].map((item) => materializeValue(item))) as T;\n\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n\n for (const [key, entry] of Object.entries(value)) defineOwnProperty(out, key, materializeValue(entry));\n\n return out as T;\n }\n\n return value;\n}\n\n/* -------------------- Schema State -------------------- */\n\ntype Preprocessor = (value: unknown) => unknown;\ntype Postprocessor = (value: unknown) => unknown;\n\nexport interface SchemaState<Output = unknown> {\n catch?: () => Output;\n defaultValue?: () => Output;\n description?: string;\n isNullable: boolean;\n isOptional: boolean;\n postprocessors: Postprocessor[];\n preprocessors: Preprocessor[];\n validators: ValidateFn[];\n}\n\nfunction defaultState<Output>(): SchemaState<Output> {\n return { isNullable: false, isOptional: false, postprocessors: [], preprocessors: [], validators: [] };\n}\n\nfunction cloneState<Output>(state: SchemaState<Output>): SchemaState<Output> {\n return {\n catch: state.catch,\n defaultValue: state.defaultValue,\n description: state.description,\n isNullable: state.isNullable,\n isOptional: state.isOptional,\n postprocessors: [...state.postprocessors],\n preprocessors: [...state.preprocessors],\n validators: [...state.validators],\n };\n}\n\n/* -------------------- Internal parse-value return type -------------------- */\n\n/** @internal */\nexport type ParseValue = { data: unknown; issues: Issue[]; typeOk: boolean };\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/* -------------------- ParseContext default -------------------- */\n\n/** @internal */\nexport function _makeCtx(messages?: Messages): ParseContext {\n return { messages: messages ?? _messages() };\n}\n\n/* -------------------- ValidateResult normalizer -------------------- */\n\nfunction normalizeValidateResult(result: ValidateResult, ctxIssues: Issue[]): Issue[] | null {\n const issues = [...ctxIssues];\n\n if (typeof result === 'string') {\n issues.push({ code: ErrorCode.custom, message: result, path: [] });\n } else if (result === false && issues.length === 0) {\n issues.push({ code: ErrorCode.custom, message: _messages().check.default(), path: [] });\n }\n\n return issues.length ? issues : null;\n}\n\n/* -------------------- Base Schema -------------------- */\n\nexport class Schema<Output = unknown, Input = Output> {\n protected state: SchemaState<Output>;\n\n protected _annotations: Record<string, unknown> = {};\n\n private _typeValidator: ValidateFn | null = null;\n\n constructor(typeValidator?: ValidateFn) {\n this.state = defaultState<Output>();\n this._typeValidator = typeValidator ?? null;\n }\n\n /* -------------------- Parse -------------------- */\n\n parse(value: unknown, ctx?: ParseContext): Output {\n const c = ctx ?? _makeCtx();\n\n return this._withCatch(() => {\n const prepared = this._prepareInput(value);\n\n if (prepared.skip) return prepared.value as Output;\n\n const coreOrPromise = this._parse(prepared.value, c);\n\n if (coreOrPromise instanceof Promise) {\n throw new SpellValidationError([\n {\n code: ErrorCode.custom,\n message: 'parse() received an async schema. Use parseAsync() instead.',\n path: [],\n },\n ]);\n }\n\n const core = coreOrPromise;\n const validationIssues = core.typeOk ? this._runValidatorsSync(core.data, c) : [];\n const allIssues = [...core.issues, ...validationIssues];\n\n if (allIssues.length) throw new SpellValidationError(allIssues);\n\n return this._runPostprocessors(core.data) as Output;\n });\n }\n\n safeParse(value: unknown, ctx?: ParseContext): ParseResult<Output> {\n try {\n return { data: this.parse(value, ctx), success: true };\n } catch (error) {\n if (SpellValidationError.is(error)) return { error, success: false };\n\n throw error;\n }\n }\n\n async parseAsync(value: unknown, ctx?: ParseContext): Promise<Output> {\n const c = ctx ?? _makeCtx();\n\n return this._withCatchAsync(async () => {\n const prepared = this._prepareInput(value);\n\n if (prepared.skip) return prepared.value as Output;\n\n const core = await this._parse(prepared.value, c);\n const validationIssues = core.typeOk ? await this._runValidatorsAsync(core.data, c) : [];\n const allIssues = [...core.issues, ...validationIssues];\n\n if (allIssues.length) throw new SpellValidationError(allIssues);\n\n return this._runPostprocessors(core.data) as Output;\n });\n }\n\n async safeParseAsync(value: unknown, ctx?: ParseContext): Promise<ParseResult<Output>> {\n try {\n return { data: await this.parseAsync(value, ctx), success: true };\n } catch (error) {\n if (SpellValidationError.is(error)) return { error, success: false };\n\n throw error;\n }\n }\n\n /**\n * Internal full parse without throwing. Returns { data, issues }.\n * Used by composite schemas (array, object, union, etc.) to avoid\n * the try/catch + object allocation overhead of safeParse().\n * @internal\n */\n _parseFullSync(value: unknown, ctx?: ParseContext): { data: unknown; issues: Issue[] } {\n const c = ctx ?? _makeCtx();\n const prepared = this._prepareInput(value);\n\n if (prepared.skip) return { data: prepared.value, issues: [] };\n\n const coreOrPromise = this._parse(prepared.value, c);\n\n if (coreOrPromise instanceof Promise) {\n throw new SpellValidationError([\n {\n code: ErrorCode.custom,\n message: 'Sync parse path received an async schema. Use parseAsync() instead.',\n path: [],\n },\n ]);\n }\n\n const core = coreOrPromise;\n const validationIssues = core.typeOk ? this._runValidatorsSync(core.data, c) : [];\n const allIssues = [...core.issues, ...validationIssues];\n\n if (allIssues.length > 0) {\n if (this.state.catch) return { data: this.state.catch(), issues: [] };\n\n return { data: core.data, issues: allIssues };\n }\n\n return { data: this._runPostprocessors(core.data), issues: [] };\n }\n\n /**\n * Async version of _parseFullSync.\n * @internal\n */\n async _parseFullAsync(value: unknown, ctx?: ParseContext): Promise<{ data: unknown; issues: Issue[] }> {\n const c = ctx ?? _makeCtx();\n const prepared = this._prepareInput(value);\n\n if (prepared.skip) return { data: prepared.value, issues: [] };\n\n const core = await this._parse(prepared.value, c);\n const validationIssues = core.typeOk ? await this._runValidatorsAsync(core.data, c) : [];\n const allIssues = [...core.issues, ...validationIssues];\n\n if (allIssues.length > 0) {\n if (this.state.catch) return { data: this.state.catch(), issues: [] };\n\n return { data: core.data, issues: allIssues };\n }\n\n return { data: this._runPostprocessors(core.data), issues: [] };\n }\n\n /* -------------------- Validators -------------------- */\n\n /**\n * Add a custom validation rule. The callback receives the typed value and an optional\n * `{ addIssue }` context for reporting multiple issues in one pass.\n *\n * **Return values:**\n * - `string` — fail with that message\n * - `false` — fail silently (use `addIssue` to report)\n * - `true` / `null` / `void` — pass\n *\n * The `|| 'message'` shorthand works naturally:\n * ```ts\n * s.string().validate(v => v.length > 0 || 'Cannot be empty')\n * ```\n *\n * For async validation, return a Promise:\n * ```ts\n * s.string().validate(async v => (await db.exists(v)) ? 'Already taken' : null)\n * ```\n */\n validate(\n fn:\n | ((value: Output, ctx: CheckContext) => ValidateResult)\n | ((value: Output, ctx: CheckContext) => Promise<ValidateResult>),\n ): this {\n const validator: ValidateFn = (value, _ctx) => {\n const ctxIssues: Issue[] = [];\n const checkCtx: CheckContext = {\n addIssue: (issue) => ctxIssues.push({ ...issue, path: issue.path ?? [] } as Issue),\n };\n const result = fn(value as Output, checkCtx);\n\n if (result instanceof Promise) {\n return result.then((r) => normalizeValidateResult(r, ctxIssues));\n }\n\n return normalizeValidateResult(result, ctxIssues);\n };\n\n return this._addConstraint(validator);\n }\n\n refine(predicate: (value: Output) => boolean, message?: MessageFn<{ value: Output }>): this {\n return this._addConstraint((value, ctx) => {\n if ((predicate as (v: unknown) => boolean)(value)) return null;\n\n const msg = message ? resolveMessage(message, { value: value as Output }) : ctx!.messages.check.default();\n\n return fail(ErrorCode.custom, msg);\n });\n }\n\n /* -------------------- Nullability / Optionality -------------------- */\n\n optional(): Schema<Output | undefined, Input | undefined> {\n const cloned = this._clone() as unknown as Schema<Output | undefined, Input | undefined>;\n\n cloned.state.isOptional = true;\n\n return cloned;\n }\n\n nullable(): Schema<Output | null, Input | null> {\n const cloned = this._clone() as unknown as Schema<Output | null, Input | null>;\n\n cloned.state.isNullable = true;\n\n return cloned;\n }\n\n nullish(): Schema<Output | null | undefined, Input | null | undefined> {\n const cloned = this._clone() as unknown as Schema<Output | null | undefined, Input | null | undefined>;\n\n cloned.state.isOptional = true;\n cloned.state.isNullable = true;\n\n return cloned;\n }\n\n required(): Schema<Exclude<Output, undefined>, Exclude<Input, undefined>> {\n const cloned = this._clone() as unknown as Schema<Exclude<Output, undefined>, Exclude<Input, undefined>>;\n\n cloned.state.isOptional = false;\n\n return cloned;\n }\n\n /* -------------------- Transforms -------------------- */\n\n default(defaultValue: Output | (() => Output)): this {\n const cloned = this._clone();\n\n cloned.state.defaultValue =\n typeof defaultValue === 'function' ? (defaultValue as () => Output) : () => materializeValue(defaultValue);\n\n return cloned;\n }\n\n catch(fallback: Output | (() => Output)): this {\n const cloned = this._clone();\n\n cloned.state.catch = typeof fallback === 'function' ? (fallback as () => Output) : () => materializeValue(fallback);\n\n return cloned;\n }\n\n transform<NewOutput>(fn: (value: Output) => NewOutput): Schema<NewOutput, Input> {\n const next = this._clone() as unknown as Schema<NewOutput, Input>;\n\n next.state.postprocessors.push(fn as (v: unknown) => unknown);\n\n return next;\n }\n\n preprocess(fn: (value: unknown) => unknown): this {\n const cloned = this._clone();\n\n cloned.state.preprocessors.push(fn);\n\n return cloned;\n }\n\n pipe<B>(next: Schema<B, NoInfer<Output>>): Schema<B, Input> {\n return new PipeSchema<B, Input>(this, next);\n }\n\n /* -------------------- Introspection -------------------- */\n\n label(description: string): this {\n const cloned = this._clone();\n\n cloned.state.description = description;\n\n return cloned;\n }\n\n toDescriptor(): SchemaDescriptor {\n if (this.state.preprocessors.length > 0) {\n _dev(\n 'toDescriptor(): this schema has preprocessors (e.g. trim(), lowercase(), coerce()). ' +\n 'Preprocessors are not serializable and will not appear in the descriptor output.',\n );\n }\n\n return this._toDescriptorImpl();\n }\n\n get description(): string | undefined {\n return this.state.description;\n }\n\n get isOptional(): boolean {\n return this.state.isOptional;\n }\n\n get isNullable(): boolean {\n return this.state.isNullable;\n }\n\n is(value: unknown): value is Output {\n return this.safeParse(value).success;\n }\n\n toJsonSchema(): JsonSchema {\n return schemaToJsonSchema(this);\n }\n\n assert(value: unknown, label?: string): asserts value is Output {\n const result = this._parseFullSync(value);\n\n if (result.issues.length === 0) return;\n\n const issues = label\n ? result.issues.map((issue) => ({\n ...issue,\n message: issue.path.length === 0 ? `${label}: ${issue.message}` : issue.message,\n }))\n : result.issues;\n\n throw new SpellValidationError(issues);\n }\n\n walk<R>(visitor: SchemaWalker<R>): R | null {\n return this._walk(visitor);\n }\n\n equals(other: AnySchema): boolean {\n if (other === this) return true;\n\n if (Object.getPrototypeOf(other) !== Object.getPrototypeOf(this)) return false;\n\n if (other.isOptional !== this.isOptional) return false;\n\n if (other.isNullable !== this.isNullable) return false;\n\n if (other.description !== this.description) return false;\n\n return this._equalsImpl(other);\n }\n\n get kind(): string {\n return this._kind;\n }\n\n protected get _kind(): string {\n return 'any';\n }\n\n /* -------------------- Protected helpers -------------------- */\n\n protected _describeBase(): { description?: string; isNullable?: true; isOptional?: true } {\n return {\n ...(this.state.description !== undefined ? { description: this.state.description } : {}),\n ...(this.state.isNullable ? { isNullable: true as const } : {}),\n ...(this.state.isOptional ? { isOptional: true as const } : {}),\n };\n }\n\n protected _annotationsEqual(other: AnySchema): boolean {\n const a = this._annotations;\n const b = (other as Schema)._annotations;\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n return keysA.every((k) => a[k] === b[k]);\n }\n\n protected _addConstraint(\n validator: ValidateFn,\n mergeAnnotations?: (current: Record<string, unknown>) => Record<string, unknown>,\n ): this {\n const next = this._clone();\n\n next.state.validators.push(validator);\n\n if (mergeAnnotations) {\n next._annotations = mergeAnnotations({ ...next._annotations });\n }\n\n return next;\n }\n\n protected _construct(state: SchemaState<any>): this {\n const next = Object.assign(Object.create(Object.getPrototypeOf(this)), this, { state }) as this;\n\n next._annotations = { ...this._annotations };\n\n return next;\n }\n\n protected _clone(): this {\n return this._construct(cloneState(this.state));\n }\n\n protected _copyStateTo<T extends Schema<any, any>>(target: T): T {\n target.state = cloneState(this.state);\n\n return target;\n }\n\n protected _walk<R>(visitor: SchemaWalker<R>): R | null {\n if (visitor.unknown) return visitor.unknown(this);\n\n return null;\n }\n\n protected _toDescriptorImpl(): SchemaDescriptor {\n return { ...this._describeBase(), kind: 'any' };\n }\n\n protected _equalsImpl(_other: AnySchema): boolean {\n return true;\n }\n\n /* -------------------- Private -------------------- */\n\n private _withCatch<T>(fn: () => T): T {\n if (!this.state.catch) return fn();\n\n try {\n return fn();\n } catch (error) {\n if (SpellValidationError.is(error)) return this.state.catch() as unknown as T;\n\n throw error;\n }\n }\n\n protected async _withCatchAsync<T>(fn: () => Promise<T>): Promise<T> {\n if (!this.state.catch) return fn();\n\n try {\n return await fn();\n } catch (error) {\n if (SpellValidationError.is(error)) return this.state.catch() as unknown as T;\n\n throw error;\n }\n }\n\n protected _prepareInput(value: unknown): { skip: true; value: null | undefined } | { skip: false; value: unknown } {\n const processed = this._runPreprocessors(value);\n const withDefault = processed === undefined && this.state.defaultValue ? this.state.defaultValue() : processed;\n\n if ((this.state.isOptional && withDefault === undefined) || (this.state.isNullable && withDefault === null)) {\n return { skip: true, value: withDefault };\n }\n\n return { skip: false, value: withDefault };\n }\n\n protected _runPreprocessors(value: unknown): unknown {\n let current = value;\n\n for (const preprocess of this.state.preprocessors) current = preprocess(current);\n\n return current;\n }\n\n protected _runPostprocessors(value: unknown): unknown {\n let current = value;\n\n for (const postprocess of this.state.postprocessors) current = postprocess(current);\n\n return current;\n }\n\n private _runValidatorsSync(value: unknown, ctx: ParseContext): Issue[] {\n if (this._typeValidator) {\n const typeResult = this._typeValidator(value, ctx);\n\n if (typeResult instanceof Promise) {\n throw new SpellValidationError([\n {\n code: ErrorCode.custom,\n message: 'Type validator returned a Promise. Use parseAsync() for async validation.',\n path: [],\n },\n ]);\n }\n\n if (typeResult && typeResult.length > 0) return typeResult;\n }\n\n const issues: Issue[] = [];\n\n for (const validate of this.state.validators) {\n const result = validate(value, ctx);\n\n if (result instanceof Promise) {\n _dev(\n 'An async validate() callback was skipped because parse()/safeParse() cannot await it. ' +\n 'The value passed this check unvalidated — use parseAsync()/safeParseAsync() instead.',\n );\n continue;\n }\n\n if (result) issues.push(...result);\n }\n\n return issues;\n }\n\n protected async _runValidatorsAsync(value: unknown, ctx: ParseContext): Promise<Issue[]> {\n if (this._typeValidator) {\n const typeResult = await this._typeValidator(value, ctx);\n\n if (typeResult && typeResult.length > 0) return typeResult;\n }\n\n const issues: Issue[] = [];\n\n for (const validate of this.state.validators) {\n const result = await validate(value, ctx);\n\n if (result) issues.push(...result);\n }\n\n return issues;\n }\n\n protected _parse(_value: unknown, _ctx: ParseContext): MaybePromise<ParseValue> {\n return { data: _value, issues: [], typeOk: true };\n }\n}\n\n/* -------------------- PipeSchema -------------------- */\n\nexport class PipeSchema<Output, Input = unknown> extends Schema<Output, Input> {\n readonly from: Schema<any, Input>;\n readonly to: Schema<Output, any>;\n\n protected override get _kind(): string {\n return 'pipe';\n }\n\n constructor(from: Schema<any, Input>, to: Schema<Output, any>) {\n super();\n this.from = from;\n this.to = to;\n }\n\n protected override _parse(value: unknown, ctx: ParseContext): MaybePromise<ParseValue> {\n const r1OrPromise = this.from._parseFullSync(value, ctx);\n\n if (r1OrPromise instanceof Promise) {\n return (r1OrPromise as Promise<{ data: unknown; issues: Issue[] }>).then((r1) => {\n if (r1.issues.length > 0) return { data: value, issues: r1.issues, typeOk: false };\n\n return this.to\n ._parseFullAsync(r1.data, ctx)\n .then((r2) =>\n r2.issues.length > 0\n ? { data: r1.data, issues: r2.issues, typeOk: false }\n : { data: r2.data, issues: [], typeOk: true },\n );\n });\n }\n\n if (r1OrPromise.issues.length > 0) return { data: value, issues: r1OrPromise.issues, typeOk: false };\n\n const r2OrPromise = this.to._parseFullSync(r1OrPromise.data, ctx);\n\n if (r2OrPromise instanceof Promise) {\n return r2OrPromise.then((r2) =>\n r2.issues.length > 0\n ? { data: r1OrPromise.data, issues: r2.issues, typeOk: false }\n : { data: r2.data, issues: [], typeOk: true },\n );\n }\n\n return r2OrPromise.issues.length > 0\n ? { data: r1OrPromise.data, issues: r2OrPromise.issues, typeOk: false }\n : { data: r2OrPromise.data, issues: [], typeOk: true };\n }\n\n protected override _walk<R>(visitor: SchemaWalker<R>): R | null {\n const fromR = this.from.walk(visitor);\n const toR = this.to.walk(visitor);\n\n if (visitor.pipe) return visitor.pipe(this, fromR, toR);\n\n return super._walk(visitor);\n }\n\n protected override _toDescriptorImpl(): SchemaDescriptor {\n return {\n ...this._describeBase(),\n from: this.from.toDescriptor(),\n kind: 'pipe',\n to: this.to.toDescriptor(),\n };\n }\n\n protected override _equalsImpl(other: AnySchema): boolean {\n if (!(other instanceof PipeSchema)) return false;\n\n return this.from.equals(other.from) && this.to.equals(other.to);\n }\n}\n"],"mappings":"6XAoDA,SAAS,EAAoB,EAAa,CACxC,GAAqB,OAAO,GAAU,WAAlC,EAA4C,OAAO,EAEvD,GAAI,MAAM,QAAQ,CAAK,EAAG,OAAO,EAAM,IAAK,GAAS,EAAiB,CAAI,CAAC,EAE3E,GAAI,aAAiB,KAAM,OAAO,IAAI,KAAK,EAAM,QAAQ,CAAC,EAE1D,GAAI,aAAiB,IAAK,CACxB,IAAM,EAAM,IAAI,IAEhB,IAAK,GAAM,CAAC,EAAK,KAAa,EAAM,QAAQ,EAAG,EAAI,IAAI,EAAiB,CAAG,EAAG,EAAiB,CAAQ,CAAC,EAExG,OAAO,CACT,CAEA,GAAI,aAAiB,IAAK,OAAO,IAAI,IAAI,CAAC,GAAG,EAAM,OAAO,CAAC,CAAC,CAAC,IAAK,GAAS,EAAiB,CAAI,CAAC,CAAC,EAElG,GAAI,EAAc,CAAK,EAAG,CACxB,IAAM,EAA+B,CAAC,EAEtC,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAK,EAAG,EAAkB,EAAK,EAAK,EAAiB,CAAK,CAAC,EAErG,OAAO,CACT,CAEA,OAAO,CACT,CAkBA,SAAS,GAA4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M,EAAO,OAAQ,EAAY,OAAQ,OAAQ,EAAM,EAEnG,IAAM,EAAc,KAAK,GAAG,eAAe,EAAY,KAAM,CAAG,EAUhE,OARI,aAAuB,QAClB,EAAY,KAAM,GACvB,EAAG,OAAO,OAAS,EACf,CAAE,KAAM,EAAY,KAAM,OAAQ,EAAG,OAAQ,OAAQ,EAAM,EAC3D,CAAE,KAAM,EAAG,KAAM,OAAQ,CAAC,EAAG,OAAQ,EAAK,CAChD,EAGK,EAAY,OAAO,OAAS,EAC/B,CAAE,KAAM,EAAY,KAAM,OAAQ,EAAY,OAAQ,OAAQ,EAAM,EACpE,CAAE,KAAM,EAAY,KAAM,OAAQ,CAAC,EAAG,OAAQ,EAAK,CACzD,CAEA,MAA4B,EAAoC,CAC9D,IAAM,EAAQ,KAAK,KAAK,KAAK,CAAO,EAC9B,EAAM,KAAK,GAAG,KAAK,CAAO,EAIhC,OAFI,EAAQ,KAAa,EAAQ,KAAK,KAAM,EAAO,CAAG,EAE/C,MAAM,MAAM,CAAO,CAC5B,CAEA,mBAAyD,CACvD,MAAO,CACL,GAAG,KAAK,cAAc,EACtB,KAAM,KAAK,KAAK,aAAa,EAC7B,KAAM,OACN,GAAI,KAAK,GAAG,aAAa,CAC3B,CACF,CAEA,YAA+B,EAA2B,CAGxD,OAFM,aAAiB,EAEhB,KAAK,KAAK,OAAO,EAAM,IAAI,GAAK,KAAK,GAAG,OAAO,EAAM,EAAE,EAFnB,EAG7C,CACF"}
|
package/dist/errors.cjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=require("./types.cjs");function t(e,t,n){return[{code:e,message:t,params:n,path:[]}]}function n(e,t){return typeof e==`function`?e(t):e}function r(e,t){return e.map(e=>({...e,path:[t,...e.path]}))}function i(e,...t){let n=e;for(let e of t){if(Array.isArray(n))return[];n=n[String(e)===`_errors`?`_errors_`:String(e)]??{_errors:[]}}return Array.isArray(n)?n:n._errors}var a=class e extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}};function o(e){return e.map(({code:e,message:t,path:n})=>`${n.length?n.join(`.`):`value`}: ${t} [${e}]`).join(`
|
|
2
|
+
`)}function s(){let e=Object.create(null);return e._errors=[],e}var c=class t extends a{issues;constructor(e,t){super(o(e),{cause:t}),this.issues=e}static is(e){return e instanceof t}bestMatch(){let t=this.issues.find(t=>t.code===e.ErrorCode.invalid_union);if(!t)return null;let n=t.params.errors;if(n.length===0)return null;let r=n.map(e=>({issues:e,score:e.reduce((e,t)=>Math.max(e,t.path.length),0)*1e3-e.length}));return r.sort((e,t)=>t.score-e.score),r[0].issues}flatten(){let e=[],t=[],n=new Map;for(let r of this.issues)if(r.path.length===0)t.push(r.message);else{let t=JSON.stringify(r.path),i=n.get(t);i===void 0?(n.set(t,e.length),e.push({messages:[r.message],path:[...r.path]})):e[i].messages.push(r.message)}return{fieldErrors:e,formErrors:t}}flattenFirst(){let{fieldErrors:e,formErrors:t}=this.flatten();return{fieldErrors:e.map(e=>({message:e.messages[0],path:e.path})),formErrors:t}}format(){let e=s();for(let t of this.issues){if(t.path.length===0){e._errors.push(t.message);continue}let n=e;for(let e of t.path){let t=String(e),r=t===`_errors`?`_errors_`:t;Object.hasOwn(n,r)||(n[r]=s()),n=n[r]}n._errors.push(t.message)}return e}};exports.SpellError=a,exports.SpellValidationError=c,exports.errorsAt=i,exports.fail=t,exports.prependIssuePath=r,exports.resolveMessage=n;
|
|
3
|
+
//# sourceMappingURL=errors.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { ErrorCode, type Issue, type MessageFn } from './types';\n\n/* -------------------- Helpers -------------------- */\n\ntype IssueParams<C extends string> = Extract<Issue, { code: C }> extends { params: infer P } ? P : undefined;\n\n/**\n * Creates a single-error failure array. Use in validator functions instead of building the array manually.\n * Typed overloads ensure params match the given error code.\n */\nexport function fail<C extends ErrorCode>(code: C, message: string, params: IssueParams<C>): Issue[];\nexport function fail(code: string, message: string, params?: Record<string, unknown>): Issue[];\nexport function fail(code: string, message: string, params?: Record<string, unknown>): Issue[] {\n return [{ code, message, params, path: [] } as Issue];\n}\n\n/** @internal */\nexport function resolveMessage<Ctx extends Record<string, unknown>>(msg: MessageFn<Ctx>, ctx: Ctx): string {\n return typeof msg === 'function' ? msg(ctx) : msg;\n}\n\nexport function prependIssuePath(issues: Issue[], prefix: string | number): Issue[] {\n return issues.map((issue) => ({ ...issue, path: [prefix, ...issue.path] }));\n}\n\n/* -------------------- FormattedErrors -------------------- */\n\nexport type FormattedErrors = {\n _errors: string[];\n [key: string]: FormattedErrors | string[];\n};\n\nexport function errorsAt(formatted: FormattedErrors, ...path: (string | number)[]): string[] {\n let node: FormattedErrors | string[] = formatted;\n\n for (const key of path) {\n if (Array.isArray(node)) return [];\n\n const safeKey = String(key) === '_errors' ? '_errors_' : String(key);\n\n node = (node as FormattedErrors)[safeKey] ?? { _errors: [] };\n }\n\n return Array.isArray(node) ? node : (node as FormattedErrors)._errors;\n}\n\n/* -------------------- SpellError -------------------- */\n\n/** Base class for all spell errors. Use `instanceof SpellError` to catch any spell-originated error. */\nexport class SpellError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is SpellError {\n return err instanceof SpellError;\n }\n}\n\n/* -------------------- SpellValidationError -------------------- */\n\nfunction formatIssues(issues: Issue[]): string {\n return issues\n .map(({ code, message, path }) => {\n const pathStr = path.length ? path.join('.') : 'value';\n\n return `${pathStr}: ${message} [${code}]`;\n })\n .join('\\n');\n}\n\nexport type FlatError = { messages: string[]; path: (string | number)[] };\nexport type FlatErrorFirst = { message: string; path: (string | number)[] };\n\nfunction createFormattedErrors(): FormattedErrors {\n const node = Object.create(null) as FormattedErrors;\n\n node._errors = [];\n\n return node;\n}\n\nexport class SpellValidationError extends SpellError {\n readonly issues: Issue[];\n\n constructor(issues: Issue[], cause?: unknown) {\n super(formatIssues(issues), { cause });\n this.issues = issues;\n }\n\n static is(err: unknown): err is SpellValidationError {\n return err instanceof SpellValidationError;\n }\n\n /**\n * Returns the union branch errors from the most-specific failing branch.\n * Surfaces the branch with the fewest issues at the deepest path — the one\n * that \"came closest\" to matching.\n */\n bestMatch(): Issue[] | null {\n const unionIssue = this.issues.find(\n (i): i is Extract<Issue, { code: 'invalid_union' }> => i.code === ErrorCode.invalid_union,\n );\n\n if (!unionIssue) return null;\n\n const branches = unionIssue.params.errors;\n\n if (branches.length === 0) return null;\n\n const scored = branches.map((branchIssues) => {\n const maxDepth = branchIssues.reduce((d, i) => Math.max(d, i.path.length), 0);\n\n return { issues: branchIssues, score: maxDepth * 1000 - branchIssues.length };\n });\n\n scored.sort((a, b) => b.score - a.score);\n\n return scored[0]!.issues;\n }\n\n flatten(): { fieldErrors: FlatError[]; formErrors: string[] } {\n const fieldErrors: FlatError[] = [];\n const formErrors: string[] = [];\n const pathMap = new Map<string, number>();\n\n for (const issue of this.issues) {\n if (issue.path.length === 0) {\n formErrors.push(issue.message);\n } else {\n const key = JSON.stringify(issue.path);\n const existing = pathMap.get(key);\n\n if (existing !== undefined) {\n fieldErrors[existing]!.messages.push(issue.message);\n } else {\n pathMap.set(key, fieldErrors.length);\n fieldErrors.push({ messages: [issue.message], path: [...issue.path] });\n }\n }\n }\n\n return { fieldErrors, formErrors };\n }\n\n flattenFirst(): { fieldErrors: FlatErrorFirst[]; formErrors: string[] } {\n const { fieldErrors, formErrors } = this.flatten();\n\n return {\n fieldErrors: fieldErrors.map((fe) => ({ message: fe.messages[0]!, path: fe.path })),\n formErrors,\n };\n }\n\n format(): FormattedErrors {\n const root = createFormattedErrors();\n\n for (const issue of this.issues) {\n if (issue.path.length === 0) {\n root._errors.push(issue.message);\n continue;\n }\n\n let node = root;\n\n for (const segment of issue.path) {\n const key = String(segment);\n\n // '_errors' is the reserved internal field; treat it as a sibling key\n // with a safe prefix to avoid collisions with the FormattedErrors shape.\n const safeKey = key === '_errors' ? '_errors_' : key;\n\n if (!Object.hasOwn(node, safeKey)) {\n node[safeKey] = createFormattedErrors();\n }\n\n node = node[safeKey] as FormattedErrors;\n }\n\n node._errors.push(issue.message);\n }\n\n return root;\n }\n}\n"],"mappings":"+BAYA,SAAgB,EAAK,EAAc,EAAiB,EAA2C,CAC7F,MAAO,CAAC,CAAE,OAAM,UAAS,SAAQ,KAAM,CAAC,CAAE,CAAU,CACtD,CAGA,SAAgB,EAAoD,EAAqB,EAAkB,CACzG,OAAO,OAAO,GAAQ,WAAa,EAAI,CAAG,EAAI,CAChD,CAEA,SAAgB,EAAiB,EAAiB,EAAkC,CAClF,OAAO,EAAO,IAAK,IAAW,CAAE,GAAG,EAAO,KAAM,CAAC,EAAQ,GAAG,EAAM,IAAI,CAAE,EAAE,CAC5E,CASA,SAAgB,EAAS,EAA4B,GAAG,EAAqC,CAC3F,IAAI,EAAmC,EAEvC,IAAK,IAAM,KAAO,EAAM,CACtB,GAAI,MAAM,QAAQ,CAAI,EAAG,MAAO,CAAC,EAIjC,EAAQ,EAFQ,OAAO,CAAG,IAAM,UAAY,WAAa,OAAO,CAAG,IAEtB,CAAE,QAAS,CAAC,CAAE,CAC7D,CAEA,OAAO,MAAM,QAAQ,CAAI,EAAI,EAAQ,EAAyB,OAChE,CAKA,IAAa,EAAb,MAAa,UAAmB,KAAM,CACpC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,IAAI,OAAO,KACvB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,CAClD,CAEA,OAAO,GAAG,EAAiC,CACzC,OAAO,aAAe,CACxB,CACF,EAIA,SAAS,EAAa,EAAyB,CAC7C,OAAO,EACJ,KAAK,CAAE,OAAM,UAAS,UAGd,GAFS,EAAK,OAAS,EAAK,KAAK,GAAG,EAAI,QAE7B,IAAI,EAAQ,IAAI,EAAK,EACxC,CA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AAE,cAAa,YAAW,CACnC,CAEA,cAAwE,CACtE,GAAM,CAAE,cAAa,cAAe,KAAK,QAAQ,EAEjD,MAAO,CACL,YAAa,EAAY,IAAK,IAAQ,CAAE,QAAS,EAAG,SAAS,GAAK,KAAM,EAAG,IAAK,EAAE,EAClF,YACF,CACF,CAEA,QAA0B,CACxB,IAAM,EAAO,EAAsB,EAEnC,IAAK,IAAM,KAAS,KAAK,OAAQ,CAC/B,GAAI,EAAM,KAAK,SAAW,EAAG,CAC3B,EAAK,QAAQ,KAAK,EAAM,OAAO,EAC/B,QACF,CAEA,IAAI,EAAO,EAEX,IAAK,IAAM,KAAW,EAAM,KAAM,CAChC,IAAM,EAAM,OAAO,CAAO,EAIpB,EAAU,IAAQ,UAAY,WAAa,EAE5C,OAAO,OAAO,EAAM,CAAO,IAC9B,EAAK,GAAW,EAAsB,GAGxC,EAAO,EAAK,EACd,CAEA,EAAK,QAAQ,KAAK,EAAM,OAAO,CACjC,CAEA,OAAO,CACT,CACF"}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { ErrorCode, type Issue } from './types';
|
|
2
|
+
type IssueParams<C extends string> = Extract<Issue, {
|
|
3
|
+
code: C;
|
|
4
|
+
}> extends {
|
|
5
|
+
params: infer P;
|
|
6
|
+
} ? P : undefined;
|
|
7
|
+
/**
|
|
8
|
+
* Creates a single-error failure array. Use in validator functions instead of building the array manually.
|
|
9
|
+
* Typed overloads ensure params match the given error code.
|
|
10
|
+
*/
|
|
11
|
+
export declare function fail<C extends ErrorCode>(code: C, message: string, params: IssueParams<C>): Issue[];
|
|
12
|
+
export declare function fail(code: string, message: string, params?: Record<string, unknown>): Issue[];
|
|
13
|
+
export declare function prependIssuePath(issues: Issue[], prefix: string | number): Issue[];
|
|
14
|
+
export type FormattedErrors = {
|
|
15
|
+
_errors: string[];
|
|
16
|
+
[key: string]: FormattedErrors | string[];
|
|
17
|
+
};
|
|
18
|
+
export declare function errorsAt(formatted: FormattedErrors, ...path: (string | number)[]): string[];
|
|
19
|
+
/** Base class for all spell errors. Use `instanceof SpellError` to catch any spell-originated error. */
|
|
20
|
+
export declare class SpellError extends Error {
|
|
21
|
+
constructor(message: string, opts?: ErrorOptions);
|
|
22
|
+
static is(err: unknown): err is SpellError;
|
|
23
|
+
}
|
|
24
|
+
export type FlatError = {
|
|
25
|
+
messages: string[];
|
|
26
|
+
path: (string | number)[];
|
|
27
|
+
};
|
|
28
|
+
export type FlatErrorFirst = {
|
|
29
|
+
message: string;
|
|
30
|
+
path: (string | number)[];
|
|
31
|
+
};
|
|
32
|
+
export declare class SpellValidationError extends SpellError {
|
|
33
|
+
readonly issues: Issue[];
|
|
34
|
+
constructor(issues: Issue[], cause?: unknown);
|
|
35
|
+
static is(err: unknown): err is SpellValidationError;
|
|
36
|
+
/**
|
|
37
|
+
* Returns the union branch errors from the most-specific failing branch.
|
|
38
|
+
* Surfaces the branch with the fewest issues at the deepest path — the one
|
|
39
|
+
* that "came closest" to matching.
|
|
40
|
+
*/
|
|
41
|
+
bestMatch(): Issue[] | null;
|
|
42
|
+
flatten(): {
|
|
43
|
+
fieldErrors: FlatError[];
|
|
44
|
+
formErrors: string[];
|
|
45
|
+
};
|
|
46
|
+
flattenFirst(): {
|
|
47
|
+
fieldErrors: FlatErrorFirst[];
|
|
48
|
+
formErrors: string[];
|
|
49
|
+
};
|
|
50
|
+
format(): FormattedErrors;
|
|
51
|
+
}
|
|
52
|
+
export {};
|
|
53
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,KAAK,KAAK,EAAkB,MAAM,SAAS,CAAC;AAIhE,KAAK,WAAW,CAAC,CAAC,SAAS,MAAM,IAAI,OAAO,CAAC,KAAK,EAAE;IAAE,IAAI,EAAE,CAAC,CAAA;CAAE,CAAC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,CAAA;CAAE,CAAC;AAU5E,qBAAa,oBAAqB,SAAQ,UAAU;IAClD,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC;gBAEb,MAAM,EAAE,KAAK,EAAE,EAAE,KAAK,CAAC,EAAE,OAAO;IAK5C,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,oBAAoB;IAIpD;;;;OAIG;IACH,SAAS,IAAI,KAAK,EAAE,GAAG,IAAI;IAsB3B,OAAO,IAAI;QAAE,WAAW,EAAE,SAAS,EAAE,CAAC;QAAC,UAAU,EAAE,MAAM,EAAE,CAAA;KAAE;IAwB7D,YAAY,IAAI;QAAE,WAAW,EAAE,cAAc,EAAE,CAAC;QAAC,UAAU,EAAE,MAAM,EAAE,CAAA;KAAE;IASvE,MAAM,IAAI,eAAe;CA8B1B"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{ErrorCode as e}from"./types.js";function t(e,t,n){return[{code:e,message:t,params:n,path:[]}]}function n(e,t){return typeof e==`function`?e(t):e}function r(e,t){return e.map(e=>({...e,path:[t,...e.path]}))}function i(e,...t){let n=e;for(let e of t){if(Array.isArray(n))return[];n=n[String(e)===`_errors`?`_errors_`:String(e)]??{_errors:[]}}return Array.isArray(n)?n:n._errors}var a=class e extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}};function o(e){return e.map(({code:e,message:t,path:n})=>`${n.length?n.join(`.`):`value`}: ${t} [${e}]`).join(`
|
|
2
|
+
`)}function s(){let e=Object.create(null);return e._errors=[],e}var c=class t extends a{issues;constructor(e,t){super(o(e),{cause:t}),this.issues=e}static is(e){return e instanceof t}bestMatch(){let t=this.issues.find(t=>t.code===e.invalid_union);if(!t)return null;let n=t.params.errors;if(n.length===0)return null;let r=n.map(e=>({issues:e,score:e.reduce((e,t)=>Math.max(e,t.path.length),0)*1e3-e.length}));return r.sort((e,t)=>t.score-e.score),r[0].issues}flatten(){let e=[],t=[],n=new Map;for(let r of this.issues)if(r.path.length===0)t.push(r.message);else{let t=JSON.stringify(r.path),i=n.get(t);i===void 0?(n.set(t,e.length),e.push({messages:[r.message],path:[...r.path]})):e[i].messages.push(r.message)}return{fieldErrors:e,formErrors:t}}flattenFirst(){let{fieldErrors:e,formErrors:t}=this.flatten();return{fieldErrors:e.map(e=>({message:e.messages[0],path:e.path})),formErrors:t}}format(){let e=s();for(let t of this.issues){if(t.path.length===0){e._errors.push(t.message);continue}let n=e;for(let e of t.path){let t=String(e),r=t===`_errors`?`_errors_`:t;Object.hasOwn(n,r)||(n[r]=s()),n=n[r]}n._errors.push(t.message)}return e}};export{a as SpellError,c as SpellValidationError,i as errorsAt,t as fail,r as prependIssuePath,n as resolveMessage};
|
|
3
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { ErrorCode, type Issue, type MessageFn } from './types';\n\n/* -------------------- Helpers -------------------- */\n\ntype IssueParams<C extends string> = Extract<Issue, { code: C }> extends { params: infer P } ? P : undefined;\n\n/**\n * Creates a single-error failure array. Use in validator functions instead of building the array manually.\n * Typed overloads ensure params match the given error code.\n */\nexport function fail<C extends ErrorCode>(code: C, message: string, params: IssueParams<C>): Issue[];\nexport function fail(code: string, message: string, params?: Record<string, unknown>): Issue[];\nexport function fail(code: string, message: string, params?: Record<string, unknown>): Issue[] {\n return [{ code, message, params, path: [] } as Issue];\n}\n\n/** @internal */\nexport function resolveMessage<Ctx extends Record<string, unknown>>(msg: MessageFn<Ctx>, ctx: Ctx): string {\n return typeof msg === 'function' ? msg(ctx) : msg;\n}\n\nexport function prependIssuePath(issues: Issue[], prefix: string | number): Issue[] {\n return issues.map((issue) => ({ ...issue, path: [prefix, ...issue.path] }));\n}\n\n/* -------------------- FormattedErrors -------------------- */\n\nexport type FormattedErrors = {\n _errors: string[];\n [key: string]: FormattedErrors | string[];\n};\n\nexport function errorsAt(formatted: FormattedErrors, ...path: (string | number)[]): string[] {\n let node: FormattedErrors | string[] = formatted;\n\n for (const key of path) {\n if (Array.isArray(node)) return [];\n\n const safeKey = String(key) === '_errors' ? '_errors_' : String(key);\n\n node = (node as FormattedErrors)[safeKey] ?? { _errors: [] };\n }\n\n return Array.isArray(node) ? node : (node as FormattedErrors)._errors;\n}\n\n/* -------------------- SpellError -------------------- */\n\n/** Base class for all spell errors. Use `instanceof SpellError` to catch any spell-originated error. */\nexport class SpellError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is SpellError {\n return err instanceof SpellError;\n }\n}\n\n/* -------------------- SpellValidationError -------------------- */\n\nfunction formatIssues(issues: Issue[]): string {\n return issues\n .map(({ code, message, path }) => {\n const pathStr = path.length ? path.join('.') : 'value';\n\n return `${pathStr}: ${message} [${code}]`;\n })\n .join('\\n');\n}\n\nexport type FlatError = { messages: string[]; path: (string | number)[] };\nexport type FlatErrorFirst = { message: string; path: (string | number)[] };\n\nfunction createFormattedErrors(): FormattedErrors {\n const node = Object.create(null) as FormattedErrors;\n\n node._errors = [];\n\n return node;\n}\n\nexport class SpellValidationError extends SpellError {\n readonly issues: Issue[];\n\n constructor(issues: Issue[], cause?: unknown) {\n super(formatIssues(issues), { cause });\n this.issues = issues;\n }\n\n static is(err: unknown): err is SpellValidationError {\n return err instanceof SpellValidationError;\n }\n\n /**\n * Returns the union branch errors from the most-specific failing branch.\n * Surfaces the branch with the fewest issues at the deepest path — the one\n * that \"came closest\" to matching.\n */\n bestMatch(): Issue[] | null {\n const unionIssue = this.issues.find(\n (i): i is Extract<Issue, { code: 'invalid_union' }> => i.code === ErrorCode.invalid_union,\n );\n\n if (!unionIssue) return null;\n\n const branches = unionIssue.params.errors;\n\n if (branches.length === 0) return null;\n\n const scored = branches.map((branchIssues) => {\n const maxDepth = branchIssues.reduce((d, i) => Math.max(d, i.path.length), 0);\n\n return { issues: branchIssues, score: maxDepth * 1000 - branchIssues.length };\n });\n\n scored.sort((a, b) => b.score - a.score);\n\n return scored[0]!.issues;\n }\n\n flatten(): { fieldErrors: FlatError[]; formErrors: string[] } {\n const fieldErrors: FlatError[] = [];\n const formErrors: string[] = [];\n const pathMap = new Map<string, number>();\n\n for (const issue of this.issues) {\n if (issue.path.length === 0) {\n formErrors.push(issue.message);\n } else {\n const key = JSON.stringify(issue.path);\n const existing = pathMap.get(key);\n\n if (existing !== undefined) {\n fieldErrors[existing]!.messages.push(issue.message);\n } else {\n pathMap.set(key, fieldErrors.length);\n fieldErrors.push({ messages: [issue.message], path: [...issue.path] });\n }\n }\n }\n\n return { fieldErrors, formErrors };\n }\n\n flattenFirst(): { fieldErrors: FlatErrorFirst[]; formErrors: string[] } {\n const { fieldErrors, formErrors } = this.flatten();\n\n return {\n fieldErrors: fieldErrors.map((fe) => ({ message: fe.messages[0]!, path: fe.path })),\n formErrors,\n };\n }\n\n format(): FormattedErrors {\n const root = createFormattedErrors();\n\n for (const issue of this.issues) {\n if (issue.path.length === 0) {\n root._errors.push(issue.message);\n continue;\n }\n\n let node = root;\n\n for (const segment of issue.path) {\n const key = String(segment);\n\n // '_errors' is the reserved internal field; treat it as a sibling key\n // with a safe prefix to avoid collisions with the FormattedErrors shape.\n const safeKey = key === '_errors' ? '_errors_' : key;\n\n if (!Object.hasOwn(node, safeKey)) {\n node[safeKey] = createFormattedErrors();\n }\n\n node = node[safeKey] as FormattedErrors;\n }\n\n node._errors.push(issue.message);\n }\n\n return root;\n }\n}\n"],"mappings":"uCAYA,SAAgB,EAAK,EAAc,EAAiB,EAA2C,CAC7F,MAAO,CAAC,CAAE,OAAM,UAAS,SAAQ,KAAM,CAAC,CAAE,CAAU,CACtD,CAGA,SAAgB,EAAoD,EAAqB,EAAkB,CACzG,OAAO,OAAO,GAAQ,WAAa,EAAI,CAAG,EAA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AChC,IAAM,EAAM,OAAO,CAAO,EAIpB,EAAU,IAAQ,UAAY,WAAa,EAE5C,OAAO,OAAO,EAAM,CAAO,IAC9B,EAAK,GAAW,EAAsB,GAGxC,EAAO,EAAK,EACd,CAEA,EAAK,QAAQ,KAAK,EAAM,OAAO,CACjC,CAEA,OAAO,CACT,CACF"}
|
package/dist/formats.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){return/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(e)}var t=new Set([`http`,`https`]);function n(e,n){try{let r=new URL(e);return(n?new Set(n.map(e=>e.toLowerCase())):t).has(r.protocol.replace(`:`,``).toLowerCase())}catch{return!1}}function r(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function i(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=new Date(e);return!Number.isNaN(t.getTime())&&t.toISOString().startsWith(e)}function a(e){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})?$/.test(e)&&!Number.isNaN(new Date(e).getTime())}function o(e){if(/^(\d{1,3}\.){3}\d{1,3}$/.test(e))return e.split(`.`).every(e=>{let t=parseInt(e,10);return t>=0&&t<=255});try{return new URL(`http://[${e}]/`),!0}catch{return!1}}function s(e){return/^c[a-z0-9]{8,}$/.test(e)}function c(e){return/^[a-z][a-z0-9]{23}$/.test(e)}function l(e){return/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(e)}function u(e,t=21){return e.length===t&&/^[A-Za-z0-9_-]+$/.test(e)}function d(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(e)}function f(e){return e.length===0||e.length%4==1?!1:/^[A-Za-z0-9_-]*={0,2}$/.test(e)}function p(e){return/^[A-Fa-f0-9]+$/.test(e)}function m(e){return/^#(?:[A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test(e)}function h(e){return/^\p{Extended_Pictographic}+$/u.test(e)}function g(e){return/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e)}function _(e){return/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/.test(e)}function v(e){return/^P(?=\d|T\d)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(\d+H)?(\d+M)?(\d+(?:\.\d+)?S)?)?$/.test(e)}function y(e){return/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.test(e)}function b(e){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}function x(e){return/^[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?$/i.test(e)}exports.isBase64=d,exports.isBase64url=f,exports.isCuid=s,exports.isCuid2=c,exports.isDuration=v,exports.isEmail=e,exports.isEmoji=h,exports.isHex=p,exports.isHexColor=m,exports.isIp=o,exports.isIsoDate=i,exports.isIsoDateTime=a,exports.isJwt=g,exports.isNanoid=u,exports.isNumeric=x,exports.isSemver=y,exports.isSlug=b,exports.isTime=_,exports.isUlid=l,exports.isUrl=n,exports.isUuid=r;
|
|
2
|
+
//# sourceMappingURL=formats.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"formats.cjs","names":[],"sources":["../src/formats.ts"],"sourcesContent":["/**\n * Pure string format validators.\n *\n * All functions take a `string` and return `boolean`. They are exported as part of the\n * public API so callers can use them independently of any Schema.\n *\n * ```ts\n * import { isEmail, isUuid } from '@vielzeug/spell';\n * isEmail('foo@bar.com'); // true\n * ```\n */\n\nexport function isEmail(v: string): boolean {\n return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/.test(v);\n}\n\nconst _DEFAULT_URL_PROTOCOLS = new Set(['http', 'https']);\n\nexport function isUrl(v: string, protocols?: readonly string[]): boolean {\n try {\n const parsed = new URL(v);\n const allowed = protocols ? new Set(protocols.map((p) => p.toLowerCase())) : _DEFAULT_URL_PROTOCOLS;\n\n return allowed.has(parsed.protocol.replace(':', '').toLowerCase());\n } catch {\n return false;\n }\n}\n\nexport function isUuid(v: string): boolean {\n return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);\n}\n\nexport function isIsoDate(v: string): boolean {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(v)) return false;\n\n const d = new Date(v);\n\n return !Number.isNaN(d.getTime()) && d.toISOString().startsWith(v);\n}\n\nexport function isIsoDateTime(v: string): boolean {\n return (\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}:\\d{2})?$/.test(v) &&\n !Number.isNaN(new Date(v).getTime())\n );\n}\n\nexport function isIp(v: string): boolean {\n // IPv4\n if (/^(\\d{1,3}\\.){3}\\d{1,3}$/.test(v)) {\n return v.split('.').every((o) => {\n const n = parseInt(o, 10);\n\n return n >= 0 && n <= 255;\n });\n }\n\n // IPv6 — rely on URL parser\n try {\n new URL(`http://[${v}]/`);\n\n return true;\n } catch {\n return false;\n }\n}\n\nexport function isCuid(v: string): boolean {\n return /^c[a-z0-9]{8,}$/.test(v);\n}\n\nexport function isCuid2(v: string): boolean {\n return /^[a-z][a-z0-9]{23}$/.test(v);\n}\n\nexport function isUlid(v: string): boolean {\n return /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(v);\n}\n\n/**\n * Validates a NanoID string. The default NanoID length is 21 characters; pass a\n * custom length to validate IDs generated with non-default sizes.\n */\nexport function isNanoid(v: string, length = 21): boolean {\n return v.length === length && /^[A-Za-z0-9_-]+$/.test(v);\n}\n\nexport function isBase64(v: string): boolean {\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(v);\n}\n\n/**\n * Validates a base64url-encoded string (RFC 4648 §5). Accepts unpadded and padded forms.\n * A string whose length % 4 === 1 is never valid base64url.\n */\nexport function isBase64url(v: string): boolean {\n if (v.length === 0 || v.length % 4 === 1) return false;\n\n return /^[A-Za-z0-9_-]*={0,2}$/.test(v);\n}\n\nexport function isHex(v: string): boolean {\n return /^[A-Fa-f0-9]+$/.test(v);\n}\n\nexport function isHexColor(v: string): boolean {\n return /^#(?:[A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test(v);\n}\n\nexport function isEmoji(v: string): boolean {\n return /^\\p{Extended_Pictographic}+$/u.test(v);\n}\n\nexport function isJwt(v: string): boolean {\n return /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/.test(v);\n}\n\nexport function isTime(v: string): boolean {\n return /^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d)?$/.test(v);\n}\n\nexport function isDuration(v: string): boolean {\n return /^P(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(T(\\d+H)?(\\d+M)?(\\d+(?:\\.\\d+)?S)?)?$/.test(v);\n}\n\nexport function isSemver(v: string): boolean {\n return /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$/.test(\n v,\n );\n}\n\nexport function isSlug(v: string): boolean {\n return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(v);\n}\n\nexport function isNumeric(v: string): boolean {\n return /^[-+]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[-+]?\\d+)?$/i.test(v);\n}\n"],"mappings":"AAYA,SAAgB,EAAQ,EAAoB,CAC1C,MAAO,mDAAmD,KAAK,CAAC,CAClE,CAEA,IAAM,EAAyB,IAAI,IAAI,CAAC,OAAQ,OAAO,CAAC,EAExD,SAAgB,EAAM,EAAW,EAAwC,CACvE,GAAI,CACF,IAAM,EAAS,IAAI,IAAI,CAAC,EAGxB,OAFgB,EAAY,IAAI,IAAI,EAAU,IAAK,GAAM,EAAE,YAAY,CAAC,CAAC,EAAI,EAAA,CAE9D,IAAI,EAAO,SAAS,QAAQ,IAAK,EAAE,CAAC,CAAC,YAAY,CAAC,CACnE,MAAQ,CACN,MAAO,EACT,CACF,CAEA,SAAgB,EAAO,EAAoB,CACzC,MAAO,kEAAkE,KAAK,CAAC,CACjF,CAEA,SAAgB,EAAU,EAAoB,CAC5C,GAAI,CAAC,sBAAsB,KAAK,CAAC,EAAG,MAAO,GAE3C,IAAM,EAAI,IAAI,KAAK,CAAC,EAEpB,MAAO,CAAC,OAAO,MAAM,EAAE,QAAQ,CAAC,GAAK,EAAE,YAAY,CAAC,CAAC,WAAW,CAAC,CACnE,CAEA,SAAgB,EAAc,EAAoB,CAChD,MACE,6EAA6E,KAAK,CAAC,GACnF,CAAC,OAAO,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAEvC,CAEA,SAAgB,EAAK,EAAoB,CAEvC,GAAI,0BAA0B,KAAK,CAAC,EAClC,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,MAAO,GAAM,CAC/B,IAAM,EAAI,SAAS,EAAG,EAAE,EAExB,OAAO,GAAK,GAAK,GAAK,GACxB,CAAC,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
|
|
3
|
+
*
|
|
4
|
+
* All functions take a `string` and return `boolean`. They are exported as part of the
|
|
5
|
+
* public API so callers can use them independently of any Schema.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* import { isEmail, isUuid } from '@vielzeug/spell';
|
|
9
|
+
* isEmail('foo@bar.com'); // true
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare function isEmail(v: string): boolean;
|
|
13
|
+
export declare function isUrl(v: string, protocols?: readonly string[]): boolean;
|
|
14
|
+
export declare function isUuid(v: string): boolean;
|
|
15
|
+
export declare function isIsoDate(v: string): boolean;
|
|
16
|
+
export declare function isIsoDateTime(v: string): boolean;
|
|
17
|
+
export declare function isIp(v: string): boolean;
|
|
18
|
+
export declare function isCuid(v: string): boolean;
|
|
19
|
+
export declare function isCuid2(v: string): boolean;
|
|
20
|
+
export declare function isUlid(v: string): boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Validates a NanoID string. The default NanoID length is 21 characters; pass a
|
|
23
|
+
* custom length to validate IDs generated with non-default sizes.
|
|
24
|
+
*/
|
|
25
|
+
export declare function isNanoid(v: string, length?: number): boolean;
|
|
26
|
+
export declare function isBase64(v: string): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Validates a base64url-encoded string (RFC 4648 §5). Accepts unpadded and padded forms.
|
|
29
|
+
* A string whose length % 4 === 1 is never valid base64url.
|
|
30
|
+
*/
|
|
31
|
+
export declare function isBase64url(v: string): boolean;
|
|
32
|
+
export declare function isHex(v: string): boolean;
|
|
33
|
+
export declare function isHexColor(v: string): boolean;
|
|
34
|
+
export declare function isEmoji(v: string): boolean;
|
|
35
|
+
export declare function isJwt(v: string): boolean;
|
|
36
|
+
export declare function isTime(v: string): boolean;
|
|
37
|
+
export declare function isDuration(v: string): boolean;
|
|
38
|
+
export declare function isSemver(v: string): boolean;
|
|
39
|
+
export declare function isSlug(v: string): boolean;
|
|
40
|
+
export declare function isNumeric(v: string): boolean;
|
|
41
|
+
//# sourceMappingURL=formats.d.ts.map
|