@atproto/lex-schema 0.0.13 → 0.0.14
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/schema.d.ts +23 -32
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +67 -53
- package/dist/core/schema.js.map +1 -1
- package/dist/core/string-format.d.ts +1 -14
- package/dist/core/string-format.d.ts.map +1 -1
- package/dist/core/string-format.js +12 -9
- package/dist/core/string-format.js.map +1 -1
- package/dist/core/validation-error.d.ts +5 -5
- package/dist/core/validation-error.d.ts.map +1 -1
- package/dist/core/validation-error.js +8 -8
- package/dist/core/validation-error.js.map +1 -1
- package/dist/core/validator.d.ts +6 -6
- package/dist/core/validator.d.ts.map +1 -1
- package/dist/core/validator.js +3 -3
- package/dist/core/validator.js.map +1 -1
- package/dist/schema/params.d.ts.map +1 -1
- package/dist/schema/params.js +4 -1
- package/dist/schema/params.js.map +1 -1
- package/dist/schema/record.d.ts +12 -6
- package/dist/schema/record.d.ts.map +1 -1
- package/dist/schema/record.js +21 -12
- package/dist/schema/record.js.map +1 -1
- package/dist/schema/typed-object.d.ts +12 -4
- package/dist/schema/typed-object.d.ts.map +1 -1
- package/dist/schema/typed-object.js +21 -12
- package/dist/schema/typed-object.js.map +1 -1
- package/dist/schema/union.d.ts.map +1 -1
- package/dist/schema/union.js +1 -1
- package/dist/schema/union.js.map +1 -1
- package/package.json +3 -3
- package/src/core/schema.ts +67 -59
- package/src/core/string-format.ts +14 -17
- package/src/core/validation-error.ts +10 -10
- package/src/core/validator.ts +9 -9
- package/src/schema/params.test.ts +16 -0
- package/src/schema/params.ts +5 -2
- package/src/schema/record.ts +27 -22
- package/src/schema/typed-object.test.ts +38 -0
- package/src/schema/typed-object.ts +29 -24
- package/src/schema/union.ts +2 -2
|
@@ -13,7 +13,7 @@ import { Issue } from './validation-issue.js';
|
|
|
13
13
|
*
|
|
14
14
|
* @example
|
|
15
15
|
* ```typescript
|
|
16
|
-
* const error = new
|
|
16
|
+
* const error = new LexValidationError([
|
|
17
17
|
* new IssueInvalidType(['user', 'age'], 'hello', ['number'])
|
|
18
18
|
* ])
|
|
19
19
|
* console.log(error.message)
|
|
@@ -24,7 +24,7 @@ import { Issue } from './validation-issue.js';
|
|
|
24
24
|
* // { error: 'InvalidRequest', message: '...', issues: [...] }
|
|
25
25
|
* ```
|
|
26
26
|
*/
|
|
27
|
-
export declare class
|
|
27
|
+
export declare class LexValidationError extends LexError<'InvalidRequest'> {
|
|
28
28
|
name: string;
|
|
29
29
|
/**
|
|
30
30
|
* The list of validation issues that caused this error.
|
|
@@ -46,7 +46,7 @@ export declare class ValidationError extends LexError {
|
|
|
46
46
|
/**
|
|
47
47
|
* Converts the error to a JSON-serializable object.
|
|
48
48
|
*
|
|
49
|
-
* @returns An object containing the error details and
|
|
49
|
+
* @returns An object containing the error details and issues details
|
|
50
50
|
*/
|
|
51
51
|
toJSON(): {
|
|
52
52
|
issues: {
|
|
@@ -70,10 +70,10 @@ export declare class ValidationError extends LexError {
|
|
|
70
70
|
* ```typescript
|
|
71
71
|
* const failures = schemas.map(s => s.safeValidate(data)).filter(r => !r.success)
|
|
72
72
|
* if (failures.length === schemas.length) {
|
|
73
|
-
* throw
|
|
73
|
+
* throw LexValidationError.fromFailures(failures)
|
|
74
74
|
* }
|
|
75
75
|
* ```
|
|
76
76
|
*/
|
|
77
|
-
static fromFailures(failures: ResultFailure<
|
|
77
|
+
static fromFailures(failures: readonly ResultFailure<LexValidationError>[]): LexValidationError;
|
|
78
78
|
}
|
|
79
79
|
//# sourceMappingURL=validation-error.d.ts.map
|
|
@@ -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;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,
|
|
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;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,kBAAmB,SAAQ,QAAQ,CAAC,gBAAgB,CAAC;IAChE,IAAI,SAAuB;IAE3B;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,CAAA;IAExB;;;;;;;;OAQG;gBACS,MAAM,EAAE,KAAK,EAAE,EAAE,OAAO,CAAC,EAAE,YAAY;IAMnD;;;;OAIG;IACM,MAAM;;;;;;;;;IAOf;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,YAAY,CACjB,QAAQ,EAAE,SAAS,aAAa,CAAC,kBAAkB,CAAC,EAAE,GACrD,kBAAkB;CAQtB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.LexValidationError = void 0;
|
|
4
4
|
const lex_data_1 = require("@atproto/lex-data");
|
|
5
5
|
const array_agg_js_1 = require("../util/array-agg.js");
|
|
6
6
|
const result_js_1 = require("./result.js");
|
|
@@ -17,7 +17,7 @@ const validation_issue_js_1 = require("./validation-issue.js");
|
|
|
17
17
|
*
|
|
18
18
|
* @example
|
|
19
19
|
* ```typescript
|
|
20
|
-
* const error = new
|
|
20
|
+
* const error = new LexValidationError([
|
|
21
21
|
* new IssueInvalidType(['user', 'age'], 'hello', ['number'])
|
|
22
22
|
* ])
|
|
23
23
|
* console.log(error.message)
|
|
@@ -28,8 +28,8 @@ const validation_issue_js_1 = require("./validation-issue.js");
|
|
|
28
28
|
* // { error: 'InvalidRequest', message: '...', issues: [...] }
|
|
29
29
|
* ```
|
|
30
30
|
*/
|
|
31
|
-
class
|
|
32
|
-
name = '
|
|
31
|
+
class LexValidationError extends lex_data_1.LexError {
|
|
32
|
+
name = 'LexValidationError';
|
|
33
33
|
/**
|
|
34
34
|
* The list of validation issues that caused this error.
|
|
35
35
|
*
|
|
@@ -54,7 +54,7 @@ class ValidationError extends lex_data_1.LexError {
|
|
|
54
54
|
/**
|
|
55
55
|
* Converts the error to a JSON-serializable object.
|
|
56
56
|
*
|
|
57
|
-
* @returns An object containing the error details and
|
|
57
|
+
* @returns An object containing the error details and issues details
|
|
58
58
|
*/
|
|
59
59
|
toJSON() {
|
|
60
60
|
return {
|
|
@@ -75,7 +75,7 @@ class ValidationError extends lex_data_1.LexError {
|
|
|
75
75
|
* ```typescript
|
|
76
76
|
* const failures = schemas.map(s => s.safeValidate(data)).filter(r => !r.success)
|
|
77
77
|
* if (failures.length === schemas.length) {
|
|
78
|
-
* throw
|
|
78
|
+
* throw LexValidationError.fromFailures(failures)
|
|
79
79
|
* }
|
|
80
80
|
* ```
|
|
81
81
|
*/
|
|
@@ -83,13 +83,13 @@ class ValidationError extends lex_data_1.LexError {
|
|
|
83
83
|
if (failures.length === 1)
|
|
84
84
|
return (0, result_js_1.failureReason)(failures[0]);
|
|
85
85
|
const issues = failures.flatMap(extractFailureIssues);
|
|
86
|
-
return new
|
|
86
|
+
return new LexValidationError(issues, {
|
|
87
87
|
// Keep the original errors as the cause chain
|
|
88
88
|
cause: failures.map(result_js_1.failureReason),
|
|
89
89
|
});
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
|
-
exports.
|
|
92
|
+
exports.LexValidationError = LexValidationError;
|
|
93
93
|
function extractFailureIssues(result) {
|
|
94
94
|
return result.reason.issues;
|
|
95
95
|
}
|
|
@@ -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;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAa,
|
|
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;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAa,kBAAmB,SAAQ,mBAA0B;IAChE,IAAI,GAAG,oBAAoB,CAAA;IAE3B;;;;;OAKG;IACM,MAAM,CAAS;IAExB;;;;;;;;OAQG;IACH,YAAY,MAAe,EAAE,OAAsB;QACjD,MAAM,SAAS,GAAG,eAAe,CAAC,MAAM,CAAC,CAAA;QACzC,KAAK,CAAC,gBAAgB,EAAE,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAA;QACtD,IAAI,CAAC,MAAM,GAAG,SAAS,CAAA;IACzB,CAAC;IAED;;;;OAIG;IACM,MAAM;QACb,OAAO;YACL,GAAG,KAAK,CAAC,MAAM,EAAE;YACjB,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;SACnD,CAAA;IACH,CAAC;IAED;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,YAAY,CACjB,QAAsD;QAEtD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAA,yBAAa,EAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAA;QAC5D,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAA;QACrD,OAAO,IAAI,kBAAkB,C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IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,EAC9C,CAAC,MAAM,EAAE,EAAE,CACT,IAAI,uCAAiB,CACnB,MAAM,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 number value type at $.user.age (got string)\"\n *\n * console.log(error.issues.length) // 1\n * console.log(error.toJSON())\n * // { error: 'InvalidRequest', message: '...', issues: [...] }\n * ```\n */\nexport class LexValidationError extends LexError<'InvalidRequest'> {\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: 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 /**\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"]}
|
package/dist/core/validator.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { PropertyKey } from './property-key.js';
|
|
2
2
|
import { ResultFailure, ResultSuccess } from './result.js';
|
|
3
|
-
import {
|
|
3
|
+
import { LexValidationError } from './validation-error.js';
|
|
4
4
|
import { Issue, MeasurableType } from './validation-issue.js';
|
|
5
5
|
/**
|
|
6
6
|
* Represents a successful validation result.
|
|
@@ -9,15 +9,15 @@ import { Issue, MeasurableType } from './validation-issue.js';
|
|
|
9
9
|
*/
|
|
10
10
|
export type ValidationSuccess<Value = unknown> = ResultSuccess<Value>;
|
|
11
11
|
/**
|
|
12
|
-
* Represents a failed validation result containing a {@link
|
|
12
|
+
* Represents a failed validation result containing a {@link LexValidationError}.
|
|
13
13
|
*/
|
|
14
|
-
export type ValidationFailure = ResultFailure<
|
|
14
|
+
export type ValidationFailure = ResultFailure<LexValidationError>;
|
|
15
15
|
/**
|
|
16
16
|
* Discriminated union representing the outcome of a validation operation.
|
|
17
17
|
*
|
|
18
18
|
* Check the `success` property to determine if validation passed or failed:
|
|
19
19
|
* - If `success` is `true`, the `value` property contains the validated data
|
|
20
|
-
* - If `success` is `false`, the `reason` property contains the {@link
|
|
20
|
+
* - If `success` is `false`, the `reason` property contains the {@link LexValidationError}
|
|
21
21
|
*
|
|
22
22
|
* @typeParam Value - The type of the validated value on success
|
|
23
23
|
*
|
|
@@ -27,7 +27,7 @@ export type ValidationFailure = ResultFailure<ValidationError>;
|
|
|
27
27
|
* if (result.success) {
|
|
28
28
|
* // result.value is string
|
|
29
29
|
* } else {
|
|
30
|
-
* // result.reason is
|
|
30
|
+
* // result.reason is LexValidationError
|
|
31
31
|
* }
|
|
32
32
|
* ```
|
|
33
33
|
*/
|
|
@@ -305,7 +305,7 @@ export declare class ValidationContext {
|
|
|
305
305
|
* @param reason - The validation error
|
|
306
306
|
* @returns A failed validation result
|
|
307
307
|
*/
|
|
308
|
-
failure(reason:
|
|
308
|
+
failure(reason: LexValidationError): ValidationFailure;
|
|
309
309
|
/**
|
|
310
310
|
* Creates a failed validation result from a single issue.
|
|
311
311
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.d.ts","sourceRoot":"","sources":["../../src/core/validator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAC/C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAoB,MAAM,aAAa,CAAA;AAC5E,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"validator.d.ts","sourceRoot":"","sources":["../../src/core/validator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAC/C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAoB,MAAM,aAAa,CAAA;AAC5E,OA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;;OAQG;IACH,WAAW,CACT,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,cAAc,EACpB,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM;IAKhB;;;;;;;;OAQG;IACH,aAAa,CACX,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,cAAc,EACpB,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM;IAKhB;;;;;;;;;;;OAWG;IACH,yBAAyB,CAAC,CAAC,EACzB,KAAK,EAAE,CAAC,EACR,QAAQ,EAAE,MAAM,CAAC,GAAG,WAAW,EAC/B,MAAM,EAAE,SAAS,OAAO,EAAE;IAO5B;;;;;;;;;;;OAWG;IACH,wBAAwB,CAAC,CAAC,EACxB,KAAK,EAAE,CAAC,EACR,QAAQ,EAAE,MAAM,CAAC,GAAG,WAAW,EAC/B,QAAQ,EAAE,MAAM;CAMnB;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,SAAS,IAAI,CAAC,SAAS;IAC3D,MAAM,IAAI,MAAM,CAAC,SAAS,SAAS,CAAA;CACpC,GACG,eAAe,CAAC,CAAC,CAAC,GAClB,CAAC,CAAA;AAEL;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,WAAW,gBAAgB,CAAC,GAAG,CAAC,SAAS;IAC7C;;;;OAIG;IACH,MAAM,IAAI,SAAS,CAAA;CACpB"}
|
package/dist/core/validator.js
CHANGED
|
@@ -98,7 +98,7 @@ class ValidationContext {
|
|
|
98
98
|
if (this.issues.length > 0) {
|
|
99
99
|
// Validator returned a success but issues were added via the context.
|
|
100
100
|
// This means the overall validation failed.
|
|
101
|
-
return (0, result_js_1.failure)(new validation_error_js_1.
|
|
101
|
+
return (0, result_js_1.failure)(new validation_error_js_1.LexValidationError(Array.from(this.issues)));
|
|
102
102
|
}
|
|
103
103
|
if (this.options.mode !== 'parse' && !Object.is(result.value, input)) {
|
|
104
104
|
// If the value changed, it means that a default (or some other
|
|
@@ -110,7 +110,7 @@ class ValidationContext {
|
|
|
110
110
|
// instead, even when delegating validation from one validator to
|
|
111
111
|
// another.
|
|
112
112
|
// This if block comes before the next one because 'this.issues' will
|
|
113
|
-
// end-up being appended to the returned
|
|
113
|
+
// end-up being appended to the returned LexValidationError (see the
|
|
114
114
|
// "failure" method below), resulting in a more complete error report.
|
|
115
115
|
return this.issueInvalidValue(input, [result.value]);
|
|
116
116
|
}
|
|
@@ -197,7 +197,7 @@ class ValidationContext {
|
|
|
197
197
|
* @returns A failed validation result
|
|
198
198
|
*/
|
|
199
199
|
issue(issue) {
|
|
200
|
-
return this.failure(new validation_error_js_1.
|
|
200
|
+
return this.failure(new validation_error_js_1.LexValidationError([...this.issues, issue]));
|
|
201
201
|
}
|
|
202
202
|
/**
|
|
203
203
|
* Creates a failure for an invalid value that doesn't match expected values.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/core/validator.ts"],"names":[],"mappings":";;;AACA,2CAA4E;AAC5E,+DAAuD;AACvD,+DAS8B;AAiK9B;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,iBAAiB;IA8EP;IA3BrB,MAAM,CAAC,QAAQ,CACb,KAAc,EACd,SAAY,EACZ,OAA2B;QAE3B,MAAM,OAAO,GAAG,IAAI,iBAAiB,CAAC;YACpC,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,EAAE;YACzB,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,UAAU;SAClC,CAAC,CAAA;QACF,OAAO,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;IAC3C,CAAC;IAED;;OAEG;IACgB,WAAW,CAAe;IAE7C;;OAEG;IACgB,MAAM,GAAY,EAAE,CAAA;IAEvC;;;;OAIG;IACH,YAAqB,OAAoC;QAApC,YAAO,GAAP,OAAO,CAA6B;QACvD,yEAAyE;QACzE,IAAI,CAAC,WAAW,GAAG,KAAK,CA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AAC,QAAQ,CAAC,CAAA;QAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,uCAAiB,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAA;IAC/D,CAAC;IAED;;;;;;;;;;;OAWG;IACH,wBAAwB,CACtB,KAAQ,EACR,QAA+B,EAC/B,QAAgB;QAEhB,MAAM,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAA;QAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,sCAAgB,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;IAClE,CAAC;CACF;AAzXD,8CAyXC","sourcesContent":["import { PropertyKey } from './property-key.js'\nimport { ResultFailure, ResultSuccess, failure, success } from './result.js'\nimport { ValidationError } from './validation-error.js'\nimport {\n Issue,\n IssueInvalidFormat,\n IssueInvalidType,\n IssueInvalidValue,\n IssueRequiredKey,\n IssueTooBig,\n IssueTooSmall,\n MeasurableType,\n} from './validation-issue.js'\n\n/**\n * Represents a successful validation result.\n *\n * @typeParam Value - The type of the validated value\n */\nexport type ValidationSuccess<Value = unknown> = ResultSuccess<Value>\n\n/**\n * Represents a failed validation result containing a {@link ValidationError}.\n */\nexport type ValidationFailure = ResultFailure<ValidationError>\n\n/**\n * Discriminated union representing the outcome of a validation operation.\n *\n * Check the `success` property to determine if validation passed or failed:\n * - If `success` is `true`, the `value` property contains the validated data\n * - If `success` is `false`, the `reason` property contains the {@link ValidationError}\n *\n * @typeParam Value - The type of the validated value on success\n *\n * @example\n * ```typescript\n * const result: ValidationResult<string> = schema.safeParse(data)\n * if (result.success) {\n * // result.value is string\n * } else {\n * // result.reason is ValidationError\n * }\n * ```\n */\nexport type ValidationResult<Value = unknown> =\n | ValidationSuccess<Value>\n | ValidationFailure\n\n/**\n * Extracts the input type that a validator accepts.\n *\n * Use this utility type to infer what type a schema will accept during validation.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const userSchema = new ObjectSchema({ name: stringSchema, age: numberSchema })\n * type UserInput = InferInput<typeof userSchema>\n * // { name: string; age: number }\n * ```\n */\nexport type InferInput<V extends Validator> = V['__lex']['input']\n\n/**\n * Extracts the output type that a validator produces after parsing.\n *\n * The output type may differ from the input type when the schema applies\n * transformations such as default values or type coercion during parsing.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const schema = new StringSchema().default('hello')\n * type Input = InferInput<typeof schema> // string | undefined\n * type Output = InferOutput<typeof schema> // string\n * ```\n */\nexport type InferOutput<V extends Validator> = V['__lex']['output']\n\n/**\n * Alias for {@link InferInput} for convenient type inference.\n *\n * @typeParam V - A validator type\n */\nexport type { InferInput as Infer }\n\nexport interface Validator<TInput = unknown, TOutput = TInput> {\n /**\n * This property is used for type inference purposes and does not actually\n * exist at runtime.\n *\n * @internal\n * @deprecated **INTERNAL API, DO NOT USE**.\n */\n readonly ['__lex']: {\n input: TInput\n output: TOutput\n }\n\n /**\n * @internal **INTERNAL API**: use {@link ValidationContext.validate} instead\n *\n * This method is implemented by subclasses to perform transformation and\n * validation of the input value. Do not call this method directly; as the\n * {@link ValidationContext.options.mode} option will **not** be enforced. See\n * {@link ValidationContext.validate} for details. When delegating validation\n * from one validator sub-class implementation to another schema,\n * {@link ValidationContext.validate} must be used instead of calling\n * {@link Validator.validateInContext}. This will allow to stop the validation\n * process if the value was transformed (by the other schema) but\n * transformations are not allowed.\n *\n * By convention, the {@link ValidationResult} must return the original input\n * value if validation was successful and no transformation was applied (i.e.\n * the input already conformed to the schema). If a default value, or any\n * other transformation was applied, the returned value can be different from\n * the input.\n *\n * This convention allows the {@link Validator.check check} and\n * {@link Validator.assert assert} methods to check whether the input value\n * exactly matches the schema (without defaults or transformations), by\n * checking if the returned value is strictly equal to the input.\n *\n * @see {@link ValidationContext.validate}\n */\n validateInContext(input: unknown, ctx: ValidationContext): ValidationResult\n}\n\n/**\n * Configuration options for validation and parsing operations.\n *\n * @example\n * ```typescript\n * // Validate mode (strict, no transformations)\n * ValidationContext.validate(data, schema, { mode: 'validate' })\n *\n * // Parse mode (allows transformations like defaults)\n * ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // With initial path for nested validation\n * ValidationContext.validate(data, schema, { path: ['user', 'profile'] })\n * ```\n */\nexport type ValidationOptions = {\n /**\n * The validation mode determining how transformations are handled.\n *\n * - `\"validate\"` (default): Strict validation where the result must be\n * strictly equal to the input value. No transformations such as applying\n * default values are allowed.\n * - `\"parse\"`: Allows the schema to transform the input value, such as\n * applying default values or performing type coercion.\n */\n mode?: 'validate' | 'parse'\n\n /**\n * The initial path to the value being validated.\n *\n * This is used to provide context in validation issues when validating\n * nested structures. The path is prepended to all issue paths.\n *\n * @example\n * ```typescript\n * // Issues will be reported at paths like \"user.name\" instead of just \"name\"\n * ValidationContext.validate(data, schema, { path: ['user'] })\n * ```\n */\n path?: readonly PropertyKey[]\n}\n\n/**\n * Manages the state and context for validation operations.\n *\n * The `ValidationContext` class is responsible for:\n * - Tracking the current path in nested structures for error reporting\n * - Collecting validation issues during traversal\n * - Enforcing validation mode (validate vs parse)\n * - Providing factory methods for creating validation results\n *\n * Use the static {@link ValidationContext.validate} method as the primary entry point\n * for validation. This ensures proper mode enforcement and issue aggregation.\n *\n * @example\n * ```typescript\n * // Primary usage via static method\n * const result = ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // Within a custom validator implementation\n * class MyValidator implements Validator {\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 */\nexport class ValidationContext {\n /**\n * Validates input against a validator in parse mode.\n *\n * In parse mode, the schema may transform the input (e.g., apply defaults).\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Validation options with mode set to 'parse'\n * @returns A validation result with the parsed output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options: ValidationOptions & {\n mode: 'parse'\n },\n ): ValidationResult<InferOutput<V>>\n /**\n * Validates input against a validator in validate mode (default).\n *\n * In validate mode, the result must be strictly equal to the input.\n * No transformations are allowed.\n *\n * @typeParam V - The validator type\n * @typeParam I - The input type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options (defaults to validate mode)\n * @returns A validation result preserving the input type intersected with the schema type\n */\n static validate<V extends Validator, I = unknown>(\n input: I,\n validator: V,\n options?: ValidationOptions & {\n mode?: 'validate'\n },\n ): ValidationResult<I & InferInput<V>>\n /**\n * Validates input against a validator with configurable options.\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options\n * @returns A validation result with either the input or output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>>\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>> {\n const context = new ValidationContext({\n path: options?.path ?? [],\n mode: options?.mode ?? 'validate',\n })\n return context.validate(input, validator)\n }\n\n /**\n * The current path being validated, used for error reporting.\n */\n protected readonly currentPath: PropertyKey[]\n\n /**\n * Accumulated validation issues collected during traversal.\n */\n protected readonly issues: Issue[] = []\n\n /**\n * Creates a new validation context with the specified options.\n *\n * @param options - The validation options (path and mode are required)\n */\n constructor(readonly options: Required<ValidationOptions>) {\n // Create a copy because we will be mutating the array during validation.\n this.currentPath = Array.from(options.path)\n }\n\n /**\n * Returns a copy of the current validation path.\n *\n * The path represents the location in the data structure being validated,\n * used for constructing meaningful error messages.\n */\n get path() {\n return Array.from(this.currentPath)\n }\n\n /**\n * Creates a new path by appending segments to the current path.\n *\n * @param path - Optional path segment(s) to append\n * @returns A new path array with the segment(s) appended\n */\n concatPath(path?: PropertyKey | readonly PropertyKey[]) {\n if (path == null) return this.path\n return this.currentPath.concat(path)\n }\n\n /**\n * Validates input against a validator within this context.\n *\n * This is the primary entry point for validation within a context. Always use\n * this method instead of calling {@link Validator.validateInContext} directly,\n * as this method enforces validation mode rules and handles transformation detection.\n *\n * @typeParam V - The validator type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @returns A validation result with the validated value or error\n */\n validate<V extends Validator>(\n input: unknown,\n validator: V,\n ): ValidationResult<InferInput<V>> {\n // This is the only place where validateInContext should be called.\n const result = validator.validateInContext(input, this)\n\n if (result.success) {\n if (this.issues.length > 0) {\n // Validator returned a success but issues were added via the context.\n // This means the overall validation failed.\n return failure(new ValidationError(Array.from(this.issues)))\n }\n\n if (this.options.mode !== 'parse' && !Object.is(result.value, input)) {\n // If the value changed, it means that a default (or some other\n // transformation) was applied, meaning that the original value did\n // *not* match the (output) schema. When not in \"parse\" mode, we\n // consider this a failure.\n\n // This check is the reason why Validator.validateInContext should not\n // be used directly, and ValidatorContext.validate should be used\n // instead, even when delegating validation from one validator to\n // another.\n\n // This if block comes before the next one because 'this.issues' will\n // end-up being appended to the returned ValidationError (see the\n // \"failure\" method below), resulting in a more complete error report.\n return this.issueInvalidValue(input, [result.value])\n }\n }\n\n return result as ValidationResult<InferInput<V>>\n }\n\n /**\n * Validates a child property of an object within this context.\n *\n * This method automatically manages the path stack, pushing the property key\n * before validation and popping it afterward. Use this for validating object\n * properties to ensure proper path tracking in error messages.\n *\n * @typeParam I - The input object type\n * @typeParam K - The property key type\n * @typeParam V - The validator type\n * @param input - The parent object containing the property\n * @param key - The property key to validate\n * @param validator - The validator to use for the property value\n * @returns A validation result for the property value\n *\n * @example\n * ```typescript\n * // In a custom object validator\n * const result = ctx.validateChild(input, 'name', stringSchema)\n * // If validation fails, error path will include 'name'\n * ```\n */\n validateChild<\n I extends object,\n K extends PropertyKey & keyof I,\n V extends Validator,\n >(input: I, key: K, validator: V): ValidationResult<InferInput<V>> {\n // @NOTE we could add support for recursive schemas by keeping track of\n // \"parent\" objects in the context and checking for circular references\n // here. This would allow us to validate recursive structures without\n // hitting maximum call stack errors, and would also allow us to provide\n // better error messages for circular reference issues. However, this is not\n // a priority at the moment as recursive structures are not supported in\n // the context of AT Protocol lexicons, and we can always add this in the\n // future if needed.\n\n // Instead of creating a new context, we just push/pop the path segment.\n this.currentPath.push(key)\n try {\n return this.validate(input[key], validator)\n } finally {\n this.currentPath.length--\n }\n }\n\n /**\n * Adds a validation issue to the context without immediately failing.\n *\n * Use this method to collect multiple issues during validation before\n * determining the final result. Issues added this way will be included\n * in the final error if validation fails.\n *\n * @param issue - The validation issue to add\n */\n addIssue(issue: Issue): void {\n this.issues.push(issue)\n }\n\n /**\n * Creates a successful validation result with the given value.\n *\n * @typeParam V - The value type\n * @param value - The validated value\n * @returns A successful validation result\n */\n success<V>(value: V): ValidationResult<V> {\n return success(value)\n }\n\n /**\n * Creates a failed validation result with the given error.\n *\n * @param reason - The validation error\n * @returns A failed validation result\n */\n failure(reason: ValidationError): ValidationFailure {\n return failure(reason)\n }\n\n /**\n * Creates a failed validation result from a single issue.\n *\n * Any previously accumulated issues in the context are included in the error.\n *\n * @param issue - The validation issue that caused the failure\n * @returns A failed validation result\n */\n issue(issue: Issue) {\n return this.failure(new ValidationError([...this.issues, issue]))\n }\n\n /**\n * Creates a failure for an invalid value that doesn't match expected values.\n *\n * @param input - The actual value that was received\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue\n */\n issueInvalidValue(input: unknown, values: readonly unknown[]) {\n return this.issue(new IssueInvalidValue(this.path, input, values))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - An array of expected type names\n * @returns A failed validation result with an invalid type issue\n */\n issueInvalidType(input: unknown, expected: readonly string[]) {\n return this.issue(new IssueInvalidType(this.path, input, expected))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue\n */\n issueUnexpectedType(input: unknown, expected: string) {\n return this.issueInvalidType(input, [expected])\n }\n\n /**\n * Creates a failure for a missing required key in an object.\n *\n * @param input - The object missing the required key\n * @param key - The name of the required key\n * @returns A failed validation result with a required key issue\n */\n issueRequiredKey(input: object, key: PropertyKey) {\n return this.issue(new IssueRequiredKey(this.path, input, key))\n }\n\n /**\n * Creates a failure for an invalid string format.\n *\n * @param input - The actual value that was received\n * @param format - The expected format name (e.g., 'did', 'handle', 'uri')\n * @param msg - Optional additional message describing the format error\n * @returns A failed validation result with an invalid format issue\n */\n issueInvalidFormat(input: unknown, format: string, msg?: string) {\n return this.issue(new IssueInvalidFormat(this.path, input, format, msg))\n }\n\n /**\n * Creates a failure for a value that exceeds a maximum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param max - The maximum allowed value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too big issue\n */\n issueTooBig(\n input: unknown,\n type: MeasurableType,\n max: number,\n actual: number,\n ) {\n return this.issue(new IssueTooBig(this.path, input, max, type, actual))\n }\n\n /**\n * Creates a failure for a value that is below a minimum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param min - The minimum required value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too small issue\n */\n issueTooSmall(\n input: unknown,\n type: MeasurableType,\n min: number,\n actual: number,\n ) {\n return this.issue(new IssueTooSmall(this.path, input, min, type, actual))\n }\n\n /**\n * Creates a failure for an invalid property value within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid value\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue at the property path\n */\n issueInvalidPropertyValue<I>(\n input: I,\n property: keyof I & PropertyKey,\n values: readonly unknown[],\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidValue(path, value, values))\n }\n\n /**\n * Creates a failure for an invalid property type within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid type\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue at the property path\n */\n issueInvalidPropertyType<I>(\n input: I,\n property: keyof I & PropertyKey,\n expected: string,\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidType(path, value, [expected]))\n }\n}\n\n/**\n * Recursively unwraps a wrapped validator to its innermost validator type.\n *\n * Some validators wrap other validators (e.g., optional, nullable). This type\n * utility recursively unwraps such wrappers to reveal the core validator.\n *\n * @typeParam T - A validator type, possibly wrapped\n *\n * @example\n * ```typescript\n * type Inner = UnwrapValidator<OptionalValidator<NullableValidator<StringSchema>>>\n * // Result: StringSchema\n * ```\n */\nexport type UnwrapValidator<T extends Validator> = T extends {\n unwrap(): infer U extends Validator\n}\n ? UnwrapValidator<U>\n : T\n\n/**\n * Interface for validators that wrap another validator.\n *\n * Implement this interface when creating validators that wrap or modify\n * the behavior of another validator (e.g., optional, nullable, transform).\n *\n * @typeParam Validator - The type of the wrapped validator\n *\n * @example\n * ```typescript\n * class OptionalSchema<V extends Validator> implements WrappedValidator<V> {\n * constructor(private inner: V) {}\n *\n * unwrap(): V {\n * return this.inner\n * }\n * }\n * ```\n */\nexport interface WrappedValidator<out Validator> {\n /**\n * Returns the inner wrapped validator.\n *\n * @returns The wrapped validator\n */\n unwrap(): Validator\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/core/validator.ts"],"names":[],"mappings":";;;AACA,2CAA4E;AAC5E,+DAA0D;AAC1D,+DAS8B;AAiK9B;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,iBAAiB;IA8EP;IA3BrB,MAAM,CAAC,QAAQ,CACb,KAAc,EACd,SAAY,EAC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CAAW,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAA;IACzE,CAAC;IAED;;;;;;;;OAQG;IACH,aAAa,CACX,KAAc,EACd,IAAoB,EACpB,GAAW,EACX,MAAc;QAEd,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,mCAAa,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAA;IAC3E,CAAC;IAED;;;;;;;;;;;OAWG;IACH,yBAAyB,CACvB,KAAQ,EACR,QAA+B,EAC/B,MAA0B;QAE1B,MAAM,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAA;QAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,uCAAiB,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAA;IAC/D,CAAC;IAED;;;;;;;;;;;OAWG;IACH,wBAAwB,CACtB,KAAQ,EACR,QAA+B,EAC/B,QAAgB;QAEhB,MAAM,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAA;QAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,sCAAgB,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;IAClE,CAAC;CACF;AAzXD,8CAyXC","sourcesContent":["import { PropertyKey } from './property-key.js'\nimport { ResultFailure, ResultSuccess, failure, success } from './result.js'\nimport { LexValidationError } from './validation-error.js'\nimport {\n Issue,\n IssueInvalidFormat,\n IssueInvalidType,\n IssueInvalidValue,\n IssueRequiredKey,\n IssueTooBig,\n IssueTooSmall,\n MeasurableType,\n} from './validation-issue.js'\n\n/**\n * Represents a successful validation result.\n *\n * @typeParam Value - The type of the validated value\n */\nexport type ValidationSuccess<Value = unknown> = ResultSuccess<Value>\n\n/**\n * Represents a failed validation result containing a {@link LexValidationError}.\n */\nexport type ValidationFailure = ResultFailure<LexValidationError>\n\n/**\n * Discriminated union representing the outcome of a validation operation.\n *\n * Check the `success` property to determine if validation passed or failed:\n * - If `success` is `true`, the `value` property contains the validated data\n * - If `success` is `false`, the `reason` property contains the {@link LexValidationError}\n *\n * @typeParam Value - The type of the validated value on success\n *\n * @example\n * ```typescript\n * const result: ValidationResult<string> = schema.safeParse(data)\n * if (result.success) {\n * // result.value is string\n * } else {\n * // result.reason is LexValidationError\n * }\n * ```\n */\nexport type ValidationResult<Value = unknown> =\n | ValidationSuccess<Value>\n | ValidationFailure\n\n/**\n * Extracts the input type that a validator accepts.\n *\n * Use this utility type to infer what type a schema will accept during validation.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const userSchema = new ObjectSchema({ name: stringSchema, age: numberSchema })\n * type UserInput = InferInput<typeof userSchema>\n * // { name: string; age: number }\n * ```\n */\nexport type InferInput<V extends Validator> = V['__lex']['input']\n\n/**\n * Extracts the output type that a validator produces after parsing.\n *\n * The output type may differ from the input type when the schema applies\n * transformations such as default values or type coercion during parsing.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const schema = new StringSchema().default('hello')\n * type Input = InferInput<typeof schema> // string | undefined\n * type Output = InferOutput<typeof schema> // string\n * ```\n */\nexport type InferOutput<V extends Validator> = V['__lex']['output']\n\n/**\n * Alias for {@link InferInput} for convenient type inference.\n *\n * @typeParam V - A validator type\n */\nexport type { InferInput as Infer }\n\nexport interface Validator<TInput = unknown, TOutput = TInput> {\n /**\n * This property is used for type inference purposes and does not actually\n * exist at runtime.\n *\n * @internal\n * @deprecated **INTERNAL API, DO NOT USE**.\n */\n readonly ['__lex']: {\n input: TInput\n output: TOutput\n }\n\n /**\n * @internal **INTERNAL API**: use {@link ValidationContext.validate} instead\n *\n * This method is implemented by subclasses to perform transformation and\n * validation of the input value. Do not call this method directly; as the\n * {@link ValidationContext.options.mode} option will **not** be enforced. See\n * {@link ValidationContext.validate} for details. When delegating validation\n * from one validator sub-class implementation to another schema,\n * {@link ValidationContext.validate} must be used instead of calling\n * {@link Validator.validateInContext}. This will allow to stop the validation\n * process if the value was transformed (by the other schema) but\n * transformations are not allowed.\n *\n * By convention, the {@link ValidationResult} must return the original input\n * value if validation was successful and no transformation was applied (i.e.\n * the input already conformed to the schema). If a default value, or any\n * other transformation was applied, the returned value can be different from\n * the input.\n *\n * This convention allows the {@link Validator.check check} and\n * {@link Validator.assert assert} methods to check whether the input value\n * exactly matches the schema (without defaults or transformations), by\n * checking if the returned value is strictly equal to the input.\n *\n * @see {@link ValidationContext.validate}\n */\n validateInContext(input: unknown, ctx: ValidationContext): ValidationResult\n}\n\n/**\n * Configuration options for validation and parsing operations.\n *\n * @example\n * ```typescript\n * // Validate mode (strict, no transformations)\n * ValidationContext.validate(data, schema, { mode: 'validate' })\n *\n * // Parse mode (allows transformations like defaults)\n * ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // With initial path for nested validation\n * ValidationContext.validate(data, schema, { path: ['user', 'profile'] })\n * ```\n */\nexport type ValidationOptions = {\n /**\n * The validation mode determining how transformations are handled.\n *\n * - `\"validate\"` (default): Strict validation where the result must be\n * strictly equal to the input value. No transformations such as applying\n * default values are allowed.\n * - `\"parse\"`: Allows the schema to transform the input value, such as\n * applying default values or performing type coercion.\n */\n mode?: 'validate' | 'parse'\n\n /**\n * The initial path to the value being validated.\n *\n * This is used to provide context in validation issues when validating\n * nested structures. The path is prepended to all issue paths.\n *\n * @example\n * ```typescript\n * // Issues will be reported at paths like \"user.name\" instead of just \"name\"\n * ValidationContext.validate(data, schema, { path: ['user'] })\n * ```\n */\n path?: readonly PropertyKey[]\n}\n\n/**\n * Manages the state and context for validation operations.\n *\n * The `ValidationContext` class is responsible for:\n * - Tracking the current path in nested structures for error reporting\n * - Collecting validation issues during traversal\n * - Enforcing validation mode (validate vs parse)\n * - Providing factory methods for creating validation results\n *\n * Use the static {@link ValidationContext.validate} method as the primary entry point\n * for validation. This ensures proper mode enforcement and issue aggregation.\n *\n * @example\n * ```typescript\n * // Primary usage via static method\n * const result = ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // Within a custom validator implementation\n * class MyValidator implements Validator {\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 */\nexport class ValidationContext {\n /**\n * Validates input against a validator in parse mode.\n *\n * In parse mode, the schema may transform the input (e.g., apply defaults).\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Validation options with mode set to 'parse'\n * @returns A validation result with the parsed output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options: ValidationOptions & {\n mode: 'parse'\n },\n ): ValidationResult<InferOutput<V>>\n /**\n * Validates input against a validator in validate mode (default).\n *\n * In validate mode, the result must be strictly equal to the input.\n * No transformations are allowed.\n *\n * @typeParam V - The validator type\n * @typeParam I - The input type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options (defaults to validate mode)\n * @returns A validation result preserving the input type intersected with the schema type\n */\n static validate<V extends Validator, I = unknown>(\n input: I,\n validator: V,\n options?: ValidationOptions & {\n mode?: 'validate'\n },\n ): ValidationResult<I & InferInput<V>>\n /**\n * Validates input against a validator with configurable options.\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options\n * @returns A validation result with either the input or output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>>\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>> {\n const context = new ValidationContext({\n path: options?.path ?? [],\n mode: options?.mode ?? 'validate',\n })\n return context.validate(input, validator)\n }\n\n /**\n * The current path being validated, used for error reporting.\n */\n protected readonly currentPath: PropertyKey[]\n\n /**\n * Accumulated validation issues collected during traversal.\n */\n protected readonly issues: Issue[] = []\n\n /**\n * Creates a new validation context with the specified options.\n *\n * @param options - The validation options (path and mode are required)\n */\n constructor(readonly options: Required<ValidationOptions>) {\n // Create a copy because we will be mutating the array during validation.\n this.currentPath = Array.from(options.path)\n }\n\n /**\n * Returns a copy of the current validation path.\n *\n * The path represents the location in the data structure being validated,\n * used for constructing meaningful error messages.\n */\n get path() {\n return Array.from(this.currentPath)\n }\n\n /**\n * Creates a new path by appending segments to the current path.\n *\n * @param path - Optional path segment(s) to append\n * @returns A new path array with the segment(s) appended\n */\n concatPath(path?: PropertyKey | readonly PropertyKey[]) {\n if (path == null) return this.path\n return this.currentPath.concat(path)\n }\n\n /**\n * Validates input against a validator within this context.\n *\n * This is the primary entry point for validation within a context. Always use\n * this method instead of calling {@link Validator.validateInContext} directly,\n * as this method enforces validation mode rules and handles transformation detection.\n *\n * @typeParam V - The validator type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @returns A validation result with the validated value or error\n */\n validate<V extends Validator>(\n input: unknown,\n validator: V,\n ): ValidationResult<InferInput<V>> {\n // This is the only place where validateInContext should be called.\n const result = validator.validateInContext(input, this)\n\n if (result.success) {\n if (this.issues.length > 0) {\n // Validator returned a success but issues were added via the context.\n // This means the overall validation failed.\n return failure(new LexValidationError(Array.from(this.issues)))\n }\n\n if (this.options.mode !== 'parse' && !Object.is(result.value, input)) {\n // If the value changed, it means that a default (or some other\n // transformation) was applied, meaning that the original value did\n // *not* match the (output) schema. When not in \"parse\" mode, we\n // consider this a failure.\n\n // This check is the reason why Validator.validateInContext should not\n // be used directly, and ValidatorContext.validate should be used\n // instead, even when delegating validation from one validator to\n // another.\n\n // This if block comes before the next one because 'this.issues' will\n // end-up being appended to the returned LexValidationError (see the\n // \"failure\" method below), resulting in a more complete error report.\n return this.issueInvalidValue(input, [result.value])\n }\n }\n\n return result as ValidationResult<InferInput<V>>\n }\n\n /**\n * Validates a child property of an object within this context.\n *\n * This method automatically manages the path stack, pushing the property key\n * before validation and popping it afterward. Use this for validating object\n * properties to ensure proper path tracking in error messages.\n *\n * @typeParam I - The input object type\n * @typeParam K - The property key type\n * @typeParam V - The validator type\n * @param input - The parent object containing the property\n * @param key - The property key to validate\n * @param validator - The validator to use for the property value\n * @returns A validation result for the property value\n *\n * @example\n * ```typescript\n * // In a custom object validator\n * const result = ctx.validateChild(input, 'name', stringSchema)\n * // If validation fails, error path will include 'name'\n * ```\n */\n validateChild<\n I extends object,\n K extends PropertyKey & keyof I,\n V extends Validator,\n >(input: I, key: K, validator: V): ValidationResult<InferInput<V>> {\n // @NOTE we could add support for recursive schemas by keeping track of\n // \"parent\" objects in the context and checking for circular references\n // here. This would allow us to validate recursive structures without\n // hitting maximum call stack errors, and would also allow us to provide\n // better error messages for circular reference issues. However, this is not\n // a priority at the moment as recursive structures are not supported in\n // the context of AT Protocol lexicons, and we can always add this in the\n // future if needed.\n\n // Instead of creating a new context, we just push/pop the path segment.\n this.currentPath.push(key)\n try {\n return this.validate(input[key], validator)\n } finally {\n this.currentPath.length--\n }\n }\n\n /**\n * Adds a validation issue to the context without immediately failing.\n *\n * Use this method to collect multiple issues during validation before\n * determining the final result. Issues added this way will be included\n * in the final error if validation fails.\n *\n * @param issue - The validation issue to add\n */\n addIssue(issue: Issue): void {\n this.issues.push(issue)\n }\n\n /**\n * Creates a successful validation result with the given value.\n *\n * @typeParam V - The value type\n * @param value - The validated value\n * @returns A successful validation result\n */\n success<V>(value: V): ValidationResult<V> {\n return success(value)\n }\n\n /**\n * Creates a failed validation result with the given error.\n *\n * @param reason - The validation error\n * @returns A failed validation result\n */\n failure(reason: LexValidationError): ValidationFailure {\n return failure(reason)\n }\n\n /**\n * Creates a failed validation result from a single issue.\n *\n * Any previously accumulated issues in the context are included in the error.\n *\n * @param issue - The validation issue that caused the failure\n * @returns A failed validation result\n */\n issue(issue: Issue) {\n return this.failure(new LexValidationError([...this.issues, issue]))\n }\n\n /**\n * Creates a failure for an invalid value that doesn't match expected values.\n *\n * @param input - The actual value that was received\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue\n */\n issueInvalidValue(input: unknown, values: readonly unknown[]) {\n return this.issue(new IssueInvalidValue(this.path, input, values))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - An array of expected type names\n * @returns A failed validation result with an invalid type issue\n */\n issueInvalidType(input: unknown, expected: readonly string[]) {\n return this.issue(new IssueInvalidType(this.path, input, expected))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue\n */\n issueUnexpectedType(input: unknown, expected: string) {\n return this.issueInvalidType(input, [expected])\n }\n\n /**\n * Creates a failure for a missing required key in an object.\n *\n * @param input - The object missing the required key\n * @param key - The name of the required key\n * @returns A failed validation result with a required key issue\n */\n issueRequiredKey(input: object, key: PropertyKey) {\n return this.issue(new IssueRequiredKey(this.path, input, key))\n }\n\n /**\n * Creates a failure for an invalid string format.\n *\n * @param input - The actual value that was received\n * @param format - The expected format name (e.g., 'did', 'handle', 'uri')\n * @param msg - Optional additional message describing the format error\n * @returns A failed validation result with an invalid format issue\n */\n issueInvalidFormat(input: unknown, format: string, msg?: string) {\n return this.issue(new IssueInvalidFormat(this.path, input, format, msg))\n }\n\n /**\n * Creates a failure for a value that exceeds a maximum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param max - The maximum allowed value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too big issue\n */\n issueTooBig(\n input: unknown,\n type: MeasurableType,\n max: number,\n actual: number,\n ) {\n return this.issue(new IssueTooBig(this.path, input, max, type, actual))\n }\n\n /**\n * Creates a failure for a value that is below a minimum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param min - The minimum required value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too small issue\n */\n issueTooSmall(\n input: unknown,\n type: MeasurableType,\n min: number,\n actual: number,\n ) {\n return this.issue(new IssueTooSmall(this.path, input, min, type, actual))\n }\n\n /**\n * Creates a failure for an invalid property value within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid value\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue at the property path\n */\n issueInvalidPropertyValue<I>(\n input: I,\n property: keyof I & PropertyKey,\n values: readonly unknown[],\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidValue(path, value, values))\n }\n\n /**\n * Creates a failure for an invalid property type within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid type\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue at the property path\n */\n issueInvalidPropertyType<I>(\n input: I,\n property: keyof I & PropertyKey,\n expected: string,\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidType(path, value, [expected]))\n }\n}\n\n/**\n * Recursively unwraps a wrapped validator to its innermost validator type.\n *\n * Some validators wrap other validators (e.g., optional, nullable). This type\n * utility recursively unwraps such wrappers to reveal the core validator.\n *\n * @typeParam T - A validator type, possibly wrapped\n *\n * @example\n * ```typescript\n * type Inner = UnwrapValidator<OptionalValidator<NullableValidator<StringSchema>>>\n * // Result: StringSchema\n * ```\n */\nexport type UnwrapValidator<T extends Validator> = T extends {\n unwrap(): infer U extends Validator\n}\n ? UnwrapValidator<U>\n : T\n\n/**\n * Interface for validators that wrap another validator.\n *\n * Implement this interface when creating validators that wrap or modify\n * the behavior of another validator (e.g., optional, nullable, transform).\n *\n * @typeParam Validator - The type of the wrapped validator\n *\n * @example\n * ```typescript\n * class OptionalSchema<V extends Validator> implements WrappedValidator<V> {\n * constructor(private inner: V) {}\n *\n * unwrap(): V {\n * return this.inner\n * }\n * }\n * ```\n */\nexport interface WrappedValidator<out Validator> {\n /**\n * Returns the inner wrapped validator.\n *\n * @returns The wrapped validator\n */\n unwrap(): Validator\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"params.d.ts","sourceRoot":"","sources":["../../src/schema/params.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,EACL,UAAU,EACV,WAAW,
|
|
1
|
+
{"version":3,"file":"params.d.ts","sourceRoot":"","sources":["../../src/schema/params.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,EACL,UAAU,EACV,WAAW,EAKX,YAAY,EACZ,MAAM,EACN,iBAAiB,EACjB,SAAS,EACT,sBAAsB,EACvB,MAAM,YAAY,CAAA;AAGnB,OAAO,EAAE,WAAW,EAAS,MAAM,YAAY,CAAA;AAC/C,OAAO,EAAE,aAAa,EAAW,MAAM,cAAc,CAAA;AAErD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AACtC,OAAO,EAAE,aAAa,EAAW,MAAM,cAAc,CAAA;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAC5C,OAAO,EAAE,cAAc,EAAY,MAAM,eAAe,CAAA;AACxD,OAAO,EAAE,YAAY,EAAU,MAAM,aAAa,CAAA;AAElD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AAErD;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAA;AACzD,QAAA,MAAM,iBAAiB,6FAA0C,CAAA;AAEjE;;GAEG;AACH,MAAM,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,WAAW,CAAC,CAAA;AAE7C;;GAEG;AACH,eAAO,MAAM,WAAW,iOAKtB,CAAA;AAEF;;GAEG;AACH,MAAM,MA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,QAAQ,CAAS;gBAEZ,KAAK,EAAE,MAAM;IAIlC,IAAI,eAAe,IAAI,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAIjD;IAED,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;IAyDxD,mBAAmB,CACjB,KAAK,EAAE,MAAM,GAAG,QAAQ,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAC1C,OAAO,CAAC,EAAE,YAAY,GACrB,WAAW,CAAC,IAAI,CAAC;IAkCpB,iBAAiB,CAAC,KAAK,EAAE,UAAU,CAAC,IAAI,CAAC,GAAG,eAAe;CAmB5D;AA2DD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,eAAO,MAAM,MAAM,SACX,MAAM,SAAS,WAAW,oBACpB,MAAM,yBAElB,CAAA"}
|
package/dist/schema/params.js
CHANGED
|
@@ -111,6 +111,9 @@ class ParamsSchema extends core_js_1.Schema {
|
|
|
111
111
|
const iterable = typeof input === 'string' ? new URLSearchParams(input) : input;
|
|
112
112
|
const entries = iterable instanceof URLSearchParams ? iterable.entries() : iterable;
|
|
113
113
|
for (const [name, value] of entries) {
|
|
114
|
+
// Ignore empty strings
|
|
115
|
+
if (!value)
|
|
116
|
+
continue;
|
|
114
117
|
const validator = this.shapeValidators.get(name);
|
|
115
118
|
const innerValidator = validator ? unwrapSchema(validator) : undefined;
|
|
116
119
|
const expectsArray = innerValidator instanceof array_js_1.ArraySchema;
|
|
@@ -204,7 +207,7 @@ function coerceParam(name, param, schema, options) {
|
|
|
204
207
|
// the index of the param in case of array params (e.g. "tags[1]"), which
|
|
205
208
|
// could be helpful for debugging. The cost overhead is not worth it though
|
|
206
209
|
// (IMO).
|
|
207
|
-
throw new core_js_1.
|
|
210
|
+
throw new core_js_1.LexValidationError([issue]);
|
|
208
211
|
}
|
|
209
212
|
function paramPath(key, options) {
|
|
210
213
|
return options?.path ? [...options.path, key] : [key];
|
|
@@ -1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IAAA,4BAAe,EAAC,SAAS,MAAM,CAEjE,aAAqB,EAAY;IACjC,OAAO,IAAI,YAAY,CAAS,UAAU,CAAC,CAAA;AAC7C,CAAC,CAAC,CAAA;AASF,SAAS,YAAY,CAAsB,MAAS;IAClD,OACE,MAAM,YAAY,4BAAc;QAChC,MAAM,YAAY,mCAAiB,EACnC,CAAC;QACD,OAAO,YAAY,CAAC,MAAM,CAAC,SAAS,CAAC,CAAA;IACvC,CAAC;IACD,OAAO,MAAyB,CAAA;AAClC,CAAC","sourcesContent":["import { isPlainObject } from '@atproto/lex-data'\nimport {\n Infer,\n InferInput,\n InferOutput,\n Issue,\n IssueInvalidType,\n IssueInvalidValue,\n ParseOptions,\n Schema,\n ValidationContext,\n ValidationError,\n Validator,\n WithOptionalProperties,\n} from '../core.js'\nimport { lazyProperty } from '../util/lazy-property.js'\nimport { memoizedOptions } from '../util/memoize.js'\nimport { ArraySchema, array } from './array.js'\nimport { BooleanSchema, boolean } from './boolean.js'\nimport { dict } from './dict.js'\nimport { EnumSchema } from './enum.js'\nimport { IntegerSchema, integer } from './integer.js'\nimport { LiteralSchema } from './literal.js'\nimport { OptionalSchema, optional } from './optional.js'\nimport { StringSchema, string } from './string.js'\nimport { union } from './union.js'\nimport { WithDefaultSchema } from './with-default.js'\n\n/**\n * Scalar types allowed in URL parameters: boolean, integer, or string.\n */\nexport type ParamScalar = Infer<typeof paramScalarSchema>\nconst paramScalarSchema = union([boolean(), integer(), string()])\n\n/**\n * A single parameter value: scalar or array of scalars.\n */\nexport type Param = Infer<typeof paramSchema>\n\n/**\n * Schema for validating individual parameter values.\n */\nexport const paramSchema = union([\n paramScalarSchema,\n array(boolean()),\n array(integer()),\n array(string()),\n])\n\n/**\n * Type for a params object with string keys and optional param values.\n */\nexport type Params = Infer<typeof paramsSchema>\n\n/**\n * Schema for validating arbitrary params objects.\n */\nexport const paramsSchema = dict(string(), optional(paramSchema))\n\nexport type ParamScalarValidator =\n // @NOTE In order to properly coerce URLSearchParams, we need to distinguish\n // between scalar and array validators, requiring to be able to detect which\n // schema types are being used, restricting the allowed param validators here.\n | LiteralSchema<string>\n | LiteralSchema<number>\n | LiteralSchema<boolean>\n | EnumSchema<string>\n | EnumSchema<number>\n // | EnumSchema<boolean> // Boolean lexicon definitions don't allow \"enum\"\n | StringSchema<any>\n | BooleanSchema\n | IntegerSchema\n\ntype AsArrayParamSchema<TSchema extends Validator> =\n // This allows to \"distribute\" any union of scalar validators into a union of\n // arrays of those validators, instead of an array of union. If TSchema is\n // BooleanSchema | IntegerSchema, we want the result to be\n // ArraySchema<BooleanSchema> | ArraySchema<IntegerSchema>, not\n // ArraySchema<BooleanSchema | IntegerSchema>, since the latter would allow\n // arrays with mixed types (e.g. [true, 42]), which we don't want.\n TSchema extends any ? ArraySchema<TSchema> : never\n\nexport type ParamValueValidator =\n | ParamScalarValidator\n | AsArrayParamSchema<ParamScalarValidator>\n\nexport type ParamValidator =\n | ParamValueValidator\n | OptionalSchema<ParamValueValidator>\n | OptionalSchema<WithDefaultSchema<ParamValueValidator>>\n | WithDefaultSchema<ParamValueValidator>\n\n/**\n * Type representing the shape of a params schema definition.\n *\n * Maps parameter names to their validators (must be Param or undefined).\n */\nexport type ParamsShape = {\n [x: string]: ParamValidator\n}\n\n/**\n * Schema for validating URL query parameters in Lexicon endpoints.\n *\n * Params are the query string parameters passed to queries, procedures,\n * and subscriptions. Values must be scalars (boolean, integer, string)\n * or arrays of scalars, as they need to be serializable to URL format.\n *\n * Provides methods for converting to/from URLSearchParams.\n *\n * @template TShape - The params shape type mapping names to validators\n *\n * @example\n * ```ts\n * const schema = new ParamsSchema({\n * limit: l.optional(l.integer({ minimum: 1, maximum: 100 })),\n * cursor: l.optional(l.string()),\n * })\n * ```\n */\nexport class ParamsSchema<\n const TShape extends ParamsShape = ParamsShape,\n> extends Schema<\n WithOptionalProperties<{\n [K in keyof TShape]: InferInput<TShape[K]>\n }>,\n WithOptionalProperties<{\n [K in keyof TShape]: InferOutput<TShape[K]>\n }>\n> {\n readonly type = 'params' as const\n\n constructor(readonly shape: TShape) {\n super()\n }\n\n get shapeValidators(): Map<string, ParamValidator> {\n const map = new Map(Object.entries(this.shape))\n\n return lazyProperty(this, 'shapeValidators', map)\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!isPlainObject(input)) {\n return ctx.issueUnexpectedType(input, 'object')\n }\n\n // Lazily copy value\n let copy: undefined | Record<string, unknown>\n\n // Ensure that non-specified params conform to param schema\n for (const key in input) {\n if (this.shapeValidators.has(key)) continue\n\n const result = ctx.validateChild(input, key, paramSchema)\n if (!result.success) return result\n\n if (result.value !== input[key]) {\n if (ctx.options.mode === 'validate') {\n // In \"validate\" mode, we can't modify the input, so we issue an error\n return ctx.issueInvalidPropertyValue(input, key, [result.value])\n }\n\n copy ??= { ...input }\n copy[key] = result.value\n }\n }\n\n for (const [key, propDef] of this.shapeValidators) {\n const result = ctx.validateChild(input, key, propDef)\n if (!result.success) {\n if (!(key in input)) {\n // Transform into \"required key\" issue\n return ctx.issueRequiredKey(input, key)\n }\n\n return result\n }\n\n // Skip copying if key is not present in input (and value is undefined)\n if (result.value === undefined && !(key in input)) {\n continue\n }\n\n if (!Object.is(result.value, input[key])) {\n if (ctx.options.mode === 'validate') {\n // In \"validate\" mode, we can't modify the input, so we issue an error\n return ctx.issueInvalidPropertyValue(input, key, [result.value])\n }\n\n // Copy on write\n copy ??= { ...input }\n copy[key] = result.value\n }\n }\n\n return ctx.success(copy ?? input)\n }\n\n fromURLSearchParams(\n input: string | Iterable<[string, string]>,\n options?: ParseOptions,\n ): InferOutput<this> {\n const params: Record<string, unknown> = {}\n\n const iterable =\n typeof input === 'string' ? new URLSearchParams(input) : input\n const entries =\n iterable instanceof URLSearchParams ? iterable.entries() : iterable\n\n for (const [name, value] of entries) {\n const validator = this.shapeValidators.get(name)\n const innerValidator = validator ? unwrapSchema(validator) : undefined\n const expectsArray = innerValidator instanceof ArraySchema\n const scalarValidator = expectsArray\n ? unwrapSchema(innerValidator.validator)\n : innerValidator\n\n const coerced = coerceParam(name, value, scalarValidator, options)\n\n const currentParam = params[name]\n if (currentParam === undefined) {\n params[name] = expectsArray ? [coerced] : coerced\n } else if (Array.isArray(currentParam)) {\n currentParam.push(coerced)\n } else {\n params[name] = [currentParam, coerced]\n }\n }\n\n return this.parse(params, options)\n }\n\n toURLSearchParams(input: InferInput<this>): URLSearchParams {\n const urlSearchParams = new URLSearchParams()\n\n // @NOTE We apply defaults here to ensure that server with different\n // defaults still receive all expected parameters.\n const params = this.parse(input)\n\n for (const [key, value] of Object.entries(params)) {\n if (Array.isArray(value)) {\n for (const v of value) {\n urlSearchParams.append(key, String(v))\n }\n } else if (value !== undefined) {\n urlSearchParams.append(key, String(value))\n }\n }\n\n return urlSearchParams\n }\n}\n\nfunction coerceParam(\n name: string,\n param: string,\n schema?: ParamScalarValidator,\n options?: ParseOptions,\n): ParamScalar {\n let issue: Issue\n\n if (!schema) {\n // The param is unknown (not defined in schema), so we don't apply any\n // coercion and just return the string value.\n return param\n } else if (schema instanceof StringSchema) {\n return param\n } else if (schema instanceof IntegerSchema) {\n if (/^-?\\d+$/.test(param)) return Number(param)\n issue = new IssueInvalidType(paramPath(name, options), param, ['integer'])\n } else if (schema instanceof BooleanSchema) {\n if (param === 'true') return true\n if (param === 'false') return false\n issue = new IssueInvalidType(paramPath(name, options), param, ['boolean'])\n } else if (schema instanceof LiteralSchema) {\n const { value } = schema\n if (String(value) === param) return value\n issue = new IssueInvalidValue(paramPath(name, options), param, [value])\n } else if (schema instanceof EnumSchema) {\n const { values } = schema\n for (const value of values) {\n if (String(value) === param) return value\n }\n issue = new IssueInvalidValue(paramPath(name, options), param, values)\n } else {\n // This should never happen. If it *does*, it means that the user of\n // lex-schema is mixing different versions of the lib, which is not\n // supported. Throwing an error here is better than silently accepting\n // invalid params and causing unexpected behavior down the line (ie. error\n // message returning the string value instead of the expected\n // boolean/number/string value).\n throw new Error(`Unsupported schema type for param coercion: ${schema}`)\n }\n\n // We were not able to coerce the param to the expected type. There is no\n // point in returning the original string value since it doesn't conform to\n // the expected schema, so we throw a validation error instead. We could\n // return the \"param\" here, which would cause the validation to fail later on\n // (see fromURLSearchParams()'s return statement). The main benefit of\n // returning the original \"param\" value is that the error path would include\n // the index of the param in case of array params (e.g. \"tags[1]\"), which\n // could be helpful for debugging. The cost overhead is not worth it though\n // (IMO).\n throw new ValidationError([issue])\n}\n\nfunction paramPath(key: string, options?: ParseOptions) {\n return options?.path ? [...options.path, key] : [key]\n}\n\n/**\n * Creates a params schema for URL query parameters.\n *\n * Params schemas validate query string parameters for Lexicon endpoints.\n * Values must be boolean, integer, string, or arrays of those types.\n *\n * @param properties - Object mapping parameter names to their validators\n * @returns A new {@link ParamsSchema} instance\n *\n * @example\n * ```ts\n * // Simple pagination params\n * const paginationParams = l.params({\n * limit: l.optional(l.withDefault(l.integer({ minimum: 1, maximum: 100 }), 50)),\n * cursor: l.optional(l.string()),\n * })\n *\n * // Required parameter\n * const actorParams = l.params({\n * actor: l.string({ format: 'at-identifier' }),\n * })\n *\n * // Array parameter (multiple values)\n * const filterParams = l.params({\n * tags: l.optional(l.array(l.string())),\n * })\n *\n * // Convert from URL\n * const urlParams = new URLSearchParams('limit=25&cursor=abc')\n * const validated = paginationParams.fromURLSearchParams(urlParams)\n *\n * // Convert to URL\n * const searchParams = paginationParams.toURLSearchParams({ limit: 25 })\n * ```\n */\nexport const params = /*#__PURE__*/ memoizedOptions(function params<\n const TShape extends ParamsShape = NonNullable<unknown>,\n>(properties: TShape = {} as TShape) {\n return new ParamsSchema<TShape>(properties)\n})\n\ntype UnwrapSchema<S extends Validator> =\n S extends OptionalSchema<infer U>\n ? UnwrapSchema<U>\n : S extends WithDefaultSchema<infer U>\n ? UnwrapSchema<U>\n : S\n\nfunction unwrapSchema<S extends Validator>(schema: S): UnwrapSchema<S> {\n while (\n schema instanceof OptionalSchema ||\n schema instanceof WithDefaultSchema\n ) {\n return unwrapSchema(schema.validator)\n }\n return schema as Unwr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;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACU,QAAA,MAAM,GAAiB,IAAA,4BAAe,EAAC,SAAS,MAAM,CAEjE,aAAqB,EAAY;IACjC,OAAO,IAAI,YAAY,CAAS,UAAU,CAAC,CAAA;AAC7C,CAAC,CAAC,CAAA;AASF,SAAS,YAAY,CAAsB,MAAS;IAClD,OACE,MAAM,YAAY,4BAAc;QAChC,MAAM,YAAY,mCAAiB,EACnC,CAAC;QACD,OAAO,YAAY,CAAC,MAAM,CAAC,SAAS,CAAC,CAAA;IACvC,CAAC;IACD,OAAO,MAAyB,CAAA;AAClC,CAAC","sourcesContent":["import { isPlainObject } from '@atproto/lex-data'\nimport {\n Infer,\n InferInput,\n InferOutput,\n Issue,\n IssueInvalidType,\n IssueInvalidValue,\n LexValidationError,\n ParseOptions,\n Schema,\n ValidationContext,\n Validator,\n WithOptionalProperties,\n} from '../core.js'\nimport { lazyProperty } from '../util/lazy-property.js'\nimport { memoizedOptions } from '../util/memoize.js'\nimport { ArraySchema, array } from './array.js'\nimport { BooleanSchema, boolean } from './boolean.js'\nimport { dict } from './dict.js'\nimport { EnumSchema } from './enum.js'\nimport { IntegerSchema, integer } from './integer.js'\nimport { LiteralSchema } from './literal.js'\nimport { OptionalSchema, optional } from './optional.js'\nimport { StringSchema, string } from './string.js'\nimport { union } from './union.js'\nimport { WithDefaultSchema } from './with-default.js'\n\n/**\n * Scalar types allowed in URL parameters: boolean, integer, or string.\n */\nexport type ParamScalar = Infer<typeof paramScalarSchema>\nconst paramScalarSchema = union([boolean(), integer(), string()])\n\n/**\n * A single parameter value: scalar or array of scalars.\n */\nexport type Param = Infer<typeof paramSchema>\n\n/**\n * Schema for validating individual parameter values.\n */\nexport const paramSchema = union([\n paramScalarSchema,\n array(boolean()),\n array(integer()),\n array(string()),\n])\n\n/**\n * Type for a params object with string keys and optional param values.\n */\nexport type Params = Infer<typeof paramsSchema>\n\n/**\n * Schema for validating arbitrary params objects.\n */\nexport const paramsSchema = dict(string(), optional(paramSchema))\n\nexport type ParamScalarValidator =\n // @NOTE In order to properly coerce URLSearchParams, we need to distinguish\n // between scalar and array validators, requiring to be able to detect which\n // schema types are being used, restricting the allowed param validators here.\n | LiteralSchema<string>\n | LiteralSchema<number>\n | LiteralSchema<boolean>\n | EnumSchema<string>\n | EnumSchema<number>\n // | EnumSchema<boolean> // Boolean lexicon definitions don't allow \"enum\"\n | StringSchema<any>\n | BooleanSchema\n | IntegerSchema\n\ntype AsArrayParamSchema<TSchema extends Validator> =\n // This allows to \"distribute\" any union of scalar validators into a union of\n // arrays of those validators, instead of an array of union. If TSchema is\n // BooleanSchema | IntegerSchema, we want the result to be\n // ArraySchema<BooleanSchema> | ArraySchema<IntegerSchema>, not\n // ArraySchema<BooleanSchema | IntegerSchema>, since the latter would allow\n // arrays with mixed types (e.g. [true, 42]), which we don't want.\n TSchema extends any ? ArraySchema<TSchema> : never\n\nexport type ParamValueValidator =\n | ParamScalarValidator\n | AsArrayParamSchema<ParamScalarValidator>\n\nexport type ParamValidator =\n | ParamValueValidator\n | OptionalSchema<ParamValueValidator>\n | OptionalSchema<WithDefaultSchema<ParamValueValidator>>\n | WithDefaultSchema<ParamValueValidator>\n\n/**\n * Type representing the shape of a params schema definition.\n *\n * Maps parameter names to their validators (must be Param or undefined).\n */\nexport type ParamsShape = {\n [x: string]: ParamValidator\n}\n\n/**\n * Schema for validating URL query parameters in Lexicon endpoints.\n *\n * Params are the query string parameters passed to queries, procedures,\n * and subscriptions. Values must be scalars (boolean, integer, string)\n * or arrays of scalars, as they need to be serializable to URL format.\n *\n * Provides methods for converting to/from URLSearchParams.\n *\n * @template TShape - The params shape type mapping names to validators\n *\n * @example\n * ```ts\n * const schema = new ParamsSchema({\n * limit: l.optional(l.integer({ minimum: 1, maximum: 100 })),\n * cursor: l.optional(l.string()),\n * })\n * ```\n */\nexport class ParamsSchema<\n const TShape extends ParamsShape = ParamsShape,\n> extends Schema<\n WithOptionalProperties<{\n [K in keyof TShape]: InferInput<TShape[K]>\n }>,\n WithOptionalProperties<{\n [K in keyof TShape]: InferOutput<TShape[K]>\n }>\n> {\n readonly type = 'params' as const\n\n constructor(readonly shape: TShape) {\n super()\n }\n\n get shapeValidators(): Map<string, ParamValidator> {\n const map = new Map(Object.entries(this.shape))\n\n return lazyProperty(this, 'shapeValidators', map)\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!isPlainObject(input)) {\n return ctx.issueUnexpectedType(input, 'object')\n }\n\n // Lazily copy value\n let copy: undefined | Record<string, unknown>\n\n // Ensure that non-specified params conform to param schema\n for (const key in input) {\n if (this.shapeValidators.has(key)) continue\n\n const result = ctx.validateChild(input, key, paramSchema)\n if (!result.success) return result\n\n if (result.value !== input[key]) {\n if (ctx.options.mode === 'validate') {\n // In \"validate\" mode, we can't modify the input, so we issue an error\n return ctx.issueInvalidPropertyValue(input, key, [result.value])\n }\n\n copy ??= { ...input }\n copy[key] = result.value\n }\n }\n\n for (const [key, propDef] of this.shapeValidators) {\n const result = ctx.validateChild(input, key, propDef)\n if (!result.success) {\n if (!(key in input)) {\n // Transform into \"required key\" issue\n return ctx.issueRequiredKey(input, key)\n }\n\n return result\n }\n\n // Skip copying if key is not present in input (and value is undefined)\n if (result.value === undefined && !(key in input)) {\n continue\n }\n\n if (!Object.is(result.value, input[key])) {\n if (ctx.options.mode === 'validate') {\n // In \"validate\" mode, we can't modify the input, so we issue an error\n return ctx.issueInvalidPropertyValue(input, key, [result.value])\n }\n\n // Copy on write\n copy ??= { ...input }\n copy[key] = result.value\n }\n }\n\n return ctx.success(copy ?? input)\n }\n\n fromURLSearchParams(\n input: string | Iterable<[string, string]>,\n options?: ParseOptions,\n ): InferOutput<this> {\n const params: Record<string, unknown> = {}\n\n const iterable =\n typeof input === 'string' ? new URLSearchParams(input) : input\n const entries =\n iterable instanceof URLSearchParams ? iterable.entries() : iterable\n\n for (const [name, value] of entries) {\n // Ignore empty strings\n if (!value) continue\n\n const validator = this.shapeValidators.get(name)\n const innerValidator = validator ? unwrapSchema(validator) : undefined\n const expectsArray = innerValidator instanceof ArraySchema\n const scalarValidator = expectsArray\n ? unwrapSchema(innerValidator.validator)\n : innerValidator\n\n const coerced = coerceParam(name, value, scalarValidator, options)\n\n const currentParam = params[name]\n if (currentParam === undefined) {\n params[name] = expectsArray ? [coerced] : coerced\n } else if (Array.isArray(currentParam)) {\n currentParam.push(coerced)\n } else {\n params[name] = [currentParam, coerced]\n }\n }\n\n return this.parse(params, options)\n }\n\n toURLSearchParams(input: InferInput<this>): URLSearchParams {\n const urlSearchParams = new URLSearchParams()\n\n // @NOTE We apply defaults here to ensure that server with different\n // defaults still receive all expected parameters.\n const params = this.parse(input)\n\n for (const [key, value] of Object.entries(params)) {\n if (Array.isArray(value)) {\n for (const v of value) {\n urlSearchParams.append(key, String(v))\n }\n } else if (value !== undefined) {\n urlSearchParams.append(key, String(value))\n }\n }\n\n return urlSearchParams\n }\n}\n\nfunction coerceParam(\n name: string,\n param: string,\n schema?: ParamScalarValidator,\n options?: ParseOptions,\n): ParamScalar {\n let issue: Issue\n\n if (!schema) {\n // The param is unknown (not defined in schema), so we don't apply any\n // coercion and just return the string value.\n return param\n } else if (schema instanceof StringSchema) {\n return param\n } else if (schema instanceof IntegerSchema) {\n if (/^-?\\d+$/.test(param)) return Number(param)\n issue = new IssueInvalidType(paramPath(name, options), param, ['integer'])\n } else if (schema instanceof BooleanSchema) {\n if (param === 'true') return true\n if (param === 'false') return false\n issue = new IssueInvalidType(paramPath(name, options), param, ['boolean'])\n } else if (schema instanceof LiteralSchema) {\n const { value } = schema\n if (String(value) === param) return value\n issue = new IssueInvalidValue(paramPath(name, options), param, [value])\n } else if (schema instanceof EnumSchema) {\n const { values } = schema\n for (const value of values) {\n if (String(value) === param) return value\n }\n issue = new IssueInvalidValue(paramPath(name, options), param, values)\n } else {\n // This should never happen. If it *does*, it means that the user of\n // lex-schema is mixing different versions of the lib, which is not\n // supported. Throwing an error here is better than silently accepting\n // invalid params and causing unexpected behavior down the line (ie. error\n // message returning the string value instead of the expected\n // boolean/number/string value).\n throw new Error(`Unsupported schema type for param coercion: ${schema}`)\n }\n\n // We were not able to coerce the param to the expected type. There is no\n // point in returning the original string value since it doesn't conform to\n // the expected schema, so we throw a validation error instead. We could\n // return the \"param\" here, which would cause the validation to fail later on\n // (see fromURLSearchParams()'s return statement). The main benefit of\n // returning the original \"param\" value is that the error path would include\n // the index of the param in case of array params (e.g. \"tags[1]\"), which\n // could be helpful for debugging. The cost overhead is not worth it though\n // (IMO).\n throw new LexValidationError([issue])\n}\n\nfunction paramPath(key: string, options?: ParseOptions) {\n return options?.path ? [...options.path, key] : [key]\n}\n\n/**\n * Creates a params schema for URL query parameters.\n *\n * Params schemas validate query string parameters for Lexicon endpoints.\n * Values must be boolean, integer, string, or arrays of those types.\n *\n * @param properties - Object mapping parameter names to their validators\n * @returns A new {@link ParamsSchema} instance\n *\n * @example\n * ```ts\n * // Simple pagination params\n * const paginationParams = l.params({\n * limit: l.optional(l.withDefault(l.integer({ minimum: 1, maximum: 100 }), 50)),\n * cursor: l.optional(l.string()),\n * })\n *\n * // Required parameter\n * const actorParams = l.params({\n * actor: l.string({ format: 'at-identifier' }),\n * })\n *\n * // Array parameter (multiple values)\n * const filterParams = l.params({\n * tags: l.optional(l.array(l.string())),\n * })\n *\n * // Convert from URL\n * const urlParams = new URLSearchParams('limit=25&cursor=abc')\n * const validated = paginationParams.fromURLSearchParams(urlParams)\n *\n * // Convert to URL\n * const searchParams = paginationParams.toURLSearchParams({ limit: 25 })\n * ```\n */\nexport const params = /*#__PURE__*/ memoizedOptions(function params<\n const TShape extends ParamsShape = NonNullable<unknown>,\n>(properties: TShape = {} as TShape) {\n return new ParamsSchema<TShape>(properties)\n})\n\ntype UnwrapSchema<S extends Validator> =\n S extends OptionalSchema<infer U>\n ? UnwrapSchema<U>\n : S extends WithDefaultSchema<infer U>\n ? UnwrapSchema<U>\n : S\n\nfunction unwrapSchema<S extends Validator>(schema: S): UnwrapSchema<S> {\n while (\n schema instanceof OptionalSchema ||\n schema instanceof WithDefaultSchema\n ) {\n return unwrapSchema(schema.validator)\n }\n return schema as UnwrapSchema<S>\n}\n"]}
|
package/dist/schema/record.d.ts
CHANGED
|
@@ -41,15 +41,21 @@ export declare class RecordSchema<const TKey extends LexiconRecordKey = any, con
|
|
|
41
41
|
readonly type: "record";
|
|
42
42
|
keySchema: RecordKeySchema<TKey>;
|
|
43
43
|
constructor(key: TKey, $type: TType, schema: TShape);
|
|
44
|
-
|
|
45
|
-
$type?: unknown;
|
|
46
|
-
}>(value: TValue): value is TypedRecord<TType, TValue>;
|
|
44
|
+
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").ValidationFailure | import("../core.js").ValidationSuccess<InferInput<TShape>>;
|
|
47
45
|
build(input: Omit<InferInput<this>, '$type'>): $Typed<InferOutput<this>, TType>;
|
|
48
|
-
|
|
46
|
+
isTypeOf<TValue extends {
|
|
49
47
|
$type?: unknown;
|
|
50
48
|
}>(value: TValue): value is TypedRecord<TType, TValue>;
|
|
51
|
-
|
|
52
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Bound alias for {@link build} for compatibility with generated utilities.
|
|
51
|
+
* @see {@link build}
|
|
52
|
+
*/
|
|
53
|
+
get $build(): typeof this.build;
|
|
54
|
+
/**
|
|
55
|
+
* Bound alias for {@link isTypeOf} for compatibility with generated utilities.
|
|
56
|
+
* @see {@link isTypeOf}
|
|
57
|
+
*/
|
|
58
|
+
get $isTypeOf(): typeof this.isTypeOf;
|
|
53
59
|
}
|
|
54
60
|
export type RecordKeySchemaOutput<Key extends LexiconRecordKey> = Key extends 'any' ? string : Key extends 'tid' ? TidString : Key extends 'nsid' ? NsidString : Key extends `literal:${infer L extends string}` ? L : never;
|
|
55
61
|
export type RecordKeySchema<Key extends LexiconRecordKey> = Schema<RecordKeySchemaOutput<Key>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../../src/schema/record.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,MAAM,EAEN,UAAU,EACV,WAAW,EACX,gBAAgB,EAChB,UAAU,EACV,MAAM,EACN,SAAS,EACT,mBAAmB,EACnB,iBAAiB,EACjB,SAAS,EACV,MAAM,YAAY,CAAA;
|
|
1
|
+
{"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../../src/schema/record.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,MAAM,EAEN,UAAU,EACV,WAAW,EACX,gBAAgB,EAChB,UAAU,EACV,MAAM,EACN,SAAS,EACT,mBAAmB,EACnB,iBAAiB,EACjB,SAAS,EACV,MAAM,YAAY,CAAA;AAKnB;;;;GAIG;AACH,MAAM,MAAM,cAAc,CAAC,CAAC,SAAS,YAAY,IAC/C,CAAC,SAAS,YAAY,CAAC,MAAM,IAAI,CAAC,GAAG,qBAAqB,CAAC,IAAI,CAAC,GAAG,KAAK,CAAA;AAE1E,MAAM,MAAM,WAAW,CACrB,KAAK,SAAS,UAAU,EACxB,MAAM,SAAS;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,IACtD,MAAM,SAAS;IAAE,KAAK,EAAE,KAAK,CAAA;CAAE,GAC/B,MAAM,GACN,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,mBAAmB,CAAC,EAAE,KAAK,CAAC,CAAA;AAEvD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,YAAY,CACvB,KAAK,CAAC,IAAI,SAAS,gBAAgB,GAAG,GAAG,EACzC,KAAK,CAAC,KAAK,SAAS,UAAU,GAAG,GAAG,EACpC,KAAK,CAAC,MAAM,SAAS,SAAS,CAAC;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,CAAC,GAAG,GAAG,CAC9D,SAAQ,MAAM,CACd,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,EACjC,MA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C,IAAI,CAAC,SAAS,GAAG,MAAM,IAAI,MAAM,EAAE,GAAG,KAAK,GAAG,CAAC,CAAA;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,wBAAgB,MAAM,CACpB,KAAK,CAAC,CAAC,SAAS,gBAAgB,EAChC,KAAK,CAAC,CAAC,SAAS,UAAU,EAC1B,KAAK,CAAC,CAAC,SAAS,SAAS,CAAC;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,CAAC,EACnD,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,GAAG,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;AAC/D,wBAAgB,MAAM,CACpB,KAAK,CAAC,CAAC,SAAS,gBAAgB,EAChC,KAAK,CAAC,CAAC,SAAS;IAAE,KAAK,EAAE,UAAU,CAAA;CAAE,EAErC,GAAG,EAAE,CAAC,EACN,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,EACxB,SAAS,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,GACrC,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAA"}
|
package/dist/schema/record.js
CHANGED
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.RecordSchema = void 0;
|
|
4
4
|
exports.record = record;
|
|
5
5
|
const core_js_1 = require("../core.js");
|
|
6
|
+
const lazy_property_js_1 = require("../util/lazy-property.js");
|
|
6
7
|
const literal_js_1 = require("./literal.js");
|
|
7
8
|
const string_js_1 = require("./string.js");
|
|
8
9
|
/**
|
|
@@ -38,18 +39,6 @@ class RecordSchema extends core_js_1.Schema {
|
|
|
38
39
|
this.schema = schema;
|
|
39
40
|
this.keySchema = recordKey(key);
|
|
40
41
|
}
|
|
41
|
-
isTypeOf(value) {
|
|
42
|
-
return value.$type === this.$type;
|
|
43
|
-
}
|
|
44
|
-
build(input) {
|
|
45
|
-
return this.parse((0, core_js_1.$typed)(input, this.$type));
|
|
46
|
-
}
|
|
47
|
-
$isTypeOf(value) {
|
|
48
|
-
return this.isTypeOf(value);
|
|
49
|
-
}
|
|
50
|
-
$build(input) {
|
|
51
|
-
return this.build(input);
|
|
52
|
-
}
|
|
53
42
|
validateInContext(input, ctx) {
|
|
54
43
|
const result = ctx.validate(input, this.schema);
|
|
55
44
|
if (!result.success) {
|
|
@@ -60,6 +49,26 @@ class RecordSchema extends core_js_1.Schema {
|
|
|
60
49
|
}
|
|
61
50
|
return result;
|
|
62
51
|
}
|
|
52
|
+
build(input) {
|
|
53
|
+
return this.parse((0, core_js_1.$typed)(input, this.$type));
|
|
54
|
+
}
|
|
55
|
+
isTypeOf(value) {
|
|
56
|
+
return value.$type === this.$type;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Bound alias for {@link build} for compatibility with generated utilities.
|
|
60
|
+
* @see {@link build}
|
|
61
|
+
*/
|
|
62
|
+
get $build() {
|
|
63
|
+
return (0, lazy_property_js_1.lazyProperty)(this, '$build', this.build.bind(this));
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Bound alias for {@link isTypeOf} for compatibility with generated utilities.
|
|
67
|
+
* @see {@link isTypeOf}
|
|
68
|
+
*/
|
|
69
|
+
get $isTypeOf() {
|
|
70
|
+
return (0, lazy_property_js_1.lazyProperty)(this, '$isTypeOf', this.isTypeOf.bind(this));
|
|
71
|
+
}
|
|
63
72
|
}
|
|
64
73
|
exports.RecordSchema = RecordSchema;
|
|
65
74
|
const keySchema = (0, string_js_1.string)({ minLength: 1 });
|