@atproto/lex-schema 0.0.11 → 0.0.13
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 +54 -0
- package/dist/core/$type.d.ts +149 -0
- package/dist/core/$type.d.ts.map +1 -1
- package/dist/core/$type.js +44 -0
- package/dist/core/$type.js.map +1 -1
- package/dist/core/record-key.d.ts +44 -0
- package/dist/core/record-key.d.ts.map +1 -1
- package/dist/core/record-key.js +30 -0
- package/dist/core/record-key.js.map +1 -1
- package/dist/core/result.d.ts +85 -4
- package/dist/core/result.d.ts.map +1 -1
- package/dist/core/result.js +60 -4
- package/dist/core/result.js.map +1 -1
- package/dist/core/schema.d.ts +232 -5
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +197 -4
- package/dist/core/schema.js.map +1 -1
- package/dist/core/string-format.d.ts +244 -11
- package/dist/core/string-format.d.ts.map +1 -1
- package/dist/core/string-format.js +150 -0
- package/dist/core/string-format.js.map +1 -1
- package/dist/core/types.d.ts +90 -3
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/types.js.map +1 -1
- package/dist/core/validation-error.d.ts +60 -0
- package/dist/core/validation-error.d.ts.map +1 -1
- package/dist/core/validation-error.js +60 -0
- package/dist/core/validation-error.js.map +1 -1
- package/dist/core/validation-issue.d.ts +61 -0
- package/dist/core/validation-issue.d.ts.map +1 -1
- package/dist/core/validation-issue.js +54 -1
- package/dist/core/validation-issue.js.map +1 -1
- package/dist/core/validator.d.ts +356 -11
- package/dist/core/validator.d.ts.map +1 -1
- package/dist/core/validator.js +203 -4
- package/dist/core/validator.js.map +1 -1
- package/dist/helpers.d.ts +12 -28
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js.map +1 -1
- package/dist/schema/array.d.ts +46 -0
- package/dist/schema/array.d.ts.map +1 -1
- package/dist/schema/array.js +16 -1
- package/dist/schema/array.js.map +1 -1
- package/dist/schema/blob.d.ts +50 -2
- package/dist/schema/blob.d.ts.map +1 -1
- package/dist/schema/blob.js +44 -2
- package/dist/schema/blob.js.map +1 -1
- package/dist/schema/boolean.d.ts +29 -0
- package/dist/schema/boolean.d.ts.map +1 -1
- package/dist/schema/boolean.js +30 -1
- package/dist/schema/boolean.js.map +1 -1
- package/dist/schema/bytes.d.ts +39 -0
- package/dist/schema/bytes.d.ts.map +1 -1
- package/dist/schema/bytes.js +34 -1
- package/dist/schema/bytes.js.map +1 -1
- package/dist/schema/cid.d.ts +39 -0
- package/dist/schema/cid.d.ts.map +1 -1
- package/dist/schema/cid.js +35 -1
- package/dist/schema/cid.js.map +1 -1
- package/dist/schema/custom.d.ts +67 -1
- package/dist/schema/custom.d.ts.map +1 -1
- package/dist/schema/custom.js +55 -0
- package/dist/schema/custom.js.map +1 -1
- package/dist/schema/dict.d.ts +45 -0
- package/dist/schema/dict.d.ts.map +1 -1
- package/dist/schema/dict.js +46 -1
- package/dist/schema/dict.js.map +1 -1
- package/dist/schema/discriminated-union.d.ts +59 -0
- package/dist/schema/discriminated-union.d.ts.map +1 -1
- package/dist/schema/discriminated-union.js +47 -1
- package/dist/schema/discriminated-union.js.map +1 -1
- package/dist/schema/enum.d.ts +49 -0
- package/dist/schema/enum.d.ts.map +1 -1
- package/dist/schema/enum.js +49 -0
- package/dist/schema/enum.js.map +1 -1
- package/dist/schema/integer.d.ts +43 -0
- package/dist/schema/integer.d.ts.map +1 -1
- package/dist/schema/integer.js +38 -1
- package/dist/schema/integer.js.map +1 -1
- package/dist/schema/intersection.d.ts +55 -0
- package/dist/schema/intersection.d.ts.map +1 -1
- package/dist/schema/intersection.js +50 -0
- package/dist/schema/intersection.js.map +1 -1
- package/dist/schema/lex-map.d.ts +37 -0
- package/dist/schema/lex-map.d.ts.map +1 -0
- package/dist/schema/lex-map.js +60 -0
- package/dist/schema/lex-map.js.map +1 -0
- package/dist/schema/lex-value.d.ts +35 -0
- package/dist/schema/lex-value.d.ts.map +1 -0
- package/dist/schema/lex-value.js +87 -0
- package/dist/schema/lex-value.js.map +1 -0
- package/dist/schema/literal.d.ts +45 -0
- package/dist/schema/literal.d.ts.map +1 -1
- package/dist/schema/literal.js +45 -0
- package/dist/schema/literal.js.map +1 -1
- package/dist/schema/never.d.ts +43 -0
- package/dist/schema/never.d.ts.map +1 -1
- package/dist/schema/never.js +44 -1
- package/dist/schema/never.js.map +1 -1
- package/dist/schema/null.d.ts +30 -0
- package/dist/schema/null.d.ts.map +1 -1
- package/dist/schema/null.js +31 -1
- package/dist/schema/null.js.map +1 -1
- package/dist/schema/nullable.d.ts +42 -0
- package/dist/schema/nullable.d.ts.map +1 -1
- package/dist/schema/nullable.js +42 -0
- package/dist/schema/nullable.js.map +1 -1
- package/dist/schema/object.d.ts +57 -0
- package/dist/schema/object.d.ts.map +1 -1
- package/dist/schema/object.js +53 -1
- package/dist/schema/object.js.map +1 -1
- package/dist/schema/optional.d.ts +43 -0
- package/dist/schema/optional.d.ts.map +1 -1
- package/dist/schema/optional.js +43 -0
- package/dist/schema/optional.js.map +1 -1
- package/dist/schema/params.d.ts +96 -12
- package/dist/schema/params.d.ts.map +1 -1
- package/dist/schema/params.js +155 -21
- package/dist/schema/params.js.map +1 -1
- package/dist/schema/payload.d.ts +111 -15
- package/dist/schema/payload.d.ts.map +1 -1
- package/dist/schema/payload.js +73 -3
- package/dist/schema/payload.js.map +1 -1
- package/dist/schema/permission-set.d.ts +58 -0
- package/dist/schema/permission-set.d.ts.map +1 -1
- package/dist/schema/permission-set.js +50 -0
- package/dist/schema/permission-set.js.map +1 -1
- package/dist/schema/permission.d.ts +42 -0
- package/dist/schema/permission.d.ts.map +1 -1
- package/dist/schema/permission.js +39 -0
- package/dist/schema/permission.js.map +1 -1
- package/dist/schema/procedure.d.ts +64 -0
- package/dist/schema/procedure.d.ts.map +1 -1
- package/dist/schema/procedure.js +64 -0
- package/dist/schema/procedure.js.map +1 -1
- package/dist/schema/query.d.ts +55 -0
- package/dist/schema/query.d.ts.map +1 -1
- package/dist/schema/query.js +55 -0
- package/dist/schema/query.js.map +1 -1
- package/dist/schema/record.d.ts +76 -25
- package/dist/schema/record.d.ts.map +1 -1
- package/dist/schema/record.js +21 -0
- package/dist/schema/record.js.map +1 -1
- package/dist/schema/ref.d.ts +51 -0
- package/dist/schema/ref.d.ts.map +1 -1
- package/dist/schema/ref.js +18 -0
- package/dist/schema/ref.js.map +1 -1
- package/dist/schema/refine.d.ts +58 -9
- package/dist/schema/refine.d.ts.map +1 -1
- package/dist/schema/refine.js.map +1 -1
- package/dist/schema/regexp.d.ts +45 -0
- package/dist/schema/regexp.d.ts.map +1 -1
- package/dist/schema/regexp.js +46 -1
- package/dist/schema/regexp.js.map +1 -1
- package/dist/schema/string.d.ts +72 -6
- package/dist/schema/string.d.ts.map +1 -1
- package/dist/schema/string.js +56 -8
- package/dist/schema/string.js.map +1 -1
- package/dist/schema/subscription.d.ts +72 -2
- package/dist/schema/subscription.d.ts.map +1 -1
- package/dist/schema/subscription.js +59 -0
- package/dist/schema/subscription.js.map +1 -1
- package/dist/schema/token.d.ts +48 -0
- package/dist/schema/token.d.ts.map +1 -1
- package/dist/schema/token.js +49 -1
- package/dist/schema/token.js.map +1 -1
- package/dist/schema/typed-object.d.ts +73 -23
- package/dist/schema/typed-object.d.ts.map +1 -1
- package/dist/schema/typed-object.js +20 -1
- package/dist/schema/typed-object.js.map +1 -1
- package/dist/schema/typed-ref.d.ts +54 -0
- package/dist/schema/typed-ref.d.ts.map +1 -1
- package/dist/schema/typed-ref.js +16 -0
- package/dist/schema/typed-ref.js.map +1 -1
- package/dist/schema/typed-union.d.ts +51 -1
- package/dist/schema/typed-union.d.ts.map +1 -1
- package/dist/schema/typed-union.js +52 -2
- package/dist/schema/typed-union.js.map +1 -1
- package/dist/schema/union.d.ts +46 -0
- package/dist/schema/union.d.ts.map +1 -1
- package/dist/schema/union.js +41 -0
- package/dist/schema/union.js.map +1 -1
- package/dist/schema/unknown.d.ts +34 -0
- package/dist/schema/unknown.d.ts.map +1 -1
- package/dist/schema/unknown.js +34 -0
- package/dist/schema/unknown.js.map +1 -1
- package/dist/schema/with-default.d.ts +45 -0
- package/dist/schema/with-default.d.ts.map +1 -1
- package/dist/schema/with-default.js +45 -0
- package/dist/schema/with-default.js.map +1 -1
- package/dist/schema.d.ts +2 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +2 -1
- package/dist/schema.js.map +1 -1
- package/dist/util/if-any.d.ts +2 -0
- package/dist/util/if-any.d.ts.map +1 -0
- package/dist/util/if-any.js +3 -0
- package/dist/util/if-any.js.map +1 -0
- package/package.json +3 -3
- package/src/core/$type.ts +150 -18
- package/src/core/record-key.ts +44 -0
- package/src/core/result.ts +86 -4
- package/src/core/schema.ts +244 -9
- package/src/core/string-format.ts +259 -13
- package/src/core/types.ts +91 -3
- package/src/core/validation-error.ts +60 -0
- package/src/core/validation-issue.ts +68 -2
- package/src/core/validator.ts +373 -12
- package/src/helpers.test.ts +110 -29
- package/src/helpers.ts +54 -25
- package/src/schema/array.test.ts +94 -79
- package/src/schema/array.ts +48 -1
- package/src/schema/blob.ts +50 -1
- package/src/schema/boolean.ts +31 -1
- package/src/schema/bytes.ts +41 -1
- package/src/schema/cid.ts +41 -1
- package/src/schema/custom.ts +68 -1
- package/src/schema/dict.ts +47 -1
- package/src/schema/discriminated-union.ts +61 -1
- package/src/schema/enum.ts +50 -0
- package/src/schema/integer.ts +45 -1
- package/src/schema/intersection.ts +56 -0
- package/src/schema/{unknown-object.test.ts → lex-map.test.ts} +9 -9
- package/src/schema/lex-map.ts +63 -0
- package/src/schema/lex-value.test.ts +81 -0
- package/src/schema/lex-value.ts +86 -0
- package/src/schema/literal.ts +46 -0
- package/src/schema/never.ts +45 -1
- package/src/schema/null.ts +32 -1
- package/src/schema/nullable.ts +43 -0
- package/src/schema/object.ts +59 -1
- package/src/schema/optional.ts +44 -0
- package/src/schema/params.test.ts +133 -38
- package/src/schema/params.ts +237 -37
- package/src/schema/payload.test.ts +3 -3
- package/src/schema/payload.ts +145 -42
- package/src/schema/permission-set.ts +58 -0
- package/src/schema/permission.ts +42 -0
- package/src/schema/procedure.ts +64 -0
- package/src/schema/query.ts +55 -0
- package/src/schema/record.ts +82 -16
- package/src/schema/ref.ts +52 -0
- package/src/schema/refine.ts +58 -9
- package/src/schema/regexp.ts +47 -1
- package/src/schema/string.test.ts +99 -2
- package/src/schema/string.ts +108 -15
- package/src/schema/subscription.ts +72 -2
- package/src/schema/token.ts +50 -1
- package/src/schema/typed-object.ts +81 -16
- package/src/schema/typed-ref.ts +55 -0
- package/src/schema/typed-union.ts +58 -3
- package/src/schema/union.ts +47 -0
- package/src/schema/unknown.ts +35 -0
- package/src/schema/with-default.ts +46 -0
- package/src/schema.ts +2 -1
- package/src/util/if-any.ts +3 -0
- package/dist/schema/unknown-object.d.ts +0 -8
- package/dist/schema/unknown-object.d.ts.map +0 -1
- package/dist/schema/unknown-object.js +0 -19
- package/dist/schema/unknown-object.js.map +0 -1
- package/src/schema/unknown-object.ts +0 -19
package/dist/schema/custom.js
CHANGED
|
@@ -3,10 +3,28 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.CustomSchema = void 0;
|
|
4
4
|
exports.custom = custom;
|
|
5
5
|
const core_js_1 = require("../core.js");
|
|
6
|
+
/**
|
|
7
|
+
* Schema with a custom validation function.
|
|
8
|
+
*
|
|
9
|
+
* Allows defining completely custom validation logic using a type guard
|
|
10
|
+
* assertion function. The function receives the input and validation context,
|
|
11
|
+
* and must return whether the input is valid.
|
|
12
|
+
*
|
|
13
|
+
* @template TValue - The validated output type
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* const schema = new CustomSchema(
|
|
18
|
+
* (input): input is Date => input instanceof Date,
|
|
19
|
+
* 'Expected a Date instance'
|
|
20
|
+
* )
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
6
23
|
class CustomSchema extends core_js_1.Schema {
|
|
7
24
|
assertion;
|
|
8
25
|
message;
|
|
9
26
|
path;
|
|
27
|
+
type = 'custom';
|
|
10
28
|
constructor(assertion, message, path) {
|
|
11
29
|
super();
|
|
12
30
|
this.assertion = assertion;
|
|
@@ -22,6 +40,43 @@ class CustomSchema extends core_js_1.Schema {
|
|
|
22
40
|
}
|
|
23
41
|
}
|
|
24
42
|
exports.CustomSchema = CustomSchema;
|
|
43
|
+
/**
|
|
44
|
+
* Creates a custom schema with a user-defined validation function.
|
|
45
|
+
*
|
|
46
|
+
* Use this when the built-in schemas don't cover your validation needs.
|
|
47
|
+
* The assertion function must be a type guard that narrows the input type.
|
|
48
|
+
*
|
|
49
|
+
* @param assertion - Type guard function that validates the input
|
|
50
|
+
* @param message - Error message when validation fails
|
|
51
|
+
* @param path - Optional path to associate with validation errors
|
|
52
|
+
* @returns A new {@link CustomSchema} instance
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```ts
|
|
56
|
+
* // Validate Date instances
|
|
57
|
+
* const dateSchema = l.custom(
|
|
58
|
+
* (input): input is Date => input instanceof Date && !isNaN(input.getTime()),
|
|
59
|
+
* 'Expected a valid Date'
|
|
60
|
+
* )
|
|
61
|
+
*
|
|
62
|
+
* // Validate specific object shape
|
|
63
|
+
* const pointSchema = l.custom(
|
|
64
|
+
* (input): input is { x: number; y: number } =>
|
|
65
|
+
* typeof input === 'object' &&
|
|
66
|
+
* input !== null &&
|
|
67
|
+
* typeof (input as any).x === 'number' &&
|
|
68
|
+
* typeof (input as any).y === 'number',
|
|
69
|
+
* 'Expected a point with x and y coordinates'
|
|
70
|
+
* )
|
|
71
|
+
*
|
|
72
|
+
* // With custom path
|
|
73
|
+
* const validConfig = l.custom(
|
|
74
|
+
* (input): input is Config => validateConfig(input),
|
|
75
|
+
* 'Invalid configuration',
|
|
76
|
+
* ['config']
|
|
77
|
+
* )
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
25
80
|
/*@__NO_SIDE_EFFECTS__*/
|
|
26
81
|
function custom(assertion, message, path) {
|
|
27
82
|
return new CustomSchema(assertion, message, path);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom.js","sourceRoot":"","sources":["../../src/schema/custom.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"custom.js","sourceRoot":"","sources":["../../src/schema/custom.ts"],"names":[],"mappings":";;;AAyGA,wBAMC;AA/GD,wCAMmB;AAwBnB;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,YAAmC,SAAQ,gBAAc;IAIjD;IACA;IACA;IALV,IAAI,GAAG,QAAiB,CAAA;IAEjC,YACmB,SAAkC,EAClC,OAAe,EACf,IAA2C;QAE5D,KAAK,EAAE,CAAA;QAJU,cAAS,GAAT,SAAS,CAAyB;QAClC,YAAO,GAAP,OAAO,CAAQ;QACf,SAAI,GAAJ,IAAI,CAAuC;IAG9D,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,EAAE,CAAC;YAC3C,MAAM,IAAI,GAAG,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;YACtC,OAAO,GAAG,CAAC,KAAK,CAAC,IAAI,qBAAW,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAA;QAC9D,CAAC;QACD,OAAO,GAAG,CAAC,OAAO,CAAC,KAAe,CAAC,CAAA;IACrC,CAAC;CACF;AAlBD,oCAkBC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,wBAAwB;AACxB,SAAgB,MAAM,CACpB,SAAkC,EAClC,OAAe,EACf,IAA2C;IAE3C,OAAO,IAAI,YAAY,CAAS,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,CAAA;AAC3D,CAAC","sourcesContent":["import {\n Issue,\n IssueCustom,\n PropertyKey,\n Schema,\n ValidationContext,\n} from '../core.js'\n\n/**\n * Context object provided to custom assertion functions.\n *\n * @property path - Current validation path as an array of property keys\n * @property addIssue - Function to add additional validation issues\n */\nexport type CustomAssertionContext = {\n path: PropertyKey[]\n addIssue(issue: Issue): void\n}\n\n/**\n * Type guard function for custom schema validation.\n *\n * @template TValue - The type to validate/narrow to\n */\nexport type CustomAssertion<TValue> = (\n this: null,\n input: unknown,\n ctx: CustomAssertionContext,\n) => input is TValue\n\n/**\n * Schema with a custom validation function.\n *\n * Allows defining completely custom validation logic using a type guard\n * assertion function. The function receives the input and validation context,\n * and must return whether the input is valid.\n *\n * @template TValue - The validated output type\n *\n * @example\n * ```ts\n * const schema = new CustomSchema(\n * (input): input is Date => input instanceof Date,\n * 'Expected a Date instance'\n * )\n * ```\n */\nexport class CustomSchema<out TValue = unknown> extends Schema<TValue> {\n readonly type = 'custom' as const\n\n constructor(\n private readonly assertion: CustomAssertion<TValue>,\n private readonly message: string,\n private readonly path?: PropertyKey | readonly PropertyKey[],\n ) {\n super()\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!this.assertion.call(null, input, ctx)) {\n const path = ctx.concatPath(this.path)\n return ctx.issue(new IssueCustom(path, input, this.message))\n }\n return ctx.success(input as TValue)\n }\n}\n\n/**\n * Creates a custom schema with a user-defined validation function.\n *\n * Use this when the built-in schemas don't cover your validation needs.\n * The assertion function must be a type guard that narrows the input type.\n *\n * @param assertion - Type guard function that validates the input\n * @param message - Error message when validation fails\n * @param path - Optional path to associate with validation errors\n * @returns A new {@link CustomSchema} instance\n *\n * @example\n * ```ts\n * // Validate Date instances\n * const dateSchema = l.custom(\n * (input): input is Date => input instanceof Date && !isNaN(input.getTime()),\n * 'Expected a valid Date'\n * )\n *\n * // Validate specific object shape\n * const pointSchema = l.custom(\n * (input): input is { x: number; y: number } =>\n * typeof input === 'object' &&\n * input !== null &&\n * typeof (input as any).x === 'number' &&\n * typeof (input as any).y === 'number',\n * 'Expected a point with x and y coordinates'\n * )\n *\n * // With custom path\n * const validConfig = l.custom(\n * (input): input is Config => validateConfig(input),\n * 'Invalid configuration',\n * ['config']\n * )\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function custom<TValue>(\n assertion: CustomAssertion<TValue>,\n message: string,\n path?: PropertyKey | readonly PropertyKey[],\n) {\n return new CustomSchema<TValue>(assertion, message, path)\n}\n"]}
|
package/dist/schema/dict.d.ts
CHANGED
|
@@ -1,12 +1,28 @@
|
|
|
1
1
|
import { InferInput, InferOutput, Schema, ValidationContext, Validator } from '../core.js';
|
|
2
2
|
/**
|
|
3
|
+
* Schema for validating dictionary/map-like objects with dynamic keys.
|
|
4
|
+
*
|
|
5
|
+
* Unlike `ObjectSchema` which validates a fixed set of properties, `DictSchema`
|
|
6
|
+
* validates objects where any string key is allowed, with both keys and values
|
|
7
|
+
* validated against their respective schemas.
|
|
8
|
+
*
|
|
3
9
|
* @note There is no dictionary in Lexicon schemas. This is a custom extension
|
|
4
10
|
* to allow map-like objects when using the lex library programmatically (i.e.
|
|
5
11
|
* not code generated from a lexicon schema).
|
|
12
|
+
*
|
|
13
|
+
* @template TKey - The validator type for dictionary keys (must validate strings)
|
|
14
|
+
* @template TValue - The validator type for dictionary values
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* const schema = new DictSchema(l.string(), l.integer())
|
|
19
|
+
* const result = schema.validate({ a: 1, b: 2, c: 3 })
|
|
20
|
+
* ```
|
|
6
21
|
*/
|
|
7
22
|
export declare class DictSchema<const TKey extends Validator<string> = any, const TValue extends Validator = any> extends Schema<Record<InferInput<TKey>, InferInput<TValue>>, Record<InferInput<TKey>, InferOutput<TValue>>> {
|
|
8
23
|
readonly keySchema: TKey;
|
|
9
24
|
readonly valueSchema: TValue;
|
|
25
|
+
readonly type: "dict";
|
|
10
26
|
constructor(keySchema: TKey, valueSchema: TValue);
|
|
11
27
|
validateInContext(input: unknown, ctx: ValidationContext, options?: {
|
|
12
28
|
ignoredKeys?: {
|
|
@@ -14,5 +30,34 @@ export declare class DictSchema<const TKey extends Validator<string> = any, cons
|
|
|
14
30
|
};
|
|
15
31
|
}): import("../core.js").ValidationResult<Record<string, unknown>>;
|
|
16
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* Creates a dictionary schema for validating map-like objects.
|
|
35
|
+
*
|
|
36
|
+
* Validates objects where all keys match the key schema and all values
|
|
37
|
+
* match the value schema. Useful for dynamic key-value mappings.
|
|
38
|
+
*
|
|
39
|
+
* @param key - Schema to validate each key (must be a string validator)
|
|
40
|
+
* @param value - Schema to validate each value
|
|
41
|
+
* @returns A new {@link DictSchema} instance
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* // String to number mapping
|
|
46
|
+
* const scoresSchema = l.dict(l.string(), l.integer())
|
|
47
|
+
* scoresSchema.parse({ alice: 100, bob: 85 })
|
|
48
|
+
*
|
|
49
|
+
* // Constrained keys
|
|
50
|
+
* const langSchema = l.dict(
|
|
51
|
+
* l.string({ minLength: 2, maxLength: 5 }), // Language codes
|
|
52
|
+
* l.string() // Translations
|
|
53
|
+
* )
|
|
54
|
+
*
|
|
55
|
+
* // Complex values
|
|
56
|
+
* const usersById = l.dict(
|
|
57
|
+
* l.string({ format: 'did' }),
|
|
58
|
+
* l.object({ name: l.string(), age: l.integer() })
|
|
59
|
+
* )
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
17
62
|
export declare function dict<const TKey extends Validator<string>, const TValue extends Validator>(key: TKey, value: TValue): DictSchema<TKey, TValue>;
|
|
18
63
|
//# sourceMappingURL=dict.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dict.d.ts","sourceRoot":"","sources":["../../src/schema/dict.ts"],"names":[],"mappings":"AACA,OAAO,EACL,UAAU,EACV,WAAW,EACX,MAAM,EACN,iBAAiB,EACjB,SAAS,EACV,MAAM,YAAY,CAAA;AAEnB
|
|
1
|
+
{"version":3,"file":"dict.d.ts","sourceRoot":"","sources":["../../src/schema/dict.ts"],"names":[],"mappings":"AACA,OAAO,EACL,UAAU,EACV,WAAW,EACX,MAAM,EACN,iBAAiB,EACjB,SAAS,EACV,MAAM,YAAY,CAAA;AAEnB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,UAAU,CACrB,KAAK,CAAC,IAAI,SAAS,SAAS,CAAC,MAAM,CAAC,GAAG,GAAG,EAC1C,KAAK,CAAC,MAAM,SAAS,SAAS,GAAG,GAAG,CACpC,SAAQ,MAAM,CACd,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC,EAC5C,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC,CAC9C;IAIG,QAAQ,CAAC,SAAS,EAAE,IAAI;IACxB,QAAQ,CAAC,WAAW,EAAE,MAAM;IAJ9B,QAAQ,CAAC,IAAI,EAAG,MAAM,CAAS;gBAGpB,SAAS,EAAE,IAAI,EACf,WAAW,EAAE,MAAM;IAK9B,iBAAiB,CACf,KAAK,EAAE,OAAO,EACd,GAAG,EAAE,iBAAiB,EACtB,OAAO,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE;YAAE,GAAG,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;SAAE,CAAA;KAAE;CAoC1D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,wBAAgB,IAAI,CAClB,KAAK,CAAC,IAAI,SAAS,SAAS,CAAC,MAAM,CAAC,EACpC,KAAK,CAAC,MAAM,SAAS,SAAS,EAC9B,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,4BAEzB"}
|
package/dist/schema/dict.js
CHANGED
|
@@ -5,13 +5,29 @@ exports.dict = dict;
|
|
|
5
5
|
const lex_data_1 = require("@atproto/lex-data");
|
|
6
6
|
const core_js_1 = require("../core.js");
|
|
7
7
|
/**
|
|
8
|
+
* Schema for validating dictionary/map-like objects with dynamic keys.
|
|
9
|
+
*
|
|
10
|
+
* Unlike `ObjectSchema` which validates a fixed set of properties, `DictSchema`
|
|
11
|
+
* validates objects where any string key is allowed, with both keys and values
|
|
12
|
+
* validated against their respective schemas.
|
|
13
|
+
*
|
|
8
14
|
* @note There is no dictionary in Lexicon schemas. This is a custom extension
|
|
9
15
|
* to allow map-like objects when using the lex library programmatically (i.e.
|
|
10
16
|
* not code generated from a lexicon schema).
|
|
17
|
+
*
|
|
18
|
+
* @template TKey - The validator type for dictionary keys (must validate strings)
|
|
19
|
+
* @template TValue - The validator type for dictionary values
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* const schema = new DictSchema(l.string(), l.integer())
|
|
24
|
+
* const result = schema.validate({ a: 1, b: 2, c: 3 })
|
|
25
|
+
* ```
|
|
11
26
|
*/
|
|
12
27
|
class DictSchema extends core_js_1.Schema {
|
|
13
28
|
keySchema;
|
|
14
29
|
valueSchema;
|
|
30
|
+
type = 'dict';
|
|
15
31
|
constructor(keySchema, valueSchema) {
|
|
16
32
|
super();
|
|
17
33
|
this.keySchema = keySchema;
|
|
@@ -19,7 +35,7 @@ class DictSchema extends core_js_1.Schema {
|
|
|
19
35
|
}
|
|
20
36
|
validateInContext(input, ctx, options) {
|
|
21
37
|
if (!(0, lex_data_1.isPlainObject)(input)) {
|
|
22
|
-
return ctx.
|
|
38
|
+
return ctx.issueUnexpectedType(input, 'dict');
|
|
23
39
|
}
|
|
24
40
|
let copy;
|
|
25
41
|
for (const key in input) {
|
|
@@ -50,6 +66,35 @@ class DictSchema extends core_js_1.Schema {
|
|
|
50
66
|
}
|
|
51
67
|
}
|
|
52
68
|
exports.DictSchema = DictSchema;
|
|
69
|
+
/**
|
|
70
|
+
* Creates a dictionary schema for validating map-like objects.
|
|
71
|
+
*
|
|
72
|
+
* Validates objects where all keys match the key schema and all values
|
|
73
|
+
* match the value schema. Useful for dynamic key-value mappings.
|
|
74
|
+
*
|
|
75
|
+
* @param key - Schema to validate each key (must be a string validator)
|
|
76
|
+
* @param value - Schema to validate each value
|
|
77
|
+
* @returns A new {@link DictSchema} instance
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* // String to number mapping
|
|
82
|
+
* const scoresSchema = l.dict(l.string(), l.integer())
|
|
83
|
+
* scoresSchema.parse({ alice: 100, bob: 85 })
|
|
84
|
+
*
|
|
85
|
+
* // Constrained keys
|
|
86
|
+
* const langSchema = l.dict(
|
|
87
|
+
* l.string({ minLength: 2, maxLength: 5 }), // Language codes
|
|
88
|
+
* l.string() // Translations
|
|
89
|
+
* )
|
|
90
|
+
*
|
|
91
|
+
* // Complex values
|
|
92
|
+
* const usersById = l.dict(
|
|
93
|
+
* l.string({ format: 'did' }),
|
|
94
|
+
* l.object({ name: l.string(), age: l.integer() })
|
|
95
|
+
* )
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
53
98
|
/*@__NO_SIDE_EFFECTS__*/
|
|
54
99
|
function dict(key, value) {
|
|
55
100
|
return new DictSchema(key, value);
|
package/dist/schema/dict.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dict.js","sourceRoot":"","sources":["../../src/schema/dict.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"dict.js","sourceRoot":"","sources":["../../src/schema/dict.ts"],"names":[],"mappings":";;;AAoHA,oBAKC;AAzHD,gDAAiD;AACjD,wCAMmB;AAEnB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAa,UAGX,SAAQ,gBAGT;IAIY;IACA;IAJF,IAAI,GAAG,MAAe,CAAA;IAE/B,YACW,SAAe,EACf,WAAmB;QAE5B,KAAK,EAAE,CAAA;QAHE,cAAS,GAAT,SAAS,CAAM;QACf,gBAAW,GAAX,WAAW,CAAQ;IAG9B,CAAC;IAED,iBAAiB,CACf,KAAc,EACd,GAAsB,EACtB,OAAuD;QAEvD,IAAI,CAAC,IAAA,wBAAa,EAAC,KAAK,CAAC,EAAE,CAAC;YAC1B,OAAO,GAAG,CAAC,mBAAmB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;QAC/C,CAAC;QAED,IAAI,IAAyC,CAAA;QAE7C,KAAK,MAAM,GAAG,IAAI,KAAK,EAAE,CAAC;YACxB,IAAI,OAAO,EAAE,WAAW,EAAE,GAAG,CAAC,GAAG,CAAC;gBAAE,SAAQ;YAE5C,MAAM,SAAS,GAAG,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,CAAA;YACnD,IAAI,CAAC,SAAS,CAAC,OAAO;gBAAE,OAAO,SAAS,CAAA;YACxC,IAAI,SAAS,CAAC,KAAK,KAAK,GAAG,EAAE,CAAC;gBAC5B,mEAAmE;gBACnE,uEAAuE;gBACvE,6DAA6D;gBAC7D,OAAO,GAAG,CAAC,gBAAgB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAA;YACzC,CAAC;YAED,MAAM,WAAW,GAAG,GAAG,CAAC,aAAa,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,CAAA;YACnE,IAAI,CAAC,WAAW,CAAC,OAAO;gBAAE,OAAO,WAAW,CAAA;YAE5C,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;gBAC9C,IAAI,GAAG,CAAC,OAAO,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;oBACpC,sEAAsE;oBACtE,OAAO,GAAG,CAAC,yBAAyB,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAA;gBACvE,CAAC;gBAED,IAAI,KAAK,EAAE,GAAG,KAAK,EAAE,CAAA;gBACrB,IAAI,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC,KAAK,CAAA;YAC/B,CAAC;QACH,CAAC;QAED,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,IAAI,KAAK,CAAC,CAAA;IACnC,CAAC;CACF;AAvDD,gCAuDC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAwB;AACxB,SAAgB,IAAI,CAGlB,GAAS,EAAE,KAAa;IACxB,OAAO,IAAI,UAAU,CAAe,GAAG,EAAE,KAAK,CAAC,CAAA;AACjD,CAAC","sourcesContent":["import { isPlainObject } from '@atproto/lex-data'\nimport {\n InferInput,\n InferOutput,\n Schema,\n ValidationContext,\n Validator,\n} from '../core.js'\n\n/**\n * Schema for validating dictionary/map-like objects with dynamic keys.\n *\n * Unlike `ObjectSchema` which validates a fixed set of properties, `DictSchema`\n * validates objects where any string key is allowed, with both keys and values\n * validated against their respective schemas.\n *\n * @note There is no dictionary in Lexicon schemas. This is a custom extension\n * to allow map-like objects when using the lex library programmatically (i.e.\n * not code generated from a lexicon schema).\n *\n * @template TKey - The validator type for dictionary keys (must validate strings)\n * @template TValue - The validator type for dictionary values\n *\n * @example\n * ```ts\n * const schema = new DictSchema(l.string(), l.integer())\n * const result = schema.validate({ a: 1, b: 2, c: 3 })\n * ```\n */\nexport class DictSchema<\n const TKey extends Validator<string> = any,\n const TValue extends Validator = any,\n> extends Schema<\n Record<InferInput<TKey>, InferInput<TValue>>,\n Record<InferInput<TKey>, InferOutput<TValue>>\n> {\n readonly type = 'dict' as const\n\n constructor(\n readonly keySchema: TKey,\n readonly valueSchema: TValue,\n ) {\n super()\n }\n\n validateInContext(\n input: unknown,\n ctx: ValidationContext,\n options?: { ignoredKeys?: { has(k: string): boolean } },\n ) {\n if (!isPlainObject(input)) {\n return ctx.issueUnexpectedType(input, 'dict')\n }\n\n let copy: undefined | Record<string, unknown>\n\n for (const key in input) {\n if (options?.ignoredKeys?.has(key)) continue\n\n const keyResult = ctx.validate(key, this.keySchema)\n if (!keyResult.success) return keyResult\n if (keyResult.value !== key) {\n // We can't safely \"move\" the key to a different name in the output\n // object (because there may already be something there), so we issue a\n // \"required key\" error if the key validation changes the key\n return ctx.issueRequiredKey(input, key)\n }\n\n const valueResult = ctx.validateChild(input, key, this.valueSchema)\n if (!valueResult.success) return valueResult\n\n if (!Object.is(valueResult.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, [valueResult.value])\n }\n\n copy ??= { ...input }\n copy[key] = valueResult.value\n }\n }\n\n return ctx.success(copy ?? input)\n }\n}\n\n/**\n * Creates a dictionary schema for validating map-like objects.\n *\n * Validates objects where all keys match the key schema and all values\n * match the value schema. Useful for dynamic key-value mappings.\n *\n * @param key - Schema to validate each key (must be a string validator)\n * @param value - Schema to validate each value\n * @returns A new {@link DictSchema} instance\n *\n * @example\n * ```ts\n * // String to number mapping\n * const scoresSchema = l.dict(l.string(), l.integer())\n * scoresSchema.parse({ alice: 100, bob: 85 })\n *\n * // Constrained keys\n * const langSchema = l.dict(\n * l.string({ minLength: 2, maxLength: 5 }), // Language codes\n * l.string() // Translations\n * )\n *\n * // Complex values\n * const usersById = l.dict(\n * l.string({ format: 'did' }),\n * l.object({ name: l.string(), age: l.integer() })\n * )\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function dict<\n const TKey extends Validator<string>,\n const TValue extends Validator,\n>(key: TKey, value: TValue) {\n return new DictSchema<TKey, TValue>(key, value)\n}\n"]}
|
|
@@ -2,7 +2,20 @@ import { InferInput, InferOutput, Schema, ValidationContext, ValidationResult, V
|
|
|
2
2
|
import { EnumSchema } from './enum.js';
|
|
3
3
|
import { LiteralSchema } from './literal.js';
|
|
4
4
|
import { ObjectSchema } from './object.js';
|
|
5
|
+
/**
|
|
6
|
+
* Type representing a single variant in a discriminated union.
|
|
7
|
+
*
|
|
8
|
+
* Must be an ObjectSchema with the discriminator property using either
|
|
9
|
+
* a LiteralSchema or EnumSchema.
|
|
10
|
+
*
|
|
11
|
+
* @template Discriminator - The discriminator property name
|
|
12
|
+
*/
|
|
5
13
|
export type DiscriminatedUnionVariant<Discriminator extends string = string> = ObjectSchema<Record<Discriminator, EnumSchema<any> | LiteralSchema<any>>>;
|
|
14
|
+
/**
|
|
15
|
+
* Type representing a non-empty tuple of discriminated union variants.
|
|
16
|
+
*
|
|
17
|
+
* @template TDiscriminator - The discriminator property name
|
|
18
|
+
*/
|
|
6
19
|
export type DiscriminatedUnionVariants<TDiscriminator extends string> = readonly [
|
|
7
20
|
DiscriminatedUnionVariant<TDiscriminator>,
|
|
8
21
|
...DiscriminatedUnionVariant<TDiscriminator>[]
|
|
@@ -16,17 +29,63 @@ type DiscriminatedUnionSchemaOutput<TVariants extends readonly Validator[]> = TV
|
|
|
16
29
|
...infer TRest extends readonly Validator[]
|
|
17
30
|
] ? InferOutput<TValidator> | DiscriminatedUnionSchemaOutput<TRest> : never;
|
|
18
31
|
/**
|
|
32
|
+
* Schema for validating discriminated unions of objects.
|
|
33
|
+
*
|
|
34
|
+
* More efficient than regular union schemas when discriminating on a known
|
|
35
|
+
* property. Looks up the correct variant schema directly based on the
|
|
36
|
+
* discriminator value instead of trying each variant in sequence.
|
|
37
|
+
*
|
|
19
38
|
* @note There is no discriminated union in Lexicon schemas. This is a custom
|
|
20
39
|
* extension to allow optimized validation of union of objects when using the
|
|
21
40
|
* lex library programmatically (i.e. not code generated from a lexicon schema).
|
|
41
|
+
*
|
|
42
|
+
* @template TDiscriminator - The discriminator property name
|
|
43
|
+
* @template TVariants - Tuple type of the variant schemas
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* const schema = new DiscriminatedUnionSchema('type', [
|
|
48
|
+
* l.object({ type: l.literal('text'), content: l.string() }),
|
|
49
|
+
* l.object({ type: l.literal('image'), url: l.string() }),
|
|
50
|
+
* ])
|
|
51
|
+
* ```
|
|
22
52
|
*/
|
|
23
53
|
export declare class DiscriminatedUnionSchema<const TDiscriminator extends string, const TVariants extends DiscriminatedUnionVariants<TDiscriminator>> extends Schema<DiscriminatedUnionSchemaInput<TVariants>, DiscriminatedUnionSchemaOutput<TVariants>> {
|
|
24
54
|
readonly discriminator: TDiscriminator;
|
|
25
55
|
readonly variants: TVariants;
|
|
56
|
+
readonly type: "discriminatedUnion";
|
|
26
57
|
readonly variantsMap: Map<unknown, DiscriminatedUnionVariant<TDiscriminator>>;
|
|
27
58
|
constructor(discriminator: TDiscriminator, variants: TVariants);
|
|
28
59
|
validateInContext(input: unknown, ctx: ValidationContext): ValidationResult<DiscriminatedUnionSchemaInput<TVariants>>;
|
|
29
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Creates a discriminated union schema for efficient object type switching.
|
|
63
|
+
*
|
|
64
|
+
* Unlike regular `union()`, this schema uses a discriminator property to
|
|
65
|
+
* directly look up the correct variant, providing O(1) validation instead
|
|
66
|
+
* of trying each variant sequentially.
|
|
67
|
+
*
|
|
68
|
+
* @param discriminator - Property name to discriminate on
|
|
69
|
+
* @param variants - Non-empty array of object schemas with the discriminator property
|
|
70
|
+
* @returns A new {@link DiscriminatedUnionSchema} instance
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```ts
|
|
74
|
+
* // Message types discriminated by 'kind'
|
|
75
|
+
* const messageSchema = l.discriminatedUnion('kind', [
|
|
76
|
+
* l.object({ kind: l.literal('text'), text: l.string() }),
|
|
77
|
+
* l.object({ kind: l.literal('image'), url: l.string(), alt: l.optional(l.string()) }),
|
|
78
|
+
* l.object({ kind: l.literal('video'), url: l.string(), duration: l.integer() }),
|
|
79
|
+
* ])
|
|
80
|
+
*
|
|
81
|
+
* // Using enums for multiple values mapping to same variant
|
|
82
|
+
* const statusSchema = l.discriminatedUnion('status', [
|
|
83
|
+
* l.object({ status: l.enum(['pending', 'processing']), startedAt: l.string() }),
|
|
84
|
+
* l.object({ status: l.literal('completed'), completedAt: l.string() }),
|
|
85
|
+
* l.object({ status: l.literal('failed'), error: l.string() }),
|
|
86
|
+
* ])
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
30
89
|
export declare function discriminatedUnion<const Discriminator extends string, const Options extends DiscriminatedUnionVariants<Discriminator>>(discriminator: Discriminator, variants: Options): DiscriminatedUnionSchema<Discriminator, Options>;
|
|
31
90
|
export {};
|
|
32
91
|
//# sourceMappingURL=discriminated-union.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discriminated-union.d.ts","sourceRoot":"","sources":["../../src/schema/discriminated-union.ts"],"names":[],"mappings":"AACA,OAAO,EACL,UAAU,EACV,WAAW,EACX,MAAM,EACN,iBAAiB,EACjB,gBAAgB,EAChB,SAAS,EACV,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAE1C,MAAM,MAAM,yBAAyB,CAAC,aAAa,SAAS,MAAM,GAAG,MAAM,IACzE,YAAY,CAAC,MAAM,CAAC,aAAa,EAAE,UAAU,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;AAE3E,MAAM,MAAM,0BAA0B,CAAC,cAAc,SAAS,MAAM,IAClE,SAAS;IACP,yBAAyB,CAAC,cAAc,CAAC;IACzC,GAAG,yBAAyB,CAAC,cAAc,CAAC,EAAE;CAC/C,CAAA;AAEH,KAAK,6BAA6B,CAAC,SAAS,SAAS,SAAS,SAAS,EAAE,IACvE,SAAS,SAAS,SAAS;IACzB,MAAM,UAAU,SAAS,SAAS;IAClC,GAAG,MAAM,KAAK,SAAS,SAAS,SAAS,EAAE;CAC5C,GACG,UAAU,CAAC,UAAU,CAAC,GAAG,6BAA6B,CAAC,KAAK,CAAC,GAC7D,KAAK,CAAA;AAEX,KAAK,8BAA8B,CAAC,SAAS,SAAS,SAAS,SAAS,EAAE,IACxE,SAAS,SAAS,SAAS;IACzB,MAAM,UAAU,SAAS,SAAS;IAClC,GAAG,MAAM,KAAK,SAAS,SAAS,SAAS,EAAE;CAC5C,GACG,WAAW,CAAC,UAAU,CAAC,GAAG,8BAA8B,CAAC,KAAK,CAAC,GAC/D,KAAK,CAAA;AAEX
|
|
1
|
+
{"version":3,"file":"discriminated-union.d.ts","sourceRoot":"","sources":["../../src/schema/discriminated-union.ts"],"names":[],"mappings":"AACA,OAAO,EACL,UAAU,EACV,WAAW,EACX,MAAM,EACN,iBAAiB,EACjB,gBAAgB,EAChB,SAAS,EACV,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAE1C;;;;;;;GAOG;AACH,MAAM,MAAM,yBAAyB,CAAC,aAAa,SAAS,MAAM,GAAG,MAAM,IACzE,YAAY,CAAC,MAAM,CAAC,aAAa,EAAE,UAAU,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;AAE3E;;;;GAIG;AACH,MAAM,MAAM,0BAA0B,CAAC,cAAc,SAAS,MAAM,IAClE,SAAS;IACP,yBAAyB,CAAC,cAAc,CAAC;IACzC,GAAG,yBAAyB,CAAC,cAAc,CAAC,EAAE;CAC/C,CAAA;AAEH,KAAK,6BAA6B,CAAC,SAAS,SAAS,SAAS,SAAS,EAAE,IACvE,SAAS,SAAS,SAAS;IACzB,MAAM,UAAU,SAAS,SAAS;IAClC,GAAG,MAAM,KAAK,SAAS,SAAS,SAAS,EAAE;CAC5C,GACG,UAAU,CAAC,UAAU,CAAC,GAAG,6BAA6B,CAAC,KAAK,CAAC,GAC7D,KAAK,CAAA;AAEX,KAAK,8BAA8B,CAAC,SAAS,SAAS,SAAS,SAAS,EAAE,IACxE,SAAS,SAAS,SAAS;IACzB,MAAM,UAAU,SAAS,SAAS;IAClC,GAAG,MAAM,KAAK,SAAS,SAAS,SAAS,EAAE;CAC5C,GACG,WAAW,CAAC,UAAU,CAAC,GAAG,8BAA8B,CAAC,KAAK,CAAC,GAC/D,KAAK,CAAA;AAEX;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,wBAAwB,CACnC,KAAK,CAAC,cAAc,SAAS,MAAM,EACnC,KAAK,CAAC,SAAS,SAAS,0BAA0B,CAAC,cAAc,CAAC,CAClE,SAAQ,MAAM,CACd,6BAA6B,CAAC,SAAS,CAAC,EACxC,8BAA8B,CAAC,SAAS,CAAC,CAC1C;IAMG,QAAQ,CAAC,aAAa,EAAE,cAAc;IACtC,QAAQ,CAAC,QAAQ,EAAE,SAAS;IAN9B,QAAQ,CAAC,IAAI,EAAG,oBAAoB,CAAS;IAE7C,QAAQ,CAAC,WAAW,EAAE,GAAG,CAAC,OAAO,EAAE,yBAAyB,CAAC,cAAc,CAAC,CAAC,CAAA;gBAGlE,aAAa,EAAE,cAAc,EAC7B,QAAQ,EAAE,SAAS;IAU9B,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;CAwBzD;AAsCD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,wBAAgB,kBAAkB,CAChC,KAAK,CAAC,aAAa,SAAS,MAAM,EAClC,KAAK,CAAC,OAAO,SAAS,0BAA0B,CAAC,aAAa,CAAC,EAC/D,aAAa,EAAE,aAAa,EAAE,QAAQ,EAAE,OAAO,oDAKhD"}
|
|
@@ -7,13 +7,31 @@ const core_js_1 = require("../core.js");
|
|
|
7
7
|
const enum_js_1 = require("./enum.js");
|
|
8
8
|
const literal_js_1 = require("./literal.js");
|
|
9
9
|
/**
|
|
10
|
+
* Schema for validating discriminated unions of objects.
|
|
11
|
+
*
|
|
12
|
+
* More efficient than regular union schemas when discriminating on a known
|
|
13
|
+
* property. Looks up the correct variant schema directly based on the
|
|
14
|
+
* discriminator value instead of trying each variant in sequence.
|
|
15
|
+
*
|
|
10
16
|
* @note There is no discriminated union in Lexicon schemas. This is a custom
|
|
11
17
|
* extension to allow optimized validation of union of objects when using the
|
|
12
18
|
* lex library programmatically (i.e. not code generated from a lexicon schema).
|
|
19
|
+
*
|
|
20
|
+
* @template TDiscriminator - The discriminator property name
|
|
21
|
+
* @template TVariants - Tuple type of the variant schemas
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* const schema = new DiscriminatedUnionSchema('type', [
|
|
26
|
+
* l.object({ type: l.literal('text'), content: l.string() }),
|
|
27
|
+
* l.object({ type: l.literal('image'), url: l.string() }),
|
|
28
|
+
* ])
|
|
29
|
+
* ```
|
|
13
30
|
*/
|
|
14
31
|
class DiscriminatedUnionSchema extends core_js_1.Schema {
|
|
15
32
|
discriminator;
|
|
16
33
|
variants;
|
|
34
|
+
type = 'discriminatedUnion';
|
|
17
35
|
variantsMap;
|
|
18
36
|
constructor(discriminator, variants) {
|
|
19
37
|
super();
|
|
@@ -26,7 +44,7 @@ class DiscriminatedUnionSchema extends core_js_1.Schema {
|
|
|
26
44
|
}
|
|
27
45
|
validateInContext(input, ctx) {
|
|
28
46
|
if (!(0, lex_data_1.isPlainObject)(input)) {
|
|
29
|
-
return ctx.
|
|
47
|
+
return ctx.issueUnexpectedType(input, 'object');
|
|
30
48
|
}
|
|
31
49
|
const { discriminator } = this;
|
|
32
50
|
if (!Object.hasOwn(input, discriminator)) {
|
|
@@ -69,6 +87,34 @@ function buildVariantsMap(discriminator, variants) {
|
|
|
69
87
|
}
|
|
70
88
|
return variantsMap;
|
|
71
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Creates a discriminated union schema for efficient object type switching.
|
|
92
|
+
*
|
|
93
|
+
* Unlike regular `union()`, this schema uses a discriminator property to
|
|
94
|
+
* directly look up the correct variant, providing O(1) validation instead
|
|
95
|
+
* of trying each variant sequentially.
|
|
96
|
+
*
|
|
97
|
+
* @param discriminator - Property name to discriminate on
|
|
98
|
+
* @param variants - Non-empty array of object schemas with the discriminator property
|
|
99
|
+
* @returns A new {@link DiscriminatedUnionSchema} instance
|
|
100
|
+
*
|
|
101
|
+
* @example
|
|
102
|
+
* ```ts
|
|
103
|
+
* // Message types discriminated by 'kind'
|
|
104
|
+
* const messageSchema = l.discriminatedUnion('kind', [
|
|
105
|
+
* l.object({ kind: l.literal('text'), text: l.string() }),
|
|
106
|
+
* l.object({ kind: l.literal('image'), url: l.string(), alt: l.optional(l.string()) }),
|
|
107
|
+
* l.object({ kind: l.literal('video'), url: l.string(), duration: l.integer() }),
|
|
108
|
+
* ])
|
|
109
|
+
*
|
|
110
|
+
* // Using enums for multiple values mapping to same variant
|
|
111
|
+
* const statusSchema = l.discriminatedUnion('status', [
|
|
112
|
+
* l.object({ status: l.enum(['pending', 'processing']), startedAt: l.string() }),
|
|
113
|
+
* l.object({ status: l.literal('completed'), completedAt: l.string() }),
|
|
114
|
+
* l.object({ status: l.literal('failed'), error: l.string() }),
|
|
115
|
+
* ])
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
72
118
|
/*@__NO_SIDE_EFFECTS__*/
|
|
73
119
|
function discriminatedUnion(discriminator, variants) {
|
|
74
120
|
return new DiscriminatedUnionSchema(discriminator, variants);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discriminated-union.js","sourceRoot":"","sources":["../../src/schema/discriminated-union.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"discriminated-union.js","sourceRoot":"","sources":["../../src/schema/discriminated-union.ts"],"names":[],"mappings":";;;AA2LA,gDAQC;AAnMD,gDAAiD;AACjD,wCAOmB;AACnB,uCAAsC;AACtC,6CAA4C;AAyC5C;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAa,wBAGX,SAAQ,gBAGT;IAMY;IACA;IANF,IAAI,GAAG,oBAA6B,CAAA;IAEpC,WAAW,CAAyD;IAE7E,YACW,aAA6B,EAC7B,QAAmB;QAE5B,KAAK,EAAE,CAAA;QAHE,kBAAa,GAAb,aAAa,CAAgB;QAC7B,aAAQ,GAAR,QAAQ,CAAW;QAI5B,wEAAwE;QACxE,2EAA2E;QAC3E,8DAA8D;QAC9D,IAAI,CAAC,WAAW,GAAG,gBAAgB,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAA;IAC9D,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,IAAI,CAAC,IAAA,wBAAa,EAAC,KAAK,CAAC,EAAE,CAAC;YAC1B,OAAO,GAAG,CAAC,mBAAmB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;QACjD,CAAC;QAED,MAAM,EAAE,aAAa,EAAE,GAAG,IAAI,CAAA;QAE9B,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,aAAa,CAAC,EAAE,CAAC;YACzC,OAAO,GAAG,CAAC,gBAAgB,CAAC,KAAK,EAAE,aAAa,CAAC,CAAA;QACnD,CAAC;QAED,MAAM,kBAAkB,GAAG,KAAK,CAAC,aAAa,CAAC,CAAA;QAE/C,MAAM,OAAO,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAA;QACxD,IAAI,OAAO,EAAE,CAAC;YACZ,OAAO,GAAG,CAAC,QAAQ,CAAC,KAAK,EAAE,OAAO,CAEjC,CAAA;QACH,CAAC;QAED,OAAO,GAAG,CAAC,yBAAyB,CAAC,KAAK,EAAE,aAAa,EAAE;YACzD,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE;SAC3B,CAAC,CAAA;IACJ,CAAC;CACF;AA/CD,4DA+CC;AAED,SAAS,gBAAgB,CACvB,aAA4B,EAC5B,QAAmD;IAEnD,MAAM,WAAW,GAAG,IAAI,GAAG,EAGxB,CAAA;IAEH,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,aAAa,CAAC,CAAA;QAC3C,IAAI,MAAM,YAAY,0BAAa,EAAE,CAAC;YACpC,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;gBAClC,MAAM,IAAI,SAAS,CAAC,oCAAoC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAA;YACzE,CAAC;YACD,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;QACxC,CAAC;aAAM,IAAI,MAAM,YAAY,oBAAU,EAAE,CAAC;YACxC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;gBAChC,IAAI,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;oBACzB,MAAM,IAAI,SAAS,CAAC,oCAAoC,GAAG,EAAE,CAAC,CAAA;gBAChE,CAAC;gBACD,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;YAC/B,CAAC;QACH,CAAC;aAAM,CAAC;YACN,sDAAsD;YAEtD,kDAAkD;YAClD,MAAM,IAAI,SAAS,CACjB,4DAA4D,CAC7D,CAAA;QACH,CAAC;IACH,CAAC;IAED,OAAO,WAAW,CAAA;AACpB,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAwB;AACxB,SAAgB,kBAAkB,CAGhC,aAA4B,EAAE,QAAiB;IAC/C,OAAO,IAAI,wBAAwB,CACjC,aAAa,EACb,QAAQ,CACT,CAAA;AACH,CAAC","sourcesContent":["import { isPlainObject } from '@atproto/lex-data'\nimport {\n InferInput,\n InferOutput,\n Schema,\n ValidationContext,\n ValidationResult,\n Validator,\n} from '../core.js'\nimport { EnumSchema } from './enum.js'\nimport { LiteralSchema } from './literal.js'\nimport { ObjectSchema } from './object.js'\n\n/**\n * Type representing a single variant in a discriminated union.\n *\n * Must be an ObjectSchema with the discriminator property using either\n * a LiteralSchema or EnumSchema.\n *\n * @template Discriminator - The discriminator property name\n */\nexport type DiscriminatedUnionVariant<Discriminator extends string = string> =\n ObjectSchema<Record<Discriminator, EnumSchema<any> | LiteralSchema<any>>>\n\n/**\n * Type representing a non-empty tuple of discriminated union variants.\n *\n * @template TDiscriminator - The discriminator property name\n */\nexport type DiscriminatedUnionVariants<TDiscriminator extends string> =\n readonly [\n DiscriminatedUnionVariant<TDiscriminator>,\n ...DiscriminatedUnionVariant<TDiscriminator>[],\n ]\n\ntype DiscriminatedUnionSchemaInput<TVariants extends readonly Validator[]> =\n TVariants extends readonly [\n infer TValidator extends Validator,\n ...infer TRest extends readonly Validator[],\n ]\n ? InferInput<TValidator> | DiscriminatedUnionSchemaInput<TRest>\n : never\n\ntype DiscriminatedUnionSchemaOutput<TVariants extends readonly Validator[]> =\n TVariants extends readonly [\n infer TValidator extends Validator,\n ...infer TRest extends readonly Validator[],\n ]\n ? InferOutput<TValidator> | DiscriminatedUnionSchemaOutput<TRest>\n : never\n\n/**\n * Schema for validating discriminated unions of objects.\n *\n * More efficient than regular union schemas when discriminating on a known\n * property. Looks up the correct variant schema directly based on the\n * discriminator value instead of trying each variant in sequence.\n *\n * @note There is no discriminated union in Lexicon schemas. This is a custom\n * extension to allow optimized validation of union of objects when using the\n * lex library programmatically (i.e. not code generated from a lexicon schema).\n *\n * @template TDiscriminator - The discriminator property name\n * @template TVariants - Tuple type of the variant schemas\n *\n * @example\n * ```ts\n * const schema = new DiscriminatedUnionSchema('type', [\n * l.object({ type: l.literal('text'), content: l.string() }),\n * l.object({ type: l.literal('image'), url: l.string() }),\n * ])\n * ```\n */\nexport class DiscriminatedUnionSchema<\n const TDiscriminator extends string,\n const TVariants extends DiscriminatedUnionVariants<TDiscriminator>,\n> extends Schema<\n DiscriminatedUnionSchemaInput<TVariants>,\n DiscriminatedUnionSchemaOutput<TVariants>\n> {\n readonly type = 'discriminatedUnion' as const\n\n readonly variantsMap: Map<unknown, DiscriminatedUnionVariant<TDiscriminator>>\n\n constructor(\n readonly discriminator: TDiscriminator,\n readonly variants: TVariants,\n ) {\n super()\n\n // Although we usually try to avoid initialization work in constructors,\n // here it is necessary to ensure that invalid discriminated throw from the\n // place of construction, rather than later during validation.\n this.variantsMap = buildVariantsMap(discriminator, variants)\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!isPlainObject(input)) {\n return ctx.issueUnexpectedType(input, 'object')\n }\n\n const { discriminator } = this\n\n if (!Object.hasOwn(input, discriminator)) {\n return ctx.issueRequiredKey(input, discriminator)\n }\n\n const discriminatorValue = input[discriminator]\n\n const variant = this.variantsMap.get(discriminatorValue)\n if (variant) {\n return ctx.validate(input, variant) as ValidationResult<\n DiscriminatedUnionSchemaInput<TVariants>\n >\n }\n\n return ctx.issueInvalidPropertyValue(input, discriminator, [\n ...this.variantsMap.keys(),\n ])\n }\n}\n\nfunction buildVariantsMap<Discriminator extends string>(\n discriminator: Discriminator,\n variants: DiscriminatedUnionVariants<Discriminator>,\n) {\n const variantsMap = new Map<\n unknown,\n DiscriminatedUnionVariant<Discriminator>\n >()\n\n for (const variant of variants) {\n const schema = variant.shape[discriminator]\n if (schema instanceof LiteralSchema) {\n if (variantsMap.has(schema.value)) {\n throw new TypeError(`Overlapping discriminator value: ${schema.value}`)\n }\n variantsMap.set(schema.value, variant)\n } else if (schema instanceof EnumSchema) {\n for (const val of schema.values) {\n if (variantsMap.has(val)) {\n throw new TypeError(`Overlapping discriminator value: ${val}`)\n }\n variantsMap.set(val, variant)\n }\n } else {\n // Only enumerable discriminator schemas are supported\n\n // Should never happen if types are used correctly\n throw new TypeError(\n `Discriminator schema must be a LiteralSchema or EnumSchema`,\n )\n }\n }\n\n return variantsMap\n}\n\n/**\n * Creates a discriminated union schema for efficient object type switching.\n *\n * Unlike regular `union()`, this schema uses a discriminator property to\n * directly look up the correct variant, providing O(1) validation instead\n * of trying each variant sequentially.\n *\n * @param discriminator - Property name to discriminate on\n * @param variants - Non-empty array of object schemas with the discriminator property\n * @returns A new {@link DiscriminatedUnionSchema} instance\n *\n * @example\n * ```ts\n * // Message types discriminated by 'kind'\n * const messageSchema = l.discriminatedUnion('kind', [\n * l.object({ kind: l.literal('text'), text: l.string() }),\n * l.object({ kind: l.literal('image'), url: l.string(), alt: l.optional(l.string()) }),\n * l.object({ kind: l.literal('video'), url: l.string(), duration: l.integer() }),\n * ])\n *\n * // Using enums for multiple values mapping to same variant\n * const statusSchema = l.discriminatedUnion('status', [\n * l.object({ status: l.enum(['pending', 'processing']), startedAt: l.string() }),\n * l.object({ status: l.literal('completed'), completedAt: l.string() }),\n * l.object({ status: l.literal('failed'), error: l.string() }),\n * ])\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function discriminatedUnion<\n const Discriminator extends string,\n const Options extends DiscriminatedUnionVariants<Discriminator>,\n>(discriminator: Discriminator, variants: Options) {\n return new DiscriminatedUnionSchema<Discriminator, Options>(\n discriminator,\n variants,\n )\n}\n"]}
|
package/dist/schema/enum.d.ts
CHANGED
|
@@ -1,9 +1,58 @@
|
|
|
1
1
|
import { Schema, ValidationContext } from '../core.js';
|
|
2
|
+
/**
|
|
3
|
+
* Schema that accepts one of several specific literal values.
|
|
4
|
+
*
|
|
5
|
+
* Validates that the input matches one of the allowed values using strict
|
|
6
|
+
* equality. Similar to TypeScript union of literals.
|
|
7
|
+
*
|
|
8
|
+
* @template TValue - The union of literal types
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* const schema = new EnumSchema(['pending', 'active', 'completed'])
|
|
13
|
+
* schema.validate('active') // success
|
|
14
|
+
* schema.validate('invalid') // fails
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
2
17
|
export declare class EnumSchema<const TValue extends null | string | number | boolean> extends Schema<TValue> {
|
|
3
18
|
readonly values: readonly TValue[];
|
|
19
|
+
readonly type: "enum";
|
|
4
20
|
constructor(values: readonly TValue[]);
|
|
5
21
|
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").ValidationResult<TValue>;
|
|
6
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* Creates an enum schema that accepts one of the specified values.
|
|
25
|
+
*
|
|
26
|
+
* Similar to TypeScript's union of string literals. Use `l.enum()` for
|
|
27
|
+
* the namespace-friendly alias.
|
|
28
|
+
*
|
|
29
|
+
* @param value - Array of allowed values
|
|
30
|
+
* @returns A new {@link EnumSchema} instance
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```ts
|
|
34
|
+
* // String enum
|
|
35
|
+
* const statusSchema = l.enum(['pending', 'active', 'completed', 'failed'])
|
|
36
|
+
*
|
|
37
|
+
* // Number enum
|
|
38
|
+
* const prioritySchema = l.enum([1, 2, 3, 4, 5])
|
|
39
|
+
*
|
|
40
|
+
* // Mixed types
|
|
41
|
+
* const mixedSchema = l.enum(['auto', 0, 1, true])
|
|
42
|
+
*
|
|
43
|
+
* // Use in objects
|
|
44
|
+
* const taskSchema = l.object({
|
|
45
|
+
* title: l.string(),
|
|
46
|
+
* status: l.enum(['todo', 'in-progress', 'done']),
|
|
47
|
+
* })
|
|
48
|
+
*
|
|
49
|
+
* // In discriminated unions
|
|
50
|
+
* const resultSchema = l.discriminatedUnion('status', [
|
|
51
|
+
* l.object({ status: l.enum(['pending', 'processing']), progress: l.integer() }),
|
|
52
|
+
* l.object({ status: l.literal('completed'), result: l.unknown() }),
|
|
53
|
+
* ])
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
7
56
|
export declare function enumSchema<const V extends null | string | number | boolean>(value: readonly V[]): EnumSchema<V>;
|
|
8
57
|
export { enumSchema as enum };
|
|
9
58
|
//# sourceMappingURL=enum.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enum.d.ts","sourceRoot":"","sources":["../../src/schema/enum.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAEtD,qBAAa,UAAU,CACrB,KAAK,CAAC,MAAM,SAAS,IAAI,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CACrD,SAAQ,MAAM,CAAC,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"enum.d.ts","sourceRoot":"","sources":["../../src/schema/enum.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAEtD;;;;;;;;;;;;;;GAcG;AACH,qBAAa,UAAU,CACrB,KAAK,CAAC,MAAM,SAAS,IAAI,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CACrD,SAAQ,MAAM,CAAC,MAAM,CAAC;IAGV,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE;IAF9C,QAAQ,CAAC,IAAI,EAAG,MAAM,CAAS;gBAEV,MAAM,EAAE,SAAS,MAAM,EAAE;IAI9C,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;CAOzD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,wBAAgB,UAAU,CAAC,KAAK,CAAC,CAAC,SAAS,IAAI,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,EACzE,KAAK,EAAE,SAAS,CAAC,EAAE,iBAGpB;AAGD,OAAO,EAAE,UAAU,IAAI,IAAI,EAAE,CAAA"}
|
package/dist/schema/enum.js
CHANGED
|
@@ -4,8 +4,24 @@ exports.EnumSchema = void 0;
|
|
|
4
4
|
exports.enumSchema = enumSchema;
|
|
5
5
|
exports.enum = enumSchema;
|
|
6
6
|
const core_js_1 = require("../core.js");
|
|
7
|
+
/**
|
|
8
|
+
* Schema that accepts one of several specific literal values.
|
|
9
|
+
*
|
|
10
|
+
* Validates that the input matches one of the allowed values using strict
|
|
11
|
+
* equality. Similar to TypeScript union of literals.
|
|
12
|
+
*
|
|
13
|
+
* @template TValue - The union of literal types
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* const schema = new EnumSchema(['pending', 'active', 'completed'])
|
|
18
|
+
* schema.validate('active') // success
|
|
19
|
+
* schema.validate('invalid') // fails
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
7
22
|
class EnumSchema extends core_js_1.Schema {
|
|
8
23
|
values;
|
|
24
|
+
type = 'enum';
|
|
9
25
|
constructor(values) {
|
|
10
26
|
super();
|
|
11
27
|
this.values = values;
|
|
@@ -18,6 +34,39 @@ class EnumSchema extends core_js_1.Schema {
|
|
|
18
34
|
}
|
|
19
35
|
}
|
|
20
36
|
exports.EnumSchema = EnumSchema;
|
|
37
|
+
/**
|
|
38
|
+
* Creates an enum schema that accepts one of the specified values.
|
|
39
|
+
*
|
|
40
|
+
* Similar to TypeScript's union of string literals. Use `l.enum()` for
|
|
41
|
+
* the namespace-friendly alias.
|
|
42
|
+
*
|
|
43
|
+
* @param value - Array of allowed values
|
|
44
|
+
* @returns A new {@link EnumSchema} instance
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```ts
|
|
48
|
+
* // String enum
|
|
49
|
+
* const statusSchema = l.enum(['pending', 'active', 'completed', 'failed'])
|
|
50
|
+
*
|
|
51
|
+
* // Number enum
|
|
52
|
+
* const prioritySchema = l.enum([1, 2, 3, 4, 5])
|
|
53
|
+
*
|
|
54
|
+
* // Mixed types
|
|
55
|
+
* const mixedSchema = l.enum(['auto', 0, 1, true])
|
|
56
|
+
*
|
|
57
|
+
* // Use in objects
|
|
58
|
+
* const taskSchema = l.object({
|
|
59
|
+
* title: l.string(),
|
|
60
|
+
* status: l.enum(['todo', 'in-progress', 'done']),
|
|
61
|
+
* })
|
|
62
|
+
*
|
|
63
|
+
* // In discriminated unions
|
|
64
|
+
* const resultSchema = l.discriminatedUnion('status', [
|
|
65
|
+
* l.object({ status: l.enum(['pending', 'processing']), progress: l.integer() }),
|
|
66
|
+
* l.object({ status: l.literal('completed'), result: l.unknown() }),
|
|
67
|
+
* ])
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
21
70
|
/*@__NO_SIDE_EFFECTS__*/
|
|
22
71
|
function enumSchema(value) {
|
|
23
72
|
return new EnumSchema(value);
|
package/dist/schema/enum.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enum.js","sourceRoot":"","sources":["../../src/schema/enum.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"enum.js","sourceRoot":"","sources":["../../src/schema/enum.ts"],"names":[],"mappings":";;;AAqEA,gCAIC;AAGsB,0BAAI;AA5E3B,wCAAsD;AAEtD;;;;;;;;;;;;;;GAcG;AACH,MAAa,UAEX,SAAQ,gBAAc;IAGD;IAFZ,IAAI,GAAG,MAAe,CAAA;IAE/B,YAAqB,MAAyB;QAC5C,KAAK,EAAE,CAAA;QADY,WAAM,GAAN,MAAM,CAAmB;IAE9C,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,IAAI,CAAE,IAAI,CAAC,MAA6B,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACzD,OAAO,GAAG,CAAC,iBAAiB,CAAC,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;QAClD,CAAC;QAED,OAAO,GAAG,CAAC,OAAO,CAAC,KAAe,CAAC,CAAA;IACrC,CAAC;CACF;AAhBD,gCAgBC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAwB;AACxB,SAAgB,UAAU,CACxB,KAAmB;IAEnB,OAAO,IAAI,UAAU,CAAI,KAAK,CAAC,CAAA;AACjC,CAAC","sourcesContent":["import { Schema, ValidationContext } from '../core.js'\n\n/**\n * Schema that accepts one of several specific literal values.\n *\n * Validates that the input matches one of the allowed values using strict\n * equality. Similar to TypeScript union of literals.\n *\n * @template TValue - The union of literal types\n *\n * @example\n * ```ts\n * const schema = new EnumSchema(['pending', 'active', 'completed'])\n * schema.validate('active') // success\n * schema.validate('invalid') // fails\n * ```\n */\nexport class EnumSchema<\n const TValue extends null | string | number | boolean,\n> extends Schema<TValue> {\n readonly type = 'enum' as const\n\n constructor(readonly values: readonly TValue[]) {\n super()\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!(this.values as readonly unknown[]).includes(input)) {\n return ctx.issueInvalidValue(input, this.values)\n }\n\n return ctx.success(input as TValue)\n }\n}\n\n/**\n * Creates an enum schema that accepts one of the specified values.\n *\n * Similar to TypeScript's union of string literals. Use `l.enum()` for\n * the namespace-friendly alias.\n *\n * @param value - Array of allowed values\n * @returns A new {@link EnumSchema} instance\n *\n * @example\n * ```ts\n * // String enum\n * const statusSchema = l.enum(['pending', 'active', 'completed', 'failed'])\n *\n * // Number enum\n * const prioritySchema = l.enum([1, 2, 3, 4, 5])\n *\n * // Mixed types\n * const mixedSchema = l.enum(['auto', 0, 1, true])\n *\n * // Use in objects\n * const taskSchema = l.object({\n * title: l.string(),\n * status: l.enum(['todo', 'in-progress', 'done']),\n * })\n *\n * // In discriminated unions\n * const resultSchema = l.discriminatedUnion('status', [\n * l.object({ status: l.enum(['pending', 'processing']), progress: l.integer() }),\n * l.object({ status: l.literal('completed'), result: l.unknown() }),\n * ])\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function enumSchema<const V extends null | string | number | boolean>(\n value: readonly V[],\n) {\n return new EnumSchema<V>(value)\n}\n\n// @NOTE \"enum\" is a reserved keyword in JS/TS\nexport { enumSchema as enum }\n"]}
|