@atproto/lex-schema 0.0.16 → 0.0.18
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 +30 -0
- package/dist/core/schema.d.ts +5 -11
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +10 -16
- package/dist/core/schema.js.map +1 -1
- package/dist/core/validation-error.d.ts +2 -2
- package/dist/core/validation-error.d.ts.map +1 -1
- package/dist/core/validation-error.js +1 -1
- package/dist/core/validation-error.js.map +1 -1
- package/dist/core/validation-issue.d.ts.map +1 -1
- package/dist/core/validation-issue.js +19 -38
- package/dist/core/validation-issue.js.map +1 -1
- package/dist/helpers.d.ts +4 -3
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +6 -1
- package/dist/helpers.js.map +1 -1
- package/dist/schema/blob.d.ts +6 -20
- package/dist/schema/blob.d.ts.map +1 -1
- package/dist/schema/blob.js +23 -28
- package/dist/schema/blob.js.map +1 -1
- package/dist/schema/payload.d.ts.map +1 -1
- package/dist/schema/payload.js +2 -3
- package/dist/schema/payload.js.map +1 -1
- package/dist/schema/record.d.ts +6 -8
- package/dist/schema/record.d.ts.map +1 -1
- package/dist/schema/record.js +1 -1
- package/dist/schema/record.js.map +1 -1
- package/dist/schema/regexp.d.ts +3 -2
- package/dist/schema/regexp.d.ts.map +1 -1
- package/dist/schema/regexp.js +6 -4
- package/dist/schema/regexp.js.map +1 -1
- package/dist/schema/string.d.ts.map +1 -1
- package/dist/schema/string.js +9 -2
- package/dist/schema/string.js.map +1 -1
- package/dist/schema/typed-object.d.ts +5 -7
- package/dist/schema/typed-object.d.ts.map +1 -1
- package/dist/schema/typed-object.js +1 -1
- package/dist/schema/typed-object.js.map +1 -1
- package/package.json +3 -3
- package/src/core/$type.test.ts +9 -5
- package/src/core/schema.ts +19 -16
- package/src/core/validation-error.ts +2 -2
- package/src/core/validation-issue.ts +20 -36
- package/src/helpers.ts +7 -1
- package/src/schema/array.test.ts +1 -1
- package/src/schema/blob.test.ts +223 -263
- package/src/schema/blob.ts +27 -46
- package/src/schema/params.test.ts +2 -2
- package/src/schema/payload.ts +2 -3
- package/src/schema/record.test.ts +135 -17
- package/src/schema/record.ts +14 -9
- package/src/schema/regexp.ts +14 -4
- package/src/schema/string.ts +8 -2
- package/src/schema/typed-object.test.ts +77 -0
- package/src/schema/typed-object.ts +11 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# @atproto/lex-schema
|
|
2
2
|
|
|
3
|
+
## 0.0.18
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#4828](https://github.com/bluesky-social/atproto/pull/4828) [`c62651d`](https://github.com/bluesky-social/atproto/commit/c62651dd69f1e18bd854b66e499b91fee9eaa856) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Accept legacy blob references in non-strict mode. Legacy blob references (objects with `cid` and `mimeType` properties) are now accepted when `strict: false`, which is the default behavior when `strictResponseProcessing` is disabled on the Client.
|
|
8
|
+
|
|
9
|
+
BREAKING: The `allowLegacy` option has been removed from the blob schema builder, and legacy blobs are now handled automatically based on the strictness mode: in strict mode they are rejected, and in non-strict mode they are accepted. Consumers should stop passing `allowLegacy` and rely on strictness configuration instead. Likewise, CLI consumers should stop using the removed `--allowLegacyBlobs` flag and use the default strict/non-strict behavior.
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [[`c62651d`](https://github.com/bluesky-social/atproto/commit/c62651dd69f1e18bd854b66e499b91fee9eaa856), [`f6f100c`](https://github.com/bluesky-social/atproto/commit/f6f100c33700a7ff58a1458109cc7420131feed0), [`c62651d`](https://github.com/bluesky-social/atproto/commit/c62651dd69f1e18bd854b66e499b91fee9eaa856), [`c62651d`](https://github.com/bluesky-social/atproto/commit/c62651dd69f1e18bd854b66e499b91fee9eaa856)]:
|
|
12
|
+
- @atproto/lex-data@0.0.15
|
|
13
|
+
|
|
14
|
+
## 0.0.17
|
|
15
|
+
|
|
16
|
+
### Patch Changes
|
|
17
|
+
|
|
18
|
+
- [#4779](https://github.com/bluesky-social/atproto/pull/4779) [`527f5d4`](https://github.com/bluesky-social/atproto/commit/527f5d4c5d0c9264c2ff6f23ad06a41163fc6809) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Update `lexErrorDataSchema` to match spec (rejecting `error` constants with whitespace)
|
|
19
|
+
|
|
20
|
+
- [#4787](https://github.com/bluesky-social/atproto/pull/4787) [`c4df84c`](https://github.com/bluesky-social/atproto/commit/c4df84cd78df68ee8cb7289e7b61b3a032ad484e) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Optimize counting of graphemes when validating strings
|
|
21
|
+
|
|
22
|
+
- [#4779](https://github.com/bluesky-social/atproto/pull/4779) [`527f5d4`](https://github.com/bluesky-social/atproto/commit/527f5d4c5d0c9264c2ff6f23ad06a41163fc6809) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Fix `build()` method of record and typed object to not perform validation.
|
|
23
|
+
|
|
24
|
+
- [#4784](https://github.com/bluesky-social/atproto/pull/4784) [`e5e5bcf`](https://github.com/bluesky-social/atproto/commit/e5e5bcf85fbc0d418f05724d684e7265be6a0be9) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Show invalid values in issue description (when stringifiable in reasonably small string)
|
|
25
|
+
|
|
26
|
+
- [#4796](https://github.com/bluesky-social/atproto/pull/4796) [`ac6bd18`](https://github.com/bluesky-social/atproto/commit/ac6bd18f1dc3397dd29008eff2a1e40702a4e138) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Allow specifying `ValidateOptions` to `matches()` and `ifMathces()` method, allowing disabling "strict" mode
|
|
27
|
+
|
|
28
|
+
- [#4799](https://github.com/bluesky-social/atproto/pull/4799) [`c5c6c7d`](https://github.com/bluesky-social/atproto/commit/c5c6c7dac3b08e5f63cc918f57705573028ad797) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Allow any encoding to match payload that don't expect any particular encoding
|
|
29
|
+
|
|
30
|
+
- Updated dependencies [[`0dbea15`](https://github.com/bluesky-social/atproto/commit/0dbea15da48a6ca913cc3a3a2d8c0ffe64d7c69a), [`d0c136c`](https://github.com/bluesky-social/atproto/commit/d0c136cba2ec8fa97017849b1023d5af5d2cc60c), [`527f5d4`](https://github.com/bluesky-social/atproto/commit/527f5d4c5d0c9264c2ff6f23ad06a41163fc6809)]:
|
|
31
|
+
- @atproto/syntax@0.5.2
|
|
32
|
+
|
|
3
33
|
## 0.0.16
|
|
4
34
|
|
|
5
35
|
### Patch Changes
|
package/dist/core/schema.d.ts
CHANGED
|
@@ -90,26 +90,23 @@ export declare abstract class Schema<out TInput = unknown, out TOutput = TInput>
|
|
|
90
90
|
* will typically arise in generic contexts, where the narrowed type is not
|
|
91
91
|
* needed.
|
|
92
92
|
*/
|
|
93
|
-
assert(input: unknown): asserts input is InferInput<this>;
|
|
93
|
+
assert(input: unknown, options?: ValidateOptions): asserts input is InferInput<this>;
|
|
94
94
|
/**
|
|
95
95
|
* Alias for {@link assert}(). Most useful in generic contexts where the
|
|
96
96
|
* validator is not exactly typed, allowing to avoid "_Assertions require
|
|
97
97
|
* every name in the call target to be declared with an explicit type
|
|
98
98
|
* annotation. ts(2775)_" errors.
|
|
99
99
|
*/
|
|
100
|
-
check(input: unknown): void;
|
|
100
|
+
check(input: unknown, options?: ValidateOptions): void;
|
|
101
101
|
/**
|
|
102
102
|
* Casts the input (by validating it) to the output type if it matches the
|
|
103
103
|
* schema, otherwise throws. This is the same as calling {@link parse}() with
|
|
104
104
|
* `mode: "validate"`.
|
|
105
105
|
*/
|
|
106
|
-
cast<I>(input: I): I & InferInput<this>;
|
|
106
|
+
cast<I>(input: I, options?: ValidateOptions): I & InferInput<this>;
|
|
107
107
|
/**
|
|
108
108
|
* Type guard that checks if the input matches this schema.
|
|
109
109
|
*
|
|
110
|
-
* @param input - The value to check
|
|
111
|
-
* @returns `true` if the input is valid according to this schema
|
|
112
|
-
*
|
|
113
110
|
* @example
|
|
114
111
|
* ```typescript
|
|
115
112
|
* if (schema.matches(data)) {
|
|
@@ -118,16 +115,13 @@ export declare abstract class Schema<out TInput = unknown, out TOutput = TInput>
|
|
|
118
115
|
* }
|
|
119
116
|
* ```
|
|
120
117
|
*/
|
|
121
|
-
matches<I>(input: I): input is I & InferInput<this>;
|
|
118
|
+
matches<I>(input: I, options?: ValidateOptions): input is I & InferInput<this>;
|
|
122
119
|
/**
|
|
123
120
|
* Returns the input if it matches this schema, otherwise returns `undefined`.
|
|
124
121
|
*
|
|
125
122
|
* This is useful for optional filtering operations where you want to
|
|
126
123
|
* conditionally extract values that match a schema.
|
|
127
124
|
*
|
|
128
|
-
* @param input - The value to check
|
|
129
|
-
* @returns The input value with narrowed type if valid, otherwise `undefined`
|
|
130
|
-
*
|
|
131
125
|
* @example
|
|
132
126
|
* ```typescript
|
|
133
127
|
* const validData = schema.ifMatches(data)
|
|
@@ -137,7 +131,7 @@ export declare abstract class Schema<out TInput = unknown, out TOutput = TInput>
|
|
|
137
131
|
* }
|
|
138
132
|
* ```
|
|
139
133
|
*/
|
|
140
|
-
ifMatches<I>(input: I): (I & InferInput<this>) | undefined;
|
|
134
|
+
ifMatches<I>(input: I, options?: ValidateOptions): (I & InferInput<this>) | undefined;
|
|
141
135
|
/**
|
|
142
136
|
* Parses the input, allowing value transformations and coercion.
|
|
143
137
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/core/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAGxD,OAAO,EACL,UAAU,EACV,WAAW,EACX,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,SAAS,EACV,MAAM,gBAAgB,CAAA;AAEvB;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,IAAI,CAAC,iBAAiB,EAAE,MAAM,CAAC,CAAA;AAE1D;;;GAGG;AACH,MAAM,MAAM,eAA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GG;IACH,IAAI,MAAM,IAAI,OAAO,IAAI,CAAC,KAAK,CAE9B;IAED;;;OAGG;IACH,IAAI,UAAU,IAAI,OAAO,IAAI,CAAC,SAAS,CAEtC;IAED;;;OAGG;IACH,IAAI,SAAS,IAAI,OAAO,IAAI,CAAC,QAAQ,CAEpC;IAED;;;OAGG;IACH,IAAI,aAAa,IAAI,OAAO,IAAI,CAAC,YAAY,CAE5C;CACF"}
|
package/dist/core/schema.js
CHANGED
|
@@ -51,8 +51,8 @@ class Schema {
|
|
|
51
51
|
* will typically arise in generic contexts, where the narrowed type is not
|
|
52
52
|
* needed.
|
|
53
53
|
*/
|
|
54
|
-
assert(input) {
|
|
55
|
-
const result =
|
|
54
|
+
assert(input, options) {
|
|
55
|
+
const result = this.safeValidate(input, options);
|
|
56
56
|
if (!result.success)
|
|
57
57
|
throw result.reason;
|
|
58
58
|
}
|
|
@@ -62,16 +62,16 @@ class Schema {
|
|
|
62
62
|
* every name in the call target to be declared with an explicit type
|
|
63
63
|
* annotation. ts(2775)_" errors.
|
|
64
64
|
*/
|
|
65
|
-
check(input) {
|
|
66
|
-
this.assert(input);
|
|
65
|
+
check(input, options) {
|
|
66
|
+
this.assert(input, options);
|
|
67
67
|
}
|
|
68
68
|
/**
|
|
69
69
|
* Casts the input (by validating it) to the output type if it matches the
|
|
70
70
|
* schema, otherwise throws. This is the same as calling {@link parse}() with
|
|
71
71
|
* `mode: "validate"`.
|
|
72
72
|
*/
|
|
73
|
-
cast(input) {
|
|
74
|
-
const result =
|
|
73
|
+
cast(input, options) {
|
|
74
|
+
const result = this.safeValidate(input, options);
|
|
75
75
|
if (result.success)
|
|
76
76
|
return result.value;
|
|
77
77
|
throw result.reason;
|
|
@@ -79,9 +79,6 @@ class Schema {
|
|
|
79
79
|
/**
|
|
80
80
|
* Type guard that checks if the input matches this schema.
|
|
81
81
|
*
|
|
82
|
-
* @param input - The value to check
|
|
83
|
-
* @returns `true` if the input is valid according to this schema
|
|
84
|
-
*
|
|
85
82
|
* @example
|
|
86
83
|
* ```typescript
|
|
87
84
|
* if (schema.matches(data)) {
|
|
@@ -90,8 +87,8 @@ class Schema {
|
|
|
90
87
|
* }
|
|
91
88
|
* ```
|
|
92
89
|
*/
|
|
93
|
-
matches(input) {
|
|
94
|
-
const result =
|
|
90
|
+
matches(input, options) {
|
|
91
|
+
const result = this.safeValidate(input, options);
|
|
95
92
|
return result.success;
|
|
96
93
|
}
|
|
97
94
|
/**
|
|
@@ -100,9 +97,6 @@ class Schema {
|
|
|
100
97
|
* This is useful for optional filtering operations where you want to
|
|
101
98
|
* conditionally extract values that match a schema.
|
|
102
99
|
*
|
|
103
|
-
* @param input - The value to check
|
|
104
|
-
* @returns The input value with narrowed type if valid, otherwise `undefined`
|
|
105
|
-
*
|
|
106
100
|
* @example
|
|
107
101
|
* ```typescript
|
|
108
102
|
* const validData = schema.ifMatches(data)
|
|
@@ -112,8 +106,8 @@ class Schema {
|
|
|
112
106
|
* }
|
|
113
107
|
* ```
|
|
114
108
|
*/
|
|
115
|
-
ifMatches(input) {
|
|
116
|
-
return this.matches(input) ? input : undefined;
|
|
109
|
+
ifMatches(input, options) {
|
|
110
|
+
return this.matches(input, options) ? input : undefined;
|
|
117
111
|
}
|
|
118
112
|
/**
|
|
119
113
|
* Parses the input, allowing value transformations and coercion.
|
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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,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAC1E,CAAC;CACF;AA7UD,wBA6UC","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(input: unknown): asserts input is InferInput<this> {\n const result = ValidationContext.validate(input, this)\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): void {\n this.assert(input)\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): I & InferInput<this> {\n const result = ValidationContext.validate(input, this)\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 * @param input - The value to check\n * @returns `true` if the input is valid according to 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>(input: I): input is I & InferInput<this> {\n const result = ValidationContext.validate(input, this)\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 * @param input - The value to check\n * @returns The input value with narrowed type if valid, otherwise `undefined`\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>(input: I): (I & InferInput<this>) | undefined {\n return this.matches(input) ? 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,+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,CA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;QACV,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAChE,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,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"]}
|
|
@@ -17,7 +17,7 @@ import { Issue } from './validation-issue.js';
|
|
|
17
17
|
* new IssueInvalidType(['user', 'age'], 'hello', ['number'])
|
|
18
18
|
* ])
|
|
19
19
|
* console.log(error.message)
|
|
20
|
-
* // "Expected
|
|
20
|
+
* // "Expected integer value type (got "some-string") at $.user.age"
|
|
21
21
|
*
|
|
22
22
|
* console.log(error.issues.length) // 1
|
|
23
23
|
* console.log(error.toJSON())
|
|
@@ -36,7 +36,7 @@ export declare class LexValidationError extends LexError<'InvalidRequest'> imple
|
|
|
36
36
|
* Issues are aggregated when possible (e.g., multiple invalid type issues
|
|
37
37
|
* at the same path are combined into a single issue listing all expected types).
|
|
38
38
|
*/
|
|
39
|
-
readonly issues: Issue[];
|
|
39
|
+
readonly issues: readonly Issue[];
|
|
40
40
|
/**
|
|
41
41
|
* Creates a new validation error from a list of issues.
|
|
42
42
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation-error.d.ts","sourceRoot":"","sources":["../../src/core/validation-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAE5C,OAAO,EAAE,aAAa,EAAiB,MAAM,aAAa,CAAA;AAC1D,OAAO,EACL,KAAK,EAGN,MAAM,uBAAuB,CAAA;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,kBACX,SAAQ,QAAQ,CAAC,gBAAgB,CACjC,YAAW,aAAa,CAAC,kBAAkB,CAAC;IAE5C,IAAI,SAAuB;IAE3B;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,CAAA;
|
|
1
|
+
{"version":3,"file":"validation-error.d.ts","sourceRoot":"","sources":["../../src/core/validation-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAE5C,OAAO,EAAE,aAAa,EAAiB,MAAM,aAAa,CAAA;AAC1D,OAAO,EACL,KAAK,EAGN,MAAM,uBAAuB,CAAA;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,kBACX,SAAQ,QAAQ,CAAC,gBAAgB,CACjC,YAAW,aAAa,CAAC,kBAAkB,CAAC;IAE5C,IAAI,SAAuB;IAE3B;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,EAAE,SAAS,KAAK,EAAE,CAAA;IAEjC;;;;;;;;OAQG;gBACS,MAAM,EAAE,KAAK,EAAE,EAAE,OAAO,CAAC,EAAE,YAAY;IAMnD,mCAAmC;IACnC,QAAQ,CAAC,OAAO,EAAG,KAAK,CAAS;IAEjC,kCAAkC;IAClC,IAAI,MAAM,SAET;IAED;;;;OAIG;IACM,MAAM;;;;;;;;;IAOf;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,YAAY,CACjB,QAAQ,EAAE,SAAS,aAAa,CAAC,kBAAkB,CAAC,EAAE,GACrD,kBAAkB;CAQtB"}
|
|
@@ -21,7 +21,7 @@ const validation_issue_js_1 = require("./validation-issue.js");
|
|
|
21
21
|
* new IssueInvalidType(['user', 'age'], 'hello', ['number'])
|
|
22
22
|
* ])
|
|
23
23
|
* console.log(error.message)
|
|
24
|
-
* // "Expected
|
|
24
|
+
* // "Expected integer value type (got "some-string") at $.user.age"
|
|
25
25
|
*
|
|
26
26
|
* console.log(error.issues.length) // 1
|
|
27
27
|
* console.log(error.toJSON())
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation-error.js","sourceRoot":"","sources":["../../src/core/validation-error.ts"],"names":[],"mappings":";;;AAAA,gDAA4C;AAC5C,uDAA+C;AAC/C,2CAA0D;AAC1D,+DAI8B;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAa,kBACX,SAAQ,mBAA0B;IAGlC,IAAI,GAAG,oBAAoB,CAAA;IAE3B;;;;;OAKG;IACM,MAAM,
|
|
1
|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CAAC,CAAC,CAAC,CAAC,IAAI,EACd,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,EACf,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CACzD,CACJ;QACD,4BAA4B;QAC5B,GAAG,MAAM,CAAC,MAAM,CACd,CAAC,KAAK,EAAE,EAAE,CACR,CAAC,CAAC,KAAK,YAAY,sCAAgB,CAAC;YACpC,CAAC,CAAC,KAAK,YAAY,uCAAiB,CAAC,CACxC;KACF,CAAA;AACH,CAAC;AAED,wBAAwB;AACxB,SAAS,oBAAoB,CAC3B,CAAyB,EACzB,CAAyB;IAEzB,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAA;IACvC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QAClC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAAE,OAAO,KAAK,CAAA;IACjC,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC","sourcesContent":["import { LexError } from '@atproto/lex-data'\nimport { arrayAgg } from '../util/array-agg.js'\nimport { ResultFailure, failureReason } from './result.js'\nimport {\n Issue,\n IssueInvalidType,\n IssueInvalidValue,\n} from './validation-issue.js'\n\n/**\n * Error thrown when validation fails.\n *\n * Contains detailed information about all validation issues encountered,\n * including the path to each invalid value and descriptions of what was\n * expected vs what was received.\n *\n * Extends {@link LexError} with the error name \"InvalidRequest\" for\n * consistency with the AT Protocol error handling conventions.\n *\n * @example\n * ```typescript\n * const error = new LexValidationError([\n * new IssueInvalidType(['user', 'age'], 'hello', ['number'])\n * ])\n * console.log(error.message)\n * // \"Expected integer value type (got \"some-string\") at $.user.age\"\n *\n * console.log(error.issues.length) // 1\n * console.log(error.toJSON())\n * // { error: 'InvalidRequest', message: '...', issues: [...] }\n * ```\n *\n * @note this class implements {@link ResultFailure} to allow it to be used\n * directly as a failure reason in validation results, avoiding the need for\n * wrapping it in an additional object.\n */\nexport class LexValidationError\n extends LexError<'InvalidRequest'>\n implements ResultFailure<LexValidationError>\n{\n name = 'LexValidationError'\n\n /**\n * The list of validation issues that caused this error.\n *\n * Issues are aggregated when possible (e.g., multiple invalid type issues\n * at the same path are combined into a single issue listing all expected types).\n */\n readonly issues: readonly Issue[]\n\n /**\n * Creates a new validation error from a list of issues.\n *\n * Issues are automatically aggregated to combine related issues at the same\n * path (e.g., multiple type expectations from a union schema).\n *\n * @param issues - The validation issues that caused this error\n * @param options - Standard Error options (e.g., `cause`)\n */\n constructor(issues: Issue[], options?: ErrorOptions) {\n const issuesAgg = aggregateIssues(issues)\n super('InvalidRequest', issuesAgg.join(', '), options)\n this.issues = issuesAgg\n }\n\n /** @see {ResultFailure.success} */\n readonly success = false as const\n\n /** @see {ResultFailure.reason} */\n get reason() {\n return this\n }\n\n /**\n * Converts the error to a JSON-serializable object.\n *\n * @returns An object containing the error details and issues details\n */\n override toJSON() {\n return {\n ...super.toJSON(),\n issues: this.issues.map((issue) => issue.toJSON()),\n }\n }\n\n /**\n * Creates a validation error by combining multiple validation failures.\n *\n * This is useful when validating against multiple possible schemas (e.g., unions)\n * and all branches fail. The resulting error contains issues from all failures.\n *\n * @param failures - The validation failures to combine\n * @returns A single validation error containing all issues from the failures\n *\n * @example\n * ```typescript\n * const failures = schemas.map(s => s.safeValidate(data)).filter(r => !r.success)\n * if (failures.length === schemas.length) {\n * throw LexValidationError.fromFailures(failures)\n * }\n * ```\n */\n static fromFailures(\n failures: readonly ResultFailure<LexValidationError>[],\n ): LexValidationError {\n if (failures.length === 1) return failureReason(failures[0])\n const issues = failures.flatMap(extractFailureIssues)\n return new LexValidationError(issues, {\n // Keep the original errors as the cause chain\n cause: failures.map(failureReason),\n })\n }\n}\n\nfunction extractFailureIssues(result: ResultFailure<LexValidationError>) {\n return result.reason.issues\n}\n\nfunction aggregateIssues(issues: Issue[]): Issue[] {\n // Quick path for common cases\n if (issues.length <= 1) return issues\n if (issues.length === 2 && issues[0].code !== issues[1].code) return issues\n\n return [\n // Aggregate invalid_type with identical paths\n ...arrayAgg(\n issues.filter((issue) => issue instanceof IssueInvalidType),\n (a, b) => comparePropertyPaths(a.path, b.path),\n (issues) =>\n new IssueInvalidType(\n issues[0].path,\n issues[0].input,\n Array.from(new Set(issues.flatMap((iss) => iss.expected))),\n ),\n ),\n // Aggregate invalid_value with identical paths\n ...arrayAgg(\n issues.filter((issue) => issue instanceof IssueInvalidValue),\n (a, b) => comparePropertyPaths(a.path, b.path),\n (issues) =>\n new IssueInvalidValue(\n issues[0].path,\n issues[0].input,\n Array.from(new Set(issues.flatMap((iss) => iss.values))),\n ),\n ),\n // Pass through other issues\n ...issues.filter(\n (issue) =>\n !(issue instanceof IssueInvalidType) &&\n !(issue instanceof IssueInvalidValue),\n ),\n ]\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction comparePropertyPaths(\n a: readonly PropertyKey[],\n b: readonly PropertyKey[],\n) {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false\n }\n return true\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation-issue.d.ts","sourceRoot":"","sources":["../../src/core/validation-issue.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"validation-issue.d.ts","sourceRoot":"","sources":["../../src/core/validation-issue.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;GAWG;AACH,8BAAsB,KAAK;IAIvB,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB,QAAQ,CAAC,IAAI,EAAE,SAAS,WAAW,EAAE;IACrC,QAAQ,CAAC,KAAK,EAAE,OAAO;IALzB,QAAQ,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA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TooBig = exports.IssueRequiredKey = exports.IssueInvalidValue = exports.IssueInvalidType = exports.IssueInvalidFormat = exports.IssueCustom = exports.Issue = void 0;
|
|
4
4
|
const lex_data_1 = require("@atproto/lex-data");
|
|
5
|
+
const STRING_PREVIEW_MAX_LENGTH = 48;
|
|
6
|
+
const STRING_PREVIEW_TRUNCATED_SUFFIX = '…';
|
|
5
7
|
/**
|
|
6
8
|
* Abstract base class for all validation issues.
|
|
7
9
|
*
|
|
@@ -116,7 +118,7 @@ class IssueInvalidType extends Issue {
|
|
|
116
118
|
this.expected = expected;
|
|
117
119
|
}
|
|
118
120
|
get message() {
|
|
119
|
-
return `Expected ${oneOf(this.expected.map(stringifyExpectedType))} value type (got ${
|
|
121
|
+
return `Expected ${oneOf(this.expected.map(stringifyExpectedType))} value type (got ${stringifyValue(this.input)})`;
|
|
120
122
|
}
|
|
121
123
|
toJSON() {
|
|
122
124
|
return {
|
|
@@ -252,13 +254,26 @@ function oneOf(arr) {
|
|
|
252
254
|
return arr[0];
|
|
253
255
|
return `one of ${arr.slice(0, -1).join(', ')} or ${arr.at(-1)}`;
|
|
254
256
|
}
|
|
255
|
-
function
|
|
257
|
+
function stringifyValue(value) {
|
|
256
258
|
switch (typeof value) {
|
|
259
|
+
case 'bigint':
|
|
260
|
+
return `${value}n`;
|
|
261
|
+
case 'number':
|
|
262
|
+
case 'boolean':
|
|
263
|
+
return String(value);
|
|
264
|
+
case 'string':
|
|
265
|
+
return JSON.stringify(value.length < STRING_PREVIEW_MAX_LENGTH
|
|
266
|
+
? value
|
|
267
|
+
: `${value.slice(0, STRING_PREVIEW_MAX_LENGTH - STRING_PREVIEW_TRUNCATED_SUFFIX.length)}${STRING_PREVIEW_TRUNCATED_SUFFIX}`);
|
|
257
268
|
case 'object':
|
|
258
269
|
if (value === null)
|
|
259
270
|
return 'null';
|
|
260
|
-
if (Array.isArray(value))
|
|
261
|
-
return
|
|
271
|
+
if (Array.isArray(value)) {
|
|
272
|
+
return `[${stringifyArray(value, stringifyValue)}]`;
|
|
273
|
+
}
|
|
274
|
+
if ((0, lex_data_1.isPlainObject)(value)) {
|
|
275
|
+
return `{${stringifyArray(Object.entries(value), stringifyObjectEntry)}}`;
|
|
276
|
+
}
|
|
262
277
|
if ((0, lex_data_1.ifCid)(value))
|
|
263
278
|
return 'cid';
|
|
264
279
|
if ((0, lex_data_1.isLegacyBlobRef)(value))
|
|
@@ -272,44 +287,10 @@ function stringifyType(value) {
|
|
|
272
287
|
if (value instanceof Set)
|
|
273
288
|
return 'set';
|
|
274
289
|
return 'object';
|
|
275
|
-
case 'number':
|
|
276
|
-
if (Number.isInteger(value) && Number.isSafeInteger(value)) {
|
|
277
|
-
return 'integer';
|
|
278
|
-
}
|
|
279
|
-
if (Number.isNaN(value)) {
|
|
280
|
-
return 'NaN';
|
|
281
|
-
}
|
|
282
|
-
if (value === Infinity) {
|
|
283
|
-
return 'Infinity';
|
|
284
|
-
}
|
|
285
|
-
if (value === -Infinity) {
|
|
286
|
-
return '-Infinity';
|
|
287
|
-
}
|
|
288
|
-
return 'float';
|
|
289
290
|
default:
|
|
290
291
|
return typeof value;
|
|
291
292
|
}
|
|
292
293
|
}
|
|
293
|
-
function stringifyValue(value) {
|
|
294
|
-
switch (typeof value) {
|
|
295
|
-
case 'bigint':
|
|
296
|
-
return `${value}n`;
|
|
297
|
-
case 'number':
|
|
298
|
-
case 'string':
|
|
299
|
-
case 'boolean':
|
|
300
|
-
return JSON.stringify(value);
|
|
301
|
-
case 'object':
|
|
302
|
-
if (Array.isArray(value)) {
|
|
303
|
-
return `[${stringifyArray(value, stringifyValue)}]`;
|
|
304
|
-
}
|
|
305
|
-
if ((0, lex_data_1.isPlainObject)(value)) {
|
|
306
|
-
return `{${stringifyArray(Object.entries(value), stringifyObjectEntry)}}`;
|
|
307
|
-
}
|
|
308
|
-
// fallthrough
|
|
309
|
-
default:
|
|
310
|
-
return stringifyType(value);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
294
|
/*@__NO_SIDE_EFFECTS__*/
|
|
314
295
|
function stringifyObjectEntry([key, _value]) {
|
|
315
296
|
return `${JSON.stringify(key)}: ...`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation-issue.js","sourceRoot":"","sources":["../../src/core/validation-issue.ts"],"names":[],"mappings":";;;AAAA,gDAAyE;AAEzE;;;;;;;;;;;GAWG;AACH,MAAsB,KAAK;IAId;IACA;IACA;IAHX,YACW,IAAY,EACZ,IAA4B,EAC5B,KAAc;QAFd,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAwB;QAC5B,UAAK,GAAL,KAAK,CAAS;IACtB,CAAC;IAEJ;;OAEG;IACH,QAAQ;QACN,OAAO,GAAG,IAAI,CAAC,OAAO,GAAG,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAA;IACrD,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;SACtB,CAAA;IACH,CAAC;CACF;AA5BD,sBA4BC;AAED;;;;GAIG;AACH,MAAa,WAAY,SAAQ,KAAK;IAEzB;IACA;IACA;IAHX,YACW,IAA4B,EAC5B,KAAc,EACd,OAAe;QAExB,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;QAJnB,SAAI,GAAJ,IAAI,CAAwB;QAC5B,UAAK,GAAL,KAAK,CAAS;QACd,YAAO,GAAP,OAAO,CAAQ;IAG1B,CAAC;CACF;AARD,kCAQC;AAED;;;;GAIG;AACH,MAAa,kBAAmB,SAAQ,KAAK;IAIhC;IACA;IAJX,YACE,IAA4B,EAC5B,KAAc,EACL,MAAc,EACd,MAAe;QAExB,KAAK,CAAC,gBAAgB,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;QAH3B,WAAM,GAAN,MAAM,CAAQ;QAC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KAAK,CAAC,EAAE,CAAC;gBACzB,OAAO,IAAI,cAAc,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,oBAAoB,CAAC,GAAG,CAAA;YAC3E,CAAC;QACH,cAAc;QACd;YACE,OAAO,aAAa,CAAC,KAAK,CAAC,CAAA;IAC/B,CAAC;AACH,CAAC;AAED,wBAAwB;AACxB,SAAS,oBAAoB,CAAC,CAAC,GAAG,EAAE,MAAM,CAAyB;IACjE,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAA;AACtC,CAAC;AAED,wBAAwB;AACxB,SAAS,cAAc,CACrB,GAAiB,EACjB,EAAuB,EACvB,CAAC,GAAG,CAAC;IAEL,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AAC7E,CAAC","sourcesContent":["import { ifCid, isLegacyBlobRef, isPlainObject } from '@atproto/lex-data'\n\n/**\n * Abstract base class for all validation issues.\n *\n * An issue represents a single validation failure, containing:\n * - A code identifying the type of issue\n * - The path to the invalid value in the data structure\n * - The actual input value that failed validation\n *\n * Subclasses add specific properties relevant to each issue type and implement\n * the {@link message} property for human-readable error messages (that don't\n * contain the error path)\n */\nexport abstract class Issue {\n abstract readonly message: string\n\n constructor(\n readonly code: string,\n readonly path: readonly PropertyKey[],\n readonly input: unknown,\n ) {}\n\n /**\n * Returns a human-readable description of the validation issue.\n */\n toString() {\n return `${this.message}${stringifyPath(this.path)}`\n }\n\n /**\n * Converts the issue to a JSON-serializable object.\n *\n * @returns An object containing the issue code, path, and message\n */\n toJSON() {\n return {\n code: this.code,\n path: this.path,\n message: this.message,\n }\n }\n}\n\n/**\n * A custom validation issue with a user-defined message.\n *\n * Use this for validation rules that don't fit into the standard issue categories.\n */\nexport class IssueCustom extends Issue {\n constructor(\n readonly path: readonly PropertyKey[],\n readonly input: unknown,\n readonly message: string,\n ) {\n super('custom', path, input)\n }\n}\n\n/**\n * Issue for string values that don't match an expected format.\n *\n * Used for AT Protocol specific formats like DID, handle, NSID, AT-URI, etc.\n */\nexport class IssueInvalidFormat extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly format: string,\n readonly detail?: string,\n ) {\n super('invalid_format', path, input)\n }\n\n override get message(): string {\n return `Invalid ${this.formatDescription}${this.detail ? ` (${this.detail}, ` : ' ('}got ${stringifyValue(this.input)})`\n }\n\n /** Returns a human-readable description of the expected format. */\n get formatDescription(): string {\n switch (this.format) {\n case 'at-identifier':\n return `AT identifier`\n case 'did':\n return `DID`\n case 'nsid':\n return `NSID`\n case 'cid':\n return `CID string`\n case 'tid':\n return `TID string`\n case 'record-key':\n return `record key`\n default:\n return this.format\n }\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n format: this.format,\n }\n }\n}\n\n/**\n * Issue for values that have an unexpected type.\n *\n * This is one of the most common validation issues, occurring when the\n * runtime type of a value doesn't match the expected schema type.\n */\nexport class IssueInvalidType extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly expected: readonly string[],\n ) {\n super('invalid_type', path, input)\n }\n\n override get message(): string {\n return `Expected ${oneOf(this.expected.map(stringifyExpectedType))} value type (got ${stringifyType(this.input)})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n expected: this.expected,\n }\n }\n}\n\n/**\n * Issue for values that don't match any of the expected literal values.\n *\n * Used when a value must be one of a specific set of allowed values\n * (e.g., enum-like constraints).\n */\nexport class IssueInvalidValue extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly values: readonly unknown[],\n ) {\n super('invalid_value', path, input)\n }\n\n override get message(): string {\n return `Expected ${oneOf(this.values.map(stringifyValue))} (got ${stringifyValue(this.input)})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n values: this.values,\n }\n }\n}\n\n/**\n * Issue for missing required object properties.\n */\nexport class IssueRequiredKey extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly key: PropertyKey,\n ) {\n super('required_key', path, input)\n }\n\n override get message(): string {\n return `Missing required key \"${String(this.key)}\"`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n key: this.key,\n }\n }\n}\n\n/**\n * The type of measurement for size constraint issues.\n *\n * - `'array'` - Array length\n * - `'string'` - String length in characters\n * - `'integer'` - Numeric value\n * - `'grapheme'` - String length in grapheme clusters\n * - `'bytes'` - Byte length\n * - `'blob'` - Blob size\n */\nexport type MeasurableType =\n | 'array'\n | 'string'\n | 'integer'\n | 'grapheme'\n | 'bytes'\n | 'blob'\n\n/**\n * Issue for values that exceed a maximum constraint.\n */\nexport class IssueTooBig extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly maximum: number,\n readonly type: MeasurableType,\n readonly actual: number,\n ) {\n super('too_big', path, input)\n }\n\n override get message(): string {\n return `${this.type} too big (maximum ${this.maximum}, got ${this.actual})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n maximum: this.maximum,\n }\n }\n}\n\n/**\n * Issue for values that are below a minimum constraint.\n */\nexport class IssueTooSmall extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly minimum: number,\n readonly type: MeasurableType,\n readonly actual: number,\n ) {\n super('too_small', path, input)\n }\n\n override get message(): string {\n return `${this.type} too small (minimum ${this.minimum}, got ${this.actual})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n minimum: this.minimum,\n }\n }\n}\n\n// -----------------------------------------------------------------------------\n// Helper functions for formatting error messages\n// -----------------------------------------------------------------------------\n\nfunction stringifyExpectedType(expected: string): string {\n if (expected === '$typed') {\n return 'an object which includes the \"$type\" property'\n }\n return expected\n}\n\nfunction stringifyPath(path: readonly PropertyKey[]) {\n return ` at ${buildJsonPath(path)}`\n}\n\nfunction buildJsonPath(path: readonly PropertyKey[]): string {\n return `$${path.map(toJsonPathSegment).join('')}`\n}\n\nfunction toJsonPathSegment(segment: PropertyKey): string {\n if (typeof segment === 'number' || typeof segment === 'symbol') {\n return `[${String(segment)}]`\n } else if (/^[a-zA-Z_$][a-zA-Z0-9_]*$/.test(segment)) {\n return `.${segment}`\n } else {\n return `[${JSON.stringify(segment)}]`\n }\n}\n\nfunction oneOf(arr: readonly string[]): string {\n if (arr.length === 0) return ''\n if (arr.length === 1) return arr[0]\n return `one of ${arr.slice(0, -1).join(', ')} or ${arr.at(-1)}`\n}\n\nfunction stringifyType(value: unknown): string {\n switch (typeof value) {\n case 'object':\n if (value === null) return 'null'\n if (Array.isArray(value)) return 'array'\n if (ifCid(value)) return 'cid'\n if (isLegacyBlobRef(value)) return 'legacy-blob'\n if (value instanceof Date) return 'date'\n if (value instanceof RegExp) return 'regexp'\n if (value instanceof Map) return 'map'\n if (value instanceof Set) return 'set'\n return 'object'\n case 'number':\n if (Number.isInteger(value) && Number.isSafeInteger(value)) {\n return 'integer'\n }\n if (Number.isNaN(value)) {\n return 'NaN'\n }\n if (value === Infinity) {\n return 'Infinity'\n }\n if (value === -Infinity) {\n return '-Infinity'\n }\n return 'float'\n default:\n return typeof value\n }\n}\n\nfunction stringifyValue(value: unknown): string {\n switch (typeof value) {\n case 'bigint':\n return `${value}n`\n case 'number':\n case 'string':\n case 'boolean':\n return JSON.stringify(value)\n case 'object':\n if (Array.isArray(value)) {\n return `[${stringifyArray(value, stringifyValue)}]`\n }\n if (isPlainObject(value)) {\n return `{${stringifyArray(Object.entries(value), stringifyObjectEntry)}}`\n }\n // fallthrough\n default:\n return stringifyType(value)\n }\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringifyObjectEntry([key, _value]: [PropertyKey, unknown]): string {\n return `${JSON.stringify(key)}: ...`\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringifyArray<T>(\n arr: readonly T[],\n fn: (item: T) => string,\n n = 2,\n): string {\n return arr.slice(0, n).map(fn).join(', ') + (arr.length > n ? ', ...' : '')\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validation-issue.js","sourceRoot":"","sources":["../../src/core/validation-issue.ts"],"names":[],"mappings":";;;AAAA,gDAAyE;AAEzE,MAAM,yBAAyB,GAAG,EAAE,CAAA;AACpC,MAAM,+BAA+B,GAAG,GAAG,CAAA;AAE3C;;;;;;;;;;;GAWG;AACH,MAAsB,KAAK;IAId;IACA;IACA;IAHX,YACW,IAAY,EACZ,IAA4B,EAC5B,KAAc;QAFd,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAwB;QAC5B,UAAK,GAAL,KAAK,CAAS;IACtB,CAAC;IAEJ;;OAEG;IACH,QAAQ;QACN,OAAO,GAAG,IAAI,CAAC,OAAO,GAAG,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAA;IACrD,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;SACtB,CAAA;IACH,CAAC;CACF;AA5BD,sBA4BC;AAED;;;;GAIG;AACH,MAAa,WAAY,SAAQ,KAAK;IAEzB;IACA;IACA;IAHX,YACW,IAA4B,EAC5B,KAAc,EACd,OAAe;QAExB,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;QAJnB,SAAI,GAAJ,IAAI,CAAwB;QAC5B,UAAK,GAAL,KAAK,CAAS;QACd,YAAO,GAAP,OAAO,CAAQ;IAG1B,CAAC;CACF;AARD,kCAQC;AAED;;;;GAIG;AACH,MAAa,kBAAmB,SAAQ,KAAK;IAIhC;IACA;IAJX,YACE,IAA4B,EAC5B,KAAc,EACL,MAAc,EACd,MAAe;QAExB,KAAK,CAAC,gBAAg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ACrB,GAAiB,EACjB,EAAuB,EACvB,CAAC,GAAG,CAAC;IAEL,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AAC7E,CAAC","sourcesContent":["import { ifCid, isLegacyBlobRef, isPlainObject } from '@atproto/lex-data'\n\nconst STRING_PREVIEW_MAX_LENGTH = 48\nconst STRING_PREVIEW_TRUNCATED_SUFFIX = '…'\n\n/**\n * Abstract base class for all validation issues.\n *\n * An issue represents a single validation failure, containing:\n * - A code identifying the type of issue\n * - The path to the invalid value in the data structure\n * - The actual input value that failed validation\n *\n * Subclasses add specific properties relevant to each issue type and implement\n * the {@link message} property for human-readable error messages (that don't\n * contain the error path)\n */\nexport abstract class Issue {\n abstract readonly message: string\n\n constructor(\n readonly code: string,\n readonly path: readonly PropertyKey[],\n readonly input: unknown,\n ) {}\n\n /**\n * Returns a human-readable description of the validation issue.\n */\n toString() {\n return `${this.message}${stringifyPath(this.path)}`\n }\n\n /**\n * Converts the issue to a JSON-serializable object.\n *\n * @returns An object containing the issue code, path, and message\n */\n toJSON() {\n return {\n code: this.code,\n path: this.path,\n message: this.message,\n }\n }\n}\n\n/**\n * A custom validation issue with a user-defined message.\n *\n * Use this for validation rules that don't fit into the standard issue categories.\n */\nexport class IssueCustom extends Issue {\n constructor(\n readonly path: readonly PropertyKey[],\n readonly input: unknown,\n readonly message: string,\n ) {\n super('custom', path, input)\n }\n}\n\n/**\n * Issue for string values that don't match an expected format.\n *\n * Used for AT Protocol specific formats like DID, handle, NSID, AT-URI, etc.\n */\nexport class IssueInvalidFormat extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly format: string,\n readonly detail?: string,\n ) {\n super('invalid_format', path, input)\n }\n\n override get message(): string {\n return `Invalid ${this.formatDescription}${this.detail ? ` (${this.detail}, ` : ' ('}got ${stringifyValue(this.input)})`\n }\n\n /** Returns a human-readable description of the expected format. */\n get formatDescription(): string {\n switch (this.format) {\n case 'at-identifier':\n return `AT identifier`\n case 'did':\n return `DID`\n case 'nsid':\n return `NSID`\n case 'cid':\n return `CID string`\n case 'tid':\n return `TID string`\n case 'record-key':\n return `record key`\n default:\n return this.format\n }\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n format: this.format,\n }\n }\n}\n\n/**\n * Issue for values that have an unexpected type.\n *\n * This is one of the most common validation issues, occurring when the\n * runtime type of a value doesn't match the expected schema type.\n */\nexport class IssueInvalidType extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly expected: readonly string[],\n ) {\n super('invalid_type', path, input)\n }\n\n override get message(): string {\n return `Expected ${oneOf(this.expected.map(stringifyExpectedType))} value type (got ${stringifyValue(this.input)})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n expected: this.expected,\n }\n }\n}\n\n/**\n * Issue for values that don't match any of the expected literal values.\n *\n * Used when a value must be one of a specific set of allowed values\n * (e.g., enum-like constraints).\n */\nexport class IssueInvalidValue extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly values: readonly unknown[],\n ) {\n super('invalid_value', path, input)\n }\n\n override get message(): string {\n return `Expected ${oneOf(this.values.map(stringifyValue))} (got ${stringifyValue(this.input)})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n values: this.values,\n }\n }\n}\n\n/**\n * Issue for missing required object properties.\n */\nexport class IssueRequiredKey extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly key: PropertyKey,\n ) {\n super('required_key', path, input)\n }\n\n override get message(): string {\n return `Missing required key \"${String(this.key)}\"`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n key: this.key,\n }\n }\n}\n\n/**\n * The type of measurement for size constraint issues.\n *\n * - `'array'` - Array length\n * - `'string'` - String length in characters\n * - `'integer'` - Numeric value\n * - `'grapheme'` - String length in grapheme clusters\n * - `'bytes'` - Byte length\n * - `'blob'` - Blob size\n */\nexport type MeasurableType =\n | 'array'\n | 'string'\n | 'integer'\n | 'grapheme'\n | 'bytes'\n | 'blob'\n\n/**\n * Issue for values that exceed a maximum constraint.\n */\nexport class IssueTooBig extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly maximum: number,\n readonly type: MeasurableType,\n readonly actual: number,\n ) {\n super('too_big', path, input)\n }\n\n override get message(): string {\n return `${this.type} too big (maximum ${this.maximum}, got ${this.actual})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n maximum: this.maximum,\n }\n }\n}\n\n/**\n * Issue for values that are below a minimum constraint.\n */\nexport class IssueTooSmall extends Issue {\n constructor(\n path: readonly PropertyKey[],\n input: unknown,\n readonly minimum: number,\n readonly type: MeasurableType,\n readonly actual: number,\n ) {\n super('too_small', path, input)\n }\n\n override get message(): string {\n return `${this.type} too small (minimum ${this.minimum}, got ${this.actual})`\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n minimum: this.minimum,\n }\n }\n}\n\n// -----------------------------------------------------------------------------\n// Helper functions for formatting error messages\n// -----------------------------------------------------------------------------\n\nfunction stringifyExpectedType(expected: string): string {\n if (expected === '$typed') {\n return 'an object which includes the \"$type\" property'\n }\n return expected\n}\n\nfunction stringifyPath(path: readonly PropertyKey[]) {\n return ` at ${buildJsonPath(path)}`\n}\n\nfunction buildJsonPath(path: readonly PropertyKey[]): string {\n return `$${path.map(toJsonPathSegment).join('')}`\n}\n\nfunction toJsonPathSegment(segment: PropertyKey): string {\n if (typeof segment === 'number' || typeof segment === 'symbol') {\n return `[${String(segment)}]`\n } else if (/^[a-zA-Z_$][a-zA-Z0-9_]*$/.test(segment)) {\n return `.${segment}`\n } else {\n return `[${JSON.stringify(segment)}]`\n }\n}\n\nfunction oneOf(arr: readonly string[]): string {\n if (arr.length === 0) return ''\n if (arr.length === 1) return arr[0]\n return `one of ${arr.slice(0, -1).join(', ')} or ${arr.at(-1)}`\n}\n\nfunction stringifyValue(value: unknown): string {\n switch (typeof value) {\n case 'bigint':\n return `${value}n`\n case 'number':\n case 'boolean':\n return String(value)\n case 'string':\n return JSON.stringify(\n value.length < STRING_PREVIEW_MAX_LENGTH\n ? value\n : `${value.slice(0, STRING_PREVIEW_MAX_LENGTH - STRING_PREVIEW_TRUNCATED_SUFFIX.length)}${STRING_PREVIEW_TRUNCATED_SUFFIX}`,\n )\n case 'object':\n if (value === null) return 'null'\n if (Array.isArray(value)) {\n return `[${stringifyArray(value, stringifyValue)}]`\n }\n if (isPlainObject(value)) {\n return `{${stringifyArray(Object.entries(value), stringifyObjectEntry)}}`\n }\n if (ifCid(value)) return 'cid'\n if (isLegacyBlobRef(value)) return 'legacy-blob'\n if (value instanceof Date) return 'date'\n if (value instanceof RegExp) return 'regexp'\n if (value instanceof Map) return 'map'\n if (value instanceof Set) return 'set'\n return 'object'\n default:\n return typeof value\n }\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringifyObjectEntry([key, _value]: [PropertyKey, unknown]): string {\n return `${JSON.stringify(key)}: ...`\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringifyArray<T>(\n arr: readonly T[],\n fn: (item: T) => string,\n n = 2,\n): string {\n return arr.slice(0, n).map(fn).join(', ') + (arr.length > n ? ', ...' : '')\n}\n"]}
|
package/dist/helpers.d.ts
CHANGED
|
@@ -24,10 +24,11 @@ export type InferMethodMessage<M extends Procedure | Query | Subscription = Proc
|
|
|
24
24
|
export type InferMethodError<M extends Procedure | Query | Subscription = Procedure | Query | Subscription> = M extends {
|
|
25
25
|
errors: readonly (infer E extends string)[];
|
|
26
26
|
} ? E : never;
|
|
27
|
+
/**
|
|
28
|
+
* @see {@link https://atproto.com/specs/xrpc#error-responses}
|
|
29
|
+
*/
|
|
27
30
|
export declare const lexErrorDataSchema: import("./schema.js").ObjectSchema<{
|
|
28
|
-
readonly error: import("./schema.js").
|
|
29
|
-
readonly minLength: 1;
|
|
30
|
-
}>;
|
|
31
|
+
readonly error: import("./schema.js").RegexpSchema<string>;
|
|
31
32
|
readonly message: import("./schema.js").OptionalSchema<import("./schema.js").StringSchema<{}>>;
|
|
32
33
|
}>;
|
|
33
34
|
//# sourceMappingURL=helpers.d.ts.map
|
package/dist/helpers.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAU,MAAM,WAAW,CAAA;AAC3D,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,oBAAoB,EACpB,SAAS,EACT,KAAK,EACL,YAAY,
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAU,MAAM,WAAW,CAAA;AAC3D,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,oBAAoB,EACpB,SAAS,EACT,KAAK,EACL,YAAY,EAKb,MAAM,aAAa,CAAA;AAEpB,MAAM,MAAM,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG;IAAE,IAAI,EAAE,CAAC,CAAA;CAAE,CAAA;AAErC,wBAAgB,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAExD;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,UAAU,GAAG,UAAU,CAAC,aAAa,CAAC,CAAA;AAElD,MAAM,MAAM,iBAAiB,CAC3B,CAAC,SAAS,SAAS,GAAG,KAAK,GAAG,YAAY,GAAG,SAAS,GAAG,KAAK,GAAG,YAAY,IAE7E,CAAC,SAAS,SAAS,CAAC,GAAG,EAAE,MAAM,OAAO,EAAE,GAAG,EAAE,GAAG,EAA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AAG,KAAK,GAAG,YAAY,IAE7E,CAAC,SAAS,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,QAAQ,EAAE,GAAG,CAAC,GACjD,WAAW,CAAC,QAAQ,CAAC,GACrB,SAAS,CAAA;AAEf,MAAM,MAAM,gBAAgB,CAE1B,CAAC,SAAS,SAAS,GAAG,KAAK,GAAG,YAAY,GAAG,SAAS,GAAG,KAAK,GAAG,YAAY,IAC3E,CAAC,SAAS;IAAE,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,SAAS,MAAM,CAAC,EAAE,CAAA;CAAE,GAAG,CAAC,GAAG,KAAK,CAAA;AAEzE;;GAEG;AACH,eAAO,MAAM,kBAAkB;;;EAKE,CAAA"}
|
package/dist/helpers.js
CHANGED
|
@@ -6,8 +6,13 @@ const schema_js_1 = require("./schema.js");
|
|
|
6
6
|
function getMain(ns) {
|
|
7
7
|
return 'main' in ns ? ns.main : ns;
|
|
8
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* @see {@link https://atproto.com/specs/xrpc#error-responses}
|
|
11
|
+
*/
|
|
9
12
|
exports.lexErrorDataSchema = (0, schema_js_1.object)({
|
|
10
|
-
error
|
|
13
|
+
// type name of the error (generic ASCII constant, no whitespace)
|
|
14
|
+
error: (0, schema_js_1.regexp)(/^[\w_-]+$/, 'Expected ASCII constant with no whitespace'),
|
|
15
|
+
// description of the error, appropriate for display to humans
|
|
11
16
|
message: (0, schema_js_1.optional)((0, schema_js_1.string)()),
|
|
12
17
|
});
|
|
13
18
|
//# sourceMappingURL=helpers.js.map
|
package/dist/helpers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";;;AAiBA,0BAEC;AAjBD,2CAWoB;AAIpB,SAAgB,OAAO,CAAmB,EAAW;IACnD,OAAO,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAA;AACpC,CAAC;AAuFD;;GAEG;AACU,QAAA,kBAAkB,GAAG,IAAA,kBAAM,EAAC;IACvC,iEAAiE;IACjE,KAAK,EAAE,IAAA,kBAAM,EAAC,WAAW,EAAE,4CAA4C,CAAC;IACxE,8DAA8D;IAC9D,OAAO,EAAE,IAAA,oBAAQ,EAAC,IAAA,kBAAM,GAAE,CAAC;CAC5B,CAAgC,CAAA","sourcesContent":["import { LexErrorData } from '@atproto/lex-data'\nimport { InferOutput, Restricted, Schema } from './core.js'\nimport {\n InferPayload,\n InferPayloadBody,\n InferPayloadEncoding,\n Procedure,\n Query,\n Subscription,\n object,\n optional,\n regexp,\n string,\n} from './schema.js'\n\nexport type Main<T> = T | { main: T }\n\nexport function getMain<T extends object>(ns: Main<T>): T {\n return 'main' in ns ? ns.main : ns\n}\n\n/**\n * Every XRPC implementation should translate `application/json` and `text/*`\n * payloads into their native equivalent ({@link LexValue} or string). Binary\n * data payloads, however, can be represented differently depending on the\n * environment and use case (e.g. `Uint8Array`, `Blob`, `Buffer`,\n * `ReadableStream`, etc.). This type is a placeholder to represent binary data\n * when not explicitly provided.\n */\nexport type BinaryData = Restricted<'Binary data'>\n\nexport type InferMethodParams<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Procedure<any, infer TParams, any, any, any>\n ? InferOutput<TParams>\n : M extends Query<any, infer TParams, any, any>\n ? InferOutput<TParams>\n : M extends Subscription<any, infer TParams, any, any>\n ? InferOutput<TParams>\n : never\n\nexport type InferMethodInput<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, infer TInput, any, any>\n ? InferPayload<TInput, B>\n : undefined\n\nexport type InferMethodInputBody<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, infer TInput, any, any>\n ? InferPayloadBody<TInput, B>\n : undefined\n\nexport type InferMethodInputEncoding<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Procedure<any, any, infer TInput, any, any>\n ? InferPayloadEncoding<TInput>\n : undefined\n\nexport type InferMethodOutput<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, any, infer TOutput, any>\n ? InferPayload<TOutput, B>\n : M extends Query<any, any, infer TOutput, any>\n ? InferPayload<TOutput, B>\n : undefined\n\nexport type InferMethodOutputBody<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, any, infer TOutput, any>\n ? InferPayloadBody<TOutput, B>\n : M extends Query<any, any, infer TOutput, any>\n ? InferPayloadBody<TOutput, B>\n : undefined\n\nexport type InferMethodOutputEncoding<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Procedure<any, any, any, infer TOutput, any>\n ? InferPayloadEncoding<TOutput>\n : M extends Query<any, any, infer TOutput, any>\n ? InferPayloadEncoding<TOutput>\n : undefined\n\nexport type InferMethodMessage<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Subscription<any, any, infer TMessage, any>\n ? InferOutput<TMessage>\n : undefined\n\nexport type InferMethodError<\n //\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> = M extends { errors: readonly (infer E extends string)[] } ? E : never\n\n/**\n * @see {@link https://atproto.com/specs/xrpc#error-responses}\n */\nexport const lexErrorDataSchema = object({\n // type name of the error (generic ASCII constant, no whitespace)\n error: regexp(/^[\\w_-]+$/, 'Expected ASCII constant with no whitespace'),\n // description of the error, appropriate for display to humans\n message: optional(string()),\n}) satisfies Schema<LexErrorData>\n"]}
|