@atproto/lex-schema 0.0.14 → 0.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/dist/core/schema.d.ts +5 -4
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +7 -2
- package/dist/core/schema.js.map +1 -1
- package/dist/core/standard-schema.d.ts +14 -0
- package/dist/core/standard-schema.d.ts.map +1 -0
- package/dist/core/standard-schema.js +27 -0
- package/dist/core/standard-schema.js.map +1 -0
- package/dist/core/string-format.d.ts +24 -17
- package/dist/core/string-format.d.ts.map +1 -1
- package/dist/core/string-format.js +57 -30
- package/dist/core/string-format.js.map +1 -1
- package/dist/core/validation-error.d.ts +10 -2
- package/dist/core/validation-error.d.ts.map +1 -1
- package/dist/core/validation-error.js +10 -0
- package/dist/core/validation-error.js.map +1 -1
- package/dist/core/validation-issue.d.ts +15 -15
- package/dist/core/validation-issue.d.ts.map +1 -1
- package/dist/core/validation-issue.js +33 -29
- package/dist/core/validation-issue.js.map +1 -1
- package/dist/core/validator.d.ts +29 -14
- package/dist/core/validator.d.ts.map +1 -1
- package/dist/core/validator.js +4 -2
- package/dist/core/validator.js.map +1 -1
- package/dist/core.d.ts +0 -1
- package/dist/core.d.ts.map +1 -1
- package/dist/core.js +0 -1
- package/dist/core.js.map +1 -1
- package/dist/schema/blob.d.ts +10 -8
- package/dist/schema/blob.d.ts.map +1 -1
- package/dist/schema/blob.js +39 -14
- package/dist/schema/blob.js.map +1 -1
- package/dist/schema/custom.d.ts +1 -1
- package/dist/schema/custom.d.ts.map +1 -1
- package/dist/schema/custom.js.map +1 -1
- package/dist/schema/never.d.ts +1 -1
- package/dist/schema/nullable.d.ts +1 -1
- package/dist/schema/payload.d.ts +2 -2
- package/dist/schema/payload.d.ts.map +1 -1
- package/dist/schema/payload.js.map +1 -1
- package/dist/schema/record.d.ts +1 -1
- package/dist/schema/ref.d.ts +1 -1
- package/dist/schema/ref.d.ts.map +1 -1
- package/dist/schema/ref.js.map +1 -1
- package/dist/schema/refine.d.ts +1 -1
- package/dist/schema/refine.d.ts.map +1 -1
- package/dist/schema/refine.js.map +1 -1
- package/dist/schema/string.js +1 -1
- package/dist/schema/string.js.map +1 -1
- package/dist/schema/typed-ref.d.ts +1 -1
- package/dist/schema/typed-union.d.ts +1 -1
- package/dist/schema/union.d.ts +2 -2
- package/dist/schema/union.d.ts.map +1 -1
- package/package.json +5 -3
- package/src/core/schema.ts +12 -11
- package/src/core/standard-schema.test.ts +124 -0
- package/src/core/standard-schema.ts +31 -0
- package/src/core/string-format.ts +73 -31
- package/src/core/validation-error.ts +16 -1
- package/src/core/validation-issue.ts +32 -32
- package/src/core/validator.ts +26 -6
- package/src/core.ts +0 -1
- package/src/schema/array.test.ts +2 -2
- package/src/schema/blob.test.ts +317 -49
- package/src/schema/blob.ts +56 -23
- package/src/schema/custom.ts +1 -7
- package/src/schema/params.test.ts +2 -2
- package/src/schema/payload.ts +2 -2
- package/src/schema/ref.ts +1 -5
- package/src/schema/refine.ts +0 -1
- package/src/schema/string.test.ts +63 -0
- package/src/schema/string.ts +1 -1
- package/dist/core/property-key.d.ts +0 -2
- package/dist/core/property-key.d.ts.map +0 -1
- package/dist/core/property-key.js +0 -3
- package/dist/core/property-key.js.map +0 -1
- package/src/core/property-key.ts +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# @atproto/lex-schema
|
|
2
2
|
|
|
3
|
+
## 0.0.16
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#4761](https://github.com/bluesky-social/atproto/pull/4761) [`6a88461`](https://github.com/bluesky-social/atproto/commit/6a88461c5aa9486269f0769b7a3d52f384581786) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Allow using a dynamic non-strict validation mode
|
|
8
|
+
|
|
9
|
+
- Updated dependencies [[`6a88461`](https://github.com/bluesky-social/atproto/commit/6a88461c5aa9486269f0769b7a3d52f384581786)]:
|
|
10
|
+
- @atproto/lex-data@0.0.14
|
|
11
|
+
|
|
12
|
+
## 0.0.15
|
|
13
|
+
|
|
14
|
+
### Patch Changes
|
|
15
|
+
|
|
16
|
+
- [#4734](https://github.com/bluesky-social/atproto/pull/4734) [`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Rename `IssueInvalidFormat`'s `message` property to `detail`
|
|
17
|
+
|
|
18
|
+
- [#4734](https://github.com/bluesky-social/atproto/pull/4734) [`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Add a read-only `message` property to the `Issue` class
|
|
19
|
+
|
|
20
|
+
- [#4734](https://github.com/bluesky-social/atproto/pull/4734) [`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe) Thanks [@matthieusieben](https://github.com/matthieusieben)! - `LexValidationError` class now implements `ResultFailure` allowing it to be used as validation return value directly (without the need to be wrapped)
|
|
21
|
+
|
|
22
|
+
- [#4734](https://github.com/bluesky-social/atproto/pull/4734) [`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Update stringification of issues (`toString()`) to consistently display the error path at the end.
|
|
23
|
+
|
|
24
|
+
- [`112b159`](https://github.com/bluesky-social/atproto/commit/112b159ec293a5c3fff41237474a3788fc47f9ca) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Export more string format type assertion utilities
|
|
25
|
+
|
|
26
|
+
- [#4734](https://github.com/bluesky-social/atproto/pull/4734) [`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe) Thanks [@matthieusieben](https://github.com/matthieusieben)! - `PropertyKey` is no longer exported. Use the global value instead.
|
|
27
|
+
|
|
28
|
+
- [#4734](https://github.com/bluesky-social/atproto/pull/4734) [`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Add [Standard Schema](https://standardschema.dev/) compatibility
|
|
29
|
+
|
|
30
|
+
- Updated dependencies [[`67eb0c1`](https://github.com/bluesky-social/atproto/commit/67eb0c19ac415e762e221b2ccda9f0bcf7b3dd6f)]:
|
|
31
|
+
- @atproto/syntax@0.5.1
|
|
32
|
+
|
|
3
33
|
## 0.0.14
|
|
4
34
|
|
|
5
35
|
### Patch Changes
|
package/dist/core/schema.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
1
2
|
import { InferInput, InferOutput, ValidationContext, ValidationOptions, ValidationResult, Validator } from './validator.js';
|
|
2
3
|
/**
|
|
3
4
|
* Options for parsing operations.
|
|
@@ -33,14 +34,13 @@ export interface SchemaInternals<out TInput = unknown, out TOutput = TInput> {
|
|
|
33
34
|
* - **Assertion methods**: `assert()`, `check()` - throw on invalid input
|
|
34
35
|
* - **Type guard methods**: `matches()`, `ifMatches()` - return boolean or optional value
|
|
35
36
|
* - **Parse methods**: `parse()`, `safeParse()` - allow value transformation/coercion
|
|
36
|
-
* - **Validate methods**: `validate()`, `safeValidate()` -
|
|
37
|
+
* - **Validate methods**: `validate()`, `safeValidate()` - validation without coercion
|
|
37
38
|
*
|
|
38
39
|
* All methods are also available with a `$` prefix (e.g., `$parse()`, `$validate()`)
|
|
39
40
|
* for consistent access in generated lexicon namespaces.
|
|
40
41
|
*
|
|
41
42
|
* @typeParam TInput - The type accepted as valid input during validation
|
|
42
43
|
* @typeParam TOutput - The type returned after parsing (may include transformations)
|
|
43
|
-
* @typeParam TInternals - Internal type structure for type inference
|
|
44
44
|
*
|
|
45
45
|
* @example
|
|
46
46
|
* ```typescript
|
|
@@ -60,14 +60,15 @@ export interface SchemaInternals<out TInput = unknown, out TOutput = TInput> {
|
|
|
60
60
|
* schema.matches(123) // false
|
|
61
61
|
* ```
|
|
62
62
|
*/
|
|
63
|
-
export declare abstract class Schema<out TInput = unknown, out TOutput = TInput
|
|
63
|
+
export declare abstract class Schema<out TInput = unknown, out TOutput = TInput> implements Validator<TInput, TOutput>, StandardSchemaV1<TInput, TOutput> {
|
|
64
64
|
/**
|
|
65
65
|
* Internal phantom property for type inference.
|
|
66
66
|
* This property does not exist at runtime.
|
|
67
67
|
*
|
|
68
68
|
* @internal
|
|
69
69
|
*/
|
|
70
|
-
readonly ['__lex']:
|
|
70
|
+
readonly ['__lex']: SchemaInternals<TInput, TOutput>;
|
|
71
|
+
get '~standard'(): StandardSchemaV1.Props<TInput, TOutput>;
|
|
71
72
|
abstract readonly type: string;
|
|
72
73
|
/**
|
|
73
74
|
* Performs validation of the input value within a validation context.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/core/schema.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/core/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAGxD,OAAO,EACL,UAAU,EACV,WAAW,EACX,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,SAAS,EACV,MAAM,gBAAgB,CAAA;AAEvB;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,IAAI,CAAC,iBAAiB,EAAE,MAAM,CAAC,CAAA;AAE1D;;;GAGG;AACH,MAAM,MAAM,eAAe,GAAG,IAAI,CAAC,iBAAiB,EAAE,MAAM,CAAC,CAAA;AAE7D;;;;;;;;;;GAUG;AACH,MAAM,WAAW,eAAe,CAAC,GAAG,CAAC,MAAM,GAAG,OAAO,EAAE,GAAG,CAAC,OAAO,GA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ED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.Schema = void 0;
|
|
4
4
|
const lazy_property_js_1 = require("../util/lazy-property.js");
|
|
5
|
+
const standard_schema_js_1 = require("./standard-schema.js");
|
|
5
6
|
const validator_js_1 = require("./validator.js");
|
|
6
7
|
/**
|
|
7
8
|
* Abstract base class for all schema validators in the lexicon system.
|
|
@@ -12,14 +13,13 @@ const validator_js_1 = require("./validator.js");
|
|
|
12
13
|
* - **Assertion methods**: `assert()`, `check()` - throw on invalid input
|
|
13
14
|
* - **Type guard methods**: `matches()`, `ifMatches()` - return boolean or optional value
|
|
14
15
|
* - **Parse methods**: `parse()`, `safeParse()` - allow value transformation/coercion
|
|
15
|
-
* - **Validate methods**: `validate()`, `safeValidate()` -
|
|
16
|
+
* - **Validate methods**: `validate()`, `safeValidate()` - validation without coercion
|
|
16
17
|
*
|
|
17
18
|
* All methods are also available with a `$` prefix (e.g., `$parse()`, `$validate()`)
|
|
18
19
|
* for consistent access in generated lexicon namespaces.
|
|
19
20
|
*
|
|
20
21
|
* @typeParam TInput - The type accepted as valid input during validation
|
|
21
22
|
* @typeParam TOutput - The type returned after parsing (may include transformations)
|
|
22
|
-
* @typeParam TInternals - Internal type structure for type inference
|
|
23
23
|
*
|
|
24
24
|
* @example
|
|
25
25
|
* ```typescript
|
|
@@ -40,6 +40,11 @@ const validator_js_1 = require("./validator.js");
|
|
|
40
40
|
* ```
|
|
41
41
|
*/
|
|
42
42
|
class Schema {
|
|
43
|
+
get '~standard'() {
|
|
44
|
+
// Lazily create, and cache, the Standard Schema adapter for this schema
|
|
45
|
+
// instance.
|
|
46
|
+
return (0, lazy_property_js_1.lazyProperty)(this, '~standard', new standard_schema_js_1.StandardSchemaAdapter(this));
|
|
47
|
+
}
|
|
43
48
|
/**
|
|
44
49
|
* @note use {@link check}() instead of {@link assert}() if you encounter a
|
|
45
50
|
* `ts(2775)` error and you are not able to fully type the validator. This
|
package/dist/core/schema.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/core/schema.ts"],"names":[],"mappings":";;;AAAA,+DAAuD;AACvD,iDAOuB;AA8BvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAsB,MAAM;IAyC1B;;;;;OAKG;IACH,MAAM,CAAC,KAAc;QACnB,MAAM,MAAM,GAAG,gCAAiB,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QACtD,IAAI,CAAC,MAAM,CAAC,OAAO;YAAE,MAAM,MAAM,CAAC,MAAM,CAAA;IAC1C,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,KAAc;QAClB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IACpB,CAAC;IAED;;;;OAIG;IACH,IAAI,CAAI,KAAQ;QACd,MAAM,MAAM,GAAG,gCAAiB,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QACtD,IAAI,MAAM,CAAC,OAAO;YAAE,OAAO,MAAM,CAAC,KAAK,CAAA;QACvC,MAAM,MAAM,CAAC,MAAM,CAAA;IACrB,CAAC;IAED;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAI,KAAQ;QACjB,MAAM,MAAM,GAAG,gCAAiB,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QACtD,OAAO,MAAM,CAAC,OAAO,CAAA;IACvB,CAAC;IAED;;;;;;;;;;;;;;;;;OAiBG;IACH,SAAS,CAAI,KAAQ;QACnB,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAA;IAChD,CAAC;IAED;;;;;;;;;;;;;;;;;OAiBG;IACH,KAAK,CAAC,KAAc,EAAE,OAAsB;QAC1C,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,C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IAED;;;OAGG;IACH,IAAI,SAAS;QACX,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAClE,CAAC;IAED;;;OAGG;IACH,IAAI,aAAa;QACf,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,eAAe,EAAE,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAC1E,CAAC;CACF;AA7UD,wBA6UC","sourcesContent":["import { lazyProperty } from '../util/lazy-property.js'\nimport {\n InferInput,\n InferOutput,\n ValidationContext,\n ValidationOptions,\n ValidationResult,\n Validator,\n} from './validator.js'\n\n/**\n * Options for parsing operations.\n * Excludes the `mode` option as it is implicitly set to `\"parse\"`.\n */\nexport type ParseOptions = Omit<ValidationOptions, 'mode'>\n\n/**\n * Options for validation operations.\n * Excludes the `mode` option as it is implicitly set to `\"validate\"`.\n */\nexport type ValidateOptions = Omit<ValidationOptions, 'mode'>\n\n/**\n * Internal type structure for schema type inference.\n *\n * This interface defines the phantom types used for compile-time type inference\n * without affecting runtime behavior. The `input` and `output` properties\n * represent the expected input type during validation and the resulting output\n * type after parsing, respectively.\n *\n * @typeParam TInput - The type accepted as input during validation\n * @typeParam TOutput - The type returned after parsing (may differ from input due to coercion)\n */\nexport interface SchemaInternals<out TInput = unknown, out TOutput = TInput> {\n input: TInput\n output: TOutput\n}\n\n/**\n * Abstract base class for all schema validators in the lexicon system.\n *\n * This class provides the standard validation interface that all schema types\n * implement. It offers multiple methods for validating and parsing data:\n *\n * - **Assertion methods**: `assert()`, `check()` - throw on invalid input\n * - **Type guard methods**: `matches()`, `ifMatches()` - return boolean or optional value\n * - **Parse methods**: `parse()`, `safeParse()` - allow value transformation/coercion\n * - **Validate methods**: `validate()`, `safeValidate()` - strict validation without coercion\n *\n * All methods are also available with a `$` prefix (e.g., `$parse()`, `$validate()`)\n * for consistent access in generated lexicon namespaces.\n *\n * @typeParam TInput - The type accepted as valid input during validation\n * @typeParam TOutput - The type returned after parsing (may include transformations)\n * @typeParam TInternals - Internal type structure for type inference\n *\n * @example\n * ```typescript\n * class MySchema extends Schema<string> {\n * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {\n * if (typeof input !== 'string') {\n * return ctx.issueUnexpectedType(input, 'string')\n * }\n * return ctx.success(input)\n * }\n * }\n *\n * const schema = new MySchema()\n * schema.assert('hello') // OK\n * schema.assert(123) // Throws LexValidationError\n * schema.matches('hello') // true\n * schema.matches(123) // false\n * ```\n */\nexport abstract class Schema<\n out TInput = unknown,\n out TOutput = TInput,\n out TInternals extends SchemaInternals<TInput, TOutput> = SchemaInternals<\n TInput,\n TOutput\n >,\n> implements Validator<TInternals['input'], TInternals['output']>\n{\n /**\n * Internal phantom property for type inference.\n * This property does not exist at runtime.\n *\n * @internal\n */\n declare readonly ['__lex']: TInternals\n\n // Needed to discriminate multiple schema types when used in unions. Without\n // this, Typescript could allow an EnumSchema<\"foo\" | \"bar\"> to be used where\n // a StringSchema is expected, since they would both be structurally\n // compatible.\n abstract readonly type: string\n\n /**\n * Performs validation of the input value within a validation context.\n *\n * This method must be implemented by subclasses to define the actual\n * validation logic. It should not be called directly; use\n * {@link ValidationContext.validate} instead to ensure proper mode enforcement.\n *\n * @param input - The value to validate\n * @param ctx - The validation context providing path tracking and issue reporting\n * @returns A validation result indicating success with the validated value or failure with issues\n *\n * @internal\n */\n abstract validateInContext(\n input: unknown,\n ctx: ValidationContext,\n ): ValidationResult\n\n /**\n * @note use {@link check}() instead of {@link assert}() if you encounter a\n * `ts(2775)` error and you are not able to fully type the validator. This\n * will typically arise in generic contexts, where the narrowed type is not\n * needed.\n */\n assert(input: unknown): asserts input is InferInput<this> {\n const result = ValidationContext.validate(input, this)\n if (!result.success) throw result.reason\n }\n\n /**\n * Alias for {@link assert}(). Most useful in generic contexts where the\n * validator is not exactly typed, allowing to avoid \"_Assertions require\n * every name in the call target to be declared with an explicit type\n * annotation. ts(2775)_\" errors.\n */\n check(input: unknown): void {\n this.assert(input)\n }\n\n /**\n * Casts the input (by validating it) to the output type if it matches the\n * schema, otherwise throws. This is the same as calling {@link parse}() with\n * `mode: \"validate\"`.\n */\n cast<I>(input: I): I & InferInput<this> {\n const result = ValidationContext.validate(input, this)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Type guard that checks if the input matches this schema.\n *\n * @param input - The value to check\n * @returns `true` if the input is valid according to this schema\n *\n * @example\n * ```typescript\n * if (schema.matches(data)) {\n * // data is narrowed to the schema's input type\n * console.log(data)\n * }\n * ```\n */\n matches<I>(input: I): input is I & InferInput<this> {\n const result = ValidationContext.validate(input, this)\n return result.success\n }\n\n /**\n * Returns the input if it matches this schema, otherwise returns `undefined`.\n *\n * This is useful for optional filtering operations where you want to\n * conditionally extract values that match a schema.\n *\n * @param input - The value to check\n * @returns The input value with narrowed type if valid, otherwise `undefined`\n *\n * @example\n * ```typescript\n * const validData = schema.ifMatches(data)\n * if (validData !== undefined) {\n * // validData is the schema's input type\n * console.log(validData)\n * }\n * ```\n */\n ifMatches<I>(input: I): (I & InferInput<this>) | undefined {\n return this.matches(input) ? input : undefined\n }\n\n /**\n * Parses the input, allowing value transformations and coercion.\n *\n * Unlike {@link validate}, this method allows the schema to transform\n * the input value (e.g., applying default values, type coercion).\n * Throws a {@link LexValidationError} if the input is invalid.\n *\n * @param input - The value to parse\n * @param options - Optional parsing configuration\n * @returns The parsed and potentially transformed value\n * @throws {LexValidationError} If the input fails validation\n *\n * @example\n * ```typescript\n * const result = schema.parse(rawData)\n * // result has defaults applied and is fully typed\n * ```\n */\n parse(input: unknown, options?: ParseOptions): InferOutput<this> {\n const result = this.safeParse(input, options)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Safely parses the input without throwing, returning a result object.\n *\n * This method allows value transformations like {@link parse}, but\n * returns a discriminated union result instead of throwing on error.\n *\n * @param input - The value to parse\n * @param options - Optional parsing configuration\n * @returns A {@link ValidationResult} with either the parsed value or validation errors\n *\n * @example\n * ```typescript\n * const result = schema.safeParse(data)\n * if (result.success) {\n * console.log(result.value)\n * } else {\n * console.error(result.reason.issues)\n * }\n * ```\n */\n safeParse(\n input: unknown,\n options?: ParseOptions,\n ): ValidationResult<InferOutput<this>> {\n return ValidationContext.validate(input, this, {\n ...options,\n mode: 'parse',\n })\n }\n\n /**\n * Validates the input strictly without allowing transformations.\n *\n * Unlike {@link parse}, this method requires the input to exactly match\n * the schema without any transformations (no defaults applied, no coercion).\n * Throws a {@link LexValidationError} if the input is invalid or would require transformation.\n *\n * @typeParam I - The input type (preserved in the return type)\n * @param input - The value to validate\n * @param options - Optional validation configuration\n * @returns The validated input with narrowed type\n * @throws {LexValidationError} If the input fails validation or requires transformation\n *\n * @example\n * ```typescript\n * const validated = schema.validate(data)\n * // validated is typed as the intersection of input type and schema type\n * ```\n */\n validate<I>(input: I, options?: ValidateOptions): I & InferInput<this> {\n const result = this.safeValidate(input, options)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Safely validates the input without throwing, returning a result object.\n *\n * This method performs strict validation like {@link validate}, but\n * returns a discriminated union result instead of throwing on error.\n *\n * @typeParam I - The input type (preserved in the result value type)\n * @param input - The value to validate\n * @param options - Optional validation configuration\n * @returns A {@link ValidationResult} with either the validated value or validation errors\n *\n * @example\n * ```typescript\n * const result = schema.safeValidate(data)\n * if (result.success) {\n * console.log(result.value)\n * } else {\n * console.error(result.reason.issues)\n * }\n * ```\n */\n safeValidate<I>(\n input: I,\n options?: ValidateOptions,\n ): ValidationResult<I & InferInput<this>> {\n return ValidationContext.validate(input, this, {\n ...options,\n mode: 'validate',\n })\n }\n\n // @NOTE Dollar-prefixed aliases\n //\n // The `lex-builder` lib generates namespaced utility functions that allow\n // accessing the schema's methods without the need to specify the \".main.\"\n // part of the namespace. This allows utilities for a particular record type\n // to be called like \"app.bsky.feed.post.<utility>()\" instead of\n // \"app.bsky.feed.post.main.<utility>()\".\n //\n // Because those utilities could conflict with other schemas (e.g. if there is\n // a lexicon definition with the same name as the \"<utility>\"), those exported\n // utilities will be prefixed with \"$\".\n //\n // Similarly, since those utilities are defined as simple \"const\", they are\n // also bound (using JS's .bind) to the schema instance, so that they can be\n // used without worrying about the context (e.g. \"app.bsky.feed.post.$parse()\"\n // will work regardless of how it is imported or called).\n //\n // In order to provide the same functionalities for non-main definitions, we\n // also define those aliases directly on the schema instance, so that they can\n // be used in the same way as the utilities generated by \"lex-builder\". For\n // example, if there is a non-main definition \"app.bsky.feed.defs.postView\",\n // it will also be possible to call \"app.bsky.feed.defs.postView.$parse()\".\n //\n // These methods are also \"bound\" to the instance so that they can be used\n // exactly like the utilities generated by \"lex-builder\", without worrying\n // about the context.\n //\n // There are two ways we could \"bind\" those methods to the instance:\n // 1. Define them as getters that return the bound method (e.g. get $parse() {\n // return this.parse.bind(this) })\n // 2. Define them as properties that are initialized in the constructor (e.g.\n // this.$parse = this.parse.bind(this))\n //\n // Since a **lot** of those methods would end-up being created in systems that\n // contains many schemas (e.g. the appview), we choose the first approach\n // (getters) in order to avoid the overhead of creating all those bound\n // functions upfront when instantiating the schemas.\n\n /**\n * Bound alias for {@link assert} for compatibility with generated utilities.\n * @see {@link assert}\n */\n get $assert(): typeof this.assert {\n return lazyProperty(this, '$assert', this.assert.bind(this))\n }\n\n /**\n * Bound alias for {@link check} for compatibility with generated utilities.\n * @see {@link check}\n */\n get $check(): typeof this.check {\n return lazyProperty(this, '$check', this.check.bind(this))\n }\n\n /**\n * Bound alias for {@link cast} for compatibility with generated utilities.\n * @see {@link cast}\n */\n get $cast(): typeof this.cast {\n return lazyProperty(this, '$cast', this.cast.bind(this))\n }\n\n /**\n * Bound alias for {@link matches} for compatibility with generated utilities.\n * @see {@link matches}\n */\n get $matches(): typeof this.matches {\n return lazyProperty(this, '$matches', this.matches.bind(this))\n }\n\n /**\n * Bound alias for {@link ifMatches} for compatibility with generated utilities.\n * @see {@link ifMatches}\n */\n get $ifMatches(): typeof this.ifMatches {\n return lazyProperty(this, '$ifMatches', this.ifMatches.bind(this))\n }\n\n /**\n * Bound alias for {@link parse} for compatibility with generated utilities.\n * @see {@link parse}\n */\n get $parse(): typeof this.parse {\n return lazyProperty(this, '$parse', this.parse.bind(this))\n }\n\n /**\n * Bound alias for {@link safeParse} for compatibility with generated utilities.\n * @see {@link safeParse}\n */\n get $safeParse(): typeof this.safeParse {\n return lazyProperty(this, '$safeParse', this.safeParse.bind(this))\n }\n\n /**\n * Bound alias for {@link validate} for compatibility with generated utilities.\n * @see {@link validate}\n */\n get $validate(): typeof this.validate {\n return lazyProperty(this, '$validate', this.validate.bind(this))\n }\n\n /**\n * Bound alias for {@link safeValidate} for compatibility with generated utilities.\n * @see {@link safeValidate}\n */\n get $safeValidate(): typeof this.safeValidate {\n return lazyProperty(this, '$safeValidate', this.safeValidate.bind(this))\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/core/schema.ts"],"names":[],"mappings":";;;AACA,+DAAuD;AACvD,6DAA4D;AAC5D,iDAOuB;AA8BvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAsB,MAAM;IAW1B,IAAI,WAAW;QACb,wEAAwE;QACxE,YAAY;QACZ,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,WAAW,EAAE,IAAI,0CAAqB,CAAC,IAAI,CAAC,CAAC,CAAA;IACzE,CAAC;IA0BD;;;;;OAKG;IACH,MAAM,CAAC,KAAc;QACnB,MAAM,MAAM,GAAG,gCAAiB,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QACtD,IAAI,CAAC,MAAM,CAAC,OAAO;YAAE,MAAM,MAAM,CAAC,MAAM,CAAA;IAC1C,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,KAAc;QAClB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IACpB,CAAC;IAED;;;;OAIG;IACH,IAAI,CAAI,KAA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C,CAAC,CAAA;IAC1D,CAAC;IAED;;;OAGG;IACH,IAAI,QAAQ;QACV,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAChE,CAAC;IAED;;;OAGG;IACH,IAAI,UAAU;QACZ,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,YAAY,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IACpE,CAAC;IAED;;;OAGG;IACH,IAAI,MAAM;QACR,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAC5D,CAAC;IAED;;;OAGG;IACH,IAAI,UAAU;QACZ,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,YAAY,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IACpE,CAAC;IAED;;;OAGG;IACH,IAAI,SAAS;QACX,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAClE,CAAC;IAED;;;OAGG;IACH,IAAI,aAAa;QACf,OAAO,IAAA,+BAAY,EAAC,IAAI,EAAE,eAAe,EAAE,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;IAC1E,CAAC;CACF;AA7UD,wBA6UC","sourcesContent":["import { StandardSchemaV1 } from '@standard-schema/spec'\nimport { lazyProperty } from '../util/lazy-property.js'\nimport { StandardSchemaAdapter } from './standard-schema.js'\nimport {\n InferInput,\n InferOutput,\n ValidationContext,\n ValidationOptions,\n ValidationResult,\n Validator,\n} from './validator.js'\n\n/**\n * Options for parsing operations.\n * Excludes the `mode` option as it is implicitly set to `\"parse\"`.\n */\nexport type ParseOptions = Omit<ValidationOptions, 'mode'>\n\n/**\n * Options for validation operations.\n * Excludes the `mode` option as it is implicitly set to `\"validate\"`.\n */\nexport type ValidateOptions = Omit<ValidationOptions, 'mode'>\n\n/**\n * Internal type structure for schema type inference.\n *\n * This interface defines the phantom types used for compile-time type inference\n * without affecting runtime behavior. The `input` and `output` properties\n * represent the expected input type during validation and the resulting output\n * type after parsing, respectively.\n *\n * @typeParam TInput - The type accepted as input during validation\n * @typeParam TOutput - The type returned after parsing (may differ from input due to coercion)\n */\nexport interface SchemaInternals<out TInput = unknown, out TOutput = TInput> {\n input: TInput\n output: TOutput\n}\n\n/**\n * Abstract base class for all schema validators in the lexicon system.\n *\n * This class provides the standard validation interface that all schema types\n * implement. It offers multiple methods for validating and parsing data:\n *\n * - **Assertion methods**: `assert()`, `check()` - throw on invalid input\n * - **Type guard methods**: `matches()`, `ifMatches()` - return boolean or optional value\n * - **Parse methods**: `parse()`, `safeParse()` - allow value transformation/coercion\n * - **Validate methods**: `validate()`, `safeValidate()` - validation without coercion\n *\n * All methods are also available with a `$` prefix (e.g., `$parse()`, `$validate()`)\n * for consistent access in generated lexicon namespaces.\n *\n * @typeParam TInput - The type accepted as valid input during validation\n * @typeParam TOutput - The type returned after parsing (may include transformations)\n *\n * @example\n * ```typescript\n * class MySchema extends Schema<string> {\n * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {\n * if (typeof input !== 'string') {\n * return ctx.issueUnexpectedType(input, 'string')\n * }\n * return ctx.success(input)\n * }\n * }\n *\n * const schema = new MySchema()\n * schema.assert('hello') // OK\n * schema.assert(123) // Throws LexValidationError\n * schema.matches('hello') // true\n * schema.matches(123) // false\n * ```\n */\nexport abstract class Schema<out TInput = unknown, out TOutput = TInput>\n implements Validator<TInput, TOutput>, StandardSchemaV1<TInput, TOutput>\n{\n /**\n * Internal phantom property for type inference.\n * This property does not exist at runtime.\n *\n * @internal\n */\n declare readonly ['__lex']: SchemaInternals<TInput, TOutput>\n\n get '~standard'(): StandardSchemaV1.Props<TInput, TOutput> {\n // Lazily create, and cache, the Standard Schema adapter for this schema\n // instance.\n return lazyProperty(this, '~standard', new StandardSchemaAdapter(this))\n }\n\n // Needed to discriminate multiple schema types when used in unions. Without\n // this, Typescript could allow an EnumSchema<\"foo\" | \"bar\"> to be used where\n // a StringSchema is expected, since they would both be structurally\n // compatible.\n abstract readonly type: string\n\n /**\n * Performs validation of the input value within a validation context.\n *\n * This method must be implemented by subclasses to define the actual\n * validation logic. It should not be called directly; use\n * {@link ValidationContext.validate} instead to ensure proper mode enforcement.\n *\n * @param input - The value to validate\n * @param ctx - The validation context providing path tracking and issue reporting\n * @returns A validation result indicating success with the validated value or failure with issues\n *\n * @internal\n */\n abstract validateInContext(\n input: unknown,\n ctx: ValidationContext,\n ): ValidationResult\n\n /**\n * @note use {@link check}() instead of {@link assert}() if you encounter a\n * `ts(2775)` error and you are not able to fully type the validator. This\n * will typically arise in generic contexts, where the narrowed type is not\n * needed.\n */\n assert(input: unknown): asserts input is InferInput<this> {\n const result = ValidationContext.validate(input, this)\n if (!result.success) throw result.reason\n }\n\n /**\n * Alias for {@link assert}(). Most useful in generic contexts where the\n * validator is not exactly typed, allowing to avoid \"_Assertions require\n * every name in the call target to be declared with an explicit type\n * annotation. ts(2775)_\" errors.\n */\n check(input: unknown): void {\n this.assert(input)\n }\n\n /**\n * Casts the input (by validating it) to the output type if it matches the\n * schema, otherwise throws. This is the same as calling {@link parse}() with\n * `mode: \"validate\"`.\n */\n cast<I>(input: I): I & InferInput<this> {\n const result = ValidationContext.validate(input, this)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Type guard that checks if the input matches this schema.\n *\n * @param input - The value to check\n * @returns `true` if the input is valid according to this schema\n *\n * @example\n * ```typescript\n * if (schema.matches(data)) {\n * // data is narrowed to the schema's input type\n * console.log(data)\n * }\n * ```\n */\n matches<I>(input: I): input is I & InferInput<this> {\n const result = ValidationContext.validate(input, this)\n return result.success\n }\n\n /**\n * Returns the input if it matches this schema, otherwise returns `undefined`.\n *\n * This is useful for optional filtering operations where you want to\n * conditionally extract values that match a schema.\n *\n * @param input - The value to check\n * @returns The input value with narrowed type if valid, otherwise `undefined`\n *\n * @example\n * ```typescript\n * const validData = schema.ifMatches(data)\n * if (validData !== undefined) {\n * // validData is the schema's input type\n * console.log(validData)\n * }\n * ```\n */\n ifMatches<I>(input: I): (I & InferInput<this>) | undefined {\n return this.matches(input) ? input : undefined\n }\n\n /**\n * Parses the input, allowing value transformations and coercion.\n *\n * Unlike {@link validate}, this method allows the schema to transform\n * the input value (e.g., applying default values, type coercion).\n * Throws a {@link LexValidationError} if the input is invalid.\n *\n * @param input - The value to parse\n * @param options - Optional parsing configuration\n * @returns The parsed and potentially transformed value\n * @throws {LexValidationError} If the input fails validation\n *\n * @example\n * ```typescript\n * const result = schema.parse(rawData)\n * // result has defaults applied and is fully typed\n * ```\n */\n parse(input: unknown, options?: ParseOptions): InferOutput<this> {\n const result = this.safeParse(input, options)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Safely parses the input without throwing, returning a result object.\n *\n * This method allows value transformations like {@link parse}, but\n * returns a discriminated union result instead of throwing on error.\n *\n * @param input - The value to parse\n * @param options - Optional parsing configuration\n * @returns A {@link ValidationResult} with either the parsed value or validation errors\n *\n * @example\n * ```typescript\n * const result = schema.safeParse(data)\n * if (result.success) {\n * console.log(result.value)\n * } else {\n * console.error(result.reason.issues)\n * }\n * ```\n */\n safeParse(\n input: unknown,\n options?: ParseOptions,\n ): ValidationResult<InferOutput<this>> {\n return ValidationContext.validate(input, this, {\n ...options,\n mode: 'parse',\n })\n }\n\n /**\n * Validates the input strictly without allowing transformations.\n *\n * Unlike {@link parse}, this method requires the input to exactly match\n * the schema without any transformations (no defaults applied, no coercion).\n * Throws a {@link LexValidationError} if the input is invalid or would require transformation.\n *\n * @typeParam I - The input type (preserved in the return type)\n * @param input - The value to validate\n * @param options - Optional validation configuration\n * @returns The validated input with narrowed type\n * @throws {LexValidationError} If the input fails validation or requires transformation\n *\n * @example\n * ```typescript\n * const validated = schema.validate(data)\n * // validated is typed as the intersection of input type and schema type\n * ```\n */\n validate<I>(input: I, options?: ValidateOptions): I & InferInput<this> {\n const result = this.safeValidate(input, options)\n if (result.success) return result.value\n throw result.reason\n }\n\n /**\n * Safely validates the input without throwing, returning a result object.\n *\n * This method performs strict validation like {@link validate}, but\n * returns a discriminated union result instead of throwing on error.\n *\n * @typeParam I - The input type (preserved in the result value type)\n * @param input - The value to validate\n * @param options - Optional validation configuration\n * @returns A {@link ValidationResult} with either the validated value or validation errors\n *\n * @example\n * ```typescript\n * const result = schema.safeValidate(data)\n * if (result.success) {\n * console.log(result.value)\n * } else {\n * console.error(result.reason.issues)\n * }\n * ```\n */\n safeValidate<I>(\n input: I,\n options?: ValidateOptions,\n ): ValidationResult<I & InferInput<this>> {\n return ValidationContext.validate(input, this, {\n ...options,\n mode: 'validate',\n })\n }\n\n // @NOTE Dollar-prefixed aliases\n //\n // The `lex-builder` lib generates namespaced utility functions that allow\n // accessing the schema's methods without the need to specify the \".main.\"\n // part of the namespace. This allows utilities for a particular record type\n // to be called like \"app.bsky.feed.post.<utility>()\" instead of\n // \"app.bsky.feed.post.main.<utility>()\".\n //\n // Because those utilities could conflict with other schemas (e.g. if there is\n // a lexicon definition with the same name as the \"<utility>\"), those exported\n // utilities will be prefixed with \"$\".\n //\n // Similarly, since those utilities are defined as simple \"const\", they are\n // also bound (using JS's .bind) to the schema instance, so that they can be\n // used without worrying about the context (e.g. \"app.bsky.feed.post.$parse()\"\n // will work regardless of how it is imported or called).\n //\n // In order to provide the same functionalities for non-main definitions, we\n // also define those aliases directly on the schema instance, so that they can\n // be used in the same way as the utilities generated by \"lex-builder\". For\n // example, if there is a non-main definition \"app.bsky.feed.defs.postView\",\n // it will also be possible to call \"app.bsky.feed.defs.postView.$parse()\".\n //\n // These methods are also \"bound\" to the instance so that they can be used\n // exactly like the utilities generated by \"lex-builder\", without worrying\n // about the context.\n //\n // There are two ways we could \"bind\" those methods to the instance:\n // 1. Define them as getters that return the bound method (e.g. get $parse() {\n // return this.parse.bind(this) })\n // 2. Define them as properties that are initialized in the constructor (e.g.\n // this.$parse = this.parse.bind(this))\n //\n // Since a **lot** of those methods would end-up being created in systems that\n // contains many schemas (e.g. the appview), we choose the first approach\n // (getters) in order to avoid the overhead of creating all those bound\n // functions upfront when instantiating the schemas.\n\n /**\n * Bound alias for {@link assert} for compatibility with generated utilities.\n * @see {@link assert}\n */\n get $assert(): typeof this.assert {\n return lazyProperty(this, '$assert', this.assert.bind(this))\n }\n\n /**\n * Bound alias for {@link check} for compatibility with generated utilities.\n * @see {@link check}\n */\n get $check(): typeof this.check {\n return lazyProperty(this, '$check', this.check.bind(this))\n }\n\n /**\n * Bound alias for {@link cast} for compatibility with generated utilities.\n * @see {@link cast}\n */\n get $cast(): typeof this.cast {\n return lazyProperty(this, '$cast', this.cast.bind(this))\n }\n\n /**\n * Bound alias for {@link matches} for compatibility with generated utilities.\n * @see {@link matches}\n */\n get $matches(): typeof this.matches {\n return lazyProperty(this, '$matches', this.matches.bind(this))\n }\n\n /**\n * Bound alias for {@link ifMatches} for compatibility with generated utilities.\n * @see {@link ifMatches}\n */\n get $ifMatches(): typeof this.ifMatches {\n return lazyProperty(this, '$ifMatches', this.ifMatches.bind(this))\n }\n\n /**\n * Bound alias for {@link parse} for compatibility with generated utilities.\n * @see {@link parse}\n */\n get $parse(): typeof this.parse {\n return lazyProperty(this, '$parse', this.parse.bind(this))\n }\n\n /**\n * Bound alias for {@link safeParse} for compatibility with generated utilities.\n * @see {@link safeParse}\n */\n get $safeParse(): typeof this.safeParse {\n return lazyProperty(this, '$safeParse', this.safeParse.bind(this))\n }\n\n /**\n * Bound alias for {@link validate} for compatibility with generated utilities.\n * @see {@link validate}\n */\n get $validate(): typeof this.validate {\n return lazyProperty(this, '$validate', this.validate.bind(this))\n }\n\n /**\n * Bound alias for {@link safeValidate} for compatibility with generated utilities.\n * @see {@link safeValidate}\n */\n get $safeValidate(): typeof this.safeValidate {\n return lazyProperty(this, '$safeValidate', this.safeValidate.bind(this))\n }\n}\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
import { Validator } from './validator.js';
|
|
3
|
+
/**
|
|
4
|
+
* The Standard Schema adapter for {@link Validator} instances.
|
|
5
|
+
*/
|
|
6
|
+
export declare class StandardSchemaAdapter<TInput, TOutput> implements StandardSchemaV1.Props<TInput, TOutput> {
|
|
7
|
+
private readonly validator;
|
|
8
|
+
readonly version = 1;
|
|
9
|
+
readonly vendor = "@atproto/lex-schema";
|
|
10
|
+
readonly types: StandardSchemaV1.Types<TInput, TOutput>;
|
|
11
|
+
constructor(validator: Validator<TInput, TOutput>);
|
|
12
|
+
validate(value: unknown, options?: StandardSchemaV1.Options): StandardSchemaV1.Result<TOutput>;
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=standard-schema.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard-schema.d.ts","sourceRoot":"","sources":["../../src/core/standard-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,EAAqB,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAE7D;;GAEG;AACH,qBAAa,qBAAqB,CAAC,MAAM,EAAE,OAAO,CAChD,YAAW,gBAAgB,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC;IAQtC,OAAO,CAAC,QAAQ,CAAC,SAAS;IANtC,QAAQ,CAAC,OAAO,KAAI;IAEpB,QAAQ,CAAC,MAAM,yBAAwB;IAEvC,SAAiB,KAAK,EAAE,gBAAgB,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;gBAElC,SAAS,EAAE,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC;IAElE,QAAQ,CACN,KAAK,EAAE,OAAO,EACd,OAAO,CAAC,EAAE,gBAAgB,CAAC,OAAO,GACjC,gBAAgB,CAAC,MAAM,CAAC,OAAO,CAAC;CAUpC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.StandardSchemaAdapter = void 0;
|
|
4
|
+
const validator_js_1 = require("./validator.js");
|
|
5
|
+
/**
|
|
6
|
+
* The Standard Schema adapter for {@link Validator} instances.
|
|
7
|
+
*/
|
|
8
|
+
class StandardSchemaAdapter {
|
|
9
|
+
validator;
|
|
10
|
+
version = 1;
|
|
11
|
+
vendor = '@atproto/lex-schema';
|
|
12
|
+
constructor(validator) {
|
|
13
|
+
this.validator = validator;
|
|
14
|
+
}
|
|
15
|
+
validate(value, options) {
|
|
16
|
+
// Perform validation in "parse" mode to ensure transformations (defaults,
|
|
17
|
+
// coercions, etc.) are applied. Also ensures that the output type is
|
|
18
|
+
// returned. Note that ValidationResult is compatible with
|
|
19
|
+
// StandardSchemaV1.Result :-)
|
|
20
|
+
return validator_js_1.ValidationContext.validate(value, this.validator, {
|
|
21
|
+
...options?.libraryOptions,
|
|
22
|
+
mode: 'parse',
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
exports.StandardSchemaAdapter = StandardSchemaAdapter;
|
|
27
|
+
//# sourceMappingURL=standard-schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard-schema.js","sourceRoot":"","sources":["../../src/core/standard-schema.ts"],"names":[],"mappings":";;;AACA,iDAA6D;AAE7D;;GAEG;AACH,MAAa,qBAAqB;IASH;IANpB,OAAO,GAAG,CAAC,CAAA;IAEX,MAAM,GAAG,qBAAqB,CAAA;IAIvC,YAA6B,SAAqC;QAArC,cAAS,GAAT,SAAS,CAA4B;IAAG,CAAC;IAEtE,QAAQ,CACN,KAAc,EACd,OAAkC;QAElC,0EAA0E;QAC1E,qEAAqE;QACrE,0DAA0D;QAC1D,8BAA8B;QAC9B,OAAO,gCAAiB,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,EAAE;YACvD,GAAG,OAAO,EAAE,cAAc;YAC1B,IAAI,EAAE,OAAO;SACd,CAAC,CAAA;IACJ,CAAC;CACF;AAxBD,sDAwBC","sourcesContent":["import { StandardSchemaV1 } from '@standard-schema/spec'\nimport { ValidationContext, Validator } from './validator.js'\n\n/**\n * The Standard Schema adapter for {@link Validator} instances.\n */\nexport class StandardSchemaAdapter<TInput, TOutput>\n implements StandardSchemaV1.Props<TInput, TOutput>\n{\n readonly version = 1\n\n readonly vendor = '@atproto/lex-schema'\n\n declare readonly types: StandardSchemaV1.Types<TInput, TOutput>\n\n constructor(private readonly validator: Validator<TInput, TOutput>) {}\n\n validate(\n value: unknown,\n options?: StandardSchemaV1.Options,\n ): StandardSchemaV1.Result<TOutput> {\n // Perform validation in \"parse\" mode to ensure transformations (defaults,\n // coercions, etc.) are applied. Also ensures that the output type is\n // returned. Note that ValidationResult is compatible with\n // StandardSchemaV1.Result :-)\n return ValidationContext.validate(value, this.validator, {\n ...options?.libraryOptions,\n mode: 'parse',\n })\n }\n}\n"]}
|
|
@@ -1,20 +1,15 @@
|
|
|
1
1
|
import { AtIdentifierString, AtUriString, DatetimeString, DidString, HandleString, NsidString, RecordKeyString, TidString, UriString } from '@atproto/syntax';
|
|
2
2
|
import { CheckFn } from '../util/assertion-util.js';
|
|
3
|
-
export { type
|
|
3
|
+
export { type AtIdentifierString, asAtIdentifierString, ifAtIdentifierString, isAtIdentifierString, } from '@atproto/syntax';
|
|
4
|
+
export { isDidIdentifier, isHandleIdentifier } from '@atproto/syntax';
|
|
5
|
+
export { type DatetimeString, asDatetimeString, ifDatetimeString, isDatetimeString, } from '@atproto/syntax';
|
|
4
6
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* @returns `true` if the value is a valid AT identifier
|
|
7
|
+
* Matches any ISO-ish datetime string. This is a more lenient check than
|
|
8
|
+
* the strict {@link isDatetimeString} guard, which only allows datetimes that
|
|
9
|
+
* fully conform to the AT Protocol specification (e.g. must include timezone).
|
|
9
10
|
*/
|
|
10
|
-
export declare
|
|
11
|
-
export
|
|
12
|
-
/**
|
|
13
|
-
* An AT identifier string - either a DID or a handle.
|
|
14
|
-
*
|
|
15
|
-
* @example `"did:plc:1234..."` or `"alice.bsky.social"`
|
|
16
|
-
*/
|
|
17
|
-
AtIdentifierString, };
|
|
11
|
+
export declare function isDatetimeStringLoose<I>(input: I): input is I & DatetimeString;
|
|
12
|
+
export { currentDatetimeString, toDatetimeString } from '@atproto/syntax';
|
|
18
13
|
/**
|
|
19
14
|
* Type guard that checks if a value is a valid AT URI.
|
|
20
15
|
*
|
|
@@ -164,6 +159,18 @@ type StringFormats = {
|
|
|
164
159
|
* Union type of all valid string format names.
|
|
165
160
|
*/
|
|
166
161
|
export type StringFormat = Extract<keyof StringFormats, string>;
|
|
162
|
+
export type StringFormatValidationOptions = {
|
|
163
|
+
/**
|
|
164
|
+
* Allows to be more lenient in validation by using a "loose" verification
|
|
165
|
+
* function, if available. The behavior of the loose verifier depends on the
|
|
166
|
+
* specific format, but generally it may allow for a wider range of valid
|
|
167
|
+
* inputs, including values that are not compliant with the AT Protocol
|
|
168
|
+
* specification.
|
|
169
|
+
*
|
|
170
|
+
* @default true
|
|
171
|
+
*/
|
|
172
|
+
strict?: boolean;
|
|
173
|
+
};
|
|
167
174
|
/**
|
|
168
175
|
* Infers the string type for a given format name.
|
|
169
176
|
*
|
|
@@ -194,7 +201,7 @@ export type InferStringFormat<F extends StringFormat> = F extends StringFormat ?
|
|
|
194
201
|
* }
|
|
195
202
|
* ```
|
|
196
203
|
*/
|
|
197
|
-
export declare function isStringFormat<I extends string, F extends StringFormat>(input: I, format: F): input is I & StringFormats[F];
|
|
204
|
+
export declare function isStringFormat<I extends string, F extends StringFormat>(input: I, format: F, options?: StringFormatValidationOptions): input is I & StringFormats[F];
|
|
198
205
|
/**
|
|
199
206
|
* Asserts that a string matches a specific format, throwing if invalid.
|
|
200
207
|
*
|
|
@@ -210,7 +217,7 @@ export declare function isStringFormat<I extends string, F extends StringFormat>
|
|
|
210
217
|
* // value is now typed as HandleString
|
|
211
218
|
* ```
|
|
212
219
|
*/
|
|
213
|
-
export declare function assertStringFormat<I extends string, F extends StringFormat>(input: I, format: F): asserts input is I & StringFormats[F];
|
|
220
|
+
export declare function assertStringFormat<I extends string, F extends StringFormat>(input: I, format: F, options?: StringFormatValidationOptions): asserts input is I & StringFormats[F];
|
|
214
221
|
/**
|
|
215
222
|
* Validates and returns a string as the specified format type, throwing if invalid.
|
|
216
223
|
*
|
|
@@ -229,7 +236,7 @@ export declare function assertStringFormat<I extends string, F extends StringFor
|
|
|
229
236
|
* // did is typed as DidString
|
|
230
237
|
* ```
|
|
231
238
|
*/
|
|
232
|
-
export declare function asStringFormat<I extends string, F extends StringFormat>(input: I, format: F): I & StringFormats[F];
|
|
239
|
+
export declare function asStringFormat<I extends string, F extends StringFormat>(input: I, format: F, options?: StringFormatValidationOptions): I & StringFormats[F];
|
|
233
240
|
/**
|
|
234
241
|
* Returns the string as the format type if valid, otherwise returns `undefined`.
|
|
235
242
|
*
|
|
@@ -250,7 +257,7 @@ export declare function asStringFormat<I extends string, F extends StringFormat>
|
|
|
250
257
|
* }
|
|
251
258
|
* ```
|
|
252
259
|
*/
|
|
253
|
-
export declare function ifStringFormat<I extends string, F extends StringFormat>(input: I, format: F): undefined | (I & StringFormats[F]);
|
|
260
|
+
export declare function ifStringFormat<I extends string, F extends StringFormat>(input: I, format: F, options?: StringFormatValidationOptions): undefined | (I & StringFormats[F]);
|
|
254
261
|
/**
|
|
255
262
|
* Array of all valid string format names.
|
|
256
263
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string-format.d.ts","sourceRoot":"","sources":["../../src/core/string-format.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"string-format.d.ts","sourceRoot":"","sources":["../../src/core/string-format.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,kBAAkB,EAClB,WAAW,EACX,cAAc,EACd,SAAS,EACT,YAAY,EACZ,UAAU,EACV,eAAe,EACf,SAAS,EACT,SAAS,EAWV,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAA;AAWnD,OAAO,EACL,KAAK,kBAAkB,EACvB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,iBAAiB,CAAA;AAGxB,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AAErE,OAAO,EACL,KAAK,cAAc,EACnB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,iBAAiB,CAAA;AAExB;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,EACrC,KAAK,EAAE,CAAC,GACP,KAAK,IAAI,CAAC,GAAG,cAAc,CAW7B;AAGD,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAEzE;;;;;GAKG;AACH,eAAO,MAAM,aAAa,EAAE,OAAO,CAAC,WAAW,CAAgB,CAAA;AAC/D,YAAY;AACV;;;;GAIG;AACH,WAAW,GACZ,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,WAAW,EAAoC,OAAO,CAAC,SAAS,CAAC,CAAA;AAC9E;;;;;;GAMG;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,CAAA;AAE9B;;;;;GAKG;AACH,eAAO,MAAM,WAAW,EAAE,OAAO,CAAC,SAAS,CAAc,CAAA;AACzD,YAAY;AACV;;;;;;GAMG;AACH,SAAS,GACV,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,cAAc,EAAE,OAAO,CAAC,YAAY,CAAiB,CAAA;AAClE,YAAY;AACV;;;;GAIG;AACH,YAAY,GACb,CAAA;AAED;;;;;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value: true });
|
|
3
|
-
exports.STRING_FORMATS = exports.isUriString = exports.isTidString = exports.isRecordKeyString = exports.isNsidString = exports.isLanguageString = exports.isHandleString = exports.isDidString = exports.isCidString = exports.isAtUriString = exports.
|
|
3
|
+
exports.STRING_FORMATS = exports.isUriString = exports.isTidString = exports.isRecordKeyString = exports.isNsidString = exports.isLanguageString = exports.isHandleString = exports.isDidString = exports.isCidString = exports.isAtUriString = exports.toDatetimeString = exports.currentDatetimeString = exports.isDatetimeString = exports.ifDatetimeString = exports.asDatetimeString = exports.isHandleIdentifier = exports.isDidIdentifier = exports.isAtIdentifierString = exports.ifAtIdentifierString = exports.asAtIdentifierString = void 0;
|
|
4
|
+
exports.isDatetimeStringLoose = isDatetimeStringLoose;
|
|
4
5
|
exports.isStringFormat = isStringFormat;
|
|
5
6
|
exports.assertStringFormat = assertStringFormat;
|
|
6
7
|
exports.asStringFormat = asStringFormat;
|
|
7
8
|
exports.ifStringFormat = ifStringFormat;
|
|
9
|
+
const iso_datestring_validator_1 = require("iso-datestring-validator");
|
|
8
10
|
const lex_data_1 = require("@atproto/lex-data");
|
|
9
11
|
const syntax_1 = require("@atproto/syntax");
|
|
10
12
|
// -----------------------------------------------------------------------------
|
|
@@ -15,18 +17,40 @@ const syntax_1 = require("@atproto/syntax");
|
|
|
15
17
|
// @TODO rework other string formats in @atproto/syntax to follow this pattern
|
|
16
18
|
// and re-export here, e.g. language tags, NSIDs, record keys, etc.
|
|
17
19
|
var syntax_2 = require("@atproto/syntax");
|
|
18
|
-
Object.defineProperty(exports, "
|
|
19
|
-
Object.defineProperty(exports, "
|
|
20
|
-
Object.defineProperty(exports, "
|
|
21
|
-
|
|
22
|
-
|
|
20
|
+
Object.defineProperty(exports, "asAtIdentifierString", { enumerable: true, get: function () { return syntax_2.asAtIdentifierString; } });
|
|
21
|
+
Object.defineProperty(exports, "ifAtIdentifierString", { enumerable: true, get: function () { return syntax_2.ifAtIdentifierString; } });
|
|
22
|
+
Object.defineProperty(exports, "isAtIdentifierString", { enumerable: true, get: function () { return syntax_2.isAtIdentifierString; } });
|
|
23
|
+
// AtIdentifierString utilities
|
|
24
|
+
var syntax_3 = require("@atproto/syntax");
|
|
25
|
+
Object.defineProperty(exports, "isDidIdentifier", { enumerable: true, get: function () { return syntax_3.isDidIdentifier; } });
|
|
26
|
+
Object.defineProperty(exports, "isHandleIdentifier", { enumerable: true, get: function () { return syntax_3.isHandleIdentifier; } });
|
|
27
|
+
var syntax_4 = require("@atproto/syntax");
|
|
28
|
+
Object.defineProperty(exports, "asDatetimeString", { enumerable: true, get: function () { return syntax_4.asDatetimeString; } });
|
|
29
|
+
Object.defineProperty(exports, "ifDatetimeString", { enumerable: true, get: function () { return syntax_4.ifDatetimeString; } });
|
|
30
|
+
Object.defineProperty(exports, "isDatetimeString", { enumerable: true, get: function () { return syntax_4.isDatetimeString; } });
|
|
23
31
|
/**
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* @returns `true` if the value is a valid AT identifier
|
|
32
|
+
* Matches any ISO-ish datetime string. This is a more lenient check than
|
|
33
|
+
* the strict {@link isDatetimeString} guard, which only allows datetimes that
|
|
34
|
+
* fully conform to the AT Protocol specification (e.g. must include timezone).
|
|
28
35
|
*/
|
|
29
|
-
|
|
36
|
+
function isDatetimeStringLoose(input) {
|
|
37
|
+
// @NOTE the returned type assertion is inaccurate wrt. the DatetimeString
|
|
38
|
+
// type definition. A more accurate solution would be to use a branded type
|
|
39
|
+
// instead of a template literal for the "datetime" format
|
|
40
|
+
if (typeof input !== 'string')
|
|
41
|
+
return false;
|
|
42
|
+
try {
|
|
43
|
+
return (0, iso_datestring_validator_1.isValidISODateString)(input);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// @NOTE isValidISODateString throws on some inputs
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// DatetimeString utilities
|
|
51
|
+
var syntax_5 = require("@atproto/syntax");
|
|
52
|
+
Object.defineProperty(exports, "currentDatetimeString", { enumerable: true, get: function () { return syntax_5.currentDatetimeString; } });
|
|
53
|
+
Object.defineProperty(exports, "toDatetimeString", { enumerable: true, get: function () { return syntax_5.toDatetimeString; } });
|
|
30
54
|
/**
|
|
31
55
|
* Type guard that checks if a value is a valid AT URI.
|
|
32
56
|
*
|
|
@@ -92,17 +116,17 @@ exports.isTidString = syntax_1.isValidTid;
|
|
|
92
116
|
exports.isUriString = syntax_1.isValidUri;
|
|
93
117
|
const stringFormatVerifiers = /*#__PURE__*/ Object.freeze({
|
|
94
118
|
__proto__: null,
|
|
95
|
-
'at-identifier':
|
|
96
|
-
'at-uri': exports.isAtUriString,
|
|
97
|
-
cid: exports.isCidString,
|
|
98
|
-
datetime: syntax_1.isDatetimeString,
|
|
99
|
-
did: exports.isDidString,
|
|
100
|
-
handle: exports.isHandleString,
|
|
101
|
-
language: exports.isLanguageString,
|
|
102
|
-
nsid: exports.isNsidString,
|
|
103
|
-
'record-key': exports.isRecordKeyString,
|
|
104
|
-
tid: exports.isTidString,
|
|
105
|
-
uri: exports.isUriString,
|
|
119
|
+
'at-identifier': [syntax_1.isAtIdentifierString],
|
|
120
|
+
'at-uri': [exports.isAtUriString],
|
|
121
|
+
cid: [exports.isCidString],
|
|
122
|
+
datetime: [syntax_1.isDatetimeString, isDatetimeStringLoose],
|
|
123
|
+
did: [exports.isDidString],
|
|
124
|
+
handle: [exports.isHandleString],
|
|
125
|
+
language: [exports.isLanguageString],
|
|
126
|
+
nsid: [exports.isNsidString],
|
|
127
|
+
'record-key': [exports.isRecordKeyString],
|
|
128
|
+
tid: [exports.isTidString],
|
|
129
|
+
uri: [exports.isUriString],
|
|
106
130
|
});
|
|
107
131
|
/**
|
|
108
132
|
* Type guard that checks if a string matches a specific format.
|
|
@@ -123,12 +147,15 @@ const stringFormatVerifiers = /*#__PURE__*/ Object.freeze({
|
|
|
123
147
|
* ```
|
|
124
148
|
*/
|
|
125
149
|
/*@__NO_SIDE_EFFECTS__*/
|
|
126
|
-
function isStringFormat(input, format) {
|
|
150
|
+
function isStringFormat(input, format, options) {
|
|
127
151
|
const formatVerifier = stringFormatVerifiers[format];
|
|
128
152
|
// Fool-proof
|
|
129
153
|
if (!formatVerifier)
|
|
130
154
|
throw new TypeError(`Unknown string format: ${format}`);
|
|
131
|
-
|
|
155
|
+
const check = options?.strict === false
|
|
156
|
+
? formatVerifier[1] ?? formatVerifier[0]
|
|
157
|
+
: formatVerifier[0];
|
|
158
|
+
return check(input);
|
|
132
159
|
}
|
|
133
160
|
/**
|
|
134
161
|
* Asserts that a string matches a specific format, throwing if invalid.
|
|
@@ -146,8 +173,8 @@ function isStringFormat(input, format) {
|
|
|
146
173
|
* ```
|
|
147
174
|
*/
|
|
148
175
|
/*@__NO_SIDE_EFFECTS__*/
|
|
149
|
-
function assertStringFormat(input, format) {
|
|
150
|
-
if (!isStringFormat(input, format)) {
|
|
176
|
+
function assertStringFormat(input, format, options) {
|
|
177
|
+
if (!isStringFormat(input, format, options)) {
|
|
151
178
|
throw new TypeError(`Invalid string format (${format}): ${input}`);
|
|
152
179
|
}
|
|
153
180
|
}
|
|
@@ -170,8 +197,8 @@ function assertStringFormat(input, format) {
|
|
|
170
197
|
* ```
|
|
171
198
|
*/
|
|
172
199
|
/*@__NO_SIDE_EFFECTS__*/
|
|
173
|
-
function asStringFormat(input, format) {
|
|
174
|
-
assertStringFormat(input, format);
|
|
200
|
+
function asStringFormat(input, format, options) {
|
|
201
|
+
assertStringFormat(input, format, options);
|
|
175
202
|
return input;
|
|
176
203
|
}
|
|
177
204
|
/**
|
|
@@ -195,8 +222,8 @@ function asStringFormat(input, format) {
|
|
|
195
222
|
* ```
|
|
196
223
|
*/
|
|
197
224
|
/*@__NO_SIDE_EFFECTS__*/
|
|
198
|
-
function ifStringFormat(input, format) {
|
|
199
|
-
return isStringFormat(input, format) ? input : undefined;
|
|
225
|
+
function ifStringFormat(input, format, options) {
|
|
226
|
+
return isStringFormat(input, format, options) ? input : undefined;
|
|
200
227
|
}
|
|
201
228
|
/**
|
|
202
229
|
* Array of all valid string format names.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string-format.js","sourceRoot":"","sources":["../../src/core/string-format.ts"],"names":[],"mappings":";;;AAwRA,wCASC;AAkBD,gDAOC;AAqBD,wCAMC;AAuBD,wCAKC;AAjXD,gDAAqD;AACrD,4CAoBwB;AAGxB,gFAAgF;AAChF,iDAAiD;AACjD,gFAAgF;AAEhF,+EAA+E;AAC/E,6EAA6E;AAC7E,8EAA8E;AAC9E,mEAAmE;AACnE,0CAOwB;AALtB,0GAAA,gBAAgB,OAAA;AAChB,+GAAA,qBAAqB,OAAA;AACrB,0GAAA,gBAAgB,OAAA;AAChB,0GAAA,gBAAgB,OAAA;AAChB,0GAAA,gBAAgB,OAAA;AAGlB;;;;;GAKG;AACU,QAAA,oBAAoB,GAAgC,4BAAW,CAAA;AAU5E;;;;;GAKG;AACU,QAAA,aAAa,GAAyB,qBAAY,CAAA;AAU/D;;;;;GAKG;AACU,QAAA,WAAW,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAA,4BAAiB,EAAC,CAAC,CAAC,CAAuB,CAAA;AAU9E;;;;;GAKG;AACU,QAAA,WAAW,GAAuB,mBAAU,CAAA;AAYzD;;;;;GAKG;AACU,QAAA,cAAc,GAA0B,sBAAa,CAAA;AAUlE;;;;;GAKG;AACU,QAAA,gBAAgB,GAAG,wBAA0C,CAAA;AAQ1E;;;;;GAKG;AACU,QAAA,YAAY,GAAwB,oBAAW,CAAA;AAY5D;;;;;GAKG;AACU,QAAA,iBAAiB,GAA6B,yBAAgB,CAAA;AAU3E;;;;;GAKG;AACU,QAAA,WAAW,GAAuB,mBAAU,CAAA;AAYzD;;;;;GAKG;AACU,QAAA,WAAW,GAAuB,mBAAU,CAAA;AAiCzD,MAAM,qBAAqB,GAEvB,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC;IAC9B,SAAS,EAAE,IAAI;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AC;AAED;;;;;;;;;GASG;AACU,QAAA,cAAc,GAAiB,MAAM,CAAC,MAAM;AACvD,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CACtB,CAAA","sourcesContent":["import { validateCidString } from '@atproto/lex-data'\nimport {\n AtIdentifierString,\n AtUriString,\n DatetimeString,\n DidString,\n HandleString,\n NsidString,\n RecordKeyString,\n TidString,\n UriString,\n isDatetimeString,\n isValidAtIdentifier as isValidAtId,\n isValidAtUri,\n isValidDid,\n isValidHandle,\n isValidLanguage,\n isValidNsid,\n isValidRecordKey,\n isValidTid,\n isValidUri,\n} from '@atproto/syntax'\nimport { CheckFn } from '../util/assertion-util.js'\n\n// -----------------------------------------------------------------------------\n// Individual string format types and type guards\n// -----------------------------------------------------------------------------\n\n// Re-exporting from @atproto/syntax without modification to preserve types and\n// documentation for types and utilities that are already well-defined there.\n// @TODO rework other string formats in @atproto/syntax to follow this pattern\n// and re-export here, e.g. language tags, NSIDs, record keys, etc.\nexport {\n type DatetimeString,\n asDatetimeString,\n currentDatetimeString,\n ifDatetimeString,\n isDatetimeString,\n toDatetimeString,\n} from '@atproto/syntax'\n\n/**\n * Type guard that checks if a value is a valid AT identifier (DID or handle).\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid AT identifier\n */\nexport const isAtIdentifierString: CheckFn<AtIdentifierString> = isValidAtId\nexport type {\n /**\n * An AT identifier string - either a DID or a handle.\n *\n * @example `\"did:plc:1234...\"` or `\"alice.bsky.social\"`\n */\n AtIdentifierString,\n}\n\n/**\n * Type guard that checks if a value is a valid AT URI.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid AT URI\n */\nexport const isAtUriString: CheckFn<AtUriString> = isValidAtUri\nexport type {\n /**\n * An AT URI string pointing to a resource in the AT Protocol network.\n *\n * @example `\"at://did:plc:1234.../app.bsky.feed.post/3k2...\"`\n */\n AtUriString,\n}\n\n/**\n * Type guard that checks if a value is a valid CID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid CID string\n */\nexport const isCidString = ((v) => validateCidString(v)) as CheckFn<CidString>\n/**\n * A Content Identifier (CID) string.\n *\n * CIDs are self-describing content addresses used to identify data by its hash.\n *\n * @example `\"bafyreig...\"`\n */\nexport type CidString = string\n\n/**\n * Type guard that checks if a value is a valid DID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid DID string\n */\nexport const isDidString: CheckFn<DidString> = isValidDid\nexport type {\n /**\n * A Decentralized Identifier (DID) string.\n *\n * DIDs are globally unique identifiers that don't require a central authority.\n *\n * @example `\"did:plc:1234abcd...\"` or `\"did:web:example.com\"`\n */\n DidString,\n}\n\n/**\n * Type guard that checks if a value is a valid handle string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid handle string\n */\nexport const isHandleString: CheckFn<HandleString> = isValidHandle\nexport type {\n /**\n * A handle string - a human-readable identifier for users.\n *\n * @example `\"alice.bsky.social\"` or `\"bob.example.com\"`\n */\n HandleString,\n}\n\n/**\n * Type guard that checks if a value is a valid BCP-47 language tag.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid language string\n */\nexport const isLanguageString = isValidLanguage as CheckFn<LanguageString>\n/**\n * A BCP-47 language tag string.\n *\n * @example `\"en\"`, `\"en-US\"`, `\"zh-Hans\"`\n */\nexport type LanguageString = string\n\n/**\n * Type guard that checks if a value is a valid NSID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid NSID string\n */\nexport const isNsidString: CheckFn<NsidString> = isValidNsid\nexport type {\n /**\n * A Namespaced Identifier (NSID) string identifying a lexicon.\n *\n * NSIDs use reverse-domain notation to identify schemas.\n *\n * @example `\"app.bsky.feed.post\"`, `\"com.atproto.repo.createRecord\"`\n */\n NsidString,\n}\n\n/**\n * Type guard that checks if a value is a valid record key string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid record key string\n */\nexport const isRecordKeyString: CheckFn<RecordKeyString> = isValidRecordKey\nexport type {\n /**\n * A record key string identifying a record within a collection.\n *\n * @example `\"3k2...\"` (TID format) or `\"self\"` (literal key)\n */\n RecordKeyString,\n}\n\n/**\n * Type guard that checks if a value is a valid TID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid TID string\n */\nexport const isTidString: CheckFn<TidString> = isValidTid\nexport type {\n /**\n * A Timestamp Identifier (TID) string.\n *\n * TIDs are time-based identifiers used for record keys.\n *\n * @example `\"3k2...\"`\n */\n TidString,\n}\n\n/**\n * Type guard that checks if a value is a valid URI string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid URI string\n */\nexport const isUriString: CheckFn<UriString> = isValidUri\nexport type {\n /**\n * A standard URI string.\n *\n * @example `\"https://example.com/path\"`\n */\n UriString,\n}\n\n// -----------------------------------------------------------------------------\n// String format registry\n// -----------------------------------------------------------------------------\n\ntype StringFormats = {\n 'at-identifier': AtIdentifierString\n 'at-uri': AtUriString\n cid: CidString\n datetime: DatetimeString\n did: DidString\n handle: HandleString\n language: LanguageString\n nsid: NsidString\n 'record-key': RecordKeyString\n tid: TidString\n uri: UriString\n}\n\n/**\n * Union type of all valid string format names.\n */\nexport type StringFormat = Extract<keyof StringFormats, string>\n\nconst stringFormatVerifiers: {\n readonly [K in StringFormat]: CheckFn<StringFormats[K]>\n} = /*#__PURE__*/ Object.freeze({\n __proto__: null,\n\n 'at-identifier': isAtIdentifierString,\n 'at-uri': isAtUriString,\n cid: isCidString,\n datetime: isDatetimeString,\n did: isDidString,\n handle: isHandleString,\n language: isLanguageString,\n nsid: isNsidString,\n 'record-key': isRecordKeyString,\n tid: isTidString,\n uri: isUriString,\n})\n\n/**\n * Infers the string type for a given format name.\n *\n * @typeParam F - The format name\n *\n * @example\n * ```typescript\n * type Did = InferStringFormat<'did'>\n * // Result: DidString\n * ```\n */\nexport type InferStringFormat<F extends StringFormat> = F extends StringFormat\n ? StringFormats[F]\n : never\n\n/**\n * Type guard that checks if a string matches a specific format.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to check\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @returns `true` if the string matches the format\n *\n * @example\n * ```typescript\n * const value: string = 'did:plc:1234...'\n * if (isStringFormat(value, 'did')) {\n * // value is typed as DidString\n * console.log('Valid DID:', value)\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isStringFormat<I extends string, F extends StringFormat>(\n input: I,\n format: F,\n): input is I & StringFormats[F] {\n const formatVerifier = stringFormatVerifiers[format]\n // Fool-proof\n if (!formatVerifier) throw new TypeError(`Unknown string format: ${format}`)\n\n return formatVerifier(input)\n}\n\n/**\n * Asserts that a string matches a specific format, throwing if invalid.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to check\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @throws {TypeError} If the string doesn't match the format\n *\n * @example\n * ```typescript\n * assertStringFormat(value, 'handle')\n * // value is now typed as HandleString\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function assertStringFormat<I extends string, F extends StringFormat>(\n input: I,\n format: F,\n): asserts input is I & StringFormats[F] {\n if (!isStringFormat(input, format)) {\n throw new TypeError(`Invalid string format (${format}): ${input}`)\n }\n}\n\n/**\n * Validates and returns a string as the specified format type, throwing if invalid.\n *\n * This is useful when you need to convert a string to a format type in an expression.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to validate against\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @returns The input typed as the format type\n * @throws {TypeError} If the string doesn't match the format\n *\n * @example\n * ```typescript\n * const did = asStringFormat(userInput, 'did')\n * // did is typed as DidString\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function asStringFormat<I extends string, F extends StringFormat>(\n input: I,\n format: F,\n): I & StringFormats[F] {\n assertStringFormat(input, format)\n return input\n}\n\n/**\n * Returns the string as the format type if valid, otherwise returns `undefined`.\n *\n * This is useful for optional validation where you want to handle invalid values\n * without throwing.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to validate against\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @returns The typed string if valid, otherwise `undefined`\n *\n * @example\n * ```typescript\n * const did = ifStringFormat(maybeInvalid, 'did')\n * if (did) {\n * // did is typed as DidString\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function ifStringFormat<I extends string, F extends StringFormat>(\n input: I,\n format: F,\n): undefined | (I & StringFormats[F]) {\n return isStringFormat(input, format) ? input : undefined\n}\n\n/**\n * Array of all valid string format names.\n *\n * @example\n * ```typescript\n * for (const format of STRING_FORMATS) {\n * console.log(format) // 'at-identifier', 'at-uri', 'cid', ...\n * }\n * ```\n */\nexport const STRING_FORMATS = /*#__PURE__*/ Object.freeze(\n /*#__PURE__*/ Object.keys(stringFormatVerifiers),\n) as readonly StringFormat[]\n"]}
|
|
1
|
+
{"version":3,"file":"string-format.js","sourceRoot":"","sources":["../../src/core/string-format.ts"],"names":[],"mappings":";;;AAwDA,sDAaC;AAoPD,wCAeC;AAkBD,gDAQC;AAqBD,wCAOC;AAuBD,wCAMC;AA3ZD,uEAA+D;AAC/D,gDAAqD;AACrD,4CAoBwB;AAGxB,gFAAgF;AAChF,iDAAiD;AACjD,gFAAgF;AAEhF,+EAA+E;AAC/E,6EAA6E;AAC7E,8EAA8E;AAC9E,mEAAmE;AAEnE,0CAKwB;AAHtB,8GAAA,oBAAoB,OAAA;AACpB,8GAAA,oBAAoB,OAAA;AACpB,8GAAA,oBAAoB,OAAA;AAGtB,+BAA+B;AAC/B,0CAAqE;AAA5D,yGAAA,eAAe,OAAA;AAAE,4GAAA,kBAAkB,OAAA;AAE5C,0CAKwB;AAHtB,0GAAA,gBAAgB,OAAA;AAChB,0GAAA,gBAAgB,OAAA;AAChB,0GAAA,gBAAgB,OAAA;AAGlB;;;;GAIG;AACH,SAAgB,qBAAqB,CACnC,KAAQ;IAER,0EAA0E;IAC1E,2EAA2E;IAC3E,0DAA0D;IAC1D,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAA;IAC3C,IAAI,CAAC;QACH,OAAO,IAAA,+CAA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C,KAAK,CAAC,CAAC,CAAC,SAAS,CAAA;AACnE,CAAC;AAED;;;;;;;;;GASG;AACU,QAAA,cAAc,GAAiB,MAAM,CAAC,MAAM;AACvD,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CACtB,CAAA","sourcesContent":["import { isValidISODateString } from 'iso-datestring-validator'\nimport { validateCidString } from '@atproto/lex-data'\nimport {\n AtIdentifierString,\n AtUriString,\n DatetimeString,\n DidString,\n HandleString,\n NsidString,\n RecordKeyString,\n TidString,\n UriString,\n isAtIdentifierString,\n isDatetimeString,\n isValidAtUri,\n isValidDid,\n isValidHandle,\n isValidLanguage,\n isValidNsid,\n isValidRecordKey,\n isValidTid,\n isValidUri,\n} from '@atproto/syntax'\nimport { CheckFn } from '../util/assertion-util.js'\n\n// -----------------------------------------------------------------------------\n// Individual string format types and type guards\n// -----------------------------------------------------------------------------\n\n// Re-exporting from @atproto/syntax without modification to preserve types and\n// documentation for types and utilities that are already well-defined there.\n// @TODO rework other string formats in @atproto/syntax to follow this pattern\n// and re-export here, e.g. language tags, NSIDs, record keys, etc.\n\nexport {\n type AtIdentifierString,\n asAtIdentifierString,\n ifAtIdentifierString,\n isAtIdentifierString,\n} from '@atproto/syntax'\n\n// AtIdentifierString utilities\nexport { isDidIdentifier, isHandleIdentifier } from '@atproto/syntax'\n\nexport {\n type DatetimeString,\n asDatetimeString,\n ifDatetimeString,\n isDatetimeString,\n} from '@atproto/syntax'\n\n/**\n * Matches any ISO-ish datetime string. This is a more lenient check than\n * the strict {@link isDatetimeString} guard, which only allows datetimes that\n * fully conform to the AT Protocol specification (e.g. must include timezone).\n */\nexport function isDatetimeStringLoose<I>(\n input: I,\n): input is I & DatetimeString {\n // @NOTE the returned type assertion is inaccurate wrt. the DatetimeString\n // type definition. A more accurate solution would be to use a branded type\n // instead of a template literal for the \"datetime\" format\n if (typeof input !== 'string') return false\n try {\n return isValidISODateString(input)\n } catch {\n // @NOTE isValidISODateString throws on some inputs\n return false\n }\n}\n\n// DatetimeString utilities\nexport { currentDatetimeString, toDatetimeString } from '@atproto/syntax'\n\n/**\n * Type guard that checks if a value is a valid AT URI.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid AT URI\n */\nexport const isAtUriString: CheckFn<AtUriString> = isValidAtUri\nexport type {\n /**\n * An AT URI string pointing to a resource in the AT Protocol network.\n *\n * @example `\"at://did:plc:1234.../app.bsky.feed.post/3k2...\"`\n */\n AtUriString,\n}\n\n/**\n * Type guard that checks if a value is a valid CID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid CID string\n */\nexport const isCidString = ((v) => validateCidString(v)) as CheckFn<CidString>\n/**\n * A Content Identifier (CID) string.\n *\n * CIDs are self-describing content addresses used to identify data by its hash.\n *\n * @example `\"bafyreig...\"`\n */\nexport type CidString = string\n\n/**\n * Type guard that checks if a value is a valid DID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid DID string\n */\nexport const isDidString: CheckFn<DidString> = isValidDid\nexport type {\n /**\n * A Decentralized Identifier (DID) string.\n *\n * DIDs are globally unique identifiers that don't require a central authority.\n *\n * @example `\"did:plc:1234abcd...\"` or `\"did:web:example.com\"`\n */\n DidString,\n}\n\n/**\n * Type guard that checks if a value is a valid handle string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid handle string\n */\nexport const isHandleString: CheckFn<HandleString> = isValidHandle\nexport type {\n /**\n * A handle string - a human-readable identifier for users.\n *\n * @example `\"alice.bsky.social\"` or `\"bob.example.com\"`\n */\n HandleString,\n}\n\n/**\n * Type guard that checks if a value is a valid BCP-47 language tag.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid language string\n */\nexport const isLanguageString = isValidLanguage as CheckFn<LanguageString>\n/**\n * A BCP-47 language tag string.\n *\n * @example `\"en\"`, `\"en-US\"`, `\"zh-Hans\"`\n */\nexport type LanguageString = string\n\n/**\n * Type guard that checks if a value is a valid NSID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid NSID string\n */\nexport const isNsidString: CheckFn<NsidString> = isValidNsid\nexport type {\n /**\n * A Namespaced Identifier (NSID) string identifying a lexicon.\n *\n * NSIDs use reverse-domain notation to identify schemas.\n *\n * @example `\"app.bsky.feed.post\"`, `\"com.atproto.repo.createRecord\"`\n */\n NsidString,\n}\n\n/**\n * Type guard that checks if a value is a valid record key string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid record key string\n */\nexport const isRecordKeyString: CheckFn<RecordKeyString> = isValidRecordKey\nexport type {\n /**\n * A record key string identifying a record within a collection.\n *\n * @example `\"3k2...\"` (TID format) or `\"self\"` (literal key)\n */\n RecordKeyString,\n}\n\n/**\n * Type guard that checks if a value is a valid TID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid TID string\n */\nexport const isTidString: CheckFn<TidString> = isValidTid\nexport type {\n /**\n * A Timestamp Identifier (TID) string.\n *\n * TIDs are time-based identifiers used for record keys.\n *\n * @example `\"3k2...\"`\n */\n TidString,\n}\n\n/**\n * Type guard that checks if a value is a valid URI string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid URI string\n */\nexport const isUriString: CheckFn<UriString> = isValidUri\nexport type {\n /**\n * A standard URI string.\n *\n * @example `\"https://example.com/path\"`\n */\n UriString,\n}\n\n// -----------------------------------------------------------------------------\n// String format registry\n// -----------------------------------------------------------------------------\n\ntype StringFormats = {\n 'at-identifier': AtIdentifierString\n 'at-uri': AtUriString\n cid: CidString\n datetime: DatetimeString\n did: DidString\n handle: HandleString\n language: LanguageString\n nsid: NsidString\n 'record-key': RecordKeyString\n tid: TidString\n uri: UriString\n}\n\n/**\n * Union type of all valid string format names.\n */\nexport type StringFormat = Extract<keyof StringFormats, string>\n\nconst stringFormatVerifiers: {\n readonly [K in StringFormat]: readonly [\n strict: CheckFn<StringFormats[K]>,\n loose?: CheckFn<StringFormats[K]>,\n ]\n} = /*#__PURE__*/ Object.freeze({\n __proto__: null,\n\n 'at-identifier': [isAtIdentifierString],\n 'at-uri': [isAtUriString],\n cid: [isCidString],\n datetime: [isDatetimeString, isDatetimeStringLoose],\n did: [isDidString],\n handle: [isHandleString],\n language: [isLanguageString],\n nsid: [isNsidString],\n 'record-key': [isRecordKeyString],\n tid: [isTidString],\n uri: [isUriString],\n})\n\nexport type StringFormatValidationOptions = {\n /**\n * Allows to be more lenient in validation by using a \"loose\" verification\n * function, if available. The behavior of the loose verifier depends on the\n * specific format, but generally it may allow for a wider range of valid\n * inputs, including values that are not compliant with the AT Protocol\n * specification.\n *\n * @default true\n */\n strict?: boolean\n}\n\n/**\n * Infers the string type for a given format name.\n *\n * @typeParam F - The format name\n *\n * @example\n * ```typescript\n * type Did = InferStringFormat<'did'>\n * // Result: DidString\n * ```\n */\nexport type InferStringFormat<F extends StringFormat> = F extends StringFormat\n ? StringFormats[F]\n : never\n\n/**\n * Type guard that checks if a string matches a specific format.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to check\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @returns `true` if the string matches the format\n *\n * @example\n * ```typescript\n * const value: string = 'did:plc:1234...'\n * if (isStringFormat(value, 'did')) {\n * // value is typed as DidString\n * console.log('Valid DID:', value)\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isStringFormat<I extends string, F extends StringFormat>(\n input: I,\n format: F,\n options?: StringFormatValidationOptions,\n): input is I & StringFormats[F] {\n const formatVerifier = stringFormatVerifiers[format]\n // Fool-proof\n if (!formatVerifier) throw new TypeError(`Unknown string format: ${format}`)\n\n const check: CheckFn<StringFormats[F]> =\n options?.strict === false\n ? formatVerifier[1] ?? formatVerifier[0]\n : formatVerifier[0]\n\n return check(input)\n}\n\n/**\n * Asserts that a string matches a specific format, throwing if invalid.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to check\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @throws {TypeError} If the string doesn't match the format\n *\n * @example\n * ```typescript\n * assertStringFormat(value, 'handle')\n * // value is now typed as HandleString\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function assertStringFormat<I extends string, F extends StringFormat>(\n input: I,\n format: F,\n options?: StringFormatValidationOptions,\n): asserts input is I & StringFormats[F] {\n if (!isStringFormat(input, format, options)) {\n throw new TypeError(`Invalid string format (${format}): ${input}`)\n }\n}\n\n/**\n * Validates and returns a string as the specified format type, throwing if invalid.\n *\n * This is useful when you need to convert a string to a format type in an expression.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to validate against\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @returns The input typed as the format type\n * @throws {TypeError} If the string doesn't match the format\n *\n * @example\n * ```typescript\n * const did = asStringFormat(userInput, 'did')\n * // did is typed as DidString\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function asStringFormat<I extends string, F extends StringFormat>(\n input: I,\n format: F,\n options?: StringFormatValidationOptions,\n): I & StringFormats[F] {\n assertStringFormat(input, format, options)\n return input\n}\n\n/**\n * Returns the string as the format type if valid, otherwise returns `undefined`.\n *\n * This is useful for optional validation where you want to handle invalid values\n * without throwing.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to validate against\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @returns The typed string if valid, otherwise `undefined`\n *\n * @example\n * ```typescript\n * const did = ifStringFormat(maybeInvalid, 'did')\n * if (did) {\n * // did is typed as DidString\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function ifStringFormat<I extends string, F extends StringFormat>(\n input: I,\n format: F,\n options?: StringFormatValidationOptions,\n): undefined | (I & StringFormats[F]) {\n return isStringFormat(input, format, options) ? input : undefined\n}\n\n/**\n * Array of all valid string format names.\n *\n * @example\n * ```typescript\n * for (const format of STRING_FORMATS) {\n * console.log(format) // 'at-identifier', 'at-uri', 'cid', ...\n * }\n * ```\n */\nexport const STRING_FORMATS = /*#__PURE__*/ Object.freeze(\n /*#__PURE__*/ Object.keys(stringFormatVerifiers),\n) as readonly StringFormat[]\n"]}
|