@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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/core/validator.ts"],"names":[],"mappings":";;;AACA,2CAA4E;AAC5E,+DAA0D;AAC1D,+DAS8B;AAiK9B;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,iBAAiB;IA8EP;IA3BrB,MAAM,CAAC,QAAQ,CACb,KAAc,EACd,SAAY,EACZ,OAA2B;QAE3B,MAAM,OAAO,GAAG,IAAI,iBAAiB,CAAC;YACpC,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,EAAE;YACzB,IAAI,EAAE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OAQG;IACH,aAAa,CACX,KAAc,EACd,IAAoB,EACpB,GAAW,EACX,MAAc;QAEd,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,mCAAa,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAA;IAC3E,CAAC;IAED;;;;;;;;;;;OAWG;IACH,yBAAyB,CACvB,KAAQ,EACR,QAA+B,EAC/B,MAA0B;QAE1B,MAAM,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAA;QAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,uCAAiB,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAA;IAC/D,CAAC;IAED;;;;;;;;;;;OAWG;IACH,wBAAwB,CACtB,KAAQ,EACR,QAA+B,EAC/B,QAAgB;QAEhB,MAAM,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAA;QAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,sCAAgB,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;IAClE,CAAC;CACF;AAzXD,8CAyXC","sourcesContent":["import { PropertyKey } from './property-key.js'\nimport { ResultFailure, ResultSuccess, failure, success } from './result.js'\nimport { LexValidationError } from './validation-error.js'\nimport {\n Issue,\n IssueInvalidFormat,\n IssueInvalidType,\n IssueInvalidValue,\n IssueRequiredKey,\n IssueTooBig,\n IssueTooSmall,\n MeasurableType,\n} from './validation-issue.js'\n\n/**\n * Represents a successful validation result.\n *\n * @typeParam Value - The type of the validated value\n */\nexport type ValidationSuccess<Value = unknown> = ResultSuccess<Value>\n\n/**\n * Represents a failed validation result containing a {@link LexValidationError}.\n */\nexport type ValidationFailure = ResultFailure<LexValidationError>\n\n/**\n * Discriminated union representing the outcome of a validation operation.\n *\n * Check the `success` property to determine if validation passed or failed:\n * - If `success` is `true`, the `value` property contains the validated data\n * - If `success` is `false`, the `reason` property contains the {@link LexValidationError}\n *\n * @typeParam Value - The type of the validated value on success\n *\n * @example\n * ```typescript\n * const result: ValidationResult<string> = schema.safeParse(data)\n * if (result.success) {\n * // result.value is string\n * } else {\n * // result.reason is LexValidationError\n * }\n * ```\n */\nexport type ValidationResult<Value = unknown> =\n | ValidationSuccess<Value>\n | ValidationFailure\n\n/**\n * Extracts the input type that a validator accepts.\n *\n * Use this utility type to infer what type a schema will accept during validation.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const userSchema = new ObjectSchema({ name: stringSchema, age: numberSchema })\n * type UserInput = InferInput<typeof userSchema>\n * // { name: string; age: number }\n * ```\n */\nexport type InferInput<V extends Validator> = V['__lex']['input']\n\n/**\n * Extracts the output type that a validator produces after parsing.\n *\n * The output type may differ from the input type when the schema applies\n * transformations such as default values or type coercion during parsing.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const schema = new StringSchema().default('hello')\n * type Input = InferInput<typeof schema> // string | undefined\n * type Output = InferOutput<typeof schema> // string\n * ```\n */\nexport type InferOutput<V extends Validator> = V['__lex']['output']\n\n/**\n * Alias for {@link InferInput} for convenient type inference.\n *\n * @typeParam V - A validator type\n */\nexport type { InferInput as Infer }\n\nexport interface Validator<TInput = unknown, TOutput = TInput> {\n /**\n * This property is used for type inference purposes and does not actually\n * exist at runtime.\n *\n * @internal\n * @deprecated **INTERNAL API, DO NOT USE**.\n */\n readonly ['__lex']: {\n input: TInput\n output: TOutput\n }\n\n /**\n * @internal **INTERNAL API**: use {@link ValidationContext.validate} instead\n *\n * This method is implemented by subclasses to perform transformation and\n * validation of the input value. Do not call this method directly; as the\n * {@link ValidationContext.options.mode} option will **not** be enforced. See\n * {@link ValidationContext.validate} for details. When delegating validation\n * from one validator sub-class implementation to another schema,\n * {@link ValidationContext.validate} must be used instead of calling\n * {@link Validator.validateInContext}. This will allow to stop the validation\n * process if the value was transformed (by the other schema) but\n * transformations are not allowed.\n *\n * By convention, the {@link ValidationResult} must return the original input\n * value if validation was successful and no transformation was applied (i.e.\n * the input already conformed to the schema). If a default value, or any\n * other transformation was applied, the returned value can be different from\n * the input.\n *\n * This convention allows the {@link Validator.check check} and\n * {@link Validator.assert assert} methods to check whether the input value\n * exactly matches the schema (without defaults or transformations), by\n * checking if the returned value is strictly equal to the input.\n *\n * @see {@link ValidationContext.validate}\n */\n validateInContext(input: unknown, ctx: ValidationContext): ValidationResult\n}\n\n/**\n * Configuration options for validation and parsing operations.\n *\n * @example\n * ```typescript\n * // Validate mode (strict, no transformations)\n * ValidationContext.validate(data, schema, { mode: 'validate' })\n *\n * // Parse mode (allows transformations like defaults)\n * ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // With initial path for nested validation\n * ValidationContext.validate(data, schema, { path: ['user', 'profile'] })\n * ```\n */\nexport type ValidationOptions = {\n /**\n * The validation mode determining how transformations are handled.\n *\n * - `\"validate\"` (default): Strict validation where the result must be\n * strictly equal to the input value. No transformations such as applying\n * default values are allowed.\n * - `\"parse\"`: Allows the schema to transform the input value, such as\n * applying default values or performing type coercion.\n */\n mode?: 'validate' | 'parse'\n\n /**\n * The initial path to the value being validated.\n *\n * This is used to provide context in validation issues when validating\n * nested structures. The path is prepended to all issue paths.\n *\n * @example\n * ```typescript\n * // Issues will be reported at paths like \"user.name\" instead of just \"name\"\n * ValidationContext.validate(data, schema, { path: ['user'] })\n * ```\n */\n path?: readonly PropertyKey[]\n}\n\n/**\n * Manages the state and context for validation operations.\n *\n * The `ValidationContext` class is responsible for:\n * - Tracking the current path in nested structures for error reporting\n * - Collecting validation issues during traversal\n * - Enforcing validation mode (validate vs parse)\n * - Providing factory methods for creating validation results\n *\n * Use the static {@link ValidationContext.validate} method as the primary entry point\n * for validation. This ensures proper mode enforcement and issue aggregation.\n *\n * @example\n * ```typescript\n * // Primary usage via static method\n * const result = ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // Within a custom validator implementation\n * class MyValidator implements Validator {\n * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {\n * if (typeof input !== 'string') {\n * return ctx.issueUnexpectedType(input, 'string')\n * }\n * return ctx.success(input)\n * }\n * }\n * ```\n */\nexport class ValidationContext {\n /**\n * Validates input against a validator in parse mode.\n *\n * In parse mode, the schema may transform the input (e.g., apply defaults).\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Validation options with mode set to 'parse'\n * @returns A validation result with the parsed output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options: ValidationOptions & {\n mode: 'parse'\n },\n ): ValidationResult<InferOutput<V>>\n /**\n * Validates input against a validator in validate mode (default).\n *\n * In validate mode, the result must be strictly equal to the input.\n * No transformations are allowed.\n *\n * @typeParam V - The validator type\n * @typeParam I - The input type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options (defaults to validate mode)\n * @returns A validation result preserving the input type intersected with the schema type\n */\n static validate<V extends Validator, I = unknown>(\n input: I,\n validator: V,\n options?: ValidationOptions & {\n mode?: 'validate'\n },\n ): ValidationResult<I & InferInput<V>>\n /**\n * Validates input against a validator with configurable options.\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options\n * @returns A validation result with either the input or output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>>\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>> {\n const context = new ValidationContext({\n path: options?.path ?? [],\n mode: options?.mode ?? 'validate',\n })\n return context.validate(input, validator)\n }\n\n /**\n * The current path being validated, used for error reporting.\n */\n protected readonly currentPath: PropertyKey[]\n\n /**\n * Accumulated validation issues collected during traversal.\n */\n protected readonly issues: Issue[] = []\n\n /**\n * Creates a new validation context with the specified options.\n *\n * @param options - The validation options (path and mode are required)\n */\n constructor(readonly options: Required<ValidationOptions>) {\n // Create a copy because we will be mutating the array during validation.\n this.currentPath = Array.from(options.path)\n }\n\n /**\n * Returns a copy of the current validation path.\n *\n * The path represents the location in the data structure being validated,\n * used for constructing meaningful error messages.\n */\n get path() {\n return Array.from(this.currentPath)\n }\n\n /**\n * Creates a new path by appending segments to the current path.\n *\n * @param path - Optional path segment(s) to append\n * @returns A new path array with the segment(s) appended\n */\n concatPath(path?: PropertyKey | readonly PropertyKey[]) {\n if (path == null) return this.path\n return this.currentPath.concat(path)\n }\n\n /**\n * Validates input against a validator within this context.\n *\n * This is the primary entry point for validation within a context. Always use\n * this method instead of calling {@link Validator.validateInContext} directly,\n * as this method enforces validation mode rules and handles transformation detection.\n *\n * @typeParam V - The validator type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @returns A validation result with the validated value or error\n */\n validate<V extends Validator>(\n input: unknown,\n validator: V,\n ): ValidationResult<InferInput<V>> {\n // This is the only place where validateInContext should be called.\n const result = validator.validateInContext(input, this)\n\n if (result.success) {\n if (this.issues.length > 0) {\n // Validator returned a success but issues were added via the context.\n // This means the overall validation failed.\n return failure(new LexValidationError(Array.from(this.issues)))\n }\n\n if (this.options.mode !== 'parse' && !Object.is(result.value, input)) {\n // If the value changed, it means that a default (or some other\n // transformation) was applied, meaning that the original value did\n // *not* match the (output) schema. When not in \"parse\" mode, we\n // consider this a failure.\n\n // This check is the reason why Validator.validateInContext should not\n // be used directly, and ValidatorContext.validate should be used\n // instead, even when delegating validation from one validator to\n // another.\n\n // This if block comes before the next one because 'this.issues' will\n // end-up being appended to the returned LexValidationError (see the\n // \"failure\" method below), resulting in a more complete error report.\n return this.issueInvalidValue(input, [result.value])\n }\n }\n\n return result as ValidationResult<InferInput<V>>\n }\n\n /**\n * Validates a child property of an object within this context.\n *\n * This method automatically manages the path stack, pushing the property key\n * before validation and popping it afterward. Use this for validating object\n * properties to ensure proper path tracking in error messages.\n *\n * @typeParam I - The input object type\n * @typeParam K - The property key type\n * @typeParam V - The validator type\n * @param input - The parent object containing the property\n * @param key - The property key to validate\n * @param validator - The validator to use for the property value\n * @returns A validation result for the property value\n *\n * @example\n * ```typescript\n * // In a custom object validator\n * const result = ctx.validateChild(input, 'name', stringSchema)\n * // If validation fails, error path will include 'name'\n * ```\n */\n validateChild<\n I extends object,\n K extends PropertyKey & keyof I,\n V extends Validator,\n >(input: I, key: K, validator: V): ValidationResult<InferInput<V>> {\n // @NOTE we could add support for recursive schemas by keeping track of\n // \"parent\" objects in the context and checking for circular references\n // here. This would allow us to validate recursive structures without\n // hitting maximum call stack errors, and would also allow us to provide\n // better error messages for circular reference issues. However, this is not\n // a priority at the moment as recursive structures are not supported in\n // the context of AT Protocol lexicons, and we can always add this in the\n // future if needed.\n\n // Instead of creating a new context, we just push/pop the path segment.\n this.currentPath.push(key)\n try {\n return this.validate(input[key], validator)\n } finally {\n this.currentPath.length--\n }\n }\n\n /**\n * Adds a validation issue to the context without immediately failing.\n *\n * Use this method to collect multiple issues during validation before\n * determining the final result. Issues added this way will be included\n * in the final error if validation fails.\n *\n * @param issue - The validation issue to add\n */\n addIssue(issue: Issue): void {\n this.issues.push(issue)\n }\n\n /**\n * Creates a successful validation result with the given value.\n *\n * @typeParam V - The value type\n * @param value - The validated value\n * @returns A successful validation result\n */\n success<V>(value: V): ValidationResult<V> {\n return success(value)\n }\n\n /**\n * Creates a failed validation result with the given error.\n *\n * @param reason - The validation error\n * @returns A failed validation result\n */\n failure(reason: LexValidationError): ValidationFailure {\n return failure(reason)\n }\n\n /**\n * Creates a failed validation result from a single issue.\n *\n * Any previously accumulated issues in the context are included in the error.\n *\n * @param issue - The validation issue that caused the failure\n * @returns A failed validation result\n */\n issue(issue: Issue) {\n return this.failure(new LexValidationError([...this.issues, issue]))\n }\n\n /**\n * Creates a failure for an invalid value that doesn't match expected values.\n *\n * @param input - The actual value that was received\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue\n */\n issueInvalidValue(input: unknown, values: readonly unknown[]) {\n return this.issue(new IssueInvalidValue(this.path, input, values))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - An array of expected type names\n * @returns A failed validation result with an invalid type issue\n */\n issueInvalidType(input: unknown, expected: readonly string[]) {\n return this.issue(new IssueInvalidType(this.path, input, expected))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue\n */\n issueUnexpectedType(input: unknown, expected: string) {\n return this.issueInvalidType(input, [expected])\n }\n\n /**\n * Creates a failure for a missing required key in an object.\n *\n * @param input - The object missing the required key\n * @param key - The name of the required key\n * @returns A failed validation result with a required key issue\n */\n issueRequiredKey(input: object, key: PropertyKey) {\n return this.issue(new IssueRequiredKey(this.path, input, key))\n }\n\n /**\n * Creates a failure for an invalid string format.\n *\n * @param input - The actual value that was received\n * @param format - The expected format name (e.g., 'did', 'handle', 'uri')\n * @param msg - Optional additional message describing the format error\n * @returns A failed validation result with an invalid format issue\n */\n issueInvalidFormat(input: unknown, format: string, msg?: string) {\n return this.issue(new IssueInvalidFormat(this.path, input, format, msg))\n }\n\n /**\n * Creates a failure for a value that exceeds a maximum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param max - The maximum allowed value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too big issue\n */\n issueTooBig(\n input: unknown,\n type: MeasurableType,\n max: number,\n actual: number,\n ) {\n return this.issue(new IssueTooBig(this.path, input, max, type, actual))\n }\n\n /**\n * Creates a failure for a value that is below a minimum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param min - The minimum required value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too small issue\n */\n issueTooSmall(\n input: unknown,\n type: MeasurableType,\n min: number,\n actual: number,\n ) {\n return this.issue(new IssueTooSmall(this.path, input, min, type, actual))\n }\n\n /**\n * Creates a failure for an invalid property value within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid value\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue at the property path\n */\n issueInvalidPropertyValue<I>(\n input: I,\n property: keyof I & PropertyKey,\n values: readonly unknown[],\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidValue(path, value, values))\n }\n\n /**\n * Creates a failure for an invalid property type within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid type\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue at the property path\n */\n issueInvalidPropertyType<I>(\n input: I,\n property: keyof I & PropertyKey,\n expected: string,\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidType(path, value, [expected]))\n }\n}\n\n/**\n * Recursively unwraps a wrapped validator to its innermost validator type.\n *\n * Some validators wrap other validators (e.g., optional, nullable). This type\n * utility recursively unwraps such wrappers to reveal the core validator.\n *\n * @typeParam T - A validator type, possibly wrapped\n *\n * @example\n * ```typescript\n * type Inner = UnwrapValidator<OptionalValidator<NullableValidator<StringSchema>>>\n * // Result: StringSchema\n * ```\n */\nexport type UnwrapValidator<T extends Validator> = T extends {\n unwrap(): infer U extends Validator\n}\n ? UnwrapValidator<U>\n : T\n\n/**\n * Interface for validators that wrap another validator.\n *\n * Implement this interface when creating validators that wrap or modify\n * the behavior of another validator (e.g., optional, nullable, transform).\n *\n * @typeParam Validator - The type of the wrapped validator\n *\n * @example\n * ```typescript\n * class OptionalSchema<V extends Validator> implements WrappedValidator<V> {\n * constructor(private inner: V) {}\n *\n * unwrap(): V {\n * return this.inner\n * }\n * }\n * ```\n */\nexport interface WrappedValidator<out Validator> {\n /**\n * Returns the inner wrapped validator.\n *\n * @returns The wrapped validator\n */\n unwrap(): Validator\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/core/validator.ts"],"names":[],"mappings":";;;AAAA,6DAA6D;AAC7D,2CAAmE;AACnE,+DAA0D;AAC1D,+DAS8B;AAkL9B;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,iBAAiB;IAiFP;IA5BrB,MAAM,CAAC,QAAQ,CACb,KAAc,EACd,SAAY,EACZ,OAA2B;QAE3B,MAAM,OAAO,GAAG,IAAI,iBAAiB,CAAC;YACpC,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,EAAE;YACzB,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,UAAU;YACjC,MAAM,EAAE,OAAO,EAAE,MAAM,IAAI,IAAI;SAChC,CAAC,CAAA;QACF,OAAO,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;IAC3C,CAAC;IAED;;OAEG;IACgB,WAAW,CAAe;IAE7C;;OAEG;IACgB,MAAM,GAAY,EAAE,CAAA;IAEvC;;;;OAIG;IACH,YAAqB,OAAoC;QAApC,YAAO,GAAP,OAAO,CAA6B;QACvD,yEAAyE;QACzE,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;IAC7C,CAAC;IAED;;;;;OAKG;IACH,IAAI,IAAI;QACN,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;IACrC,CAAC;IAED;;;;;OAKG;IACH,UAAU,CAAC,IAA2C;QACpD,IAAI,IAAI,IAAI,IAAI;YAAE,OAAO,IAAI,CAAC,IAAI,CAAA;QAClC,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACtC,CAAC;IAED;;;;;;;;;;;OAWG;IACH,QAAQ,C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,CAAC,IAAI,sCAAgB,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;IAClE,CAAC;CACF;AA5XD,8CA4XC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { ResultFailure, ResultSuccess, success } from './result.js'\nimport { LexValidationError } from './validation-error.js'\nimport {\n Issue,\n IssueInvalidFormat,\n IssueInvalidType,\n IssueInvalidValue,\n IssueRequiredKey,\n IssueTooBig,\n IssueTooSmall,\n MeasurableType,\n} from './validation-issue.js'\n\n/**\n * Represents a successful validation result.\n *\n * @typeParam Value - The type of the validated value\n */\nexport type ValidationSuccess<Value = unknown> = ResultSuccess<Value>\n\n/**\n * Represents a failed validation result containing a {@link LexValidationError}.\n *\n * @extends ResultFailure<LexValidationError>\n * @see {@link ResultFailure}\n * @see {@link LexValidationError}\n */\nexport type ValidationFailure = LexValidationError\n\n/**\n * Discriminated union representing the outcome of a validation operation.\n *\n * Check the `success` property to determine if validation passed or failed:\n * - If `success` is `true`, the `value` property contains the validated data\n * - If `success` is `false`, the `reason` property contains the {@link LexValidationError}\n *\n * @typeParam Value - The type of the validated value on success\n *\n * @example\n * ```typescript\n * const result: ValidationResult<string> = schema.safeParse(data)\n * if (result.success) {\n * // result.value is string\n * } else {\n * // result.reason is LexValidationError\n * }\n * ```\n */\nexport type ValidationResult<Value = unknown> =\n | ValidationSuccess<Value>\n | ValidationFailure\n\n/**\n * Extracts the input type that a validator accepts.\n *\n * Use this utility type to infer what type a schema will accept during validation.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const userSchema = new ObjectSchema({ name: stringSchema, age: numberSchema })\n * type UserInput = InferInput<typeof userSchema>\n * // { name: string; age: number }\n * ```\n */\nexport type InferInput<V extends Validator> = V['__lex']['input']\n\n/**\n * Extracts the output type that a validator produces after parsing.\n *\n * The output type may differ from the input type when the schema applies\n * transformations such as default values or type coercion during parsing.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const schema = new StringSchema().default('hello')\n * type Input = InferInput<typeof schema> // string | undefined\n * type Output = InferOutput<typeof schema> // string\n * ```\n */\nexport type InferOutput<V extends Validator> = V['__lex']['output']\n\n/**\n * Alias for {@link InferInput} for convenient type inference.\n *\n * @typeParam V - A validator type\n */\nexport type { InferInput as Infer }\n\nexport interface Validator<TInput = unknown, TOutput = TInput> {\n /**\n * This property is used for type inference purposes and does not actually\n * exist at runtime.\n *\n * @internal\n * @deprecated **INTERNAL API, DO NOT USE**.\n */\n readonly ['__lex']: {\n input: TInput\n output: TOutput\n }\n\n /**\n * @internal **INTERNAL API**: use {@link ValidationContext.validate} instead\n *\n * This method is implemented by subclasses to perform transformation and\n * validation of the input value. Do not call this method directly; as the\n * {@link ValidationContext.options.mode} option will **not** be enforced. See\n * {@link ValidationContext.validate} for details. When delegating validation\n * from one validator sub-class implementation to another schema,\n * {@link ValidationContext.validate} must be used instead of calling\n * {@link Validator.validateInContext}. This will allow to stop the validation\n * process if the value was transformed (by the other schema) but\n * transformations are not allowed.\n *\n * By convention, the {@link ValidationResult} must return the original input\n * value if validation was successful and no transformation was applied (i.e.\n * the input already conformed to the schema). If a default value, or any\n * other transformation was applied, the returned value can be different from\n * the input.\n *\n * This convention allows the {@link Validator.check check} and\n * {@link Validator.assert assert} methods to check whether the input value\n * exactly matches the schema (without defaults or transformations), by\n * checking if the returned value is strictly equal to the input.\n *\n * @see {@link ValidationContext.validate}\n */\n validateInContext(input: unknown, ctx: ValidationContext): ValidationResult\n}\n\n/**\n * Configuration options for validation and parsing operations.\n *\n * @example\n * ```typescript\n * // Validate mode (strict, no transformations)\n * ValidationContext.validate(data, schema, { mode: 'validate' })\n *\n * // Parse mode (allows transformations like defaults)\n * ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // With initial path for nested validation\n * ValidationContext.validate(data, schema, { path: ['user', 'profile'] })\n * ```\n */\nexport type ValidationOptions = {\n /**\n * The validation mode determining how transformations are handled.\n *\n * - `\"validate\"`: Strict validation where the result must be\n * strictly equal to the input value. No transformations such as applying\n * default values are allowed.\n * - `\"parse\"`: Allows the schema to transform the input value, such as\n * applying default values or performing type coercion.\n *\n * @default \"validate\"\n */\n mode?: 'validate' | 'parse'\n\n /**\n * The initial path to the value being validated.\n *\n * This is used to provide context in validation issues when validating\n * nested structures. The path is prepended to all issue paths.\n *\n * @example\n * ```typescript\n * // Issues will be reported at paths like \"user.name\" instead of just \"name\"\n * ValidationContext.validate(data, schema, { path: ['user'] })\n * ```\n */\n path?: readonly PropertyKey[]\n\n /**\n * Whether to enforce strict validation rules (e.g., MIME type matching, size\n * limits, datetime format).\n *\n * This is typically useful to allow more lax validation when parsing server\n * responses, while enforcing strict validation for user input.\n *\n * @default true\n */\n strict?: boolean\n}\n\n/**\n * Manages the state and context for validation operations.\n *\n * The `ValidationContext` class is responsible for:\n * - Tracking the current path in nested structures for error reporting\n * - Collecting validation issues during traversal\n * - Enforcing validation mode (validate vs parse)\n * - Providing factory methods for creating validation results\n *\n * Use the static {@link ValidationContext.validate} method as the primary entry point\n * for validation. This ensures proper mode enforcement and issue aggregation.\n *\n * @example\n * ```typescript\n * // Primary usage via static method\n * const result = ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // Within a custom validator implementation\n * class MyValidator implements Validator {\n * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {\n * if (typeof input !== 'string') {\n * return ctx.issueUnexpectedType(input, 'string')\n * }\n * return ctx.success(input)\n * }\n * }\n * ```\n */\nexport class ValidationContext {\n /**\n * Validates input against a validator in parse mode.\n *\n * In parse mode, the schema may transform the input (e.g., apply defaults).\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Validation options with mode set to 'parse'\n * @returns A validation result with the parsed output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options: ValidationOptions & {\n mode: 'parse'\n },\n ): ValidationResult<InferOutput<V>>\n\n /**\n * Validates input against a validator in validate mode (default).\n *\n * In validate mode, the result must be strictly equal to the input.\n * No transformations are allowed.\n *\n * @typeParam V - The validator type\n * @typeParam I - The input type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options (defaults to validate mode)\n * @returns A validation result preserving the input type intersected with the schema type\n */\n static validate<V extends Validator, I = unknown>(\n input: I,\n validator: V,\n options?: ValidationOptions & {\n mode?: 'validate'\n },\n ): ValidationResult<I & InferInput<V>>\n\n /**\n * Validates input against a validator with configurable options.\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options\n * @returns A validation result with either the input or output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>>\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>> {\n const context = new ValidationContext({\n path: options?.path ?? [],\n mode: options?.mode ?? 'validate',\n strict: options?.strict ?? true,\n })\n return context.validate(input, validator)\n }\n\n /**\n * The current path being validated, used for error reporting.\n */\n protected readonly currentPath: PropertyKey[]\n\n /**\n * Accumulated validation issues collected during traversal.\n */\n protected readonly issues: Issue[] = []\n\n /**\n * Creates a new validation context with the specified options.\n *\n * @param options - The validation options (path and mode are required)\n */\n constructor(readonly options: Required<ValidationOptions>) {\n // Create a copy because we will be mutating the array during validation.\n this.currentPath = Array.from(options.path)\n }\n\n /**\n * Returns a copy of the current validation path.\n *\n * The path represents the location in the data structure being validated,\n * used for constructing meaningful error messages.\n */\n get path() {\n return Array.from(this.currentPath)\n }\n\n /**\n * Creates a new path by appending segments to the current path.\n *\n * @param path - Optional path segment(s) to append\n * @returns A new path array with the segment(s) appended\n */\n concatPath(path?: PropertyKey | readonly PropertyKey[]) {\n if (path == null) return this.path\n return this.currentPath.concat(path)\n }\n\n /**\n * Validates input against a validator within this context.\n *\n * This is the primary entry point for validation within a context. Always use\n * this method instead of calling {@link Validator.validateInContext} directly,\n * as this method enforces validation mode rules and handles transformation detection.\n *\n * @typeParam V - The validator type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @returns A validation result with the validated value or error\n */\n validate<V extends Validator>(\n input: unknown,\n validator: V,\n ): ValidationResult<InferInput<V>> {\n // This is the only place where validateInContext should be called.\n const result = validator.validateInContext(input, this)\n\n if (result.success) {\n if (this.issues.length > 0) {\n // Validator returned a success but issues were added via the context.\n // This means the overall validation failed.\n return new LexValidationError(Array.from(this.issues))\n }\n\n if (this.options.mode !== 'parse' && !Object.is(result.value, input)) {\n // If the value changed, it means that a default (or some other\n // transformation) was applied, meaning that the original value did\n // *not* match the (output) schema. When not in \"parse\" mode, we\n // consider this a failure.\n\n // This check is the reason why Validator.validateInContext should not\n // be used directly, and ValidatorContext.validate should be used\n // instead, even when delegating validation from one validator to\n // another.\n\n // This if block comes before the next one because 'this.issues' will\n // end-up being appended to the returned LexValidationError (see the\n // \"failure\" method below), resulting in a more complete error report.\n return this.issueInvalidValue(input, [result.value])\n }\n }\n\n return result as ValidationResult<InferInput<V>>\n }\n\n /**\n * Validates a child property of an object within this context.\n *\n * This method automatically manages the path stack, pushing the property key\n * before validation and popping it afterward. Use this for validating object\n * properties to ensure proper path tracking in error messages.\n *\n * @typeParam I - The input object type\n * @typeParam K - The property key type\n * @typeParam V - The validator type\n * @param input - The parent object containing the property\n * @param key - The property key to validate\n * @param validator - The validator to use for the property value\n * @returns A validation result for the property value\n *\n * @example\n * ```typescript\n * // In a custom object validator\n * const result = ctx.validateChild(input, 'name', stringSchema)\n * // If validation fails, error path will include 'name'\n * ```\n */\n validateChild<\n I extends object,\n K extends PropertyKey & keyof I,\n V extends Validator,\n >(input: I, key: K, validator: V): ValidationResult<InferInput<V>> {\n // @NOTE we could add support for recursive schemas by keeping track of\n // \"parent\" objects in the context and checking for circular references\n // here. This would allow us to validate recursive structures without\n // hitting maximum call stack errors, and would also allow us to provide\n // better error messages for circular reference issues. However, this is not\n // a priority at the moment as recursive structures are not supported in\n // the context of AT Protocol lexicons, and we can always add this in the\n // future if needed.\n\n // Instead of creating a new context, we just push/pop the path segment.\n this.currentPath.push(key)\n try {\n return this.validate(input[key], validator)\n } finally {\n this.currentPath.length--\n }\n }\n\n /**\n * Adds a validation issue to the context without immediately failing.\n *\n * Use this method to collect multiple issues during validation before\n * determining the final result. Issues added this way will be included\n * in the final error if validation fails.\n *\n * @param issue - The validation issue to add\n */\n addIssue(issue: Issue): void {\n this.issues.push(issue)\n }\n\n /**\n * Creates a successful validation result with the given value.\n *\n * @typeParam V - The value type\n * @param value - The validated value\n * @returns A successful validation result\n */\n success<V>(value: V): ValidationResult<V> {\n return success(value)\n }\n\n /**\n * Creates a failed validation result with the given error.\n *\n * @param reason - The validation error\n * @returns A failed validation result\n */\n failure(reason: LexValidationError): ValidationFailure {\n return reason\n }\n\n /**\n * Creates a failed validation result from a single issue.\n *\n * Any previously accumulated issues in the context are included in the error.\n *\n * @param issue - The validation issue that caused the failure\n * @returns A failed validation result\n */\n issue(issue: Issue) {\n return this.failure(new LexValidationError([...this.issues, issue]))\n }\n\n /**\n * Creates a failure for an invalid value that doesn't match expected values.\n *\n * @param input - The actual value that was received\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue\n */\n issueInvalidValue(input: unknown, values: readonly unknown[]) {\n return this.issue(new IssueInvalidValue(this.path, input, values))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - An array of expected type names\n * @returns A failed validation result with an invalid type issue\n */\n issueInvalidType(input: unknown, expected: readonly string[]) {\n return this.issue(new IssueInvalidType(this.path, input, expected))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue\n */\n issueUnexpectedType(input: unknown, expected: string) {\n return this.issueInvalidType(input, [expected])\n }\n\n /**\n * Creates a failure for a missing required key in an object.\n *\n * @param input - The object missing the required key\n * @param key - The name of the required key\n * @returns A failed validation result with a required key issue\n */\n issueRequiredKey(input: object, key: PropertyKey) {\n return this.issue(new IssueRequiredKey(this.path, input, key))\n }\n\n /**\n * Creates a failure for an invalid string format.\n *\n * @param input - The actual value that was received\n * @param format - The expected format name (e.g., 'did', 'handle', 'uri')\n * @param msg - Optional additional message describing the format error\n * @returns A failed validation result with an invalid format issue\n */\n issueInvalidFormat(input: unknown, format: string, msg?: string) {\n return this.issue(new IssueInvalidFormat(this.path, input, format, msg))\n }\n\n /**\n * Creates a failure for a value that exceeds a maximum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param max - The maximum allowed value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too big issue\n */\n issueTooBig(\n input: unknown,\n type: MeasurableType,\n max: number,\n actual: number,\n ) {\n return this.issue(new IssueTooBig(this.path, input, max, type, actual))\n }\n\n /**\n * Creates a failure for a value that is below a minimum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param min - The minimum required value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too small issue\n */\n issueTooSmall(\n input: unknown,\n type: MeasurableType,\n min: number,\n actual: number,\n ) {\n return this.issue(new IssueTooSmall(this.path, input, min, type, actual))\n }\n\n /**\n * Creates a failure for an invalid property value within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid value\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue at the property path\n */\n issueInvalidPropertyValue<I>(\n input: I,\n property: keyof I & PropertyKey,\n values: readonly unknown[],\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidValue(path, value, values))\n }\n\n /**\n * Creates a failure for an invalid property type within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid type\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue at the property path\n */\n issueInvalidPropertyType<I>(\n input: I,\n property: keyof I & PropertyKey,\n expected: string,\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidType(path, value, [expected]))\n }\n}\n\n/**\n * Recursively unwraps a wrapped validator to its innermost validator type.\n *\n * Some validators wrap other validators (e.g., optional, nullable). This type\n * utility recursively unwraps such wrappers to reveal the core validator.\n *\n * @typeParam T - A validator type, possibly wrapped\n *\n * @example\n * ```typescript\n * type Inner = UnwrapValidator<OptionalValidator<NullableValidator<StringSchema>>>\n * // Result: StringSchema\n * ```\n */\nexport type UnwrapValidator<T extends Validator> = T extends {\n unwrap(): infer U extends Validator\n}\n ? UnwrapValidator<U>\n : T\n\n/**\n * Interface for validators that wrap another validator.\n *\n * Implement this interface when creating validators that wrap or modify\n * the behavior of another validator (e.g., optional, nullable, transform).\n *\n * @typeParam Validator - The type of the wrapped validator\n *\n * @example\n * ```typescript\n * class OptionalSchema<V extends Validator> implements WrappedValidator<V> {\n * constructor(private inner: V) {}\n *\n * unwrap(): V {\n * return this.inner\n * }\n * }\n * ```\n */\nexport interface WrappedValidator<out Validator> {\n /**\n * Returns the inner wrapped validator.\n *\n * @returns The wrapped validator\n */\n unwrap(): Validator\n}\n"]}
|
package/dist/core.d.ts
CHANGED
package/dist/core.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAA;AAC/B,cAAc,
|
|
1
|
+
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAA;AAC/B,cAAc,sBAAsB,CAAA;AACpC,cAAc,kBAAkB,CAAA;AAChC,cAAc,kBAAkB,CAAA;AAChC,cAAc,yBAAyB,CAAA;AACvC,cAAc,iBAAiB,CAAA;AAC/B,cAAc,4BAA4B,CAAA;AAC1C,cAAc,4BAA4B,CAAA;AAC1C,cAAc,qBAAqB,CAAA"}
|
package/dist/core.js
CHANGED
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
const tslib_1 = require("tslib");
|
|
4
4
|
tslib_1.__exportStar(require("./core/$type.js"), exports);
|
|
5
|
-
tslib_1.__exportStar(require("./core/property-key.js"), exports);
|
|
6
5
|
tslib_1.__exportStar(require("./core/record-key.js"), exports);
|
|
7
6
|
tslib_1.__exportStar(require("./core/result.js"), exports);
|
|
8
7
|
tslib_1.__exportStar(require("./core/schema.js"), exports);
|
package/dist/core.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":";;;AAAA,0DAA+B;AAC/B
|
|
1
|
+
{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":";;;AAAA,0DAA+B;AAC/B,+DAAoC;AACpC,2DAAgC;AAChC,2DAAgC;AAChC,kEAAuC;AACvC,0DAA+B;AAC/B,qEAA0C;AAC1C,qEAA0C;AAC1C,8DAAmC","sourcesContent":["export * from './core/$type.js'\nexport * from './core/record-key.js'\nexport * from './core/result.js'\nexport * from './core/schema.js'\nexport * from './core/string-format.js'\nexport * from './core/types.js'\nexport * from './core/validation-error.js'\nexport * from './core/validation-issue.js'\nexport * from './core/validator.js'\n"]}
|
package/dist/schema/blob.d.ts
CHANGED
|
@@ -1,24 +1,26 @@
|
|
|
1
|
-
import { BlobRef,
|
|
1
|
+
import { BlobRef, LegacyBlobRef, isBlobRef, isLegacyBlobRef } from '@atproto/lex-data';
|
|
2
2
|
import { Schema, ValidationContext } from '../core.js';
|
|
3
3
|
/**
|
|
4
4
|
* Configuration options for blob schema validation.
|
|
5
|
-
*
|
|
6
|
-
* @property allowLegacy - Whether to allow legacy blob references format
|
|
7
|
-
* @property accept - List of accepted MIME types (supports wildcards like 'image/*' or '*\/*')
|
|
8
|
-
* @property maxSize - Maximum blob size in bytes
|
|
9
5
|
*/
|
|
10
|
-
export type BlobSchemaOptions =
|
|
6
|
+
export type BlobSchemaOptions = {
|
|
11
7
|
/**
|
|
12
8
|
* Whether to allow legacy blob references format
|
|
9
|
+
*
|
|
10
|
+
* @default false
|
|
13
11
|
* @see {@link LegacyBlobRef}
|
|
14
12
|
*/
|
|
15
13
|
allowLegacy?: boolean;
|
|
16
14
|
/**
|
|
17
|
-
* List of accepted
|
|
15
|
+
* List of accepted MIME types (supports wildcards like 'image/*' or '*\/*')
|
|
16
|
+
*
|
|
17
|
+
* @default undefined // accepts all MIME types
|
|
18
18
|
*/
|
|
19
19
|
accept?: string[];
|
|
20
20
|
/**
|
|
21
|
-
* Maximum size in bytes
|
|
21
|
+
* Maximum blob size in bytes
|
|
22
|
+
*
|
|
23
|
+
* @default undefined // no size limit
|
|
22
24
|
*/
|
|
23
25
|
maxSize?: number;
|
|
24
26
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"blob.d.ts","sourceRoot":"","sources":["../../src/schema/blob.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EACP,
|
|
1
|
+
{"version":3,"file":"blob.d.ts","sourceRoot":"","sources":["../../src/schema/blob.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EACP,aAAa,EACb,SAAS,EACT,eAAe,EAEhB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAGtD;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B;;;;;OAKG;IACH,WAAW,CAAC,EAAE,OAAO,CAAA;IAErB;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,EAAE,CAAA;IAEjB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAA;AAED,YAAY,EAAE,OAAO,EAAE,aAAa,EAAE,CAAA;AACtC,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,CAAA;AAErC;;;;;;;;;;;;;;GAcG;AACH,qBAAa,UAAU,CACrB,KAAK,CAAC,QAAQ,SAAS,iBAAiB,GAAG,WAAW,CAAC,OAAO,CAAC,CAC/D,SAAQ,MAAM,CACd,QAAQ,SAAS;IAAE,WAAW,EAAE,IAAI,CAAA;CAAE,GAAG,OAAO,GAAG,aAAa,GAAG,OAAO,CAC3E;IAGa,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ;IAFvC,QAAQ,CAAC,IAAI,EAAG,MAAM,CAAS;gBAEV,OAAO,CAAC,EAAE,QAAQ,YAAA;IAIvC,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;IAwBxD,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;CAKnC;AA6CD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,IAAI,GACf,CAAC,SAAS,iBAAiB;kBAAmB,KAAK;aACzC,CAAC,kBAEX,CAAA"}
|
package/dist/schema/blob.js
CHANGED
|
@@ -29,23 +29,21 @@ class BlobSchema extends core_js_1.Schema {
|
|
|
29
29
|
this.options = options;
|
|
30
30
|
}
|
|
31
31
|
validateInContext(input, ctx) {
|
|
32
|
-
const blob = input
|
|
33
|
-
? (0, lex_data_1.isBlobRef)(input, this.options)
|
|
34
|
-
? input
|
|
35
|
-
: null
|
|
36
|
-
: this.options?.allowLegacy === true && (0, lex_data_1.isLegacyBlobRef)(input)
|
|
37
|
-
? input
|
|
38
|
-
: null;
|
|
32
|
+
const blob = parseValue.call(ctx, input, this.options);
|
|
39
33
|
if (!blob) {
|
|
40
34
|
return ctx.issueUnexpectedType(input, 'blob');
|
|
41
35
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
36
|
+
// In non-strict mode, we allow blob refs to pass through without MIME
|
|
37
|
+
// type or size checks.
|
|
38
|
+
if (ctx.options.strict) {
|
|
39
|
+
const accept = this.options?.accept;
|
|
40
|
+
if (accept && !matchesMime(blob.mimeType, accept)) {
|
|
41
|
+
return ctx.issueInvalidPropertyValue(blob, 'mimeType', accept);
|
|
42
|
+
}
|
|
43
|
+
const maxSize = this.options?.maxSize;
|
|
44
|
+
if (maxSize != null && 'size' in blob && blob.size > maxSize) {
|
|
45
|
+
return ctx.issueTooBig(blob, 'blob', maxSize, blob.size);
|
|
46
|
+
}
|
|
49
47
|
}
|
|
50
48
|
return ctx.success(blob);
|
|
51
49
|
}
|
|
@@ -57,6 +55,33 @@ class BlobSchema extends core_js_1.Schema {
|
|
|
57
55
|
}
|
|
58
56
|
}
|
|
59
57
|
exports.BlobSchema = BlobSchema;
|
|
58
|
+
function parseValue(input, options) {
|
|
59
|
+
// If there is a $type property, we treat if as a potential BlobRef and
|
|
60
|
+
// validate accordingly.
|
|
61
|
+
if (input?.$type !== undefined) {
|
|
62
|
+
// Use the context's option for the "strict" check
|
|
63
|
+
return (0, lex_data_1.isBlobRef)(input, this.options) ? input : null;
|
|
64
|
+
}
|
|
65
|
+
// If there is no $type property, we may be dealing with a legacy blob ref. If
|
|
66
|
+
// legacy refs are allowed, validate against the legacy format. If not
|
|
67
|
+
// allowed, but we are in non-strict "parse" mode, coerce legacy refs into
|
|
68
|
+
// standard BlobRef format for backward compatibility. Otherwise, reject the
|
|
69
|
+
// value.
|
|
70
|
+
if (options?.allowLegacy) {
|
|
71
|
+
if ((0, lex_data_1.isLegacyBlobRef)(input)) {
|
|
72
|
+
return input;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
else if (!this.options.strict && this.options.mode === 'parse') {
|
|
76
|
+
if ((0, lex_data_1.isLegacyBlobRef)(input)) {
|
|
77
|
+
const { cid, mimeType } = input;
|
|
78
|
+
const ref = (0, lex_data_1.parseCidSafe)(cid);
|
|
79
|
+
if (ref)
|
|
80
|
+
return { $type: 'blob', ref, mimeType, size: -1 };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
60
85
|
function matchesMime(mime, accepted) {
|
|
61
86
|
if (accepted.includes('*/*'))
|
|
62
87
|
return true;
|
package/dist/schema/blob.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"blob.js","sourceRoot":"","sources":["../../src/schema/blob.ts"],"names":[],"mappings":";;;AAAA,gDAM0B;
|
|
1
|
+
{"version":3,"file":"blob.js","sourceRoot":"","sources":["../../src/schema/blob.ts"],"names":[],"mappings":";;;AAAA,gDAM0B;AAgCjB,0FAnCP,oBAAS,OAmCO;AAAE,gGAlClB,0BAAe,OAkCkB;AA/BnC,wCAAsD;AACtD,mDAAoD;AAgCpD;;;;;;;;;;;;;;GAcG;AACH,MAAa,UAEX,SAAQ,gBAET;IAGsB;IAFZ,IAAI,GAAG,MAAe,CAAA;IAE/B,YAAqB,OAAkB;QACrC,KAAK,EAAE,CAAA;QADY,YAAO,GAAP,OAAO,CAAW;IAEvC,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAA;QAEtD,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,OAAO,GAAG,CAAC,mBAAmB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;QAC/C,CAAC;QAED,sEAAsE;QACtE,uBAAuB;QACvB,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;YACvB,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,EAAE,MAAM,CAAA;YACnC,IAAI,MAAM,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC;gBAClD,OAAO,GAAG,CAAC,yBAAyB,CAAC,IAAI,EAAE,UAAU,EAAE,MAAM,CAAC,CAAA;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,CAAC;YAC3B,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAA;YAC/B,MAAM,GAAG,GAAG,IAAA,uBAAY,EAAC,GAAG,CAAC,CAAA;YAC7B,IAAI,GAAG;gBAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAA;QAC5D,CAAC;IACH,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC;AAED,SAAS,WAAW,CAAC,IAAY,EAAE,QAAkB;IACnD,IAAI,QAAQ,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAA;IACzC,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAA;IACxC,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;YAChE,OAAO,IAAI,CAAA;QACb,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACU,QAAA,IAAI,GAAiB,IAAA,4BAAe,EAAC,UAEhD,OAAW;IACX,OAAO,IAAI,UAAU,CAAC,OAAO,CAAC,CAAA;AAChC,CAAC,CAAC,CAAA","sourcesContent":["import {\n BlobRef,\n LegacyBlobRef,\n isBlobRef,\n isLegacyBlobRef,\n parseCidSafe,\n} from '@atproto/lex-data'\nimport { Schema, ValidationContext } from '../core.js'\nimport { memoizedOptions } from '../util/memoize.js'\n\n/**\n * Configuration options for blob schema validation.\n */\nexport type BlobSchemaOptions = {\n /**\n * Whether to allow legacy blob references format\n *\n * @default false\n * @see {@link LegacyBlobRef}\n */\n allowLegacy?: boolean\n\n /**\n * List of accepted MIME types (supports wildcards like 'image/*' or '*\\/*')\n *\n * @default undefined // accepts all MIME types\n */\n accept?: string[]\n\n /**\n * Maximum blob size in bytes\n *\n * @default undefined // no size limit\n */\n maxSize?: number\n}\n\nexport type { BlobRef, LegacyBlobRef }\nexport { isBlobRef, isLegacyBlobRef }\n\n/**\n * Schema for validating blob references in AT Protocol.\n *\n * Validates BlobRef objects which contain a CID reference to binary data,\n * along with metadata like MIME type and size. Can optionally accept\n * legacy blob reference format.\n *\n * @template TOptions - The configuration options type\n *\n * @example\n * ```ts\n * const schema = new BlobSchema({ accept: ['image/*'], maxSize: 1000000 })\n * const result = schema.validate(blobRef)\n * ```\n */\nexport class BlobSchema<\n const TOptions extends BlobSchemaOptions = NonNullable<unknown>,\n> extends Schema<\n TOptions extends { allowLegacy: true } ? BlobRef | LegacyBlobRef : BlobRef\n> {\n readonly type = 'blob' as const\n\n constructor(readonly options?: TOptions) {\n super()\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n const blob = parseValue.call(ctx, input, this.options)\n\n if (!blob) {\n return ctx.issueUnexpectedType(input, 'blob')\n }\n\n // In non-strict mode, we allow blob refs to pass through without MIME\n // type or size checks.\n if (ctx.options.strict) {\n const accept = this.options?.accept\n if (accept && !matchesMime(blob.mimeType, accept)) {\n return ctx.issueInvalidPropertyValue(blob, 'mimeType', accept)\n }\n\n const maxSize = this.options?.maxSize\n if (maxSize != null && 'size' in blob && blob.size > maxSize) {\n return ctx.issueTooBig(blob, 'blob', maxSize, blob.size)\n }\n }\n\n return ctx.success(blob)\n }\n\n matchesMime(mime: string): boolean {\n const accept = this.options?.accept\n if (!accept) return true\n return matchesMime(mime, accept)\n }\n}\n\nfunction parseValue(\n this: ValidationContext,\n input: unknown,\n options?: BlobSchemaOptions,\n): BlobRef | LegacyBlobRef | null {\n // If there is a $type property, we treat if as a potential BlobRef and\n // validate accordingly.\n if ((input as any)?.$type !== undefined) {\n // Use the context's option for the \"strict\" check\n return isBlobRef(input, this.options) ? input : null\n }\n\n // If there is no $type property, we may be dealing with a legacy blob ref. If\n // legacy refs are allowed, validate against the legacy format. If not\n // allowed, but we are in non-strict \"parse\" mode, coerce legacy refs into\n // standard BlobRef format for backward compatibility. Otherwise, reject the\n // value.\n if (options?.allowLegacy) {\n if (isLegacyBlobRef(input)) {\n return input\n }\n } else if (!this.options.strict && this.options.mode === 'parse') {\n if (isLegacyBlobRef(input)) {\n const { cid, mimeType } = input\n const ref = parseCidSafe(cid)\n if (ref) return { $type: 'blob', ref, mimeType, size: -1 }\n }\n }\n\n return null\n}\n\nfunction matchesMime(mime: string, accepted: string[]): boolean {\n if (accepted.includes('*/*')) return true\n if (accepted.includes(mime)) return true\n for (const value of accepted) {\n if (value.endsWith('/*') && mime.startsWith(value.slice(0, -1))) {\n return true\n }\n }\n return false\n}\n\n/**\n * Creates a blob schema for validating blob references with optional constraints.\n *\n * Blob references are used in AT Protocol to reference binary data stored\n * separately from records. They contain a CID, MIME type, and size information.\n *\n * @param options - Optional configuration for MIME type filtering and size limits\n * @returns A new {@link BlobSchema} instance\n *\n * @example\n * ```ts\n * // Basic blob reference\n * const fileSchema = l.blob()\n *\n * // Image files only\n * const imageSchema = l.blob({ accept: ['image/png', 'image/jpeg', 'image/gif'] })\n *\n * // Any image type with size limit\n * const avatarSchema = l.blob({ accept: ['image/*'], maxSize: 1000000 })\n *\n * // Allow legacy format\n * const legacySchema = l.blob({ allowLegacy: true })\n * ```\n */\nexport const blob = /*#__PURE__*/ memoizedOptions(function <\n O extends BlobSchemaOptions = { allowLegacy?: false },\n>(options?: O) {\n return new BlobSchema(options)\n})\n"]}
|
package/dist/schema/custom.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom.d.ts","sourceRoot":"","sources":["../../src/schema/custom.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"custom.d.ts","sourceRoot":"","sources":["../../src/schema/custom.ts"],"names":[],"mappings":"A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","sources":["../../src/schema/custom.ts"],"names":[],"mappings":";;;AAmGA,wBAMC;AAzGD,wCAA0E;AAwB1E;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,YAAmC,SAAQ,gBAAc;IAIjD;IACA;IACA;IALV,IAAI,GAAG,QAAiB,CAAA;IAEjC,YACmB,SAAkC,EAClC,OAAe,EACf,IAA2C;QAE5D,KAAK,EAAE,CAAA;QAJU,cAAS,GAAT,SAAS,CAAyB;QAClC,YAAO,GAAP,OAAO,CAAQ;QACf,SAAI,GAAJ,IAAI,CAAuC;IAG9D,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,EAAE,CAAC;YAC3C,MAAM,IAAI,GAAG,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;YACtC,OAAO,GAAG,CAAC,KAAK,CAAC,IAAI,qBAAW,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAA;QAC9D,CAAC;QACD,OAAO,GAAG,CAAC,OAAO,CAAC,KAAe,CAAC,CAAA;IACrC,CAAC;CACF;AAlBD,oCAkBC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,wBAAwB;AACxB,SAAgB,MAAM,CACpB,SAAkC,EAClC,OAAe,EACf,IAA2C;IAE3C,OAAO,IAAI,YAAY,CAAS,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,CAAA;AAC3D,CAAC","sourcesContent":["import { Issue, IssueCustom, Schema, ValidationContext } from '../core.js'\n\n/**\n * Context object provided to custom assertion functions.\n *\n * @property path - Current validation path as an array of property keys\n * @property addIssue - Function to add additional validation issues\n */\nexport type CustomAssertionContext = {\n path: PropertyKey[]\n addIssue(issue: Issue): void\n}\n\n/**\n * Type guard function for custom schema validation.\n *\n * @template TValue - The type to validate/narrow to\n */\nexport type CustomAssertion<TValue> = (\n this: null,\n input: unknown,\n ctx: CustomAssertionContext,\n) => input is TValue\n\n/**\n * Schema with a custom validation function.\n *\n * Allows defining completely custom validation logic using a type guard\n * assertion function. The function receives the input and validation context,\n * and must return whether the input is valid.\n *\n * @template TValue - The validated output type\n *\n * @example\n * ```ts\n * const schema = new CustomSchema(\n * (input): input is Date => input instanceof Date,\n * 'Expected a Date instance'\n * )\n * ```\n */\nexport class CustomSchema<out TValue = unknown> extends Schema<TValue> {\n readonly type = 'custom' as const\n\n constructor(\n private readonly assertion: CustomAssertion<TValue>,\n private readonly message: string,\n private readonly path?: PropertyKey | readonly PropertyKey[],\n ) {\n super()\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!this.assertion.call(null, input, ctx)) {\n const path = ctx.concatPath(this.path)\n return ctx.issue(new IssueCustom(path, input, this.message))\n }\n return ctx.success(input as TValue)\n }\n}\n\n/**\n * Creates a custom schema with a user-defined validation function.\n *\n * Use this when the built-in schemas don't cover your validation needs.\n * The assertion function must be a type guard that narrows the input type.\n *\n * @param assertion - Type guard function that validates the input\n * @param message - Error message when validation fails\n * @param path - Optional path to associate with validation errors\n * @returns A new {@link CustomSchema} instance\n *\n * @example\n * ```ts\n * // Validate Date instances\n * const dateSchema = l.custom(\n * (input): input is Date => input instanceof Date && !isNaN(input.getTime()),\n * 'Expected a valid Date'\n * )\n *\n * // Validate specific object shape\n * const pointSchema = l.custom(\n * (input): input is { x: number; y: number } =>\n * typeof input === 'object' &&\n * input !== null &&\n * typeof (input as any).x === 'number' &&\n * typeof (input as any).y === 'number',\n * 'Expected a point with x and y coordinates'\n * )\n *\n * // With custom path\n * const validConfig = l.custom(\n * (input): input is Config => validateConfig(input),\n * 'Invalid configuration',\n * ['config']\n * )\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function custom<TValue>(\n assertion: CustomAssertion<TValue>,\n message: string,\n path?: PropertyKey | readonly PropertyKey[],\n) {\n return new CustomSchema<TValue>(assertion, message, path)\n}\n"]}
|
package/dist/schema/never.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ import { Schema, ValidationContext } from '../core.js';
|
|
|
13
13
|
*/
|
|
14
14
|
export declare class NeverSchema extends Schema<never> {
|
|
15
15
|
readonly type: "never";
|
|
16
|
-
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").
|
|
16
|
+
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").LexValidationError;
|
|
17
17
|
}
|
|
18
18
|
/**
|
|
19
19
|
* Creates a never schema that always fails validation.
|
|
@@ -18,7 +18,7 @@ export declare class NullableSchema<const TValidator extends Validator> extends
|
|
|
18
18
|
readonly validator: TValidator;
|
|
19
19
|
readonly type: "nullable";
|
|
20
20
|
constructor(validator: TValidator);
|
|
21
|
-
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").
|
|
21
|
+
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").LexValidationError | import("../core.js").ValidationSuccess<null> | import("../core.js").ValidationSuccess<InferInput<TValidator>>;
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
24
|
* Creates a nullable schema that accepts null in addition to the wrapped type.
|
package/dist/schema/payload.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { LexValue } from '@atproto/lex-data';
|
|
2
|
-
import {
|
|
2
|
+
import { InferInput, Schema, Validator } from '../core.js';
|
|
3
3
|
import { ObjectSchema } from './object.js';
|
|
4
4
|
export type { LexValue };
|
|
5
5
|
type ToBodyMime<TEncoding extends string> = TEncoding extends '*/*' ? `${string}/${string}` : TEncoding extends `${infer T extends string}/*` ? `${T}/${string}` : TEncoding;
|
|
6
|
-
type ToBodyType<TEncoding extends string, TSchema, TBinary> = TSchema extends Schema ?
|
|
6
|
+
type ToBodyType<TEncoding extends string, TSchema, TBinary> = TSchema extends Schema ? InferInput<TSchema> : TEncoding extends `application/json` ? LexValue : TBinary;
|
|
7
7
|
/**
|
|
8
8
|
* Infers the type of a Payload's encoding and body.
|
|
9
9
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payload.d.ts","sourceRoot":"","sources":["../../src/schema/payload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAC5C,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"payload.d.ts","sourceRoot":"","sources":["../../src/schema/payload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAC1D,OAAO,EAAE,YAAY,EAAU,MAAM,aAAa,CAAA;AAElD,YAAY,EAAE,QAAQ,EAAE,CAAA;AAExB,KAAK,UAAU,CAAC,SAAS,SAAS,MAAM,IAAI,SAAS,SAAS,KAAK,GAC/D,GAAG,MAAM,IAAI,MAAM,EAAE,GACrB,SAAS,SAAS,GAAG,MAAM,CAAC,SAAS,MAAM,IAAI,GAC7C,GAAG,CAAC,IAAI,MAAM,EAAE,GAChB,SAAS,CAAA;AAEf,KAAK,UAAU,CACb,SAAS,SAAS,MAAM,EACxB,OAAO,EACP,OAAO,IACL,OAAO,SAAS,MAAM,GACtB,UAAU,CAAC,OAAO,CAAC,GACnB,SAAS,SAAS,kBAAkB,GAClC,QAAQ,GACR,OAAO,CAAA;AAEb;;;;;GAKG;AACH,MAAM,MAAM,YAAY,CAAC,QAAQ,SAAS,OAAO,EAAE,OAAO,IACxD,QAAQ,SAAS,OAAO,CAAC,MAAM,SAAS,EAAE,MAAM,OAAO,CAAC,GACpD,SAAS,SAAS,MAAM,GACtB;IACE,QAAQ,EAAE,UAAU,CAAC,SAAS,CAAC,CAAA;IAC/B,IAAI,EAAE,UAAU,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;CAC9C,GACD,SAAS,GACX,KAAK,CAAA;AAEX;;;;;;GAMG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IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YAC5B,OAAO,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;QAC/C,CAAC;QAED,gEAAgE;QAChE,IAAI,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YAC3B,OAAO,KAAK,CAAA;QACd,CAAC;QAED,OAAO,QAAQ,KAAK,IAAI,CAAA;IAC1B,CAAC;CACF;AA7CD,0BA6CC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAwB;AACxB,SAAgB,OAAO,CAGrB,WAAc,SAAc,EAAE,YAAe,SAAc;IAC3D,OAAO,IAAI,OAAO,CAAO,QAAQ,EAAE,SAAS,CAAC,CAAA;AAC/C,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAwB;AACxB,SAAgB,WAAW,CAEzB,UAAa;IACb,OAAO,OAAO,CAAC,kBAAkB,EAAE,IAAA,kBAAM,EAAC,UAAU,CAAC,CAAC,CAAA;AACxD,CAAC","sourcesContent":["import { LexValue } from '@atproto/lex-data'\nimport {
|
|
1
|
+
{"version":3,"file":"payload.js","sourceRoot":"","sources":["../../src/schema/payload.ts"],"names":[],"mappings":";;;AAuKA,0BAKC;AA4BD,kCAIC;AA1MD,2CAAkD;AAwElD;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,OAAO;IAKP;IACA;IAFX,YACW,QAAmB,EACnB,MAAe;QADf,aAAQ,GAAR,QAAQ,CAAW;QACnB,WAAM,GAAN,MAAM,CAAS;QAExB,IAAI,QAAQ,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACnD,MAAM,IAAI,SAAS,CAAC,qDAAqD,CAAC,CAAA;QAC5E,CAAC;IACH,CAAC;IAED;;;OAGG;IACH,eAAe,CAAC,WAA+B;QAC7C,MAAM,EA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js'\nimport { ObjectSchema, object } from './object.js'\n\nexport type { LexValue }\n\ntype ToBodyMime<TEncoding extends string> = TEncoding extends '*/*'\n ? `${string}/${string}`\n : TEncoding extends `${infer T extends string}/*`\n ? `${T}/${string}`\n : TEncoding\n\ntype ToBodyType<\n TEncoding extends string,\n TSchema,\n TBinary,\n> = TSchema extends Schema\n ? InferInput<TSchema>\n : TEncoding extends `application/json`\n ? LexValue\n : TBinary\n\n/**\n * Infers the type of a Payload's encoding and body.\n *\n * @template TPayload - The Payload type\n * @template TBody - Fallback body type for non-JSON encodings\n */\nexport type InferPayload<TPayload extends Payload, TBinary> =\n TPayload extends Payload<infer TEncoding, infer TSchema>\n ? TEncoding extends string\n ? {\n encoding: ToBodyMime<TEncoding>\n body: ToBodyType<TEncoding, TSchema, TBinary>\n }\n : undefined\n : never\n\n/**\n * Converts schema encoding patterns to data encoding types.\n *\n * Handles wildcards like '*\\/*' and 'image/*' in MIME types.\n *\n * @template TPayload - The Payload type\n */\nexport type InferPayloadEncoding<TPayload extends Payload> =\n TPayload extends Payload<infer TEncoding, any>\n ? TEncoding extends string\n ? ToBodyMime<TEncoding>\n : undefined\n : never\n\n/**\n * Infers the body type from a Payload and fallback type.\n *\n * @template TPayload - The Payload type\n * @template TBody - Fallback body type for non-JSON encodings without schema\n */\nexport type InferPayloadBody<TPayload extends Payload, TBinary> =\n TPayload extends Payload<infer TEncoding, infer TSchema>\n ? TEncoding extends string\n ? ToBodyType<TEncoding, TSchema, TBinary>\n : undefined\n : never\n\n/**\n * Determines valid schema type based on encoding presence.\n *\n * @template E - The encoding string type, or undefined\n */\nexport type PayloadSchema<E extends string | undefined> = E extends undefined\n ? undefined\n : Schema<LexValue> | undefined\n\n/**\n * Represents a payload definition for Lexicon endpoints.\n *\n * Payloads define the body format for HTTP requests and responses.\n * They consist of an encoding (MIME type) and an optional schema\n * for validating the body content.\n *\n * @template TEncoding - The MIME type string, or undefined for no body\n * @template TPayload - The schema type for body validation\n *\n * @example\n * ```ts\n * const jsonPayload = new Payload('application/json', l.object({ data: l.string() }))\n * const binaryPayload = new Payload('image/*', undefined)\n * const noPayload = new Payload(undefined, undefined)\n * ```\n */\nexport class Payload<\n const TEncoding extends string | undefined = string | undefined,\n const TSchema extends PayloadSchema<TEncoding> = PayloadSchema<TEncoding>,\n> {\n constructor(\n readonly encoding: TEncoding,\n readonly schema: TSchema,\n ) {\n if (encoding === undefined && schema !== undefined) {\n throw new TypeError('schema cannot be defined when encoding is undefined')\n }\n }\n\n /**\n * Checks whether the given content-type matches the expected payload schema's\n * encoding.\n */\n matchesEncoding(contentType: string | undefined): boolean {\n const { encoding } = this\n\n // Handle undefined cases\n if (encoding === undefined) {\n // Expecting no body\n return contentType == null\n } else if (contentType == null) {\n // Expecting a body, but got no content-type\n return false\n }\n\n if (encoding === '*/*') {\n return true\n }\n\n const mime = contentType?.split(';', 1)[0].trim()\n if (encoding.endsWith('/*')) {\n return mime.startsWith(encoding.slice(0, -1))\n }\n\n // Invalid: Lexicon can only specify \"*/*\" or \"type/*\" wildcards\n if (encoding.includes('*')) {\n return false\n }\n\n return encoding === mime\n }\n}\n\n/**\n * Creates a payload definition for Lexicon endpoint bodies.\n *\n * Defines the expected MIME type and optional validation schema for\n * request or response bodies.\n *\n * @param encoding - MIME type string (e.g., 'application/json', 'image/*'), or undefined for no body\n * @param validator - Optional schema for validating the body content. Must be undefined if encoding is undefined.\n * @returns A new {@link Payload} instance\n *\n * @example\n * ```ts\n * // JSON payload with schema\n * const output = l.payload('application/json', l.object({\n * posts: l.array(postSchema),\n * cursor: l.optional(l.string()),\n * }))\n *\n * // Binary payload (no schema validation)\n * const blobInput = l.payload('*\\/*', undefined)\n *\n * // Image payload with wildcard\n * const imageInput = l.payload('image/*', undefined)\n *\n * // No payload (for endpoints without body)\n * const noBody = l.payload()\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function payload<\n const E extends string | undefined = undefined,\n const S extends PayloadSchema<E> = undefined,\n>(encoding: E = undefined as E, validator: S = undefined as S) {\n return new Payload<E, S>(encoding, validator)\n}\n\n/**\n * Creates a JSON payload with an object schema.\n *\n * Convenience function for the common case of JSON request/response bodies.\n * Equivalent to `l.payload('application/json', l.object(properties))`.\n *\n * @param properties - Object mapping property names to validators\n * @returns A new {@link Payload} instance with 'application/json' encoding\n *\n * @example\n * ```ts\n * // Query output\n * const profileOutput = l.jsonPayload({\n * did: l.string({ format: 'did' }),\n * handle: l.string({ format: 'handle' }),\n * displayName: l.optional(l.string()),\n * })\n *\n * // Procedure input\n * const createPostInput = l.jsonPayload({\n * text: l.string({ maxGraphemes: 300 }),\n * createdAt: l.string({ format: 'datetime' }),\n * })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function jsonPayload<\n P extends Record<string, Validator<undefined | LexValue>>,\n>(properties: P): Payload<'application/json', ObjectSchema<P>> {\n return payload('application/json', object(properties))\n}\n"]}
|
package/dist/schema/record.d.ts
CHANGED
|
@@ -41,7 +41,7 @@ export declare class RecordSchema<const TKey extends LexiconRecordKey = any, con
|
|
|
41
41
|
readonly type: "record";
|
|
42
42
|
keySchema: RecordKeySchema<TKey>;
|
|
43
43
|
constructor(key: TKey, $type: TType, schema: TShape);
|
|
44
|
-
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").
|
|
44
|
+
validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").LexValidationError | import("../core.js").ValidationSuccess<InferInput<TShape>>;
|
|
45
45
|
build(input: Omit<InferInput<this>, '$type'>): $Typed<InferOutput<this>, TType>;
|
|
46
46
|
isTypeOf<TValue extends {
|
|
47
47
|
$type?: unknown;
|
package/dist/schema/ref.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ export type RefSchemaGetter<out TValidator extends Validator> = () => TValidator
|
|
|
22
22
|
* })
|
|
23
23
|
* ```
|
|
24
24
|
*/
|
|
25
|
-
export declare class RefSchema<const TValidator extends Validator> extends Schema<InferInput<TValidator>, InferOutput<TValidator
|
|
25
|
+
export declare class RefSchema<const TValidator extends Validator> extends Schema<InferInput<TValidator>, InferOutput<TValidator>> implements WrappedValidator<TValidator> {
|
|
26
26
|
#private;
|
|
27
27
|
readonly type: "ref";
|
|
28
28
|
constructor(getter: RefSchemaGetter<TValidator>);
|
package/dist/schema/ref.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ref.d.ts","sourceRoot":"","sources":["../../src/schema/ref.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,MAAM,EACN,iBAAiB,EACjB,SAAS,EACT,gBAAgB,EACjB,MAAM,YAAY,CAAA;AAEnB;;;;GAIG;AACH,MAAM,MAAM,eAAe,CAAC,GAAG,CAAC,UAAU,SAAS,SAAS,IAAI,MAAM,UAAU,CAAA;AAEhF;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,SAAS,CAAC,KAAK,CAAC,UAAU,SAAS,SAAS,CACvD,SAAQ,MAAM,
|
|
1
|
+
{"version":3,"file":"ref.d.ts","sourceRoot":"","sources":["../../src/schema/ref.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,MAAM,EACN,iBAAiB,EACjB,SAAS,EACT,gBAAgB,EACjB,MAAM,YAAY,CAAA;AAEnB;;;;GAIG;AACH,MAAM,MAAM,eAAe,CAAC,GAAG,CAAC,UAAU,SAAS,SAAS,IAAI,MAAM,UAAU,CAAA;AAEhF;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,SAAS,CAAC,KAAK,CAAC,UAAU,SAAS,SAAS,CACvD,SAAQ,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,WAAW,CAAC,UAAU,CAAC,CAC9D,YAAW,gBAAgB,CAAC,UAAU,CAAC;;IAEvC,QAAQ,CAAC,IAAI,EAAG,KAAK,CAAS;gBAIlB,MAAM,EAAE,eAAe,CAAC,UAAU,CAAC;IAS/C,IAAI,SAAS,IAAI,UAAU,CAE1B;IAED,MAAM,IAAI,UAAU;IAIpB,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;CAGzD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,wBAAgB,GAAG,CAAC,KAAK,CAAC,UAAU,SAAS,SAAS,EACpD,GAAG,EAAE,eAAe,CAAC,UAAU,CAAC,GAC/B,SAAS,CAAC,UAAU,CAAC,CAAA;AACxB,wBAAgB,GAAG,CAAC,MAAM,EAAE,OAAO,SAAS,MAAM,GAAG,MAAM,EACzD,GAAG,EAAE,eAAe,CAAC,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAC/C,SAAS,CAAC,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA"}
|
package/dist/schema/ref.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../src/schema/ref.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../src/schema/ref.ts"],"names":[],"mappings":";;;AAkGA,kBAIC;AAtGD,wCAOmB;AASnB;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,SACX,SAAQ,gBAAuD;IAGtD,IAAI,GAAG,KAAc,CAAA;IAE9B,OAAO,CAA6B;IAEpC,YAAY,MAAmC;QAC7C,uEAAuE;QACvE,sEAAsE;QAEtE,KAAK,EAAE,CAAA;QAEP,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;IACvB,CAAC;IAED,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAChC,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC,SAAS,CAAA;IACvB,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,OAAO,GAAG,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,CAAA;IAC5C,CAAC;CACF;AA5BD,8BA4BC;AAqCD,SAAgB,GAAG,CACjB,GAAgC;IAEhC,OAAO,IAAI,SAAS,CAAa,GAAG,CAAC,CAAA;AACvC,CAAC","sourcesContent":["import {\n InferInput,\n InferOutput,\n Schema,\n ValidationContext,\n Validator,\n WrappedValidator,\n} from '../core.js'\n\n/**\n * Function type that returns a validator, used for lazy schema resolution.\n *\n * @template TValidator - The validator type that will be returned\n */\nexport type RefSchemaGetter<out TValidator extends Validator> = () => TValidator\n\n/**\n * Schema for creating references to other schemas with lazy resolution.\n *\n * Useful for handling circular references or breaking module dependency cycles.\n * The referenced schema is resolved lazily when first needed for validation.\n *\n * @template TValidator - The referenced validator type\n *\n * @example\n * ```ts\n * // Self-referential schema for tree structure\n * const nodeSchema = l.object({\n * value: l.string(),\n * children: l.array(l.ref(() => nodeSchema)),\n * })\n * ```\n */\nexport class RefSchema<const TValidator extends Validator>\n extends Schema<InferInput<TValidator>, InferOutput<TValidator>>\n implements WrappedValidator<TValidator>\n{\n readonly type = 'ref' as const\n\n #getter: RefSchemaGetter<TValidator>\n\n constructor(getter: RefSchemaGetter<TValidator>) {\n // @NOTE In order to avoid circular dependency issues, we don't resolve\n // the schema here. Instead, we resolve it lazily when first accessed.\n\n super()\n\n this.#getter = getter\n }\n\n get validator(): TValidator {\n return this.#getter.call(null)\n }\n\n unwrap(): TValidator {\n return this.validator\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n return ctx.validate(input, this.validator)\n }\n}\n\n/**\n * Creates a reference schema with lazy resolution.\n *\n * Allows referencing schemas that may not be defined yet, enabling\n * circular references and breaking dependency cycles. The getter function\n * is called lazily when validation is first performed.\n *\n * @param get - Function that returns the referenced validator\n * @returns A new {@link RefSchema} instance\n *\n * @example\n * ```ts\n * // Circular reference - tree node that contains children of the same type\n * const treeNodeSchema = l.object({\n * name: l.string(),\n * children: l.optional(l.array(l.ref(() => treeNodeSchema))),\n * })\n *\n * // Cross-module reference\n * const commentSchema = l.object({\n * text: l.string(),\n * author: l.ref(() => userSchema), // userSchema defined elsewhere\n * })\n *\n * // Explicitly typed reference\n * const itemSchema = l.ref<Item>(() => complexItemSchema)\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function ref<const TValidator extends Validator>(\n get: RefSchemaGetter<TValidator>,\n): RefSchema<TValidator>\nexport function ref<TInput, TOutput extends TInput = TInput>(\n get: RefSchemaGetter<Validator<TInput, TOutput>>,\n): RefSchema<Validator<TInput, TOutput>>\nexport function ref<const TValidator extends Validator>(\n get: RefSchemaGetter<TValidator>,\n) {\n return new RefSchema<TValidator>(get)\n}\n"]}
|
package/dist/schema/refine.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refine.d.ts","sourceRoot":"","sources":["../../src/schema/refine.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,
|
|
1
|
+
{"version":3,"file":"refine.d.ts","sourceRoot":"","sources":["../../src/schema/refine.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EAIV,SAAS,EACV,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAA;AAEpD;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,IAAI;IAC/B,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,sBAAsB,KAAK,OAAO,CAAA;IACzD,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,WAAW,GAAG,SAAS,WAAW,EAAE,CAAA;CAC5C,CAAA;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,mBAAmB,CAAC,CAAC,EAAE,GAAG,SAAS,CAAC,IAAI;IAClD,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,sBAAsB,KAAK,KAAK,IAAI,GAAG,CAAA;IAC1E,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,WAAW,GAAG,SAAS,WAAW,EAAE,CAAA;CAC5C,CAAA;AAED;;;;GAIG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,IAC3B,CAAC,SAAS,eAAe,CAAC,MAAM,CAAC,CAAC,GAC9B,CAAC,GACD,CAAC,SAAS,mBAAmB,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,GACzC,CAAC,GACD,KAAK,CAAA;AAEb;;;;;GAKG;AACH,MAAM,MAAM,UAAU,CAAC,CAAC,GAAG,GAAG,EAAE,GAAG,SAAS,CAAC,GAAG,CAAC,IAC7C,eAAe,CAAC,CAAC,CAAC,GAClB,mBAAmB,CAAC,CAAC,EAAE,GAAG,CAAC,CAAA;AAE/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,wBAAgB,MAAM,CACpB,KAAK,CAAC,UAAU,SAAS,SAAS,EAClC,MAAM,SAAS,UAAU,CAAC,UAAU,CAAC,EAErC,MAAM,EAAE,UAAU,EAClB,UAAU,EAAE,mBAAmB,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,GAC9D,UAAU,GAAG,SAAS,CAAC,MAAM,CAAC,CAAA;AACjC,wBAAgB,MAAM,CAAC,KAAK,CAAC,UAAU,SAAS,SAAS,EACvD,MAAM,EAAE,UAAU,EAClB,UAAU,EAAE,eAAe,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,GAClD,UAAU,CAAA;AACb,wBAAgB,MAAM,CACpB,WAAW,SAAS,UAAU,EAC9B,KAAK,CAAC,UAAU,SAAS,SAAS,CAAC,eAAe,CAAC,WAAW,CAAC,CAAC,EAChE,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,GAAG,UAAU,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refine.js","sourceRoot":"","sources":["../../src/schema/refine.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"refine.js","sourceRoot":"","sources":["../../src/schema/refine.ts"],"names":[],"mappings":";;AAkHA,wBAiBC;AAnID,wCAMmB;AA2GnB,wBAAwB;AACxB,SAAgB,MAAM,CACpB,MAAkB,EAClB,UAA+B;IAE/B,wEAAwE;IACxE,4EAA4E;IAC5E,4EAA4E;IAC5E,6BAA6B;IAC7B,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE;QAC3B,iBAAiB,EAAE;YACjB,8DAA8D;YAC9D,KAAK,EAAE,wBAAwB,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;YAC5D,UAAU,EAAE,KAAK;YACjB,QAAQ,EAAE,KAAK;YACf,YAAY,EAAE,IAAI;SACnB;KACF,CAAC,CAAA;AACJ,CAAC;AAED,wBAAwB;AACxB,SAAS,wBAAwB,CAK/B,KAAc,EACd,GAAsB;IAEtB,MAAM,MAAM,GAAG,GAAG,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;IAC/C,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,OAAO,MAAM,CAAA;IAElC,MAAM,WAAW,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,CAAA;IACvE,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,IAAI,GAAG,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;QACjD,OAAO,GAAG,CAAC,KAAK,CAAC,IAAI,qBAAW,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAA;IACzE,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import {\n InferInput,\n IssueCustom,\n ValidationContext,\n ValidationResult,\n Validator,\n} from '../core.js'\nimport { CustomAssertionContext } from './custom.js'\n\n/**\n * Configuration for a refinement check that validates a condition.\n *\n * @template T - The type being validated\n * @property check - Function that returns true if the value passes the check\n * @property message - Error message when the check fails\n * @property path - Optional path to associate with the error\n */\nexport type RefinementCheck<T> = {\n check: (value: T, ctx: CustomAssertionContext) => boolean\n message: string\n path?: PropertyKey | readonly PropertyKey[]\n}\n\n/**\n * Configuration for a refinement assertion that narrows the type.\n *\n * @template T - The input type being validated\n * @template Out - The narrowed output type\n * @property check - Type guard function that narrows the type\n * @property message - Error message when the assertion fails\n * @property path - Optional path to associate with the error\n */\nexport type RefinementAssertion<T, Out extends T> = {\n check: (this: null, value: T, ctx: CustomAssertionContext) => value is Out\n message: string\n path?: PropertyKey | readonly PropertyKey[]\n}\n\n/**\n * Infers the input type from a refinement configuration.\n *\n * @template R - The refinement type\n */\nexport type InferRefinement<R> =\n R extends RefinementCheck<infer T>\n ? T\n : R extends RefinementAssertion<infer T, any>\n ? T\n : never\n\n/**\n * Union type of refinement check or assertion.\n *\n * @template T - The input type being validated\n * @template Out - The output type (same as T for checks, narrowed for assertions)\n */\nexport type Refinement<T = any, Out extends T = T> =\n | RefinementCheck<T>\n | RefinementAssertion<T, Out>\n\n/**\n * Creates a refined schema by adding additional validation constraints.\n *\n * Wraps an existing schema with an additional check function. The base schema\n * is validated first, then the refinement check is applied to the result.\n *\n * @param schema - The base schema to refine\n * @param refinement - The refinement check or assertion to apply\n * @returns A new schema that includes the refinement\n *\n * @example\n * ```ts\n * // Simple check refinement\n * const positiveInt = l.refine(l.integer(), {\n * check: (value) => value > 0,\n * message: 'Value must be positive',\n * })\n *\n * positiveInt.parse(5) // 5\n * positiveInt.parse(-1) // throws\n *\n * // Type-narrowing assertion\n * const nonEmptyString = l.refine(l.string(), {\n * check: (value): value is string & { length: number } => value.length > 0,\n * message: 'String must not be empty',\n * })\n *\n * // With custom path for nested errors\n * const validDateRange = l.refine(\n * l.object({ start: l.string(), end: l.string() }),\n * {\n * check: (v) => new Date(v.start) < new Date(v.end),\n * message: 'Start date must be before end date',\n * path: ['end'],\n * }\n * )\n * ```\n */\nexport function refine<\n const TValidator extends Validator,\n TInput extends InferInput<TValidator>,\n>(\n schema: TValidator,\n refinement: RefinementAssertion<InferInput<TValidator>, TInput>,\n): TValidator & Validator<TInput>\nexport function refine<const TValidator extends Validator>(\n schema: TValidator,\n refinement: RefinementCheck<InferInput<TValidator>>,\n): TValidator\nexport function refine<\n TRefinement extends Refinement,\n const TValidator extends Validator<InferRefinement<TRefinement>>,\n>(schema: TValidator, refinement: TRefinement): TValidator\n/*@__NO_SIDE_EFFECTS__*/\nexport function refine<const TValidator extends Validator>(\n schema: TValidator,\n refinement: Refinement<unknown>,\n): TValidator {\n // This is basically the same as monkey patching the \"validateInContext\"\n // method to the schema, but done in a way that does not mutate the original\n // schema. This is safe to do because Validators don't update their internal\n // state over their lifetime.\n return Object.create(schema, {\n validateInContext: {\n // We do not use an arrow function to avoid creating a closure\n value: validateInContextUnbound.bind({ schema, refinement }),\n enumerable: false,\n writable: false,\n configurable: true,\n },\n })\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction validateInContextUnbound<S extends Validator>(\n this: {\n schema: S\n refinement: Refinement<InferInput<S>>\n },\n input: unknown,\n ctx: ValidationContext,\n): ValidationResult<InferInput<S>> {\n const result = ctx.validate(input, this.schema)\n if (!result.success) return result\n\n const checkResult = this.refinement.check.call(null, result.value, ctx)\n if (!checkResult) {\n const path = ctx.concatPath(this.refinement.path)\n return ctx.issue(new IssueCustom(path, input, this.refinement.message))\n }\n\n return result\n}\n"]}
|
package/dist/schema/string.js
CHANGED
|
@@ -74,7 +74,7 @@ class StringSchema extends core_js_1.Schema {
|
|
|
74
74
|
}
|
|
75
75
|
}
|
|
76
76
|
const format = this.options.format;
|
|
77
|
-
if (format != null && !(0, core_js_1.isStringFormat)(str, format)) {
|
|
77
|
+
if (format != null && !(0, core_js_1.isStringFormat)(str, format, ctx.options)) {
|
|
78
78
|
return ctx.issueInvalidFormat(str, format);
|
|
79
79
|
}
|
|
80
80
|
return ctx.success(str);
|