@atproto/lex-schema 0.0.20 → 0.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/CHANGELOG.md +18 -0
- package/dist/core/$type.js +2 -6
- package/dist/core/$type.js.map +1 -1
- package/dist/core/record-key.js +4 -8
- package/dist/core/record-key.js.map +1 -1
- package/dist/core/result.js +6 -14
- package/dist/core/result.js.map +1 -1
- package/dist/core/schema.js +16 -20
- package/dist/core/schema.js.map +1 -1
- package/dist/core/standard-schema.js +5 -10
- package/dist/core/standard-schema.js.map +1 -1
- package/dist/core/string-format.d.ts.map +1 -1
- package/dist/core/string-format.js +37 -61
- package/dist/core/string-format.js.map +1 -1
- package/dist/core/types.js +1 -2
- package/dist/core/validation-error.js +14 -25
- package/dist/core/validation-error.js.map +1 -1
- package/dist/core/validation-issue.js +12 -40
- package/dist/core/validation-issue.js.map +1 -1
- package/dist/core/validator.js +19 -28
- package/dist/core/validator.js.map +1 -1
- package/dist/core.js +9 -12
- package/dist/core.js.map +1 -1
- package/dist/external.js +3 -6
- package/dist/external.js.map +1 -1
- package/dist/helpers.js +5 -9
- package/dist/helpers.js.map +1 -1
- package/dist/index.js +3 -7
- package/dist/index.js.map +1 -1
- package/dist/schema/array.js +5 -11
- package/dist/schema/array.js.map +1 -1
- package/dist/schema/blob.js +10 -17
- package/dist/schema/blob.js.map +1 -1
- package/dist/schema/boolean.js +8 -9
- package/dist/schema/boolean.js.map +1 -1
- package/dist/schema/bytes.js +7 -12
- package/dist/schema/bytes.js.map +1 -1
- package/dist/schema/cid.js +7 -12
- package/dist/schema/cid.js.map +1 -1
- package/dist/schema/custom.js +5 -13
- package/dist/schema/custom.js.map +1 -1
- package/dist/schema/dict.js +6 -13
- package/dist/schema/dict.js.map +1 -1
- package/dist/schema/discriminated-union.js +10 -18
- package/dist/schema/discriminated-union.js.map +1 -1
- package/dist/schema/enum.js +6 -11
- package/dist/schema/enum.js.map +1 -1
- package/dist/schema/integer.js +5 -10
- package/dist/schema/integer.js.map +1 -1
- package/dist/schema/intersection.js +4 -11
- package/dist/schema/intersection.js.map +1 -1
- package/dist/schema/lex-map.js +13 -14
- package/dist/schema/lex-map.js.map +1 -1
- package/dist/schema/lex-value.js +11 -12
- package/dist/schema/lex-value.js.map +1 -1
- package/dist/schema/literal.js +4 -10
- package/dist/schema/literal.js.map +1 -1
- package/dist/schema/never.js +8 -9
- package/dist/schema/never.js.map +1 -1
- package/dist/schema/null.js +9 -10
- package/dist/schema/null.js.map +1 -1
- package/dist/schema/nullable.js +5 -10
- package/dist/schema/nullable.js.map +1 -1
- package/dist/schema/object.js +8 -14
- package/dist/schema/object.js.map +1 -1
- package/dist/schema/optional.js +5 -10
- package/dist/schema/optional.js.map +1 -1
- package/dist/schema/params.js +39 -44
- package/dist/schema/params.js.map +1 -1
- package/dist/schema/payload.js +5 -13
- package/dist/schema/payload.js.map +1 -1
- package/dist/schema/permission-set.js +2 -10
- package/dist/schema/permission-set.js.map +1 -1
- package/dist/schema/permission.js +2 -9
- package/dist/schema/permission.js.map +1 -1
- package/dist/schema/procedure.js +3 -13
- package/dist/schema/procedure.js.map +1 -1
- package/dist/schema/query.js +3 -12
- package/dist/schema/query.js.map +1 -1
- package/dist/schema/record.js +15 -24
- package/dist/schema/record.js.map +1 -1
- package/dist/schema/ref.js +4 -9
- package/dist/schema/ref.js.map +1 -1
- package/dist/schema/refine.js +3 -6
- package/dist/schema/refine.js.map +1 -1
- package/dist/schema/regexp.js +4 -11
- package/dist/schema/regexp.js.map +1 -1
- package/dist/schema/string.js +15 -26
- package/dist/schema/string.js.map +1 -1
- package/dist/schema/subscription.js +3 -12
- package/dist/schema/subscription.js.map +1 -1
- package/dist/schema/token.js +5 -11
- package/dist/schema/token.js.map +1 -1
- package/dist/schema/typed-object.js +11 -18
- package/dist/schema/typed-object.js.map +1 -1
- package/dist/schema/typed-ref.js +4 -9
- package/dist/schema/typed-ref.js.map +1 -1
- package/dist/schema/typed-union.js +8 -15
- package/dist/schema/typed-union.js.map +1 -1
- package/dist/schema/union.js +5 -11
- package/dist/schema/union.js.map +1 -1
- package/dist/schema/unknown.js +8 -9
- package/dist/schema/unknown.js.map +1 -1
- package/dist/schema/with-default.js +4 -11
- package/dist/schema/with-default.js.map +1 -1
- package/dist/schema.js +38 -41
- package/dist/schema.js.map +1 -1
- package/dist/util/array-agg.js +1 -4
- package/dist/util/array-agg.js.map +1 -1
- package/dist/util/assertion-util.js +1 -2
- package/dist/util/if-any.js +1 -2
- package/dist/util/lazy-property.js +1 -4
- package/dist/util/lazy-property.js.map +1 -1
- package/dist/util/memoize.js +2 -6
- package/dist/util/memoize.js.map +1 -1
- package/package.json +7 -8
- package/src/core/string-format.ts +2 -1
- package/src/helpers.test.ts +52 -52
- package/src/schema/record.test.ts +2 -2
- package/src/schema/ref.test.ts +1 -1
- package/src/schema/string.test.ts +6 -6
- package/src/schema/subscription.test.ts +4 -4
- package/src/schema/typed-object.test.ts +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @atproto/lex-schema
|
|
2
2
|
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#4929](https://github.com/bluesky-social/atproto/pull/4929) [`f01c59f`](https://github.com/bluesky-social/atproto/commit/f01c59f5bd3f75fb8b47a9eecd4858b84033fb7c) Thanks [@devinivy](https://github.com/devinivy)! - **BREAKING:** Drop support for Node.js 18 and 20. Node.js 22 is now the minimum supported version. Docker images now use Node.js 24.
|
|
8
|
+
|
|
9
|
+
- [#4943](https://github.com/bluesky-social/atproto/pull/4943) [`c459153`](https://github.com/bluesky-social/atproto/commit/c459153395a30ce89e050892c8fab7dc98e019b9) Thanks [@devinivy](https://github.com/devinivy)! - **BREAKING:** Convert to pure ESM. All packages now ship `"type": "module"` with ES module output and Node16 module resolution.
|
|
10
|
+
|
|
11
|
+
Node.js 22's `require()` compatibility layer can still load these packages in CommonJS code.
|
|
12
|
+
|
|
13
|
+
- [#4930](https://github.com/bluesky-social/atproto/pull/4930) [`908bece`](https://github.com/bluesky-social/atproto/commit/908bece169258bff5ad121e5eec157d6ded6f705) Thanks [@devinivy](https://github.com/devinivy)! - Build with TypeScript 6.0.
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- Updated dependencies [[`f01c59f`](https://github.com/bluesky-social/atproto/commit/f01c59f5bd3f75fb8b47a9eecd4858b84033fb7c), [`c459153`](https://github.com/bluesky-social/atproto/commit/c459153395a30ce89e050892c8fab7dc98e019b9), [`908bece`](https://github.com/bluesky-social/atproto/commit/908bece169258bff5ad121e5eec157d6ded6f705)]:
|
|
18
|
+
- @atproto/lex-data@0.1.0
|
|
19
|
+
- @atproto/syntax@0.6.0
|
|
20
|
+
|
|
3
21
|
## 0.0.20
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/dist/core/$type.js
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.$type = $type;
|
|
4
|
-
exports.$typed = $typed;
|
|
5
1
|
/**
|
|
6
2
|
* Constructs a `$type` string value from an NSID and definition name.
|
|
7
3
|
*
|
|
@@ -24,7 +20,7 @@ exports.$typed = $typed;
|
|
|
24
20
|
* ```
|
|
25
21
|
*/
|
|
26
22
|
/*@__NO_SIDE_EFFECTS__*/
|
|
27
|
-
function $type(nsid, hash) {
|
|
23
|
+
export function $type(nsid, hash) {
|
|
28
24
|
return (hash === 'main' ? nsid : `${nsid}#${hash}`);
|
|
29
25
|
}
|
|
30
26
|
/**
|
|
@@ -50,7 +46,7 @@ function $type(nsid, hash) {
|
|
|
50
46
|
* console.log(typed === same) // true
|
|
51
47
|
* ```
|
|
52
48
|
*/
|
|
53
|
-
function $typed(value, $type) {
|
|
49
|
+
export function $typed(value, $type) {
|
|
54
50
|
return value.$type === $type ? value : { ...value, $type };
|
|
55
51
|
}
|
|
56
52
|
//# sourceMappingURL=$type.js.map
|
package/dist/core/$type.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"$type.js","sourceRoot":"","sources":["../../src/core/$type.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"$type.js","sourceRoot":"","sources":["../../src/core/$type.ts"],"names":[],"mappings":"AA+CA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAwB;AACxB,MAAM,UAAU,KAAK,CACnB,IAAO,EACP,IAAO;IAEP,OAAO,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,IAAI,EAAE,CAAgB,CAAA;AACpE,CAAC;AAuBD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,MAAM,CACpB,KAAQ,EACR,KAAQ;IAER,OAAO,KAAK,CAAC,KAAK,KAAK,KAAK,CAAC,CAAC,CAAE,KAAsB,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,KAAK,EAAE,CAAA;AAC9E,CAAC","sourcesContent":["import { NsidString } from './string-format.js'\nimport { OmitKey, Simplify } from './types.js'\n\n/**\n * Constructs the `$type` string type for a given NSID and hash.\n *\n * The `$type` value identifies a schema definition within a lexicon:\n * - For \"main\" definitions: just the NSID (e.g., `'app.bsky.feed.post'`)\n * - For named definitions: NSID + hash + name (e.g., `'app.bsky.feed.defs#postView'`)\n *\n * @typeParam N - The NSID string type\n * @typeParam H - The hash/definition name (use `'main'` for the main definition)\n *\n * @example\n * ```typescript\n * type MainType = $Type<'app.bsky.feed.post', 'main'>\n * // Result: 'app.bsky.feed.post'\n *\n * type DefType = $Type<'app.bsky.feed.defs', 'postView'>\n * // Result: 'app.bsky.feed.defs#postView'\n * ```\n */\nexport type $Type<\n N extends NsidString = NsidString,\n H extends string = string,\n> = N extends NsidString\n ? string extends H\n ? N | `${N}#${string}`\n : H extends 'main'\n ? N\n : `${N}#${H}`\n : never\n\n/**\n * Extracts the `$type` string type from an object type.\n *\n * @typeParam O - An object type with an optional `$type` property\n *\n * @example\n * ```typescript\n * type Post = { $type: 'app.bsky.feed.post'; text: string }\n * type PostType = $TypeOf<Post>\n * // Result: 'app.bsky.feed.post'\n * ```\n */\nexport type $TypeOf<O extends { $type?: string }> = NonNullable<O['$type']>\n\n/**\n * Constructs a `$type` string value from an NSID and definition name.\n *\n * For the \"main\" definition, returns just the NSID. For named definitions,\n * returns the NSID followed by `#` and the definition name.\n *\n * @typeParam N - The NSID string type\n * @typeParam H - The definition name type\n * @param nsid - The NSID of the lexicon\n * @param hash - The definition name within the lexicon (use `'main'` for the main definition)\n * @returns The constructed `$type` string\n *\n * @example\n * ```typescript\n * $type('app.bsky.feed.post', 'main')\n * // Returns: 'app.bsky.feed.post'\n *\n * $type('app.bsky.feed.defs', 'postView')\n * // Returns: 'app.bsky.feed.defs#postView'\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function $type<N extends NsidString, H extends string>(\n nsid: N,\n hash: H,\n): $Type<N, H> {\n return (hash === 'main' ? nsid : `${nsid}#${hash}`) as $Type<N, H>\n}\n\n/**\n * Represents an object with a required `$type` property.\n *\n * This type adds a `$type` property to an existing object type, useful for\n * representing typed AT Protocol objects.\n *\n * @typeParam V - The base object type\n * @typeParam T - The `$type` string literal type\n *\n * @example\n * ```typescript\n * type Post = $Typed<{ text: string; createdAt: string }, 'app.bsky.feed.post'>\n * // Result: { $type: 'app.bsky.feed.post'; text: string; createdAt: string }\n * ```\n */\nexport type $Typed<V, T extends string = string> = Simplify<\n V & {\n $type: T\n }\n>\n\n/**\n * Ensures an object has the specified `$type` property.\n *\n * If the object already has the correct `$type`, returns it unchanged.\n * Otherwise, creates a new object with the `$type` property added.\n *\n * @typeParam V - The object type (may already have `$type`)\n * @typeParam T - The expected `$type` string\n * @param value - The object to add `$type` to\n * @param $type - The `$type` value to ensure\n * @returns The object with the `$type` property\n *\n * @example\n * ```typescript\n * const post = $typed({ text: 'hello' }, 'app.bsky.feed.post')\n * // Result: { $type: 'app.bsky.feed.post', text: 'hello' }\n *\n * // If already typed, returns same object\n * const typed = { $type: 'app.bsky.feed.post', text: 'hello' }\n * const same = $typed(typed, 'app.bsky.feed.post')\n * console.log(typed === same) // true\n * ```\n */\nexport function $typed<V extends { $type?: unknown }, T extends string>(\n value: V,\n $type: T,\n): $Typed<V, T> {\n return value.$type === $type ? (value as $Typed<V, T>) : { ...value, $type }\n}\n\n/**\n * Represents an object with an optional `$type` property.\n *\n * This is used for objects that may or may not have type information,\n * such as input parameters that accept both typed and untyped values.\n *\n * @typeParam V - The base object type\n * @typeParam T - The optional `$type` string literal type\n */\nexport type $TypedMaybe<V, T extends string = string> = Simplify<\n V & {\n $type?: T\n }\n>\n\n/**\n * Removes the `$type` property from an object type.\n *\n * Useful for extracting the \"content\" of a typed object without the type marker.\n *\n * @typeParam V - An object type with an optional `$type` property\n *\n * @example\n * ```typescript\n * type Post = { $type: 'app.bsky.feed.post'; text: string }\n * type PostContent = Un$Typed<Post>\n * // Result: { text: string }\n * ```\n */\nexport type Un$Typed<V extends { $type?: string }> = OmitKey<V, '$type'>\n\n/**\n * Unique symbol for branding unknown `$type` strings.\n * @internal\n */\ndeclare const unknown$TypeSymbol: unique symbol\n\n/**\n * Represents an unknown or unrecognized `$type` string.\n *\n * This branded type is used in union types to distinguish between\n * known typed objects and unknown typed objects (from open unions).\n * The branding prevents accidentally matching known `$type` values.\n */\nexport type Unknown$Type = string & { [unknown$TypeSymbol]: true }\n\n/**\n * Represents an object with an unknown `$type` value.\n *\n * This type is used in open union schemas to represent typed objects that\n * don't match any of the known types. The {@link Unknown$Type} branding ensures\n * that invalid instances of known types don't accidentally match this type.\n *\n * For example, in an open union like:\n * ```typescript\n * type MyOpenUnion = { $type: 'A'; a: number } | Unknown$TypedObject\n * ```\n *\n * A value `{ $type: 'A' }` (missing the required `a` property) will NOT match\n * `Unknown$TypedObject` because `'A'` is not assignable to `Unknown$Type`.\n * This ensures that malformed instances of known types are properly rejected.\n *\n * @example\n * ```typescript\n * // This represents any typed object we don't recognize\n * const unknownTyped: Unknown$TypedObject = {\n * $type: 'some.unknown.type' as Unknown$Type,\n * // ... arbitrary properties\n * }\n * ```\n */\nexport type Unknown$TypedObject = { $type: Unknown$Type }\n"]}
|
package/dist/core/record-key.js
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isLexiconRecordKey = isLexiconRecordKey;
|
|
4
|
-
exports.asLexiconRecordKey = asLexiconRecordKey;
|
|
5
|
-
const syntax_1 = require("@atproto/syntax");
|
|
1
|
+
import { isValidRecordKey } from '@atproto/syntax';
|
|
6
2
|
/**
|
|
7
3
|
* Type guard that checks if a value is a valid lexicon record key constraint.
|
|
8
4
|
*
|
|
@@ -19,14 +15,14 @@ const syntax_1 = require("@atproto/syntax");
|
|
|
19
15
|
* ```
|
|
20
16
|
*/
|
|
21
17
|
/*@__NO_SIDE_EFFECTS__*/
|
|
22
|
-
function isLexiconRecordKey(key) {
|
|
18
|
+
export function isLexiconRecordKey(key) {
|
|
23
19
|
return (key === 'any' ||
|
|
24
20
|
key === 'nsid' ||
|
|
25
21
|
key === 'tid' ||
|
|
26
22
|
(typeof key === 'string' &&
|
|
27
23
|
key.startsWith('literal:') &&
|
|
28
24
|
key.length > 8 &&
|
|
29
|
-
|
|
25
|
+
isValidRecordKey(key.slice(8))));
|
|
30
26
|
}
|
|
31
27
|
/**
|
|
32
28
|
* Validates and returns a value as a lexicon record key constraint, throwing if invalid.
|
|
@@ -44,7 +40,7 @@ function isLexiconRecordKey(key) {
|
|
|
44
40
|
* ```
|
|
45
41
|
*/
|
|
46
42
|
/*@__NO_SIDE_EFFECTS__*/
|
|
47
|
-
function asLexiconRecordKey(key) {
|
|
43
|
+
export function asLexiconRecordKey(key) {
|
|
48
44
|
if (isLexiconRecordKey(key))
|
|
49
45
|
return key;
|
|
50
46
|
throw new Error(`Invalid record key: ${String(key)}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"record-key.js","sourceRoot":"","sources":["../../src/core/record-key.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"record-key.js","sourceRoot":"","sources":["../../src/core/record-key.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAkBlD;;;;;;;;;;;;;;GAcG;AACH,wBAAwB;AACxB,MAAM,UAAU,kBAAkB,CAAI,GAAM;IAC1C,OAAO,CACL,GAAG,KAAK,KAAK;QACb,GAAG,KAAK,MAAM;QACd,GAAG,KAAK,KAAK;QACb,CAAC,OAAO,GAAG,KAAK,QAAQ;YACtB,GAAG,CAAC,UAAU,CAAC,UAAU,CAAC;YAC1B,GAAG,CAAC,MAAM,GAAG,CAAC;YACd,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAClC,CAAA;AACH,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAwB;AACxB,MAAM,UAAU,kBAAkB,CAAC,GAAY;IAC7C,IAAI,kBAAkB,CAAC,GAAG,CAAC;QAAE,OAAO,GAAG,CAAA;IACvC,MAAM,IAAI,KAAK,CAAC,uBAAuB,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;AACvD,CAAC","sourcesContent":["import { isValidRecordKey } from '@atproto/syntax'\n\n/**\n * The valid record key constraint types in a lexicon definition.\n *\n * - `'any'` - Accepts any valid record key\n * - `'nsid'` - Record key must be a valid NSID\n * - `'tid'` - Record key must be a valid TID\n * - `'literal:...'` - Record key must be the exact specified value\n *\n * @example\n * ```typescript\n * const constraint: LexiconRecordKey = 'tid'\n * const literalConstraint: LexiconRecordKey = 'literal:self'\n * ```\n */\nexport type LexiconRecordKey = 'any' | 'nsid' | 'tid' | `literal:${string}`\n\n/**\n * Type guard that checks if a value is a valid lexicon record key constraint.\n *\n * @typeParam T - The input type\n * @param key - The value to check\n * @returns `true` if the value is a valid record key constraint\n *\n * @example\n * ```typescript\n * if (isLexiconRecordKey(value)) {\n * // value is typed as LexiconRecordKey\n * console.log('Valid constraint:', value)\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isLexiconRecordKey<T>(key: T): key is T & LexiconRecordKey {\n return (\n key === 'any' ||\n key === 'nsid' ||\n key === 'tid' ||\n (typeof key === 'string' &&\n key.startsWith('literal:') &&\n key.length > 8 &&\n isValidRecordKey(key.slice(8)))\n )\n}\n\n/**\n * Validates and returns a value as a lexicon record key constraint, throwing if invalid.\n *\n * @param key - The value to validate\n * @returns The value typed as {@link LexiconRecordKey}\n * @throws {Error} If the value is not a valid record key constraint\n *\n * @example\n * ```typescript\n * const constraint = asLexiconRecordKey('tid')\n * // constraint is typed as LexiconRecordKey\n *\n * asLexiconRecordKey('invalid') // throws Error\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function asLexiconRecordKey(key: unknown): LexiconRecordKey {\n if (isLexiconRecordKey(key)) return key\n throw new Error(`Invalid record key: ${String(key)}`)\n}\n"]}
|
package/dist/core/result.js
CHANGED
|
@@ -1,11 +1,3 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.success = success;
|
|
4
|
-
exports.failure = failure;
|
|
5
|
-
exports.failureReason = failureReason;
|
|
6
|
-
exports.successValue = successValue;
|
|
7
|
-
exports.catchall = catchall;
|
|
8
|
-
exports.createCatcher = createCatcher;
|
|
9
1
|
/**
|
|
10
2
|
* Creates a successful result wrapping the given value.
|
|
11
3
|
*
|
|
@@ -21,7 +13,7 @@ exports.createCatcher = createCatcher;
|
|
|
21
13
|
* ```
|
|
22
14
|
*/
|
|
23
15
|
/*@__NO_SIDE_EFFECTS__*/
|
|
24
|
-
function success(value) {
|
|
16
|
+
export function success(value) {
|
|
25
17
|
return { success: true, value };
|
|
26
18
|
}
|
|
27
19
|
/**
|
|
@@ -39,7 +31,7 @@ function success(value) {
|
|
|
39
31
|
* ```
|
|
40
32
|
*/
|
|
41
33
|
/*@__NO_SIDE_EFFECTS__*/
|
|
42
|
-
function failure(reason) {
|
|
34
|
+
export function failure(reason) {
|
|
43
35
|
return { success: false, reason };
|
|
44
36
|
}
|
|
45
37
|
/**
|
|
@@ -57,7 +49,7 @@ function failure(reason) {
|
|
|
57
49
|
* ```
|
|
58
50
|
*/
|
|
59
51
|
/*@__NO_SIDE_EFFECTS__*/
|
|
60
|
-
function failureReason(result) {
|
|
52
|
+
export function failureReason(result) {
|
|
61
53
|
return result.reason;
|
|
62
54
|
}
|
|
63
55
|
/**
|
|
@@ -75,7 +67,7 @@ function failureReason(result) {
|
|
|
75
67
|
* ```
|
|
76
68
|
*/
|
|
77
69
|
/*@__NO_SIDE_EFFECTS__*/
|
|
78
|
-
function successValue(result) {
|
|
70
|
+
export function successValue(result) {
|
|
79
71
|
return result.value;
|
|
80
72
|
}
|
|
81
73
|
/**
|
|
@@ -98,7 +90,7 @@ function successValue(result) {
|
|
|
98
90
|
* ```
|
|
99
91
|
*/
|
|
100
92
|
/*@__NO_SIDE_EFFECTS__*/
|
|
101
|
-
function catchall(err) {
|
|
93
|
+
export function catchall(err) {
|
|
102
94
|
if (err instanceof Error)
|
|
103
95
|
return failure(err);
|
|
104
96
|
return failure(new Error('Unknown error', { cause: err }));
|
|
@@ -127,7 +119,7 @@ function catchall(err) {
|
|
|
127
119
|
* }
|
|
128
120
|
*/
|
|
129
121
|
/*@__NO_SIDE_EFFECTS__*/
|
|
130
|
-
function createCatcher(Ctor) {
|
|
122
|
+
export function createCatcher(Ctor) {
|
|
131
123
|
return (err) => {
|
|
132
124
|
if (err instanceof Ctor)
|
|
133
125
|
return failure(err);
|
package/dist/core/result.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"result.js","sourceRoot":"","sources":["../../src/core/result.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"result.js","sourceRoot":"","sources":["../../src/core/result.ts"],"names":[],"mappings":"AA+BA;;;;;;;;;;;;;GAaG;AACH,wBAAwB;AACxB,MAAM,UAAU,OAAO,CAAI,KAAQ;IACjC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;AACjC,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAwB;AACxB,MAAM,UAAU,OAAO,CAAI,MAAS;IAClC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAA;AACnC,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAwB;AACxB,MAAM,UAAU,aAAa,CAAI,MAAwB;IACvD,OAAO,MAAM,CAAC,MAAM,CAAA;AACtB,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAwB;AACxB,MAAM,UAAU,YAAY,CAAI,MAAwB;IACtD,OAAO,MAAM,CAAC,KAAK,CAAA;AACrB,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAwB;AACxB,MAAM,UAAU,QAAQ,CAAC,GAAY;IACnC,IAAI,GAAG,YAAY,KAAK;QAAE,OAAO,OAAO,CAAC,GAAG,CAAC,CAAA;IAC7C,OAAO,OAAO,CAAC,IAAI,KAAK,CAAC,eAAe,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,CAAA;AAC5D,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAwB;AACxB,MAAM,UAAU,aAAa,CAAI,IAA+B;IAC9D,OAAO,CAAC,GAAY,EAAoB,EAAE;QACxC,IAAI,GAAG,YAAY,IAAI;YAAE,OAAO,OAAO,CAAC,GAAG,CAAC,CAAA;QAC5C,MAAM,GAAG,CAAA;IACX,CAAC,CAAA;AACH,CAAC","sourcesContent":["export type ResultSuccess<V = any> = { success: true; value: V }\n\n/**\n * Represents a failed result containing an error reason.\n *\n * @typeParam E - The type of the error reason\n */\nexport type ResultFailure<E = Error> = { success: false; reason: E }\n\n/**\n * A discriminated union type representing either a success or failure outcome.\n *\n * Check the `success` property to determine the outcome and access the\n * appropriate property (`value` for success, `reason` for failure).\n *\n * @typeParam V - The type of the success value\n * @typeParam E - The type of the error reason\n *\n * @example\n * ```typescript\n * function parseJson(text: string): Result<unknown, SyntaxError> {\n * try {\n * return success(JSON.parse(text))\n * } catch (e) {\n * return failure(e as SyntaxError)\n * }\n * }\n * ```\n */\nexport type Result<V = any, E = Error> = ResultSuccess<V> | ResultFailure<E>\n\n/**\n * Creates a successful result wrapping the given value.\n *\n * @typeParam V - The type of the value\n * @param value - The success value to wrap\n * @returns {ResultSuccess} A success result containing the value\n *\n * @example\n * ```typescript\n * const result = success(42)\n * console.log(result.success) // true\n * console.log(result.value) // 42\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function success<V>(value: V): ResultSuccess<V> {\n return { success: true, value }\n}\n\n/**\n * Creates a failed result wrapping the given error reason.\n *\n * @typeParam E - The type of the error reason\n * @param reason - The error reason to wrap\n * @returns {ResultFailure} A failure result containing the error\n *\n * @example\n * ```typescript\n * const result = failure(new Error('Something went wrong'))\n * console.log(result.success) // false\n * console.log(result.reason.message) // \"Something went wrong\"\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function failure<E>(reason: E): ResultFailure<E> {\n return { success: false, reason }\n}\n\n/**\n * Extracts the error reason from a failure result.\n *\n * @typeParam T - The type of the error reason\n * @param result - A failure result\n * @returns {T} The error reason\n *\n * @example\n * ```typescript\n * const result = failure(new Error('oops'))\n * const error = failureReason(result)\n * console.log(error.message) // \"oops\"\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function failureReason<T>(result: ResultFailure<T>): T {\n return result.reason\n}\n\n/**\n * Extracts the value from a success result.\n *\n * @typeParam T - The type of the success value\n * @param result - A success result\n * @returns {T} The success value\n *\n * @example\n * ```typescript\n * const result = success(42)\n * const value = successValue(result)\n * console.log(value) // 42\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function successValue<T>(result: ResultSuccess<T>): T {\n return result.value\n}\n\n/**\n * Catches any error and wraps it in a {@link ResultFailure<Error>}.\n *\n * @param err - The error to catch.\n * @returns {ResultFailure} A failure result containing the error.\n * @example\n *\n * ```ts\n * declare function someFunction(): Promise<string>\n *\n * const result = await someFunction().then(success, catchall)\n * if (result.success) {\n * console.log(result.value) // string\n * } else {\n * console.error(result.reason instanceof Error) // true\n * console.error(result.reason.message) // string\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function catchall(err: unknown): ResultFailure<Error> {\n if (err instanceof Error) return failure(err)\n return failure(new Error('Unknown error', { cause: err }))\n}\n\n/**\n * Creates a catcher function for the given constructor that wraps caught errors\n * in a {@link ResultFailure}.\n *\n * @example\n *\n * ```ts\n * class FooError extends Error {}\n * class BarError extends Error {}\n *\n * declare function someFunction(): Promise<string>\n *\n * const result = await someFunction()\n * .then(success)\n * .catch(createCatcher(FooError))\n * .catch(createCatcher(BarError))\n *\n * if (result.success) {\n * console.log(result.value) // string\n * } else {\n * console.error(result.reason) // FooError | BarError\n * }\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function createCatcher<T>(Ctor: new (...args: any[]) => T) {\n return (err: unknown): ResultFailure<T> => {\n if (err instanceof Ctor) return failure(err)\n throw err\n }\n}\n"]}
|
package/dist/core/schema.js
CHANGED
|
@@ -1,9 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
const lazy_property_js_1 = require("../util/lazy-property.js");
|
|
5
|
-
const standard_schema_js_1 = require("./standard-schema.js");
|
|
6
|
-
const validator_js_1 = require("./validator.js");
|
|
1
|
+
import { lazyProperty } from '../util/lazy-property.js';
|
|
2
|
+
import { StandardSchemaAdapter } from './standard-schema.js';
|
|
3
|
+
import { ValidationContext, } from './validator.js';
|
|
7
4
|
/**
|
|
8
5
|
* Abstract base class for all schema validators in the lexicon system.
|
|
9
6
|
*
|
|
@@ -39,11 +36,11 @@ const validator_js_1 = require("./validator.js");
|
|
|
39
36
|
* schema.matches(123) // false
|
|
40
37
|
* ```
|
|
41
38
|
*/
|
|
42
|
-
class Schema {
|
|
39
|
+
export class Schema {
|
|
43
40
|
get '~standard'() {
|
|
44
41
|
// Lazily create, and cache, the Standard Schema adapter for this schema
|
|
45
42
|
// instance.
|
|
46
|
-
return
|
|
43
|
+
return lazyProperty(this, '~standard', new StandardSchemaAdapter(this));
|
|
47
44
|
}
|
|
48
45
|
/**
|
|
49
46
|
* @note use {@link check}() instead of {@link assert}() if you encounter a
|
|
@@ -154,7 +151,7 @@ class Schema {
|
|
|
154
151
|
* ```
|
|
155
152
|
*/
|
|
156
153
|
safeParse(input, options) {
|
|
157
|
-
return
|
|
154
|
+
return ValidationContext.validate(input, this, {
|
|
158
155
|
...options,
|
|
159
156
|
mode: 'parse',
|
|
160
157
|
});
|
|
@@ -206,7 +203,7 @@ class Schema {
|
|
|
206
203
|
* ```
|
|
207
204
|
*/
|
|
208
205
|
safeValidate(input, options) {
|
|
209
|
-
return
|
|
206
|
+
return ValidationContext.validate(input, this, {
|
|
210
207
|
...options,
|
|
211
208
|
mode: 'validate',
|
|
212
209
|
});
|
|
@@ -253,64 +250,63 @@ class Schema {
|
|
|
253
250
|
* @see {@link assert}
|
|
254
251
|
*/
|
|
255
252
|
get $assert() {
|
|
256
|
-
return
|
|
253
|
+
return lazyProperty(this, '$assert', this.assert.bind(this));
|
|
257
254
|
}
|
|
258
255
|
/**
|
|
259
256
|
* Bound alias for {@link check} for compatibility with generated utilities.
|
|
260
257
|
* @see {@link check}
|
|
261
258
|
*/
|
|
262
259
|
get $check() {
|
|
263
|
-
return
|
|
260
|
+
return lazyProperty(this, '$check', this.check.bind(this));
|
|
264
261
|
}
|
|
265
262
|
/**
|
|
266
263
|
* Bound alias for {@link cast} for compatibility with generated utilities.
|
|
267
264
|
* @see {@link cast}
|
|
268
265
|
*/
|
|
269
266
|
get $cast() {
|
|
270
|
-
return
|
|
267
|
+
return lazyProperty(this, '$cast', this.cast.bind(this));
|
|
271
268
|
}
|
|
272
269
|
/**
|
|
273
270
|
* Bound alias for {@link matches} for compatibility with generated utilities.
|
|
274
271
|
* @see {@link matches}
|
|
275
272
|
*/
|
|
276
273
|
get $matches() {
|
|
277
|
-
return
|
|
274
|
+
return lazyProperty(this, '$matches', this.matches.bind(this));
|
|
278
275
|
}
|
|
279
276
|
/**
|
|
280
277
|
* Bound alias for {@link ifMatches} for compatibility with generated utilities.
|
|
281
278
|
* @see {@link ifMatches}
|
|
282
279
|
*/
|
|
283
280
|
get $ifMatches() {
|
|
284
|
-
return
|
|
281
|
+
return lazyProperty(this, '$ifMatches', this.ifMatches.bind(this));
|
|
285
282
|
}
|
|
286
283
|
/**
|
|
287
284
|
* Bound alias for {@link parse} for compatibility with generated utilities.
|
|
288
285
|
* @see {@link parse}
|
|
289
286
|
*/
|
|
290
287
|
get $parse() {
|
|
291
|
-
return
|
|
288
|
+
return lazyProperty(this, '$parse', this.parse.bind(this));
|
|
292
289
|
}
|
|
293
290
|
/**
|
|
294
291
|
* Bound alias for {@link safeParse} for compatibility with generated utilities.
|
|
295
292
|
* @see {@link safeParse}
|
|
296
293
|
*/
|
|
297
294
|
get $safeParse() {
|
|
298
|
-
return
|
|
295
|
+
return lazyProperty(this, '$safeParse', this.safeParse.bind(this));
|
|
299
296
|
}
|
|
300
297
|
/**
|
|
301
298
|
* Bound alias for {@link validate} for compatibility with generated utilities.
|
|
302
299
|
* @see {@link validate}
|
|
303
300
|
*/
|
|
304
301
|
get $validate() {
|
|
305
|
-
return
|
|
302
|
+
return lazyProperty(this, '$validate', this.validate.bind(this));
|
|
306
303
|
}
|
|
307
304
|
/**
|
|
308
305
|
* Bound alias for {@link safeValidate} for compatibility with generated utilities.
|
|
309
306
|
* @see {@link safeValidate}
|
|
310
307
|
*/
|
|
311
308
|
get $safeValidate() {
|
|
312
|
-
return
|
|
309
|
+
return lazyProperty(this, '$safeValidate', this.safeValidate.bind(this));
|
|
313
310
|
}
|
|
314
311
|
}
|
|
315
|
-
exports.Schema = Schema;
|
|
316
312
|
//# sourceMappingURL=schema.js.map
|
package/dist/core/schema.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/core/schema.ts"],"names":[],"mappings":";;;AACA,+DAAuD;AACvD,6DAA4D;AAC5D,iDAOuB;AA8BvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAsB,MAAM;IAW1B,IAAI,WAAW;QACb,wEAAwE;QACxE,YAAY;QACZ,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,WAAW,EAAE,IAAI,0CAAqB,CAAC,IAAI,CAAC,CAAC,CAAA;IACzE,CAAC;IA0BD;;;;;OAKG;IACH,MAAM,CACJ,KAAc,EACd,OAAyB;QAEzB,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;QAChD,IAAI,CAAC,MAAM,CAAC,OAAO;YAAE,MAAM,MAAM,CAAC,MAAM,CAAA;IAC1C,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,KAAc,EAAE,OAAyB;QAC7C,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;IAC7B,CAAC;IAED;;;;OAIG;IACH,IAAI,CAAI,KAAQ,EAAE,OAAyB;QACzC,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;QAChD,IAAI,MAAM,CAAC,OAAO;YAAE,OAAO,MAAM,CAAC,KAAK,CAAA;QACvC,MAAM,MAAM,CAAC,MAAM,CAAA;IACrB,CAAC;IAED;;;;;;;;;;OAUG;IACH,OAAO,CACL,KAAQ,EACR,OAAyB;QAEzB,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC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AC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IACpE,CAAC;IAED;;;OAGG;IACH,IAAI,MAAM;QACR,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAC5D,CAAC;IAED;;;OAGG;IACH,IAAI,UAAU;QACZ,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,YAAY,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IACpE,CAAC;IAED;;;OAGG;IACH,IAAI,SAAS;QACX,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAClE,CAAC;IAED;;;OAGG;IACH,IAAI,aAAa;QACf,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,eAAe,EAAE,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAC1E,CAAC;CACF;AAhVD,wBAgVC","sourcesContent":["import { StandardSchemaV1 } from '@standard-schema/spec'\nimport { lazyProperty } from '../util/lazy-property.js'\nimport { StandardSchemaAdapter } from './standard-schema.js'\nimport {\n InferInput,\n InferOutput,\n ValidationContext,\n ValidationOptions,\n ValidationResult,\n Validator,\n} from './validator.js'\n\n/**\n * Options for parsing operations.\n * Excludes the `mode` option as it is implicitly set to `\"parse\"`.\n */\nexport type ParseOptions = Omit<ValidationOptions, 'mode'>\n\n/**\n * Options for validation operations.\n * Excludes the `mode` option as it is implicitly set to `\"validate\"`.\n */\nexport type ValidateOptions = Omit<ValidationOptions, 'mode'>\n\n/**\n * Internal type structure for schema type inference.\n *\n * This interface defines the phantom types used for compile-time type inference\n * without affecting runtime behavior. The `input` and `output` properties\n * represent the expected input type during validation and the resulting output\n * type after parsing, respectively.\n *\n * @typeParam TInput - The type accepted as input during validation\n * @typeParam TOutput - The type returned after parsing (may differ from input due to coercion)\n */\nexport interface SchemaInternals<out TInput = unknown, out TOutput = TInput> {\n input: TInput\n output: TOutput\n}\n\n/**\n * Abstract base class for all schema validators in the lexicon system.\n *\n * This class provides the standard validation interface that all schema types\n * implement. It offers multiple methods for validating and parsing data:\n *\n * - **Assertion methods**: `assert()`, `check()` - throw on invalid input\n * - **Type guard methods**: `matches()`, `ifMatches()` - return boolean or optional value\n * - **Parse methods**: `parse()`, `safeParse()` - allow value transformation/coercion\n * - **Validate methods**: `validate()`, `safeValidate()` - validation without coercion\n *\n * All methods are also available with a `$` prefix (e.g., `$parse()`, `$validate()`)\n * for consistent access in generated lexicon namespaces.\n *\n * @typeParam TInput - The type accepted as valid input during validation\n * @typeParam TOutput - The type returned after parsing (may include transformations)\n *\n * @example\n * ```typescript\n * class MySchema extends Schema<string> {\n * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {\n * if (typeof input !== 'string') {\n * return ctx.issueUnexpectedType(input, 'string')\n * }\n * return ctx.success(input)\n * }\n * }\n *\n * const schema = new MySchema()\n * schema.assert('hello') // OK\n * schema.assert(123) // Throws LexValidationError\n * schema.matches('hello') // true\n * schema.matches(123) // false\n * ```\n */\nexport abstract class Schema<out TInput = unknown, out TOutput = TInput>\n implements Validator<TInput, TOutput>, StandardSchemaV1<TInput, TOutput>\n{\n /**\n * Internal phantom property for type inference.\n * This property does not exist at runtime.\n *\n * @internal\n */\n declare readonly ['__lex']: SchemaInternals<TInput, TOutput>\n\n get '~standard'(): StandardSchemaV1.Props<TInput, TOutput> {\n // Lazily create, and cache, the Standard Schema adapter for this schema\n // instance.\n return lazyProperty(this, '~standard', new StandardSchemaAdapter(this))\n }\n\n // Needed to discriminate multiple schema types when used in unions. Without\n // this, Typescript could allow an EnumSchema<\"foo\" | \"bar\"> to be used where\n // a StringSchema is expected, since they would both be structurally\n // compatible.\n abstract readonly type: string\n\n /**\n * Performs validation of the input value within a validation context.\n *\n * This method must be implemented by subclasses to define the actual\n * validation logic. It should not be called directly; use\n * {@link ValidationContext.validate} instead to ensure proper mode enforcement.\n *\n * @param input - The value to validate\n * @param ctx - The validation context providing path tracking and issue reporting\n * @returns A validation result indicating success with the validated value or failure with issues\n *\n * @internal\n */\n abstract validateInContext(\n input: unknown,\n ctx: ValidationContext,\n ): ValidationResult\n\n /**\n * @note use {@link check}() instead of {@link assert}() if you encounter a\n * `ts(2775)` error and you are not able to fully type the validator. This\n * will typically arise in generic contexts, where the narrowed type is not\n * needed.\n */\n assert(\n input: unknown,\n options?: ValidateOptions,\n ): asserts input is InferInput<this> {\n const result = this.safeValidate(input, options)\n if (!result.success) throw result.reason\n }\n\n /**\n * Alias for {@link assert}(). Most useful in generic contexts where the\n * validator is not exactly typed, allowing to avoid \"_Assertions require\n * every name in the call target to be declared with an explicit type\n * annotation. ts(2775)_\" errors.\n */\n check(input: unknown, options?: ValidateOptions): void {\n this.assert(input, options)\n }\n\n /**\n * Casts the input (by validating it) to the output type if it matches the\n * schema, otherwise throws. This is the same as calling {@link parse}() with\n * `mode: \"validate\"`.\n */\n cast<I>(input: I, options?: ValidateOptions): I & InferInput<this> {\n const result = this.safeValidate(input, options)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Type guard that checks if the input matches this schema.\n *\n * @example\n * ```typescript\n * if (schema.matches(data)) {\n * // data is narrowed to the schema's input type\n * console.log(data)\n * }\n * ```\n */\n matches<I>(\n input: I,\n options?: ValidateOptions,\n ): input is I & InferInput<this> {\n const result = this.safeValidate(input, options)\n return result.success\n }\n\n /**\n * Returns the input if it matches this schema, otherwise returns `undefined`.\n *\n * This is useful for optional filtering operations where you want to\n * conditionally extract values that match a schema.\n *\n * @example\n * ```typescript\n * const validData = schema.ifMatches(data)\n * if (validData !== undefined) {\n * // validData is the schema's input type\n * console.log(validData)\n * }\n * ```\n */\n ifMatches<I>(\n input: I,\n options?: ValidateOptions,\n ): (I & InferInput<this>) | undefined {\n return this.matches(input, options) ? input : undefined\n }\n\n /**\n * Parses the input, allowing value transformations and coercion.\n *\n * Unlike {@link validate}, this method allows the schema to transform\n * the input value (e.g., applying default values, type coercion).\n * Throws a {@link LexValidationError} if the input is invalid.\n *\n * @param input - The value to parse\n * @param options - Optional parsing configuration\n * @returns The parsed and potentially transformed value\n * @throws {LexValidationError} If the input fails validation\n *\n * @example\n * ```typescript\n * const result = schema.parse(rawData)\n * // result has defaults applied and is fully typed\n * ```\n */\n parse(input: unknown, options?: ParseOptions): InferOutput<this> {\n const result = this.safeParse(input, options)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Safely parses the input without throwing, returning a result object.\n *\n * This method allows value transformations like {@link parse}, but\n * returns a discriminated union result instead of throwing on error.\n *\n * @param input - The value to parse\n * @param options - Optional parsing configuration\n * @returns A {@link ValidationResult} with either the parsed value or validation errors\n *\n * @example\n * ```typescript\n * const result = schema.safeParse(data)\n * if (result.success) {\n * console.log(result.value)\n * } else {\n * console.error(result.reason.issues)\n * }\n * ```\n */\n safeParse(\n input: unknown,\n options?: ParseOptions,\n ): ValidationResult<InferOutput<this>> {\n return ValidationContext.validate(input, this, {\n ...options,\n mode: 'parse',\n })\n }\n\n /**\n * Validates the input strictly without allowing transformations.\n *\n * Unlike {@link parse}, this method requires the input to exactly match\n * the schema without any transformations (no defaults applied, no coercion).\n * Throws a {@link LexValidationError} if the input is invalid or would require transformation.\n *\n * @typeParam I - The input type (preserved in the return type)\n * @param input - The value to validate\n * @param options - Optional validation configuration\n * @returns The validated input with narrowed type\n * @throws {LexValidationError} If the input fails validation or requires transformation\n *\n * @example\n * ```typescript\n * const validated = schema.validate(data)\n * // validated is typed as the intersection of input type and schema type\n * ```\n */\n validate<I>(input: I, options?: ValidateOptions): I & InferInput<this> {\n const result = this.safeValidate(input, options)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Safely validates the input without throwing, returning a result object.\n *\n * This method performs strict validation like {@link validate}, but\n * returns a discriminated union result instead of throwing on error.\n *\n * @typeParam I - The input type (preserved in the result value type)\n * @param input - The value to validate\n * @param options - Optional validation configuration\n * @returns A {@link ValidationResult} with either the validated value or validation errors\n *\n * @example\n * ```typescript\n * const result = schema.safeValidate(data)\n * if (result.success) {\n * console.log(result.value)\n * } else {\n * console.error(result.reason.issues)\n * }\n * ```\n */\n safeValidate<I>(\n input: I,\n options?: ValidateOptions,\n ): ValidationResult<I & InferInput<this>> {\n return ValidationContext.validate(input, this, {\n ...options,\n mode: 'validate',\n })\n }\n\n // @NOTE Dollar-prefixed aliases\n //\n // The `lex-builder` lib generates namespaced utility functions that allow\n // accessing the schema's methods without the need to specify the \".main.\"\n // part of the namespace. This allows utilities for a particular record type\n // to be called like \"app.bsky.feed.post.<utility>()\" instead of\n // \"app.bsky.feed.post.main.<utility>()\".\n //\n // Because those utilities could conflict with other schemas (e.g. if there is\n // a lexicon definition with the same name as the \"<utility>\"), those exported\n // utilities will be prefixed with \"$\".\n //\n // Similarly, since those utilities are defined as simple \"const\", they are\n // also bound (using JS's .bind) to the schema instance, so that they can be\n // used without worrying about the context (e.g. \"app.bsky.feed.post.$parse()\"\n // will work regardless of how it is imported or called).\n //\n // In order to provide the same functionalities for non-main definitions, we\n // also define those aliases directly on the schema instance, so that they can\n // be used in the same way as the utilities generated by \"lex-builder\". For\n // example, if there is a non-main definition \"app.bsky.feed.defs.postView\",\n // it will also be possible to call \"app.bsky.feed.defs.postView.$parse()\".\n //\n // These methods are also \"bound\" to the instance so that they can be used\n // exactly like the utilities generated by \"lex-builder\", without worrying\n // about the context.\n //\n // There are two ways we could \"bind\" those methods to the instance:\n // 1. Define them as getters that return the bound method (e.g. get $parse() {\n // return this.parse.bind(this) })\n // 2. Define them as properties that are initialized in the constructor (e.g.\n // this.$parse = this.parse.bind(this))\n //\n // Since a **lot** of those methods would end-up being created in systems that\n // contains many schemas (e.g. the appview), we choose the first approach\n // (getters) in order to avoid the overhead of creating all those bound\n // functions upfront when instantiating the schemas.\n\n /**\n * Bound alias for {@link assert} for compatibility with generated utilities.\n * @see {@link assert}\n */\n get $assert(): typeof this.assert {\n return lazyProperty(this, '$assert', this.assert.bind(this))\n }\n\n /**\n * Bound alias for {@link check} for compatibility with generated utilities.\n * @see {@link check}\n */\n get $check(): typeof this.check {\n return lazyProperty(this, '$check', this.check.bind(this))\n }\n\n /**\n * Bound alias for {@link cast} for compatibility with generated utilities.\n * @see {@link cast}\n */\n get $cast(): typeof this.cast {\n return lazyProperty(this, '$cast', this.cast.bind(this))\n }\n\n /**\n * Bound alias for {@link matches} for compatibility with generated utilities.\n * @see {@link matches}\n */\n get $matches(): typeof this.matches {\n return lazyProperty(this, '$matches', this.matches.bind(this))\n }\n\n /**\n * Bound alias for {@link ifMatches} for compatibility with generated utilities.\n * @see {@link ifMatches}\n */\n get $ifMatches(): typeof this.ifMatches {\n return lazyProperty(this, '$ifMatches', this.ifMatches.bind(this))\n }\n\n /**\n * Bound alias for {@link parse} for compatibility with generated utilities.\n * @see {@link parse}\n */\n get $parse(): typeof this.parse {\n return lazyProperty(this, '$parse', this.parse.bind(this))\n }\n\n /**\n * Bound alias for {@link safeParse} for compatibility with generated utilities.\n * @see {@link safeParse}\n */\n get $safeParse(): typeof this.safeParse {\n return lazyProperty(this, '$safeParse', this.safeParse.bind(this))\n }\n\n /**\n * Bound alias for {@link validate} for compatibility with generated utilities.\n * @see {@link validate}\n */\n get $validate(): typeof this.validate {\n return lazyProperty(this, '$validate', this.validate.bind(this))\n }\n\n /**\n * Bound alias for {@link safeValidate} for compatibility with generated utilities.\n * @see {@link safeValidate}\n */\n get $safeValidate(): typeof this.safeValidate {\n return lazyProperty(this, '$safeValidate', this.safeValidate.bind(this))\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/core/schema.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAA;AAC5D,OA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AAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IACpE,CAAC;IAED;;;OAGG;IACH,IAAI,SAAS;QACX,OAAO,YAAY,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAClE,CAAC;IAED;;;OAGG;IACH,IAAI,aAAa;QACf,OAAO,YAAY,CAAC,IAAI,EAAE,eAAe,EAAE,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAC1E,CAAC;CACF","sourcesContent":["import { StandardSchemaV1 } from '@standard-schema/spec'\nimport { lazyProperty } from '../util/lazy-property.js'\nimport { StandardSchemaAdapter } from './standard-schema.js'\nimport {\n InferInput,\n InferOutput,\n ValidationContext,\n ValidationOptions,\n ValidationResult,\n Validator,\n} from './validator.js'\n\n/**\n * Options for parsing operations.\n * Excludes the `mode` option as it is implicitly set to `\"parse\"`.\n */\nexport type ParseOptions = Omit<ValidationOptions, 'mode'>\n\n/**\n * Options for validation operations.\n * Excludes the `mode` option as it is implicitly set to `\"validate\"`.\n */\nexport type ValidateOptions = Omit<ValidationOptions, 'mode'>\n\n/**\n * Internal type structure for schema type inference.\n *\n * This interface defines the phantom types used for compile-time type inference\n * without affecting runtime behavior. The `input` and `output` properties\n * represent the expected input type during validation and the resulting output\n * type after parsing, respectively.\n *\n * @typeParam TInput - The type accepted as input during validation\n * @typeParam TOutput - The type returned after parsing (may differ from input due to coercion)\n */\nexport interface SchemaInternals<out TInput = unknown, out TOutput = TInput> {\n input: TInput\n output: TOutput\n}\n\n/**\n * Abstract base class for all schema validators in the lexicon system.\n *\n * This class provides the standard validation interface that all schema types\n * implement. It offers multiple methods for validating and parsing data:\n *\n * - **Assertion methods**: `assert()`, `check()` - throw on invalid input\n * - **Type guard methods**: `matches()`, `ifMatches()` - return boolean or optional value\n * - **Parse methods**: `parse()`, `safeParse()` - allow value transformation/coercion\n * - **Validate methods**: `validate()`, `safeValidate()` - validation without coercion\n *\n * All methods are also available with a `$` prefix (e.g., `$parse()`, `$validate()`)\n * for consistent access in generated lexicon namespaces.\n *\n * @typeParam TInput - The type accepted as valid input during validation\n * @typeParam TOutput - The type returned after parsing (may include transformations)\n *\n * @example\n * ```typescript\n * class MySchema extends Schema<string> {\n * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {\n * if (typeof input !== 'string') {\n * return ctx.issueUnexpectedType(input, 'string')\n * }\n * return ctx.success(input)\n * }\n * }\n *\n * const schema = new MySchema()\n * schema.assert('hello') // OK\n * schema.assert(123) // Throws LexValidationError\n * schema.matches('hello') // true\n * schema.matches(123) // false\n * ```\n */\nexport abstract class Schema<out TInput = unknown, out TOutput = TInput>\n implements Validator<TInput, TOutput>, StandardSchemaV1<TInput, TOutput>\n{\n /**\n * Internal phantom property for type inference.\n * This property does not exist at runtime.\n *\n * @internal\n */\n declare readonly ['__lex']: SchemaInternals<TInput, TOutput>\n\n get '~standard'(): StandardSchemaV1.Props<TInput, TOutput> {\n // Lazily create, and cache, the Standard Schema adapter for this schema\n // instance.\n return lazyProperty(this, '~standard', new StandardSchemaAdapter(this))\n }\n\n // Needed to discriminate multiple schema types when used in unions. Without\n // this, Typescript could allow an EnumSchema<\"foo\" | \"bar\"> to be used where\n // a StringSchema is expected, since they would both be structurally\n // compatible.\n abstract readonly type: string\n\n /**\n * Performs validation of the input value within a validation context.\n *\n * This method must be implemented by subclasses to define the actual\n * validation logic. It should not be called directly; use\n * {@link ValidationContext.validate} instead to ensure proper mode enforcement.\n *\n * @param input - The value to validate\n * @param ctx - The validation context providing path tracking and issue reporting\n * @returns A validation result indicating success with the validated value or failure with issues\n *\n * @internal\n */\n abstract validateInContext(\n input: unknown,\n ctx: ValidationContext,\n ): ValidationResult\n\n /**\n * @note use {@link check}() instead of {@link assert}() if you encounter a\n * `ts(2775)` error and you are not able to fully type the validator. This\n * will typically arise in generic contexts, where the narrowed type is not\n * needed.\n */\n assert(\n input: unknown,\n options?: ValidateOptions,\n ): asserts input is InferInput<this> {\n const result = this.safeValidate(input, options)\n if (!result.success) throw result.reason\n }\n\n /**\n * Alias for {@link assert}(). Most useful in generic contexts where the\n * validator is not exactly typed, allowing to avoid \"_Assertions require\n * every name in the call target to be declared with an explicit type\n * annotation. ts(2775)_\" errors.\n */\n check(input: unknown, options?: ValidateOptions): void {\n this.assert(input, options)\n }\n\n /**\n * Casts the input (by validating it) to the output type if it matches the\n * schema, otherwise throws. This is the same as calling {@link parse}() with\n * `mode: \"validate\"`.\n */\n cast<I>(input: I, options?: ValidateOptions): I & InferInput<this> {\n const result = this.safeValidate(input, options)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Type guard that checks if the input matches this schema.\n *\n * @example\n * ```typescript\n * if (schema.matches(data)) {\n * // data is narrowed to the schema's input type\n * console.log(data)\n * }\n * ```\n */\n matches<I>(\n input: I,\n options?: ValidateOptions,\n ): input is I & InferInput<this> {\n const result = this.safeValidate(input, options)\n return result.success\n }\n\n /**\n * Returns the input if it matches this schema, otherwise returns `undefined`.\n *\n * This is useful for optional filtering operations where you want to\n * conditionally extract values that match a schema.\n *\n * @example\n * ```typescript\n * const validData = schema.ifMatches(data)\n * if (validData !== undefined) {\n * // validData is the schema's input type\n * console.log(validData)\n * }\n * ```\n */\n ifMatches<I>(\n input: I,\n options?: ValidateOptions,\n ): (I & InferInput<this>) | undefined {\n return this.matches(input, options) ? input : undefined\n }\n\n /**\n * Parses the input, allowing value transformations and coercion.\n *\n * Unlike {@link validate}, this method allows the schema to transform\n * the input value (e.g., applying default values, type coercion).\n * Throws a {@link LexValidationError} if the input is invalid.\n *\n * @param input - The value to parse\n * @param options - Optional parsing configuration\n * @returns The parsed and potentially transformed value\n * @throws {LexValidationError} If the input fails validation\n *\n * @example\n * ```typescript\n * const result = schema.parse(rawData)\n * // result has defaults applied and is fully typed\n * ```\n */\n parse(input: unknown, options?: ParseOptions): InferOutput<this> {\n const result = this.safeParse(input, options)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Safely parses the input without throwing, returning a result object.\n *\n * This method allows value transformations like {@link parse}, but\n * returns a discriminated union result instead of throwing on error.\n *\n * @param input - The value to parse\n * @param options - Optional parsing configuration\n * @returns A {@link ValidationResult} with either the parsed value or validation errors\n *\n * @example\n * ```typescript\n * const result = schema.safeParse(data)\n * if (result.success) {\n * console.log(result.value)\n * } else {\n * console.error(result.reason.issues)\n * }\n * ```\n */\n safeParse(\n input: unknown,\n options?: ParseOptions,\n ): ValidationResult<InferOutput<this>> {\n return ValidationContext.validate(input, this, {\n ...options,\n mode: 'parse',\n })\n }\n\n /**\n * Validates the input strictly without allowing transformations.\n *\n * Unlike {@link parse}, this method requires the input to exactly match\n * the schema without any transformations (no defaults applied, no coercion).\n * Throws a {@link LexValidationError} if the input is invalid or would require transformation.\n *\n * @typeParam I - The input type (preserved in the return type)\n * @param input - The value to validate\n * @param options - Optional validation configuration\n * @returns The validated input with narrowed type\n * @throws {LexValidationError} If the input fails validation or requires transformation\n *\n * @example\n * ```typescript\n * const validated = schema.validate(data)\n * // validated is typed as the intersection of input type and schema type\n * ```\n */\n validate<I>(input: I, options?: ValidateOptions): I & InferInput<this> {\n const result = this.safeValidate(input, options)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Safely validates the input without throwing, returning a result object.\n *\n * This method performs strict validation like {@link validate}, but\n * returns a discriminated union result instead of throwing on error.\n *\n * @typeParam I - The input type (preserved in the result value type)\n * @param input - The value to validate\n * @param options - Optional validation configuration\n * @returns A {@link ValidationResult} with either the validated value or validation errors\n *\n * @example\n * ```typescript\n * const result = schema.safeValidate(data)\n * if (result.success) {\n * console.log(result.value)\n * } else {\n * console.error(result.reason.issues)\n * }\n * ```\n */\n safeValidate<I>(\n input: I,\n options?: ValidateOptions,\n ): ValidationResult<I & InferInput<this>> {\n return ValidationContext.validate(input, this, {\n ...options,\n mode: 'validate',\n })\n }\n\n // @NOTE Dollar-prefixed aliases\n //\n // The `lex-builder` lib generates namespaced utility functions that allow\n // accessing the schema's methods without the need to specify the \".main.\"\n // part of the namespace. This allows utilities for a particular record type\n // to be called like \"app.bsky.feed.post.<utility>()\" instead of\n // \"app.bsky.feed.post.main.<utility>()\".\n //\n // Because those utilities could conflict with other schemas (e.g. if there is\n // a lexicon definition with the same name as the \"<utility>\"), those exported\n // utilities will be prefixed with \"$\".\n //\n // Similarly, since those utilities are defined as simple \"const\", they are\n // also bound (using JS's .bind) to the schema instance, so that they can be\n // used without worrying about the context (e.g. \"app.bsky.feed.post.$parse()\"\n // will work regardless of how it is imported or called).\n //\n // In order to provide the same functionalities for non-main definitions, we\n // also define those aliases directly on the schema instance, so that they can\n // be used in the same way as the utilities generated by \"lex-builder\". For\n // example, if there is a non-main definition \"app.bsky.feed.defs.postView\",\n // it will also be possible to call \"app.bsky.feed.defs.postView.$parse()\".\n //\n // These methods are also \"bound\" to the instance so that they can be used\n // exactly like the utilities generated by \"lex-builder\", without worrying\n // about the context.\n //\n // There are two ways we could \"bind\" those methods to the instance:\n // 1. Define them as getters that return the bound method (e.g. get $parse() {\n // return this.parse.bind(this) })\n // 2. Define them as properties that are initialized in the constructor (e.g.\n // this.$parse = this.parse.bind(this))\n //\n // Since a **lot** of those methods would end-up being created in systems that\n // contains many schemas (e.g. the appview), we choose the first approach\n // (getters) in order to avoid the overhead of creating all those bound\n // functions upfront when instantiating the schemas.\n\n /**\n * Bound alias for {@link assert} for compatibility with generated utilities.\n * @see {@link assert}\n */\n get $assert(): typeof this.assert {\n return lazyProperty(this, '$assert', this.assert.bind(this))\n }\n\n /**\n * Bound alias for {@link check} for compatibility with generated utilities.\n * @see {@link check}\n */\n get $check(): typeof this.check {\n return lazyProperty(this, '$check', this.check.bind(this))\n }\n\n /**\n * Bound alias for {@link cast} for compatibility with generated utilities.\n * @see {@link cast}\n */\n get $cast(): typeof this.cast {\n return lazyProperty(this, '$cast', this.cast.bind(this))\n }\n\n /**\n * Bound alias for {@link matches} for compatibility with generated utilities.\n * @see {@link matches}\n */\n get $matches(): typeof this.matches {\n return lazyProperty(this, '$matches', this.matches.bind(this))\n }\n\n /**\n * Bound alias for {@link ifMatches} for compatibility with generated utilities.\n * @see {@link ifMatches}\n */\n get $ifMatches(): typeof this.ifMatches {\n return lazyProperty(this, '$ifMatches', this.ifMatches.bind(this))\n }\n\n /**\n * Bound alias for {@link parse} for compatibility with generated utilities.\n * @see {@link parse}\n */\n get $parse(): typeof this.parse {\n return lazyProperty(this, '$parse', this.parse.bind(this))\n }\n\n /**\n * Bound alias for {@link safeParse} for compatibility with generated utilities.\n * @see {@link safeParse}\n */\n get $safeParse(): typeof this.safeParse {\n return lazyProperty(this, '$safeParse', this.safeParse.bind(this))\n }\n\n /**\n * Bound alias for {@link validate} for compatibility with generated utilities.\n * @see {@link validate}\n */\n get $validate(): typeof this.validate {\n return lazyProperty(this, '$validate', this.validate.bind(this))\n }\n\n /**\n * Bound alias for {@link safeValidate} for compatibility with generated utilities.\n * @see {@link safeValidate}\n */\n get $safeValidate(): typeof this.safeValidate {\n return lazyProperty(this, '$safeValidate', this.safeValidate.bind(this))\n }\n}\n"]}
|
|
@@ -1,27 +1,22 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.StandardSchemaAdapter = void 0;
|
|
4
|
-
const validator_js_1 = require("./validator.js");
|
|
1
|
+
import { ValidationContext } from './validator.js';
|
|
5
2
|
/**
|
|
6
3
|
* The Standard Schema adapter for {@link Validator} instances.
|
|
7
4
|
*/
|
|
8
|
-
class StandardSchemaAdapter {
|
|
9
|
-
validator;
|
|
10
|
-
version = 1;
|
|
11
|
-
vendor = '@atproto/lex-schema';
|
|
5
|
+
export class StandardSchemaAdapter {
|
|
12
6
|
constructor(validator) {
|
|
13
7
|
this.validator = validator;
|
|
8
|
+
this.version = 1;
|
|
9
|
+
this.vendor = '@atproto/lex-schema';
|
|
14
10
|
}
|
|
15
11
|
validate(value, options) {
|
|
16
12
|
// Perform validation in "parse" mode to ensure transformations (defaults,
|
|
17
13
|
// coercions, etc.) are applied. Also ensures that the output type is
|
|
18
14
|
// returned. Note that ValidationResult is compatible with
|
|
19
15
|
// StandardSchemaV1.Result :-)
|
|
20
|
-
return
|
|
16
|
+
return ValidationContext.validate(value, this.validator, {
|
|
21
17
|
...options?.libraryOptions,
|
|
22
18
|
mode: 'parse',
|
|
23
19
|
});
|
|
24
20
|
}
|
|
25
21
|
}
|
|
26
|
-
exports.StandardSchemaAdapter = StandardSchemaAdapter;
|
|
27
22
|
//# sourceMappingURL=standard-schema.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standard-schema.js","sourceRoot":"","sources":["../../src/core/standard-schema.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"standard-schema.js","sourceRoot":"","sources":["../../src/core/standard-schema.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAa,MAAM,gBAAgB,CAAA;AAE7D;;GAEG;AACH,MAAM,OAAO,qBAAqB;IAShC,YAA6B,SAAqC;QAArC,cAAS,GAAT,SAAS,CAA4B;QANzD,YAAO,GAAG,CAAC,CAAA;QAEX,WAAM,GAAG,qBAAqB,CAAA;IAI8B,CAAC;IAEtE,QAAQ,CACN,KAAc,EACd,OAAkC;QAElC,0EAA0E;QAC1E,qEAAqE;QACrE,0DAA0D;QAC1D,8BAA8B;QAC9B,OAAO,iBAAiB,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,EAAE;YACvD,GAAG,OAAO,EAAE,cAAc;YAC1B,IAAI,EAAE,OAAO;SACd,CAAC,CAAA;IACJ,CAAC;CACF","sourcesContent":["import { StandardSchemaV1 } from '@standard-schema/spec'\nimport { ValidationContext, Validator } from './validator.js'\n\n/**\n * The Standard Schema adapter for {@link Validator} instances.\n */\nexport class StandardSchemaAdapter<TInput, TOutput>\n implements StandardSchemaV1.Props<TInput, TOutput>\n{\n readonly version = 1\n\n readonly vendor = '@atproto/lex-schema'\n\n declare readonly types: StandardSchemaV1.Types<TInput, TOutput>\n\n constructor(private readonly validator: Validator<TInput, TOutput>) {}\n\n validate(\n value: unknown,\n options?: StandardSchemaV1.Options,\n ): StandardSchemaV1.Result<TOutput> {\n // Perform validation in \"parse\" mode to ensure transformations (defaults,\n // coercions, etc.) are applied. Also ensures that the output type is\n // returned. Note that ValidationResult is compatible with\n // StandardSchemaV1.Result :-)\n return ValidationContext.validate(value, this.validator, {\n ...options?.libraryOptions,\n mode: 'parse',\n })\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string-format.d.ts","sourceRoot":"","sources":["../../src/core/string-format.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"string-format.d.ts","sourceRoot":"","sources":["../../src/core/string-format.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,kBAAkB,EAClB,WAAW,EACX,cAAc,EACd,SAAS,EACT,YAAY,EACZ,UAAU,EACV,eAAe,EACf,SAAS,EACT,SAAS,EAWV,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAA;AAWnD,OAAO,EACL,KAAK,kBAAkB,EACvB,oBAAoB,EACpB,wBAAwB,EACxB,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,iBAAiB,CAAA;AAGxB,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AAErE,OAAO,EACL,KAAK,cAAc,EACnB,gBAAgB,EAChB,oBAAoB,EACpB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,iBAAiB,CAAA;AAExB;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,EACvC,KAAK,EAAE,CAAC,GACP,KAAK,IAAI,CAAC,GAAG,cAAc,CAW7B;AAGD,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAEzE,OAAO,EACL,KAAK,WAAW,EAChB,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