@atproto/lex-schema 0.0.10 → 0.0.12
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 +26 -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 +229 -2
- 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 +61 -1
- 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 +51 -0
- package/dist/core/validation-issue.js.map +1 -1
- package/dist/core/validator.d.ts +347 -10
- package/dist/core/validator.d.ts.map +1 -1
- package/dist/core/validator.js +184 -3
- package/dist/core/validator.js.map +1 -1
- package/dist/helpers.d.ts +13 -25
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +2 -2
- package/dist/helpers.js.map +1 -1
- package/dist/schema/array.d.ts +45 -0
- package/dist/schema/array.d.ts.map +1 -1
- package/dist/schema/array.js +14 -0
- package/dist/schema/array.js.map +1 -1
- package/dist/schema/blob.d.ts +46 -0
- package/dist/schema/blob.d.ts.map +1 -1
- package/dist/schema/blob.js +39 -0
- package/dist/schema/blob.js.map +1 -1
- package/dist/schema/boolean.d.ts +28 -0
- package/dist/schema/boolean.d.ts.map +1 -1
- package/dist/schema/boolean.js +28 -0
- package/dist/schema/boolean.js.map +1 -1
- package/dist/schema/bytes.d.ts +38 -0
- package/dist/schema/bytes.d.ts.map +1 -1
- package/dist/schema/bytes.js +32 -0
- package/dist/schema/bytes.js.map +1 -1
- package/dist/schema/cid.d.ts +38 -0
- package/dist/schema/cid.d.ts.map +1 -1
- package/dist/schema/cid.js +33 -0
- package/dist/schema/cid.js.map +1 -1
- package/dist/schema/custom.d.ts +66 -1
- package/dist/schema/custom.d.ts.map +1 -1
- package/dist/schema/custom.js +54 -0
- package/dist/schema/custom.js.map +1 -1
- package/dist/schema/dict.d.ts +44 -0
- package/dist/schema/dict.d.ts.map +1 -1
- package/dist/schema/dict.js +44 -0
- package/dist/schema/dict.js.map +1 -1
- package/dist/schema/discriminated-union.d.ts +58 -0
- package/dist/schema/discriminated-union.d.ts.map +1 -1
- package/dist/schema/discriminated-union.js +45 -0
- package/dist/schema/discriminated-union.js.map +1 -1
- package/dist/schema/enum.d.ts +48 -0
- package/dist/schema/enum.d.ts.map +1 -1
- package/dist/schema/enum.js +48 -0
- package/dist/schema/enum.js.map +1 -1
- package/dist/schema/integer.d.ts +42 -0
- package/dist/schema/integer.d.ts.map +1 -1
- package/dist/schema/integer.js +36 -0
- package/dist/schema/integer.js.map +1 -1
- package/dist/schema/intersection.d.ts +54 -0
- package/dist/schema/intersection.d.ts.map +1 -1
- package/dist/schema/intersection.js +49 -0
- package/dist/schema/intersection.js.map +1 -1
- package/dist/schema/literal.d.ts +44 -0
- package/dist/schema/literal.d.ts.map +1 -1
- package/dist/schema/literal.js +44 -0
- package/dist/schema/literal.js.map +1 -1
- package/dist/schema/never.d.ts +42 -0
- package/dist/schema/never.d.ts.map +1 -1
- package/dist/schema/never.js +42 -0
- package/dist/schema/never.js.map +1 -1
- package/dist/schema/null.d.ts +29 -0
- package/dist/schema/null.d.ts.map +1 -1
- package/dist/schema/null.js +29 -0
- package/dist/schema/null.js.map +1 -1
- package/dist/schema/nullable.d.ts +41 -0
- package/dist/schema/nullable.d.ts.map +1 -1
- package/dist/schema/nullable.js +41 -0
- package/dist/schema/nullable.js.map +1 -1
- package/dist/schema/object.d.ts +56 -0
- package/dist/schema/object.d.ts.map +1 -1
- package/dist/schema/object.js +51 -0
- package/dist/schema/object.js.map +1 -1
- package/dist/schema/optional.d.ts +42 -0
- package/dist/schema/optional.d.ts.map +1 -1
- package/dist/schema/optional.js +42 -0
- package/dist/schema/optional.js.map +1 -1
- package/dist/schema/params.d.ts +89 -7
- package/dist/schema/params.d.ts.map +1 -1
- package/dist/schema/params.js +84 -10
- 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 +70 -0
- 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 +63 -8
- package/dist/schema/record.d.ts.map +1 -1
- package/dist/schema/record.js +20 -0
- package/dist/schema/record.js.map +1 -1
- package/dist/schema/ref.d.ts +50 -0
- package/dist/schema/ref.d.ts.map +1 -1
- package/dist/schema/ref.js +17 -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 +44 -0
- package/dist/schema/regexp.d.ts.map +1 -1
- package/dist/schema/regexp.js +44 -0
- package/dist/schema/regexp.js.map +1 -1
- package/dist/schema/string.d.ts +50 -0
- package/dist/schema/string.d.ts.map +1 -1
- package/dist/schema/string.js +41 -0
- 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 +47 -0
- package/dist/schema/token.d.ts.map +1 -1
- package/dist/schema/token.js +47 -0
- package/dist/schema/token.js.map +1 -1
- package/dist/schema/typed-object.d.ts +62 -8
- package/dist/schema/typed-object.d.ts.map +1 -1
- package/dist/schema/typed-object.js +18 -0
- package/dist/schema/typed-object.js.map +1 -1
- package/dist/schema/typed-ref.d.ts +53 -0
- package/dist/schema/typed-ref.d.ts.map +1 -1
- package/dist/schema/typed-ref.js +15 -0
- package/dist/schema/typed-ref.js.map +1 -1
- package/dist/schema/typed-union.d.ts +50 -1
- package/dist/schema/typed-union.d.ts.map +1 -1
- package/dist/schema/typed-union.js +50 -1
- package/dist/schema/typed-union.js.map +1 -1
- package/dist/schema/union.d.ts +45 -0
- package/dist/schema/union.d.ts.map +1 -1
- package/dist/schema/union.js +40 -0
- package/dist/schema/union.js.map +1 -1
- package/dist/schema/unknown-object.d.ts +34 -0
- package/dist/schema/unknown-object.d.ts.map +1 -1
- package/dist/schema/unknown-object.js +31 -0
- package/dist/schema/unknown-object.js.map +1 -1
- package/dist/schema/unknown.d.ts +33 -0
- package/dist/schema/unknown.d.ts.map +1 -1
- package/dist/schema/unknown.js +33 -0
- package/dist/schema/unknown.js.map +1 -1
- package/dist/schema/with-default.d.ts +44 -0
- package/dist/schema/with-default.d.ts.map +1 -1
- package/dist/schema/with-default.js +44 -0
- package/dist/schema/with-default.js.map +1 -1
- package/package.json +4 -4
- 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 +236 -7
- 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 +65 -0
- package/src/core/validator.ts +351 -10
- package/src/helpers.test.ts +110 -29
- package/src/helpers.ts +14 -14
- package/src/schema/array.test.ts +94 -79
- package/src/schema/array.ts +45 -0
- package/src/schema/blob.ts +46 -0
- package/src/schema/boolean.ts +28 -0
- package/src/schema/bytes.ts +38 -0
- package/src/schema/cid.ts +38 -0
- package/src/schema/custom.ts +66 -1
- package/src/schema/dict.ts +44 -0
- package/src/schema/discriminated-union.ts +58 -0
- package/src/schema/enum.ts +48 -0
- package/src/schema/integer.ts +42 -0
- package/src/schema/intersection.ts +54 -0
- package/src/schema/literal.ts +44 -0
- package/src/schema/never.ts +42 -0
- package/src/schema/null.ts +29 -0
- package/src/schema/nullable.ts +41 -0
- package/src/schema/object.ts +56 -0
- package/src/schema/optional.ts +42 -0
- package/src/schema/params.test.ts +58 -2
- package/src/schema/params.ts +124 -16
- package/src/schema/payload.test.ts +3 -3
- package/src/schema/payload.ts +142 -38
- 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 +63 -8
- package/src/schema/ref.ts +50 -0
- package/src/schema/refine.ts +58 -9
- package/src/schema/regexp.ts +44 -0
- package/src/schema/string.ts +50 -0
- package/src/schema/subscription.ts +72 -2
- package/src/schema/token.ts +47 -0
- package/src/schema/typed-object.ts +62 -8
- package/src/schema/typed-ref.ts +53 -0
- package/src/schema/typed-union.ts +55 -2
- package/src/schema/union.ts +45 -0
- package/src/schema/unknown-object.ts +34 -0
- package/src/schema/unknown.ts +33 -0
- package/src/schema/with-default.ts +44 -0
|
@@ -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;IAEG,QAAQ,CAAC,SAAS,EAAE,IAAI;IACxB,QAAQ,CAAC,WAAW,EAAE,MAAM;gBADnB,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,9 +5,24 @@ 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;
|
|
@@ -50,6 +65,35 @@ class DictSchema extends core_js_1.Schema {
|
|
|
50
65
|
}
|
|
51
66
|
}
|
|
52
67
|
exports.DictSchema = DictSchema;
|
|
68
|
+
/**
|
|
69
|
+
* Creates a dictionary schema for validating map-like objects.
|
|
70
|
+
*
|
|
71
|
+
* Validates objects where all keys match the key schema and all values
|
|
72
|
+
* match the value schema. Useful for dynamic key-value mappings.
|
|
73
|
+
*
|
|
74
|
+
* @param key - Schema to validate each key (must be a string validator)
|
|
75
|
+
* @param value - Schema to validate each value
|
|
76
|
+
* @returns A new {@link DictSchema} instance
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* // String to number mapping
|
|
81
|
+
* const scoresSchema = l.dict(l.string(), l.integer())
|
|
82
|
+
* scoresSchema.parse({ alice: 100, bob: 85 })
|
|
83
|
+
*
|
|
84
|
+
* // Constrained keys
|
|
85
|
+
* const langSchema = l.dict(
|
|
86
|
+
* l.string({ minLength: 2, maxLength: 5 }), // Language codes
|
|
87
|
+
* l.string() // Translations
|
|
88
|
+
* )
|
|
89
|
+
*
|
|
90
|
+
* // Complex values
|
|
91
|
+
* const usersById = l.dict(
|
|
92
|
+
* l.string({ format: 'did' }),
|
|
93
|
+
* l.object({ name: l.string(), age: l.integer() })
|
|
94
|
+
* )
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
53
97
|
/*@__NO_SIDE_EFFECTS__*/
|
|
54
98
|
function dict(key, value) {
|
|
55
99
|
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":";;;AAkHA,oBAKC;AAvHD,gDAAiD;AACjD,wCAMmB;AAEnB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAa,UAGX,SAAQ,gBAGT;IAEY;IACA;IAFX,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,gBAAgB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;QAC5C,CAAC;QAED,IAAI,IAAyC,CAAA;QAE7C,KAAK,MAAM,GAA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AS,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 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.issueInvalidType(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,9 +29,26 @@ 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;
|
|
@@ -27,6 +57,34 @@ export declare class DiscriminatedUnionSchema<const TDiscriminator extends strin
|
|
|
27
57
|
constructor(discriminator: TDiscriminator, variants: TVariants);
|
|
28
58
|
validateInContext(input: unknown, ctx: ValidationContext): ValidationResult<DiscriminatedUnionSchemaInput<TVariants>>;
|
|
29
59
|
}
|
|
60
|
+
/**
|
|
61
|
+
* Creates a discriminated union schema for efficient object type switching.
|
|
62
|
+
*
|
|
63
|
+
* Unlike regular `union()`, this schema uses a discriminator property to
|
|
64
|
+
* directly look up the correct variant, providing O(1) validation instead
|
|
65
|
+
* of trying each variant sequentially.
|
|
66
|
+
*
|
|
67
|
+
* @param discriminator - Property name to discriminate on
|
|
68
|
+
* @param variants - Non-empty array of object schemas with the discriminator property
|
|
69
|
+
* @returns A new {@link DiscriminatedUnionSchema} instance
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```ts
|
|
73
|
+
* // Message types discriminated by 'kind'
|
|
74
|
+
* const messageSchema = l.discriminatedUnion('kind', [
|
|
75
|
+
* l.object({ kind: l.literal('text'), text: l.string() }),
|
|
76
|
+
* l.object({ kind: l.literal('image'), url: l.string(), alt: l.optional(l.string()) }),
|
|
77
|
+
* l.object({ kind: l.literal('video'), url: l.string(), duration: l.integer() }),
|
|
78
|
+
* ])
|
|
79
|
+
*
|
|
80
|
+
* // Using enums for multiple values mapping to same variant
|
|
81
|
+
* const statusSchema = l.discriminatedUnion('status', [
|
|
82
|
+
* l.object({ status: l.enum(['pending', 'processing']), startedAt: l.string() }),
|
|
83
|
+
* l.object({ status: l.literal('completed'), completedAt: l.string() }),
|
|
84
|
+
* l.object({ status: l.literal('failed'), error: l.string() }),
|
|
85
|
+
* ])
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
30
88
|
export declare function discriminatedUnion<const Discriminator extends string, const Options extends DiscriminatedUnionVariants<Discriminator>>(discriminator: Discriminator, variants: Options): DiscriminatedUnionSchema<Discriminator, Options>;
|
|
31
89
|
export {};
|
|
32
90
|
//# 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,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0B,CAAC,cAAc,CAAC,CAClE,SAAQ,MAAM,CACd,6BAA6B,CAAC,SAAS,CAAC,EACxC,8BAA8B,CAAC,SAAS,CAAC,CAC1C;IAIG,QAAQ,CAAC,aAAa,EAAE,cAAc;IACtC,QAAQ,CAAC,QAAQ,EAAE,SAAS;IAJ9B,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,9 +7,26 @@ 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;
|
|
@@ -69,6 +86,34 @@ function buildVariantsMap(discriminator, variants) {
|
|
|
69
86
|
}
|
|
70
87
|
return variantsMap;
|
|
71
88
|
}
|
|
89
|
+
/**
|
|
90
|
+
* Creates a discriminated union schema for efficient object type switching.
|
|
91
|
+
*
|
|
92
|
+
* Unlike regular `union()`, this schema uses a discriminator property to
|
|
93
|
+
* directly look up the correct variant, providing O(1) validation instead
|
|
94
|
+
* of trying each variant sequentially.
|
|
95
|
+
*
|
|
96
|
+
* @param discriminator - Property name to discriminate on
|
|
97
|
+
* @param variants - Non-empty array of object schemas with the discriminator property
|
|
98
|
+
* @returns A new {@link DiscriminatedUnionSchema} instance
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```ts
|
|
102
|
+
* // Message types discriminated by 'kind'
|
|
103
|
+
* const messageSchema = l.discriminatedUnion('kind', [
|
|
104
|
+
* l.object({ kind: l.literal('text'), text: l.string() }),
|
|
105
|
+
* l.object({ kind: l.literal('image'), url: l.string(), alt: l.optional(l.string()) }),
|
|
106
|
+
* l.object({ kind: l.literal('video'), url: l.string(), duration: l.integer() }),
|
|
107
|
+
* ])
|
|
108
|
+
*
|
|
109
|
+
* // Using enums for multiple values mapping to same variant
|
|
110
|
+
* const statusSchema = l.discriminatedUnion('status', [
|
|
111
|
+
* l.object({ status: l.enum(['pending', 'processing']), startedAt: l.string() }),
|
|
112
|
+
* l.object({ status: l.literal('completed'), completedAt: l.string() }),
|
|
113
|
+
* l.object({ status: l.literal('failed'), error: l.string() }),
|
|
114
|
+
* ])
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
72
117
|
/*@__NO_SIDE_EFFECTS__*/
|
|
73
118
|
function discriminatedUnion(discriminator, variants) {
|
|
74
119
|
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":";;;AAyLA,gDAQC;AAjMD,gDAAiD;AACjD,wCAOmB;AACnB,uCAAsC;AACtC,6CAA4C;AAyC5C;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAa,wBAGX,SAAQ,gBAGT;IAIY;IACA;IAJF,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,gBAAgB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;QAC9C,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,C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O,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 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.issueInvalidType(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,57 @@
|
|
|
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[];
|
|
4
19
|
constructor(values: readonly TValue[]);
|
|
5
20
|
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").ValidationResult<TValue>;
|
|
6
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* Creates an enum schema that accepts one of the specified values.
|
|
24
|
+
*
|
|
25
|
+
* Similar to TypeScript's union of string literals. Use `l.enum()` for
|
|
26
|
+
* the namespace-friendly alias.
|
|
27
|
+
*
|
|
28
|
+
* @param value - Array of allowed values
|
|
29
|
+
* @returns A new {@link EnumSchema} instance
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* // String enum
|
|
34
|
+
* const statusSchema = l.enum(['pending', 'active', 'completed', 'failed'])
|
|
35
|
+
*
|
|
36
|
+
* // Number enum
|
|
37
|
+
* const prioritySchema = l.enum([1, 2, 3, 4, 5])
|
|
38
|
+
*
|
|
39
|
+
* // Mixed types
|
|
40
|
+
* const mixedSchema = l.enum(['auto', 0, 1, true])
|
|
41
|
+
*
|
|
42
|
+
* // Use in objects
|
|
43
|
+
* const taskSchema = l.object({
|
|
44
|
+
* title: l.string(),
|
|
45
|
+
* status: l.enum(['todo', 'in-progress', 'done']),
|
|
46
|
+
* })
|
|
47
|
+
*
|
|
48
|
+
* // In discriminated unions
|
|
49
|
+
* const resultSchema = l.discriminatedUnion('status', [
|
|
50
|
+
* l.object({ status: l.enum(['pending', 'processing']), progress: l.integer() }),
|
|
51
|
+
* l.object({ status: l.literal('completed'), result: l.unknown() }),
|
|
52
|
+
* ])
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
7
55
|
export declare function enumSchema<const V extends null | string | number | boolean>(value: readonly V[]): EnumSchema<V>;
|
|
8
56
|
export { enumSchema as enum };
|
|
9
57
|
//# 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;IACV,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE;gBAAzB,MAAM,EAAE,SAAS,MAAM,EAAE;IAI9C,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;CAOzD;
|
|
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;IACV,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE;gBAAzB,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,6 +4,21 @@ 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;
|
|
9
24
|
constructor(values) {
|
|
@@ -18,6 +33,39 @@ class EnumSchema extends core_js_1.Schema {
|
|
|
18
33
|
}
|
|
19
34
|
}
|
|
20
35
|
exports.EnumSchema = EnumSchema;
|
|
36
|
+
/**
|
|
37
|
+
* Creates an enum schema that accepts one of the specified values.
|
|
38
|
+
*
|
|
39
|
+
* Similar to TypeScript's union of string literals. Use `l.enum()` for
|
|
40
|
+
* the namespace-friendly alias.
|
|
41
|
+
*
|
|
42
|
+
* @param value - Array of allowed values
|
|
43
|
+
* @returns A new {@link EnumSchema} instance
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* // String enum
|
|
48
|
+
* const statusSchema = l.enum(['pending', 'active', 'completed', 'failed'])
|
|
49
|
+
*
|
|
50
|
+
* // Number enum
|
|
51
|
+
* const prioritySchema = l.enum([1, 2, 3, 4, 5])
|
|
52
|
+
*
|
|
53
|
+
* // Mixed types
|
|
54
|
+
* const mixedSchema = l.enum(['auto', 0, 1, true])
|
|
55
|
+
*
|
|
56
|
+
* // Use in objects
|
|
57
|
+
* const taskSchema = l.object({
|
|
58
|
+
* title: l.string(),
|
|
59
|
+
* status: l.enum(['todo', 'in-progress', 'done']),
|
|
60
|
+
* })
|
|
61
|
+
*
|
|
62
|
+
* // In discriminated unions
|
|
63
|
+
* const resultSchema = l.discriminatedUnion('status', [
|
|
64
|
+
* l.object({ status: l.enum(['pending', 'processing']), progress: l.integer() }),
|
|
65
|
+
* l.object({ status: l.literal('completed'), result: l.unknown() }),
|
|
66
|
+
* ])
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
21
69
|
/*@__NO_SIDE_EFFECTS__*/
|
|
22
70
|
function enumSchema(value) {
|
|
23
71
|
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":";;;AAmEA,gCAIC;AAGsB,0BAAI;AA1E3B,wCAAsD;AAEtD;;;;;;;;;;;;;;GAcG;AACH,MAAa,UAEX,SAAQ,gBAAc;IACD;IAArB,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;AAdD,gCAcC;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 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"]}
|
package/dist/schema/integer.d.ts
CHANGED
|
@@ -1,12 +1,54 @@
|
|
|
1
1
|
import { Schema, ValidationContext } from '../core.js';
|
|
2
|
+
/**
|
|
3
|
+
* Configuration options for integer schema validation.
|
|
4
|
+
*
|
|
5
|
+
* @property minimum - Minimum allowed value (inclusive)
|
|
6
|
+
* @property maximum - Maximum allowed value (inclusive)
|
|
7
|
+
*/
|
|
2
8
|
export type IntegerSchemaOptions = {
|
|
3
9
|
minimum?: number;
|
|
4
10
|
maximum?: number;
|
|
5
11
|
};
|
|
12
|
+
/**
|
|
13
|
+
* Schema for validating integer values with optional range constraints.
|
|
14
|
+
*
|
|
15
|
+
* Only accepts safe integers (values that can be exactly represented in JavaScript).
|
|
16
|
+
* Use {@link IntegerSchemaOptions} to constrain the allowed range.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* const schema = new IntegerSchema({ minimum: 0, maximum: 100 })
|
|
21
|
+
* const result = schema.validate(42)
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
6
24
|
export declare class IntegerSchema extends Schema<number> {
|
|
7
25
|
readonly options?: IntegerSchemaOptions | undefined;
|
|
8
26
|
constructor(options?: IntegerSchemaOptions | undefined);
|
|
9
27
|
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").ValidationResult<number>;
|
|
10
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Creates an integer schema with optional minimum and maximum constraints.
|
|
31
|
+
*
|
|
32
|
+
* Validates that the input is a safe integer (can be exactly represented in JavaScript)
|
|
33
|
+
* and optionally falls within a specified range.
|
|
34
|
+
*
|
|
35
|
+
* @param options - Optional configuration for minimum and maximum values
|
|
36
|
+
* @returns A new {@link IntegerSchema} instance
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* // Basic integer
|
|
41
|
+
* const countSchema = l.integer()
|
|
42
|
+
*
|
|
43
|
+
* // With minimum value
|
|
44
|
+
* const positiveSchema = l.integer({ minimum: 1 })
|
|
45
|
+
*
|
|
46
|
+
* // With range constraints
|
|
47
|
+
* const percentSchema = l.integer({ minimum: 0, maximum: 100 })
|
|
48
|
+
*
|
|
49
|
+
* // Age validation
|
|
50
|
+
* const ageSchema = l.integer({ minimum: 0, maximum: 150 })
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
11
53
|
export declare const integer: (options?: IntegerSchemaOptions) => IntegerSchema;
|
|
12
54
|
//# sourceMappingURL=integer.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integer.d.ts","sourceRoot":"","sources":["../../src/schema/integer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAGtD,MAAM,MAAM,oBAAoB,GAAG;IACjC,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAA;AAED,qBAAa,aAAc,SAAQ,MAAM,CAAC,MAAM,CAAC;IACnC,QAAQ,CAAC,OAAO,CAAC,EAAE,oBAAoB;gBAA9B,OAAO,CAAC,EAAE,oBAAoB,YAAA;IAInD,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;CAezD;AASD,eAAO,MAAM,OAAO,aACR,oBAAoB,kBAG9B,CAAA"}
|
|
1
|
+
{"version":3,"file":"integer.d.ts","sourceRoot":"","sources":["../../src/schema/integer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAGtD;;;;;GAKG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAA;AAED;;;;;;;;;;;GAWG;AACH,qBAAa,aAAc,SAAQ,MAAM,CAAC,MAAM,CAAC;IACnC,QAAQ,CAAC,OAAO,CAAC,EAAE,oBAAoB;gBAA9B,OAAO,CAAC,EAAE,oBAAoB,YAAA;IAInD,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;CAezD;AASD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,OAAO,aACR,oBAAoB,kBAG9B,CAAA"}
|
package/dist/schema/integer.js
CHANGED
|
@@ -3,6 +3,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.integer = exports.IntegerSchema = void 0;
|
|
4
4
|
const core_js_1 = require("../core.js");
|
|
5
5
|
const memoize_js_1 = require("../util/memoize.js");
|
|
6
|
+
/**
|
|
7
|
+
* Schema for validating integer values with optional range constraints.
|
|
8
|
+
*
|
|
9
|
+
* Only accepts safe integers (values that can be exactly represented in JavaScript).
|
|
10
|
+
* Use {@link IntegerSchemaOptions} to constrain the allowed range.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* const schema = new IntegerSchema({ minimum: 0, maximum: 100 })
|
|
15
|
+
* const result = schema.validate(42)
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
6
18
|
class IntegerSchema extends core_js_1.Schema {
|
|
7
19
|
options;
|
|
8
20
|
constructor(options) {
|
|
@@ -29,6 +41,30 @@ exports.IntegerSchema = IntegerSchema;
|
|
|
29
41
|
function isInteger(input) {
|
|
30
42
|
return Number.isSafeInteger(input);
|
|
31
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* Creates an integer schema with optional minimum and maximum constraints.
|
|
46
|
+
*
|
|
47
|
+
* Validates that the input is a safe integer (can be exactly represented in JavaScript)
|
|
48
|
+
* and optionally falls within a specified range.
|
|
49
|
+
*
|
|
50
|
+
* @param options - Optional configuration for minimum and maximum values
|
|
51
|
+
* @returns A new {@link IntegerSchema} instance
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```ts
|
|
55
|
+
* // Basic integer
|
|
56
|
+
* const countSchema = l.integer()
|
|
57
|
+
*
|
|
58
|
+
* // With minimum value
|
|
59
|
+
* const positiveSchema = l.integer({ minimum: 1 })
|
|
60
|
+
*
|
|
61
|
+
* // With range constraints
|
|
62
|
+
* const percentSchema = l.integer({ minimum: 0, maximum: 100 })
|
|
63
|
+
*
|
|
64
|
+
* // Age validation
|
|
65
|
+
* const ageSchema = l.integer({ minimum: 0, maximum: 150 })
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
32
68
|
exports.integer = (0, memoize_js_1.memoizedOptions)(function (options) {
|
|
33
69
|
return new IntegerSchema(options);
|
|
34
70
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integer.js","sourceRoot":"","sources":["../../src/schema/integer.ts"],"names":[],"mappings":";;;AAAA,wCAAsD;AACtD,mDAAoD;
|
|
1
|
+
{"version":3,"file":"integer.js","sourceRoot":"","sources":["../../src/schema/integer.ts"],"names":[],"mappings":";;;AAAA,wCAAsD;AACtD,mDAAoD;AAapD;;;;;;;;;;;GAWG;AACH,MAAa,aAAc,SAAQ,gBAAc;IAC1B;IAArB,YAAqB,OAA8B;QACjD,KAAK,EAAE,CAAA;QADY,YAAO,GAAP,OAAO,CAAuB;IAEnD,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;YACtB,OAAO,GAAG,CAAC,gBAAgB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;QAC/C,CAAC;QAED,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,IAAI,IAAI,IAAI,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;YAClE,OAAO,GAAG,CAAC,aAAa,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;QACzE,CAAC;QAED,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,IAAI,IAAI,IAAI,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;YAClE,OAAO,GAAG,CAAC,WAAW,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;QACvE,CAAC;QAED,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;IAC3B,CAAC;CACF;AApBD,sCAoBC;AAED;;GAEG;AACH,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,CAAA;AACpC,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACU,QAAA,OAAO,GAAiB,IAAA,4BAAe,EAAC,UACnD,OAA8B;IAE9B,OAAO,IAAI,aAAa,CAAC,OAAO,CAAC,CAAA;AACnC,CAAC,CAAC,CAAA","sourcesContent":["import { Schema, ValidationContext } from '../core.js'\nimport { memoizedOptions } from '../util/memoize.js'\n\n/**\n * Configuration options for integer schema validation.\n *\n * @property minimum - Minimum allowed value (inclusive)\n * @property maximum - Maximum allowed value (inclusive)\n */\nexport type IntegerSchemaOptions = {\n minimum?: number\n maximum?: number\n}\n\n/**\n * Schema for validating integer values with optional range constraints.\n *\n * Only accepts safe integers (values that can be exactly represented in JavaScript).\n * Use {@link IntegerSchemaOptions} to constrain the allowed range.\n *\n * @example\n * ```ts\n * const schema = new IntegerSchema({ minimum: 0, maximum: 100 })\n * const result = schema.validate(42)\n * ```\n */\nexport class IntegerSchema extends Schema<number> {\n constructor(readonly options?: IntegerSchemaOptions) {\n super()\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!isInteger(input)) {\n return ctx.issueInvalidType(input, 'integer')\n }\n\n if (this.options?.minimum != null && input < this.options.minimum) {\n return ctx.issueTooSmall(input, 'integer', this.options.minimum, input)\n }\n\n if (this.options?.maximum != null && input > this.options.maximum) {\n return ctx.issueTooBig(input, 'integer', this.options.maximum, input)\n }\n\n return ctx.success(input)\n }\n}\n\n/**\n * Simple wrapper around {@link Number.isSafeInteger} that acts as a type guard.\n */\nfunction isInteger(input: unknown): input is number {\n return Number.isSafeInteger(input)\n}\n\n/**\n * Creates an integer schema with optional minimum and maximum constraints.\n *\n * Validates that the input is a safe integer (can be exactly represented in JavaScript)\n * and optionally falls within a specified range.\n *\n * @param options - Optional configuration for minimum and maximum values\n * @returns A new {@link IntegerSchema} instance\n *\n * @example\n * ```ts\n * // Basic integer\n * const countSchema = l.integer()\n *\n * // With minimum value\n * const positiveSchema = l.integer({ minimum: 1 })\n *\n * // With range constraints\n * const percentSchema = l.integer({ minimum: 0, maximum: 100 })\n *\n * // Age validation\n * const ageSchema = l.integer({ minimum: 0, maximum: 150 })\n * ```\n */\nexport const integer = /*#__PURE__*/ memoizedOptions(function (\n options?: IntegerSchemaOptions,\n) {\n return new IntegerSchema(options)\n})\n"]}
|
|
@@ -2,10 +2,15 @@ import { InferInput, InferOutput, Schema, Simplify, ValidationContext } from '..
|
|
|
2
2
|
import { DictSchema } from './dict.js';
|
|
3
3
|
import { ObjectSchema } from './object.js';
|
|
4
4
|
/**
|
|
5
|
+
* Type utility for computing the intersection of two object types.
|
|
6
|
+
*
|
|
5
7
|
* Allows to more accurately represent the intersection of two object types
|
|
6
8
|
* where both types may share some keys, and one of them uses an index
|
|
7
9
|
* signature.
|
|
8
10
|
*
|
|
11
|
+
* @template A - First object type (typically from ObjectSchema)
|
|
12
|
+
* @template B - Second object type (typically from DictSchema)
|
|
13
|
+
*
|
|
9
14
|
* @see {@link https://www.typescriptlang.org/play/?#code/C4TwDgpgBAglC8UDeUBmB7dAuKByARgIYBOuUAvlAGTJQDaA+lAJYB2UAzsMWwOYC6OVgFcAtvgjEKAKGkATCAGMANiWiL0rLlEI4YsjVuBQA1hBA4uPVrwRQARBnT2Dm7QDdCy4dESE6ZiD8UAD0IVAi4pJQABQcABbowspyUBIORMT2AJSyEAAeYOjExqCQUACSrMCSHErAzJoAPNJQsFAFNaxyHFAASkrFck1WfAA0UMKsJqzoAO6sAHxjrVAAQh35XT39g8TDozYTUzPzSyuLdqtwVKttMYHoqO00j88bnRDdvawQ7pJ3NpQAD860BbRwSHBQLadAA0ix2G91oJ1vDggAfWABcxPF5QOH8aFtci5aRlaAwVDMfIQVKIKo1Yh1RQNZq0Jw4AgkMjkCYoRiIzjcPioyISKTkRayBQqNRQQzaQgAMRpdL01NpclcRignm8EFVWrsKrVchxQVC4XF0SxmSAA Playground link}
|
|
10
15
|
*/
|
|
11
16
|
export type Intersect<A, B> = B[keyof B] extends never ? A : keyof A & keyof B extends never ? // If A and B don't overlap, just return A & B
|
|
@@ -13,11 +18,60 @@ A & B : // Otherwise, properly represent the fact that accessing using an
|
|
|
13
18
|
A & {
|
|
14
19
|
[K in keyof B]: B[K] | A[keyof A & K];
|
|
15
20
|
};
|
|
21
|
+
/**
|
|
22
|
+
* Schema for combining an object schema with a dictionary schema.
|
|
23
|
+
*
|
|
24
|
+
* Validates that the input matches both the fixed object shape and allows
|
|
25
|
+
* additional properties that match the dictionary schema. Properties defined
|
|
26
|
+
* in the object schema are validated by the object, and remaining properties
|
|
27
|
+
* are validated by the dictionary.
|
|
28
|
+
*
|
|
29
|
+
* @template Left - The ObjectSchema type for fixed properties
|
|
30
|
+
* @template Right - The DictSchema type for additional properties
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```ts
|
|
34
|
+
* const schema = new IntersectionSchema(
|
|
35
|
+
* l.object({ name: l.string() }),
|
|
36
|
+
* l.dict(l.string(), l.integer())
|
|
37
|
+
* )
|
|
38
|
+
* // Validates: { name: 'test', score: 100, count: 5 }
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
16
41
|
export declare class IntersectionSchema<const Left extends ObjectSchema = any, const Right extends DictSchema = any> extends Schema<Simplify<Intersect<InferInput<Left>, InferInput<Right>>>, Simplify<Intersect<InferOutput<Left>, InferOutput<Right>>>> {
|
|
17
42
|
protected readonly left: Left;
|
|
18
43
|
protected readonly right: Right;
|
|
19
44
|
constructor(left: Left, right: Right);
|
|
20
45
|
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").ValidationResult<Record<string, unknown>>;
|
|
21
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Creates an intersection schema combining fixed object properties with dynamic dictionary properties.
|
|
49
|
+
*
|
|
50
|
+
* Useful for objects that have a known set of properties plus additional
|
|
51
|
+
* arbitrary properties that follow a pattern.
|
|
52
|
+
*
|
|
53
|
+
* @param left - Object schema defining the fixed, known properties
|
|
54
|
+
* @param right - Dictionary schema for validating additional properties
|
|
55
|
+
* @returns A new {@link IntersectionSchema} instance
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```ts
|
|
59
|
+
* // Object with fixed and dynamic properties
|
|
60
|
+
* const configSchema = l.intersection(
|
|
61
|
+
* l.object({
|
|
62
|
+
* version: l.integer(),
|
|
63
|
+
* name: l.string(),
|
|
64
|
+
* }),
|
|
65
|
+
* l.dict(l.string(), l.string()) // Additional string properties
|
|
66
|
+
* )
|
|
67
|
+
*
|
|
68
|
+
* configSchema.parse({
|
|
69
|
+
* version: 1,
|
|
70
|
+
* name: 'my-config',
|
|
71
|
+
* customField: 'value',
|
|
72
|
+
* anotherField: 'another',
|
|
73
|
+
* })
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
22
76
|
export declare function intersection<const Left extends ObjectSchema, const Right extends DictSchema>(left: Left, right: Right): IntersectionSchema<Left, Right>;
|
|
23
77
|
//# sourceMappingURL=intersection.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intersection.d.ts","sourceRoot":"","sources":["../../src/schema/intersection.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,MAAM,EACN,QAAQ,EACR,iBAAiB,EAClB,MAAM,YAA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