Initial commit - Todo app frontend

This commit is contained in:
2026-01-28 16:46:44 +00:00
commit 95b816a2e6
15978 changed files with 2514406 additions and 0 deletions

9
node_modules/zod-validation-error/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,9 @@
(The MIT License)
Copyright 2022 Causaly, Inc <front-end@causaly.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

504
node_modules/zod-validation-error/README.md generated vendored Normal file
View File

@@ -0,0 +1,504 @@
# zod-validation-error
Wrap zod validation errors in user-friendly readable messages.
[![Build Status](https://github.com/causaly/zod-validation-error/actions/workflows/ci.yml/badge.svg)](https://github.com/causaly/zod-validation-error/actions/workflows/ci.yml) [![npm version](https://img.shields.io/npm/v/zod-validation-error.svg?color=0c0)](https://www.npmjs.com/package/zod-validation-error)
#### Features
- User-friendly readable error messages with extensive configuration options;
- Preserves original error details accessible via `error.details`;
- Provides a custom error map for better user-friendly messages;
- Supports both Zod v3 and v4.
**_Note:_** This version of `zod-validation-error` works with zod v4. If you are looking for zod v3 support, please refer to the [v3 documentation](./README.v3.md)
## Installation
```bash
npm install zod-validation-error
```
#### Requirements
- Node.js v.18+
- TypeScript v.4.5+
## Quick start
```typescript
import { z as zod } from 'zod';
import { fromError, createErrorMap } from 'zod-validation-error';
// configure zod to use zod-validation-error's error map
// this is optional, you may also use your own custom error map or zod's native error map
// we recommend using zod-validation-error's error map for better user-friendly messages
// see https://zod.dev/error-customization for further details
zod.config({
customError: createErrorMap(),
});
// create zod schema
const zodSchema = zod.object({
id: zod.int().positive(),
email: zod.email(),
});
// parse some invalid value
try {
zodSchema.parse({
id: 1,
email: 'coyote@acme', // note: invalid email
});
} catch (err) {
const validationError = fromError(err);
// the error is now readable by the user
// you may print it to console
console.log(validationError.toString());
// or return it as an actual error
return validationError;
}
```
## Motivation
Zod errors are difficult to consume for the end-user. This library wraps Zod validation errors in user-friendly readable messages that can be exposed to the outer world, while maintaining the original errors in an array for _dev_ use.
### Example
#### Input (from Zod)
```json
[
{
"origin": "number",
"code": "too_small",
"minimum": 0,
"inclusive": false,
"path": ["id"],
"message": "Number must be greater than 0 at \"id\""
},
{
"origin": "string",
"code": "invalid_format",
"format": "email",
"pattern": "/^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/",
"path": ["email"],
"message": "Invalid email at \"email\""
}
]
```
#### Output
```
Validation error: Number must be greater than 0 at "id"; Invalid email at "email"
```
## API
- [ValidationError(message[, options])](#validationerror)
- [createErrorMap(options)](#createErrorMap)
- [createMessageBuilder(options)](#createMessageBuilder)
- [isValidationError(error)](#isvalidationerror)
- [isValidationErrorLike(error)](#isvalidationerrorlike)
- [isZodErrorLike(error)](#iszoderrorlike)
- [fromError(error[, options])](#fromerror)
- [fromZodIssue(zodIssue[, options])](#fromzodissue)
- [fromZodError(zodError[, options])](#fromzoderror)
- [toValidationError([options]) => (error) => ValidationError](#tovalidationerror)
### ValidationError
Main `ValidationError` class, extending JavaScript's native `Error`.
#### Arguments
- `message` - _string_; error message (required)
- `options` - _ErrorOptions_; error options as per [JavaScript definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error#options) (optional)
- `options.cause` - _any_; can be used to hold the original zod error (optional)
#### Example 1: construct new ValidationError with `message`
```typescript
import { ValidationError } from 'zod-validation-error';
const error = new ValidationError('foobar');
console.log(error instanceof Error); // prints true
```
#### Example 2: construct new ValidationError with `message` and `options.cause`
```typescript
import { z as zod } from 'zod';
import { ValidationError } from 'zod-validation-error';
const error = new ValidationError('foobar', {
cause: new zod.ZodError([
{
origin: 'number',
code: 'too_small',
minimum: 0,
inclusive: false,
path: ['id'],
message: 'Number must be greater than 0 at "id"',
input: -1,
},
]),
});
console.log(error.details); // prints issues from zod error
```
### createErrorMap
Creates zod-validation-error's `errorMap`, which is used to format issues into user-friendly error messages.
We think that zod's native error map is not user-friendly enough, so we provide our own implementation that formats issues into human-readable messages.
Note: zod-validation-error's `errorMap` is an errorMap like all others and thus can also be used directly with `zod` (see https://zod.dev/error-customization for further details), e.g.
#### Arguments
- `options` - _Object_; formatting options (optional)
##### createErrorMap Options
| Name | Type | Description |
| ------------------------------- | :-------------------------------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `displayInvalidFormatDetails` | `boolean` | Indicates whether to display invalid format details (e.g. regexp pattern) in the error message (optional, defaults to `false`) |
| `maxAllowedValuesToDisplay` | `number` | Max number of allowed values to display (optional, defaults to `10`). Allowed values beyond this limit will be hidden. |
| `allowedValuesSeparator` | `string` | Used to concatenate allowed values in the message (optional, defaults to `", "`) |
| `allowedValuesLastSeparator` | `string \| undefined` | Used to concatenate last allowed value in the message (optional, defaults to `" or "`). Set to `undefined` to disable. |
| `wrapAllowedValuesInQuote` | `boolean` | Indicates whether to wrap allowed values in quotes (optional, defaults to `true`). Note that this only applies to string values. |
| `maxUnrecognizedKeysToDisplay` | `number` | Max number of unrecognized keys to display in the error message (optional, defaults to `5`) |
| `unrecognizedKeysSeparator` | `string` | Used to concatenate unrecognized keys in the message (optional, defaults to `", "`) |
| `unrecognizedKeysLastSeparator` | `string \| undefined` | Used to concatenate the last unrecognized key in message (optional, defaults to `" and "`). Set to `undefined` to disable. |
| `wrapUnrecognizedKeysInQuote` | `boolean` | Indicates whether to wrap unrecognized keys in quotes (optional, defaults to `true`). Note that this only applies to string keys. |
| `dateLocalization` | `boolean \| Intl.LocalesArgument` | Indicates whether to localize date values (optional, defaults to `true`). If set to `true`, it will use the default locale of the environment. You can also pass `Intl.LocalesArgument` to specify a custom locale. |
| `numberLocalization` | `boolean \| Intl.LocalesArgument` | Indicates whether to localize numeric values (optional, defaults to `true`). If set to `true`, it will use the default locale of the environment. You can also pass `Intl.LocalesArgument` to specify a custom locale. |
#### Example
```typescript
import { z as zod } from 'zod';
import { createErrorMap } from 'zod-validation-error';
zod.config({
customError: createErrorMap({
// default values are used when not specified
displayInvalidFormatDetails: true,
}),
});
```
### createMessageBuilder
Creates zod-validation-error's default `MessageBuilder`, which is used to produce user-friendly error messages.
Meant to be passed as an option to [fromError](#fromerror), [fromZodIssue](#fromzodissue), [fromZodError](#fromzoderror) or [toValidationError](#tovalidationerror).
#### Arguments
- `options` - _Object_; formatting options (optional)
##### createMessageBuilder Options
| Name | Type | Description |
| -------------------- | :-------------------: | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `maxIssuesInMessage` | `number` | Max issues to include in user-friendly message (optional, defaults to `99`) |
| `issueSeparator` | `string` | Used to concatenate issues in user-friendly message (optional, defaults to `";"`) |
| `unionSeparator` | `string` | Used to concatenate union-issues in user-friendly message (optional, defaults to `" or "`) |
| `prefix` | `string \| undefined` | Prefix to use in user-friendly message (optional, defaults to `"Validation error"`). Pass `undefined` to disable prefix completely. |
| `prefixSeparator` | `string` | Used to concatenate prefix with rest of the user-friendly message (optional, defaults to `": "`). Not used when `prefix` is `undefined`. |
| `includePath` | `boolean` | Indicates whether to include the erroneous property key in the error message (optional, defaults to `true`) |
| `forceTitleCase` | `boolean` | Indicates whether to convert individual issue messages to title case (optional, defaults to `true`). |
#### Example
```typescript
import { createMessageBuilder } from 'zod-validation-error';
const messageBuilder = createMessageBuilder({
maxIssuesInMessage: 3,
includePath: false,
});
```
### isValidationError
A [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on `instanceof` comparison.
#### Arguments
- `error` - error instance (required)
#### Example
```typescript
import { z as zod } from 'zod';
import { ValidationError, isValidationError } from 'zod-validation-error';
const err = new ValidationError('foobar');
isValidationError(err); // returns true
const invalidErr = new Error('foobar');
isValidationError(err); // returns false
```
### isValidationErrorLike
A [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on _heuristics_ comparison.
_Why do we need heuristics since we can use a simple `instanceof` comparison?_ Because of multi-version inconsistencies. For instance, it's possible that a dependency is using an older `zod-validation-error` version internally. In such case, the `instanceof` comparison will yield invalid results because module deduplication does not apply at npm/yarn level and the prototype is different.
tl;dr if you are uncertain then it is preferable to use `isValidationErrorLike` instead of `isValidationError`.
#### Arguments
- `error` - error instance (required)
#### Example
```typescript
import { ValidationError, isValidationErrorLike } from 'zod-validation-error';
const err = new ValidationError('foobar');
isValidationErrorLike(err); // returns true
const invalidErr = new Error('foobar');
isValidationErrorLike(err); // returns false
```
### isZodErrorLike
A [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on _heuristics_ comparison.
_Why do we need heuristics since we can use a simple `instanceof` comparison?_ Because of multi-version inconsistencies. For instance, it's possible that a dependency is using an older `zod` version internally. In such case, the `instanceof` comparison will yield invalid results because module deduplication does not apply at npm/yarn level and the prototype is different.
#### Arguments
- `error` - error instance (required)
#### Example
```typescript
import { z as zod } from 'zod';
import { ValidationError, isZodErrorLike } from 'zod-validation-error';
const zodValidationErr = new ValidationError('foobar');
isZodErrorLike(zodValidationErr); // returns false
const genericErr = new Error('foobar');
isZodErrorLike(genericErr); // returns false
const zodErr = new zod.ZodError([
{
origin: 'number',
code: 'too_small',
minimum: 0,
inclusive: false,
path: ['id'],
message: 'Number must be greater than 0 at "id"',
input: -1,
},
]);
isZodErrorLike(zodErr); // returns true
```
### fromError
Converts an error to `ValidationError`.
_What is the difference between `fromError` and `fromZodError`?_ The `fromError` function is a less strict version of `fromZodError`. It can accept an unknown error and attempt to convert it to a `ValidationError`.
#### Arguments
- `error` - _unknown_; an error (required)
- `options` - _Object_; formatting options (optional)
- `messageBuilder` - _MessageBuilder_; a function that accepts an array of `zod.ZodIssue` objects and returns a user-friendly error message in the form of a `string` (optional).
#### Notes
Alternatively, you may pass [createMessageBuilder options](#createmessagebuilder-options) directly as `options`. These will be used as arguments to create the `MessageBuilder` instance internally.
### fromZodIssue
Converts a single zod issue to `ValidationError`.
#### Arguments
- `zodIssue` - _zod.ZodIssue_; a ZodIssue instance (required)
- `options` - _Object_; formatting options (optional)
- `messageBuilder` - _MessageBuilder_; a function that accepts an array of `zod.ZodIssue` objects and returns a user-friendly error message in the form of a `string` (optional).
#### Notes
Alternatively, you may pass [createMessageBuilder options](#createmessagebuilder-options) directly as `options`. These will be used as arguments to create the `MessageBuilder` instance internally.
### fromZodError
Converts zod error to `ValidationError`.
_Why is the difference between `ZodError` and `ZodIssue`?_ A `ZodError` is a collection of 1 or more `ZodIssue` instances. It's what you get when you call `zodSchema.parse()`.
#### Arguments
- `zodError` - _zod.ZodError_; a ZodError instance (required)
- `options` - _Object_; formatting options (optional)
- `messageBuilder` - _MessageBuilder_; a function that accepts an array of `zod.ZodIssue` objects and returns a user-friendly error message in the form of a `string` (optional).
#### Notes
Alternatively, you may pass [createMessageBuilder options](#createmessagebuilder-optionscreateMessageBuilder) directly as `options`. These will be used as arguments to create the `MessageBuilder` instance internally.
### toValidationError
A curried version of `fromZodError` meant to be used for FP (Functional Programming). Note it first takes the options object if needed and returns a function that converts the `zodError` to a `ValidationError` object
```js
toValidationError(options) => (zodError) => ValidationError
```
#### Example using fp-ts
```typescript
import * as Either from 'fp-ts/Either';
import { z as zod } from 'zod';
import { toValidationError, ValidationError } from 'zod-validation-error';
// create zod schema
const zodSchema = zod
.object({
id: zod.int().positive(),
email: zod.email(),
})
.brand<'User'>();
export type User = zod.infer<typeof zodSchema>;
export function parse(
value: zod.input<typeof zodSchema>
): Either.Either<ValidationError, User> {
return Either.tryCatch(() => schema.parse(value), toValidationError());
}
```
## FAQ
### What is the difference between zod-validation-error and zod's own [prettifyError](https://zod.dev/error-formatting#zprettifyerror)?
While both libraries aim to provide a human-readable string representation of a zod error, they differ in several ways...
1. **End-user focus**: zod-validation-error provides opinionated, user-friendly error messages designed to be displayed directly to end-users in forms or API responses.
1. **Customization options**: zod-validation-error offers extensive configuration for message formatting, such as controlling path inclusion, allowed values display, localization, and more.
1. **Error handling**: zod-validation-error maintains the original error details while providing a clean, consistent interface through the ValidationError class.
1. **Integration flexibility**: Beyond just formatting, zod-validation-error provides utility functions for error detection and conversion that work well in various architectural patterns, e.g. functional programming.
Disclaimer: as per this [comment](https://github.com/causaly/zod-validation-error/issues/455#issuecomment-2811895152), we have no intention to antagonize zod. In fact, we are happy to decommission this module assuming it's in the best interest of the community. As of now, it seems that there's room for both `zod-validation-error` and `prettifyError`, also based on Colin McDonnell's [response](https://github.com/causaly/zod-validation-error/issues/455#issuecomment-2814466019).
### Do I need to use `zod-validation-error`'s error map?
No, you can use zod's native error map if you prefer. However, we recommend using `zod-validation-error`'s error map for better user-friendly messages.
You may also use your own custom error map if you have specific requirements, e.g. internationalization.
### Where can I see how `zod-validation-error`'s error map formatting works?
The easiest way to understand how `zod-validation-error`'s error map works is to look at the [tests](./lib/v4/errorMap/errorMap.test.ts). They cover various scenarios and demonstrate how the error map formats issues into user-friendly messages.
### How to distinguish between errors
Use the `isValidationErrorLike` type guard.
#### Example
Scenario: Distinguish between `ValidationError` VS generic `Error` in order to respond with 400 VS 500 HTTP status code respectively.
```typescript
import { isValidationErrorLike } from 'zod-validation-error';
try {
func(); // throws Error - or - ValidationError
} catch (err) {
if (isValidationErrorLike(err)) {
return 400; // Bad Data (this is a client error)
}
return 500; // Server Error
}
```
### How to use `ValidationError` outside `zod`
It's possible to implement custom validation logic outside `zod` and throw a `ValidationError`.
#### Example 1: passing custom message
```typescript
import { ValidationError } from 'zod-validation-error';
import { Buffer } from 'node:buffer';
function parseBuffer(buf: unknown): Buffer {
if (!Buffer.isBuffer(buf)) {
throw new ValidationError('Invalid argument; expected buffer');
}
return buf;
}
```
#### Example 2: passing custom message and original error as cause
```typescript
import { ValidationError } from 'zod-validation-error';
try {
// do something that throws an error
} catch (err) {
throw new ValidationError('Something went deeply wrong', { cause: err });
}
```
### How to use `ValidationError` with custom "error map"
Zod supports customizing error messages by providing a custom "error map". You may combine this with `zod-validation-error` to produce user-friendly messages.
#### Example: produce user-friendly error messages using the `customError` property
If all you need is to produce user-friendly error messages you may use the `customError` property.
```typescript
import { z as zod } from 'zod';
import { createErrorMap } from 'zod-validation-error';
zod.config({
customError: createErrorMap({
includePath: true,
}),
});
```
`zod-validation-error` will respect the `customError` property when it is set, no further configuration is needed.
### Does `zod-validation-error` support CommonJS
Yes, `zod-validation-error` supports CommonJS out-of-the-box. All you need to do is import it using `require`.
#### Example
```typescript
const { ValidationError } = require('zod-validation-error');
```
## Contribute
Source code contributions are most welcome. Please open a PR, ensure the linter is satisfied and all tests pass.
#### We are hiring
Causaly is building the world's largest biomedical knowledge platform, using technologies such as TypeScript, React and Node.js. Find out more about our openings at https://jobs.ashbyhq.com/causaly.
## License
MIT

558
node_modules/zod-validation-error/README.v3.md generated vendored Normal file
View File

@@ -0,0 +1,558 @@
# zod-validation-error
Wrap zod validation errors in user-friendly readable messages.
[![Build Status](https://github.com/causaly/zod-validation-error/actions/workflows/ci.yml/badge.svg)](https://github.com/causaly/zod-validation-error/actions/workflows/ci.yml) [![npm version](https://img.shields.io/npm/v/zod-validation-error.svg?color=0c0)](https://www.npmjs.com/package/zod-validation-error)
#### Features
- User-friendly readable messages, configurable via options;
- Maintain original issues under `error.details`;
- Supports both `zod` v3 and v4.
**_Note:_** This is the v3 version of `zod-validation-error`. If you are looking for zod v4 support, please click [here](/README.md).
## Installation
```bash
npm install zod-validation-error
```
#### Requirements
- Node.js v.18+
- TypeScript v.4.5+
## Quick start
```typescript
import { z as zod } from 'zod/v3';
import { fromError } from 'zod-validation-error/v3';
// create zod schema
const zodSchema = zod.object({
id: zod.number().int().positive(),
email: zod.string().email(),
});
// parse some invalid value
try {
zodSchema.parse({
id: 1,
email: 'foobar', // note: invalid email
});
} catch (err) {
const validationError = fromError(err);
// the error is now readable by the user
// you may print it to console
console.log(validationError.toString());
// or return it as an actual error
return validationError;
}
```
## Motivation
Zod errors are difficult to consume for the end-user. This library wraps Zod validation errors in user-friendly readable messages that can be exposed to the outer world, while maintaining the original errors in an array for _dev_ use.
### Example
#### Input (from Zod)
```json
[
{
"code": "too_small",
"inclusive": false,
"message": "Number must be greater than 0",
"minimum": 0,
"path": ["id"],
"type": "number"
},
{
"code": "invalid_string",
"message": "Invalid email",
"path": ["email"],
"validation": "email"
}
]
```
#### Output
```
Validation error: Number must be greater than 0 at "id"; Invalid email at "email"
```
## API
- [ValidationError(message[, options])](#validationerror)
- [createMessageBuilder(props)](#createMessageBuilder)
- [errorMap](#errormap)
- [isValidationError(error)](#isvalidationerror)
- [isValidationErrorLike(error)](#isvalidationerrorlike)
- [isZodErrorLike(error)](#iszoderrorlike)
- [fromError(error[, options])](#fromerror)
- [fromZodIssue(zodIssue[, options])](#fromzodissue)
- [fromZodError(zodError[, options])](#fromzoderror)
- [toValidationError([options]) => (error) => ValidationError](#tovalidationerror)
### ValidationError
Main `ValidationError` class, extending native JavaScript `Error`.
#### Arguments
- `message` - _string_; error message (required)
- `options` - _ErrorOptions_; error options as per [JavaScript definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error#options) (optional)
- `options.cause` - _any_; can be used to hold the original zod error (optional)
#### Example 1: construct new ValidationError with `message`
```typescript
const { ValidationError } = require('zod-validation-error');
const error = new ValidationError('foobar');
console.log(error instanceof Error); // prints true
```
#### Example 2: construct new ValidationError with `message` and `options.cause`
```typescript
import { z as zod } from 'zod/v3';
const { ValidationError } = require('zod-validation-error');
const error = new ValidationError('foobar', {
cause: new zod.ZodError([
{
code: 'invalid_string',
message: 'Invalid email',
path: ['email'],
validation: 'email',
},
]),
});
console.log(error.details); // prints issues from zod error
```
### createMessageBuilder
Creates zod-validation-error's default `MessageBuilder`, which is used to produce user-friendly error messages.
Meant to be passed as an option to [fromError](#fromerror), [fromZodIssue](#fromzodissue), [fromZodError](#fromzoderror) or [toValidationError](#tovalidationerror).
You may read more on the concept of the `MessageBuilder` further [below](#MessageBuilder).
#### Arguments
- `props` - _Object_; formatting options (optional)
- `maxIssuesInMessage` - _number_; max issues to include in user-friendly message (optional, defaults to 99)
- `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to ";")
- `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to ", or")
- `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to "Validation error"). Pass `null` to disable prefix completely.
- `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to ": "). Not used when `prefix` is `null`.
- `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).
#### Example
```typescript
import { createMessageBuilder } from 'zod-validation-error/v3';
const messageBuilder = createMessageBuilder({
includePath: false,
maxIssuesInMessage: 3,
});
```
### errorMap
A custom error map to use with zod's `setErrorMap` method and get user-friendly messages automatically.
#### Example
```typescript
import { z as zod } from 'zod/v3';
import { errorMap } from 'zod-validation-error/v3';
zod.setErrorMap(errorMap);
```
### isValidationError
A [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on `instanceof` comparison.
#### Arguments
- `error` - error instance (required)
#### Example
```typescript
import { z as zod } from 'zod/v3';
import { ValidationError, isValidationError } from 'zod-validation-error/v3';
const err = new ValidationError('foobar');
isValidationError(err); // returns true
const invalidErr = new Error('foobar');
isValidationError(err); // returns false
```
### isValidationErrorLike
A [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on _heuristics_ comparison.
_Why do we need heuristics since we can use a simple `instanceof` comparison?_ Because of multi-version inconsistencies. For instance, it's possible that a dependency is using an older `zod-validation-error` version internally. In such case, the `instanceof` comparison will yield invalid results because module deduplication does not apply at npm/yarn level and the prototype is different.
tl;dr if you are uncertain then it is preferable to use `isValidationErrorLike` instead of `isValidationError`.
#### Arguments
- `error` - error instance (required)
#### Example
```typescript
import {
ValidationError,
isValidationErrorLike,
} from 'zod-validation-error/v3';
const err = new ValidationError('foobar');
isValidationErrorLike(err); // returns true
const invalidErr = new Error('foobar');
isValidationErrorLike(err); // returns false
```
### isZodErrorLike
A [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on _heuristics_ comparison.
_Why do we need heuristics since we can use a simple `instanceof` comparison?_ Because of multi-version inconsistencies. For instance, it's possible that a dependency is using an older `zod` version internally. In such case, the `instanceof` comparison will yield invalid results because module deduplication does not apply at npm/yarn level and the prototype is different.
#### Arguments
- `error` - error instance (required)
#### Example
```typescript
import { z as zod } from 'zod/v3';
import { ValidationError, isZodErrorLike } from 'zod-validation-error/v3';
const zodValidationErr = new ValidationError('foobar');
isZodErrorLike(zodValidationErr); // returns false
const genericErr = new Error('foobar');
isZodErrorLike(genericErr); // returns false
const zodErr = new zod.ZodError([
{
code: zod.ZodIssueCode.custom,
path: [],
message: 'foobar',
fatal: true,
},
]);
isZodErrorLike(zodErr); // returns true
```
### fromError
Converts an error to `ValidationError`.
_What is the difference between `fromError` and `fromZodError`?_ The `fromError` function is a less strict version of `fromZodError`. It can accept an unknown error and attempt to convert it to a `ValidationError`.
#### Arguments
- `error` - _unknown_; an error (required)
- `options` - _Object_; formatting options (optional)
- `messageBuilder` - _MessageBuilder_; a function that accepts an array of `zod.ZodIssue` objects and returns a user-friendly error message in the form of a `string` (optional).
#### Notes
Alternatively, you may pass the following `options` instead of a `messageBuilder`.
- `options` - _Object_; formatting options (optional)
- `maxIssuesInMessage` - _number_; max issues to include in user-friendly message (optional, defaults to 99)
- `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to ";")
- `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to ", or")
- `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to "Validation error"). Pass `null` to disable prefix completely.
- `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to ": "). Not used when `prefix` is `null`.
- `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).
They will be passed as arguments to the [createMessageBuilder](#createMessageBuilder) function. The only reason they exist is to provide backwards-compatibility with older versions of `zod-validation-error`. They should however be considered deprecated and may be removed in the future.
### fromZodIssue
Converts a single zod issue to `ValidationError`.
#### Arguments
- `zodIssue` - _zod.ZodIssue_; a ZodIssue instance (required)
- `options` - _Object_; formatting options (optional)
- `messageBuilder` - _MessageBuilder_; a function that accepts an array of `zod.ZodIssue` objects and returns a user-friendly error message in the form of a `string` (optional).
#### Notes
Alternatively, you may pass the following `options` instead of a `messageBuilder`.
- `options` - _Object_; formatting options (optional)
- `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to ";")
- `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to ", or")
- `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to "Validation error"). Pass `null` to disable prefix completely.
- `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to ": "). Not used when `prefix` is `null`.
- `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).
They will be passed as arguments to the [createMessageBuilder](#createMessageBuilder) function. The only reason they exist is to provide backwards-compatibility with older versions of `zod-validation-error`. They should however be considered deprecated and may be removed in the future.
### fromZodError
Converts zod error to `ValidationError`.
_Why is the difference between `ZodError` and `ZodIssue`?_ A `ZodError` is a collection of 1 or more `ZodIssue` instances. It's what you get when you call `zodSchema.parse()`.
#### Arguments
- `zodError` - _zod.ZodError_; a ZodError instance (required)
- `options` - _Object_; formatting options (optional)
- `messageBuilder` - _MessageBuilder_; a function that accepts an array of `zod.ZodIssue` objects and returns a user-friendly error message in the form of a `string` (optional).
#### Notes
Alternatively, you may pass the following `options` instead of a `messageBuilder`.
- `options` - _Object_; formatting options (optional)
- `maxIssuesInMessage` - _number_; max issues to include in user-friendly message (optional, defaults to 99)
- `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to ";")
- `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to ", or")
- `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to "Validation error"). Pass `null` to disable prefix completely.
- `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to ": "). Not used when `prefix` is `null`.
- `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).
They will be passed as arguments to the [createMessageBuilder](#createMessageBuilder) function. The only reason they exist is to provide backwards-compatibility with older versions of `zod-validation-error`. They should however be considered deprecated and may be removed in the future.
### toValidationError
A curried version of `fromZodError` meant to be used for FP (Functional Programming). Note it first takes the options object if needed and returns a function that converts the `zodError` to a `ValidationError` object
```js
toValidationError(options) => (zodError) => ValidationError
```
#### Example using fp-ts
```typescript
import * as Either from 'fp-ts/Either';
import { z as zod } from 'zod/v3';
import { toValidationError, ValidationError } from 'zod-validation-error/v3';
// create zod schema
const zodSchema = zod
.object({
id: zod.number().int().positive(),
email: zod.string().email(),
})
.brand<'User'>();
export type User = zod.infer<typeof zodSchema>;
export function parse(
value: zod.input<typeof zodSchema>
): Either.Either<ValidationError, User> {
return Either.tryCatch(() => schema.parse(value), toValidationError());
}
```
## MessageBuilder
`zod-validation-error` can be configured with a custom `MessageBuilder` function in order to produce case-specific error messages.
#### Example
For instance, one may want to print `invalid_string` errors to the console in red color.
```typescript
import { z as zod } from 'zod/v3';
import { type MessageBuilder, fromError } from 'zod-validation-error/v3';
import chalk from 'chalk';
// create custom MessageBuilder
const myMessageBuilder: MessageBuilder = (issues) => {
return (
issues
// format error message
.map((issue) => {
if (issue.code === zod.ZodIssueCode.invalid_string) {
return chalk.red(issue.message);
}
return issue.message;
})
// join as string with new-line character
.join('\n')
);
};
// create zod schema
const zodSchema = zod.object({
id: zod.number().int().positive(),
email: zod.string().email(),
});
// parse some invalid value
try {
zodSchema.parse({
id: 1,
email: 'foobar', // note: invalid email value
});
} catch (err) {
const validationError = fromError(err, {
messageBuilder: myMessageBuilder,
});
// the error is now displayed with red letters
console.log(validationError.toString());
}
```
## FAQ
### How to distinguish between errors
Use the `isValidationErrorLike` type guard.
#### Example
Scenario: Distinguish between `ValidationError` VS generic `Error` in order to respond with 400 VS 500 HTTP status code respectively.
```typescript
import * as Either from 'fp-ts/Either';
import { z as zod } from 'zod/v3';
import { isValidationErrorLike } from 'zod-validation-error/v3';
try {
func(); // throws Error - or - ValidationError
} catch (err) {
if (isValidationErrorLike(err)) {
return 400; // Bad Data (this is a client error)
}
return 500; // Server Error
}
```
### How to use `ValidationError` outside `zod`
It's possible to implement custom validation logic outside `zod` and throw a `ValidationError`.
#### Example 1: passing custom message
```typescript
import { ValidationError } from 'zod-validation-error/v3';
import { Buffer } from 'node:buffer';
function parseBuffer(buf: unknown): Buffer {
if (!Buffer.isBuffer(buf)) {
throw new ValidationError('Invalid argument; expected buffer');
}
return buf;
}
```
#### Example 2: passing custom message and original error as cause
```typescript
import { ValidationError } from 'zod-validation-error/v3';
try {
// do something that throws an error
} catch (err) {
throw new ValidationError('Something went deeply wrong', { cause: err });
}
```
### How to use `ValidationError` with custom "error map"
Zod supports customizing error messages by providing a custom "error map". You may combine this with `zod-validation-error` to produce user-friendly messages.
#### Example 1: produce user-friendly error messages using the `errorMap` property
If all you need is to produce user-friendly error messages you may use the `errorMap` property.
```typescript
import { z as zod } from 'zod/v3';
import { errorMap } from 'zod-validation-error/v3';
zod.setErrorMap(errorMap);
```
#### Example 2: extra customization using `fromZodIssue`
If you need to customize some error code, you may use the `fromZodIssue` function.
```typescript
import { z as zod } from 'zod/v3';
import { fromZodIssue } from 'zod-validation-error/v3';
const customErrorMap: zod.ZodErrorMap = (issue, ctx) => {
switch (issue.code) {
case ZodIssueCode.invalid_type: {
return {
message:
'Custom error message of your preference for invalid_type errors',
};
}
default: {
const validationError = fromZodIssue({
...issue,
// fallback to the default error message
// when issue does not have a message
message: issue.message ?? ctx.defaultError,
});
return {
message: validationError.message,
};
}
}
};
zod.setErrorMap(customErrorMap);
```
### How to use `zod-validation-error` with `react-hook-form`?
```typescript
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { errorMap } from 'zod-validation-error/v3';
useForm({
resolver: zodResolver(schema, { errorMap }),
});
```
### Does `zod-validation-error` support CommonJS
Yes, `zod-validation-error` supports CommonJS out-of-the-box. All you need to do is import it using `require`.
#### Example
```typescript
const { ValidationError } = require('zod-validation-error');
```
## Contribute
Source code contributions are most welcome. Please open a PR, ensure the linter is satisfied and all tests pass.
#### We are hiring
Causaly is building the world's largest biomedical knowledge platform, using technologies such as TypeScript, React and Node.js. Find out more about our openings at https://jobs.ashbyhq.com/causaly.
## License
MIT

108
node_modules/zod-validation-error/package.json generated vendored Normal file
View File

@@ -0,0 +1,108 @@
{
"name": "zod-validation-error",
"version": "4.0.2",
"description": "Wrap zod validation errors in user-friendly readable messages",
"keywords": [
"zod",
"error",
"validation"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git://github.com/causaly/zod-validation-error.git"
},
"author": {
"name": "Dimitrios C. Michalakos",
"email": "dimitris@jmike.gr",
"url": "https://github.com/jmike"
},
"contributors": [
{
"name": "Thanos Karagiannis",
"email": "hey@maestros.io",
"url": "https://github.com/thanoskrg"
},
{
"name": "Nikos Tsompanides",
"email": "nikostsompanides@gmail.com",
"url": "https://github.com/NikosTsompanides"
},
{
"name": "Nikos Kalogridis",
"url": "https://github.com/nikoskalogridis"
}
],
"main": "./v4/index.js",
"module": "./v4/index.mjs",
"types": "./v4/index.d.ts",
"exports": {
".": {
"types": "./v4/index.d.ts",
"require": "./v4/index.js",
"import": "./v4/index.mjs"
},
"./v3": {
"types": "./v3/index.d.ts",
"require": "./v3/index.js",
"import": "./v3/index.mjs"
},
"./v4": {
"types": "./v4/index.d.ts",
"require": "./v4/index.js",
"import": "./v4/index.mjs"
}
},
"files": [
"v3",
"v4"
],
"publishConfig": {
"access": "public"
},
"sideEffects": false,
"engines": {
"node": ">=18.0.0"
},
"scripts": {
"typecheck": "tsc --noEmit",
"build": "tsup --config ./tsup.config.ts",
"lint": "eslint lib --ext .ts",
"format": "prettier --config ./.prettierrc --ignore-path .gitignore -w .",
"test": "vitest run",
"changeset": "changeset",
"prerelease": "npm run build && npm run test",
"release": "changeset publish",
"prepare": "husky"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --config ./.prettierrc.json --write"
]
},
"devDependencies": {
"@changesets/changelog-github": "^0.5.0",
"@changesets/cli": "^2.27.7",
"@commitlint/cli": "^18.0.0",
"@commitlint/config-conventional": "^18.0.0",
"@types/node": "^20.5.0",
"@typescript-eslint/eslint-plugin": "^6.4.1",
"@typescript-eslint/parser": "^6.4.1",
"concurrently": "^8.2.0",
"eslint": "^8.4.1",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-prettier": "^4.2.1",
"husky": "^9.1.7",
"lint-staged": "^15.0.1",
"prettier": "^2.8.8",
"tsup": "^8.0.2",
"typescript": "^5.1.6",
"vitest": "^3.1.2",
"zod": "^4.0.2"
},
"peerDependencies": {
"zod": "^3.25.0 || ^4.0.0"
}
}

50
node_modules/zod-validation-error/v3/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,50 @@
import * as zod from 'zod/v3';
interface ErrorOptions {
cause?: unknown;
}
declare class ValidationError extends Error {
name: 'ZodValidationError';
details: Array<zod.ZodIssue>;
constructor(message?: string, options?: ErrorOptions);
toString(): string;
}
declare function isValidationError(err: unknown): err is ValidationError;
declare function isValidationErrorLike(err: unknown): err is ValidationError;
declare function isZodErrorLike(err: unknown): err is zod.ZodError;
declare const errorMap: zod.ZodErrorMap;
type NonEmptyArray<T> = [T, ...T[]];
type ZodIssue = zod.ZodIssue;
type MessageBuilder = (issues: NonEmptyArray<ZodIssue>) => string;
type CreateMessageBuilderProps = {
issueSeparator?: string;
unionSeparator?: string;
prefix?: string | null;
prefixSeparator?: string;
includePath?: boolean;
maxIssuesInMessage?: number;
};
declare function createMessageBuilder(props?: CreateMessageBuilderProps): MessageBuilder;
type ZodError = zod.ZodError;
type FromZodErrorOptions = {
messageBuilder: MessageBuilder;
} | CreateMessageBuilderProps;
declare function fromZodError(zodError: ZodError, options?: FromZodErrorOptions): ValidationError;
declare function fromError(err: unknown, options?: FromZodErrorOptions): ValidationError;
type FromZodIssueOptions = {
messageBuilder: MessageBuilder;
} | Omit<CreateMessageBuilderProps, 'maxIssuesInMessage'>;
declare function fromZodIssue(issue: ZodIssue, options?: FromZodIssueOptions): ValidationError;
declare const toValidationError: (options?: FromZodErrorOptions) => (err: unknown) => ValidationError;
export { type ErrorOptions, type FromZodErrorOptions, type FromZodIssueOptions, type MessageBuilder, type NonEmptyArray, ValidationError, type ZodError, type ZodIssue, createMessageBuilder, errorMap, fromError, fromZodError, fromZodIssue, isValidationError, isValidationErrorLike, isZodErrorLike, toValidationError };

50
node_modules/zod-validation-error/v3/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,50 @@
import * as zod from 'zod/v3';
interface ErrorOptions {
cause?: unknown;
}
declare class ValidationError extends Error {
name: 'ZodValidationError';
details: Array<zod.ZodIssue>;
constructor(message?: string, options?: ErrorOptions);
toString(): string;
}
declare function isValidationError(err: unknown): err is ValidationError;
declare function isValidationErrorLike(err: unknown): err is ValidationError;
declare function isZodErrorLike(err: unknown): err is zod.ZodError;
declare const errorMap: zod.ZodErrorMap;
type NonEmptyArray<T> = [T, ...T[]];
type ZodIssue = zod.ZodIssue;
type MessageBuilder = (issues: NonEmptyArray<ZodIssue>) => string;
type CreateMessageBuilderProps = {
issueSeparator?: string;
unionSeparator?: string;
prefix?: string | null;
prefixSeparator?: string;
includePath?: boolean;
maxIssuesInMessage?: number;
};
declare function createMessageBuilder(props?: CreateMessageBuilderProps): MessageBuilder;
type ZodError = zod.ZodError;
type FromZodErrorOptions = {
messageBuilder: MessageBuilder;
} | CreateMessageBuilderProps;
declare function fromZodError(zodError: ZodError, options?: FromZodErrorOptions): ValidationError;
declare function fromError(err: unknown, options?: FromZodErrorOptions): ValidationError;
type FromZodIssueOptions = {
messageBuilder: MessageBuilder;
} | Omit<CreateMessageBuilderProps, 'maxIssuesInMessage'>;
declare function fromZodIssue(issue: ZodIssue, options?: FromZodIssueOptions): ValidationError;
declare const toValidationError: (options?: FromZodErrorOptions) => (err: unknown) => ValidationError;
export { type ErrorOptions, type FromZodErrorOptions, type FromZodIssueOptions, type MessageBuilder, type NonEmptyArray, ValidationError, type ZodError, type ZodIssue, createMessageBuilder, errorMap, fromError, fromZodError, fromZodIssue, isValidationError, isValidationErrorLike, isZodErrorLike, toValidationError };

309
node_modules/zod-validation-error/v3/index.js generated vendored Normal file
View File

@@ -0,0 +1,309 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// lib/v3/index.ts
var index_exports = {};
__export(index_exports, {
ValidationError: () => ValidationError,
createMessageBuilder: () => createMessageBuilder,
errorMap: () => errorMap,
fromError: () => fromError,
fromZodError: () => fromZodError,
fromZodIssue: () => fromZodIssue,
isValidationError: () => isValidationError,
isValidationErrorLike: () => isValidationErrorLike,
isZodErrorLike: () => isZodErrorLike,
toValidationError: () => toValidationError
});
module.exports = __toCommonJS(index_exports);
// lib/v3/isZodErrorLike.ts
function isZodErrorLike(err) {
return err instanceof Error && err.name === "ZodError" && "issues" in err && Array.isArray(err.issues);
}
// lib/v3/ValidationError.ts
var ValidationError = class extends Error {
name;
details;
constructor(message, options) {
super(message, options);
this.name = "ZodValidationError";
this.details = getIssuesFromErrorOptions(options);
}
toString() {
return this.message;
}
};
function getIssuesFromErrorOptions(options) {
if (options) {
const cause = options.cause;
if (isZodErrorLike(cause)) {
return cause.issues;
}
}
return [];
}
// lib/v3/isValidationError.ts
function isValidationError(err) {
return err instanceof ValidationError;
}
// lib/v3/isValidationErrorLike.ts
function isValidationErrorLike(err) {
return err instanceof Error && err.name === "ZodValidationError";
}
// lib/v3/fromZodIssue.ts
var zod2 = __toESM(require("zod/v3"));
// lib/v3/MessageBuilder.ts
var zod = __toESM(require("zod/v3"));
// lib/utils/NonEmptyArray.ts
function isNonEmptyArray(value) {
return value.length !== 0;
}
// lib/utils/stringify.ts
function stringifySymbol(symbol) {
return symbol.description ?? "";
}
// lib/utils/joinPath.ts
var identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;
function joinPath(path) {
if (path.length === 1) {
let propertyKey = path[0];
if (typeof propertyKey === "symbol") {
propertyKey = stringifySymbol(propertyKey);
}
return propertyKey.toString() || '""';
}
return path.reduce((acc, propertyKey) => {
if (typeof propertyKey === "number") {
return acc + "[" + propertyKey.toString() + "]";
}
if (typeof propertyKey === "symbol") {
propertyKey = stringifySymbol(propertyKey);
}
if (propertyKey.includes('"')) {
return acc + '["' + escapeQuotes(propertyKey) + '"]';
}
if (!identifierRegex.test(propertyKey)) {
return acc + '["' + propertyKey + '"]';
}
const separator = acc.length === 0 ? "" : ".";
return acc + separator + propertyKey;
}, "");
}
function escapeQuotes(str) {
return str.replace(/"/g, '\\"');
}
// lib/v3/config.ts
var ISSUE_SEPARATOR = "; ";
var MAX_ISSUES_IN_MESSAGE = 99;
var PREFIX = "Validation error";
var PREFIX_SEPARATOR = ": ";
var UNION_SEPARATOR = ", or ";
// lib/v3/MessageBuilder.ts
function createMessageBuilder(props = {}) {
const {
issueSeparator = ISSUE_SEPARATOR,
unionSeparator = UNION_SEPARATOR,
prefixSeparator = PREFIX_SEPARATOR,
prefix = PREFIX,
includePath = true,
maxIssuesInMessage = MAX_ISSUES_IN_MESSAGE
} = props;
return (issues) => {
const message = issues.slice(0, maxIssuesInMessage).map(
(issue) => getMessageFromZodIssue({
issue,
issueSeparator,
unionSeparator,
includePath
})
).join(issueSeparator);
return prefixMessage(message, prefix, prefixSeparator);
};
}
function getMessageFromZodIssue(props) {
const { issue, issueSeparator, unionSeparator, includePath } = props;
if (issue.code === zod.ZodIssueCode.invalid_union) {
return issue.unionErrors.reduce((acc, zodError) => {
const newIssues = zodError.issues.map(
(issue2) => getMessageFromZodIssue({
issue: issue2,
issueSeparator,
unionSeparator,
includePath
})
).join(issueSeparator);
if (!acc.includes(newIssues)) {
acc.push(newIssues);
}
return acc;
}, []).join(unionSeparator);
}
if (issue.code === zod.ZodIssueCode.invalid_arguments) {
return [
issue.message,
...issue.argumentsError.issues.map(
(issue2) => getMessageFromZodIssue({
issue: issue2,
issueSeparator,
unionSeparator,
includePath
})
)
].join(issueSeparator);
}
if (issue.code === zod.ZodIssueCode.invalid_return_type) {
return [
issue.message,
...issue.returnTypeError.issues.map(
(issue2) => getMessageFromZodIssue({
issue: issue2,
issueSeparator,
unionSeparator,
includePath
})
)
].join(issueSeparator);
}
if (includePath && isNonEmptyArray(issue.path)) {
if (issue.path.length === 1) {
const identifier = issue.path[0];
if (typeof identifier === "number") {
return `${issue.message} at index ${identifier}`;
}
}
return `${issue.message} at "${joinPath(issue.path)}"`;
}
return issue.message;
}
function prefixMessage(message, prefix, prefixSeparator) {
if (prefix !== null) {
if (message.length > 0) {
return [prefix, message].join(prefixSeparator);
}
return prefix;
}
if (message.length > 0) {
return message;
}
return PREFIX;
}
// lib/v3/fromZodIssue.ts
function fromZodIssue(issue, options = {}) {
const messageBuilder = createMessageBuilderFromOptions(options);
const message = messageBuilder([issue]);
return new ValidationError(message, { cause: new zod2.ZodError([issue]) });
}
function createMessageBuilderFromOptions(options) {
if ("messageBuilder" in options) {
return options.messageBuilder;
}
return createMessageBuilder(options);
}
// lib/v3/errorMap.ts
var errorMap = (issue, ctx) => {
const error = fromZodIssue({
...issue,
// fallback to the default error message
// when issue does not have a message
message: issue.message ?? ctx.defaultError
});
return {
message: error.message
};
};
// lib/v3/fromZodError.ts
function fromZodError(zodError, options = {}) {
if (!isZodErrorLike(zodError)) {
throw new TypeError(
`Invalid zodError param; expected instance of ZodError. Did you mean to use the "${fromError.name}" method instead?`
);
}
return fromZodErrorWithoutRuntimeCheck(zodError, options);
}
function fromZodErrorWithoutRuntimeCheck(zodError, options = {}) {
const zodIssues = zodError.errors;
let message;
if (isNonEmptyArray(zodIssues)) {
const messageBuilder = createMessageBuilderFromOptions2(options);
message = messageBuilder(zodIssues);
} else {
message = zodError.message;
}
return new ValidationError(message, { cause: zodError });
}
function createMessageBuilderFromOptions2(options) {
if ("messageBuilder" in options) {
return options.messageBuilder;
}
return createMessageBuilder(options);
}
// lib/v3/toValidationError.ts
var toValidationError = (options = {}) => (err) => {
if (isZodErrorLike(err)) {
return fromZodErrorWithoutRuntimeCheck(err, options);
}
if (err instanceof Error) {
return new ValidationError(err.message, { cause: err });
}
return new ValidationError("Unknown error");
};
// lib/v3/fromError.ts
function fromError(err, options = {}) {
return toValidationError(options)(err);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ValidationError,
createMessageBuilder,
errorMap,
fromError,
fromZodError,
fromZodIssue,
isValidationError,
isValidationErrorLike,
isZodErrorLike,
toValidationError
});
//# sourceMappingURL=index.js.map

1
node_modules/zod-validation-error/v3/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

263
node_modules/zod-validation-error/v3/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,263 @@
// lib/v3/isZodErrorLike.ts
function isZodErrorLike(err) {
return err instanceof Error && err.name === "ZodError" && "issues" in err && Array.isArray(err.issues);
}
// lib/v3/ValidationError.ts
var ValidationError = class extends Error {
name;
details;
constructor(message, options) {
super(message, options);
this.name = "ZodValidationError";
this.details = getIssuesFromErrorOptions(options);
}
toString() {
return this.message;
}
};
function getIssuesFromErrorOptions(options) {
if (options) {
const cause = options.cause;
if (isZodErrorLike(cause)) {
return cause.issues;
}
}
return [];
}
// lib/v3/isValidationError.ts
function isValidationError(err) {
return err instanceof ValidationError;
}
// lib/v3/isValidationErrorLike.ts
function isValidationErrorLike(err) {
return err instanceof Error && err.name === "ZodValidationError";
}
// lib/v3/fromZodIssue.ts
import * as zod2 from "zod/v3";
// lib/v3/MessageBuilder.ts
import * as zod from "zod/v3";
// lib/utils/NonEmptyArray.ts
function isNonEmptyArray(value) {
return value.length !== 0;
}
// lib/utils/stringify.ts
function stringifySymbol(symbol) {
return symbol.description ?? "";
}
// lib/utils/joinPath.ts
var identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;
function joinPath(path) {
if (path.length === 1) {
let propertyKey = path[0];
if (typeof propertyKey === "symbol") {
propertyKey = stringifySymbol(propertyKey);
}
return propertyKey.toString() || '""';
}
return path.reduce((acc, propertyKey) => {
if (typeof propertyKey === "number") {
return acc + "[" + propertyKey.toString() + "]";
}
if (typeof propertyKey === "symbol") {
propertyKey = stringifySymbol(propertyKey);
}
if (propertyKey.includes('"')) {
return acc + '["' + escapeQuotes(propertyKey) + '"]';
}
if (!identifierRegex.test(propertyKey)) {
return acc + '["' + propertyKey + '"]';
}
const separator = acc.length === 0 ? "" : ".";
return acc + separator + propertyKey;
}, "");
}
function escapeQuotes(str) {
return str.replace(/"/g, '\\"');
}
// lib/v3/config.ts
var ISSUE_SEPARATOR = "; ";
var MAX_ISSUES_IN_MESSAGE = 99;
var PREFIX = "Validation error";
var PREFIX_SEPARATOR = ": ";
var UNION_SEPARATOR = ", or ";
// lib/v3/MessageBuilder.ts
function createMessageBuilder(props = {}) {
const {
issueSeparator = ISSUE_SEPARATOR,
unionSeparator = UNION_SEPARATOR,
prefixSeparator = PREFIX_SEPARATOR,
prefix = PREFIX,
includePath = true,
maxIssuesInMessage = MAX_ISSUES_IN_MESSAGE
} = props;
return (issues) => {
const message = issues.slice(0, maxIssuesInMessage).map(
(issue) => getMessageFromZodIssue({
issue,
issueSeparator,
unionSeparator,
includePath
})
).join(issueSeparator);
return prefixMessage(message, prefix, prefixSeparator);
};
}
function getMessageFromZodIssue(props) {
const { issue, issueSeparator, unionSeparator, includePath } = props;
if (issue.code === zod.ZodIssueCode.invalid_union) {
return issue.unionErrors.reduce((acc, zodError) => {
const newIssues = zodError.issues.map(
(issue2) => getMessageFromZodIssue({
issue: issue2,
issueSeparator,
unionSeparator,
includePath
})
).join(issueSeparator);
if (!acc.includes(newIssues)) {
acc.push(newIssues);
}
return acc;
}, []).join(unionSeparator);
}
if (issue.code === zod.ZodIssueCode.invalid_arguments) {
return [
issue.message,
...issue.argumentsError.issues.map(
(issue2) => getMessageFromZodIssue({
issue: issue2,
issueSeparator,
unionSeparator,
includePath
})
)
].join(issueSeparator);
}
if (issue.code === zod.ZodIssueCode.invalid_return_type) {
return [
issue.message,
...issue.returnTypeError.issues.map(
(issue2) => getMessageFromZodIssue({
issue: issue2,
issueSeparator,
unionSeparator,
includePath
})
)
].join(issueSeparator);
}
if (includePath && isNonEmptyArray(issue.path)) {
if (issue.path.length === 1) {
const identifier = issue.path[0];
if (typeof identifier === "number") {
return `${issue.message} at index ${identifier}`;
}
}
return `${issue.message} at "${joinPath(issue.path)}"`;
}
return issue.message;
}
function prefixMessage(message, prefix, prefixSeparator) {
if (prefix !== null) {
if (message.length > 0) {
return [prefix, message].join(prefixSeparator);
}
return prefix;
}
if (message.length > 0) {
return message;
}
return PREFIX;
}
// lib/v3/fromZodIssue.ts
function fromZodIssue(issue, options = {}) {
const messageBuilder = createMessageBuilderFromOptions(options);
const message = messageBuilder([issue]);
return new ValidationError(message, { cause: new zod2.ZodError([issue]) });
}
function createMessageBuilderFromOptions(options) {
if ("messageBuilder" in options) {
return options.messageBuilder;
}
return createMessageBuilder(options);
}
// lib/v3/errorMap.ts
var errorMap = (issue, ctx) => {
const error = fromZodIssue({
...issue,
// fallback to the default error message
// when issue does not have a message
message: issue.message ?? ctx.defaultError
});
return {
message: error.message
};
};
// lib/v3/fromZodError.ts
function fromZodError(zodError, options = {}) {
if (!isZodErrorLike(zodError)) {
throw new TypeError(
`Invalid zodError param; expected instance of ZodError. Did you mean to use the "${fromError.name}" method instead?`
);
}
return fromZodErrorWithoutRuntimeCheck(zodError, options);
}
function fromZodErrorWithoutRuntimeCheck(zodError, options = {}) {
const zodIssues = zodError.errors;
let message;
if (isNonEmptyArray(zodIssues)) {
const messageBuilder = createMessageBuilderFromOptions2(options);
message = messageBuilder(zodIssues);
} else {
message = zodError.message;
}
return new ValidationError(message, { cause: zodError });
}
function createMessageBuilderFromOptions2(options) {
if ("messageBuilder" in options) {
return options.messageBuilder;
}
return createMessageBuilder(options);
}
// lib/v3/toValidationError.ts
var toValidationError = (options = {}) => (err) => {
if (isZodErrorLike(err)) {
return fromZodErrorWithoutRuntimeCheck(err, options);
}
if (err instanceof Error) {
return new ValidationError(err.message, { cause: err });
}
return new ValidationError("Unknown error");
};
// lib/v3/fromError.ts
function fromError(err, options = {}) {
return toValidationError(options)(err);
}
export {
ValidationError,
createMessageBuilder,
errorMap,
fromError,
fromZodError,
fromZodIssue,
isValidationError,
isValidationErrorLike,
isZodErrorLike,
toValidationError
};
//# sourceMappingURL=index.mjs.map

1
node_modules/zod-validation-error/v3/index.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

66
node_modules/zod-validation-error/v4/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,66 @@
import * as zod from 'zod/v4/core';
declare const ZOD_VALIDATION_ERROR_NAME = "ZodValidationError";
interface ErrorOptions {
cause?: unknown;
}
declare class ValidationError extends Error {
name: typeof ZOD_VALIDATION_ERROR_NAME;
details: Array<zod.$ZodIssue>;
constructor(message?: string, options?: ErrorOptions);
toString(): string;
}
declare function isValidationError(err: unknown): err is ValidationError;
declare function isValidationErrorLike(err: unknown): err is ValidationError;
declare function isZodErrorLike(err: unknown): err is zod.$ZodError;
type ErrorMapOptions = {
dateLocalization: boolean | Intl.LocalesArgument;
numberLocalization: boolean | Intl.LocalesArgument;
displayInvalidFormatDetails: boolean;
allowedValuesSeparator: string;
allowedValuesLastSeparator: string | undefined;
wrapAllowedValuesInQuote: boolean;
maxAllowedValuesToDisplay: number;
unrecognizedKeysSeparator: string;
unrecognizedKeysLastSeparator: string | undefined;
wrapUnrecognizedKeysInQuote: boolean;
maxUnrecognizedKeysToDisplay: number;
};
declare function createErrorMap(partialOptions?: Partial<ErrorMapOptions>): zod.$ZodErrorMap<zod.$ZodIssue>;
type NonEmptyArray<T> = [T, ...T[]];
type ZodIssue = zod.$ZodIssue;
type MessageBuilder = (issues: NonEmptyArray<ZodIssue>) => string;
type MessageBuilderOptions = {
prefix: string | null | undefined;
prefixSeparator: string;
maxIssuesInMessage: number;
issueSeparator: string;
unionSeparator: string;
includePath: boolean;
forceTitleCase: boolean;
};
declare function createMessageBuilder(partialOptions?: Partial<MessageBuilderOptions>): MessageBuilder;
type ZodError = zod.$ZodError;
type FromZodErrorOptions = {
messageBuilder: MessageBuilder;
} | Partial<MessageBuilderOptions>;
declare function fromZodError(zodError: ZodError, options?: FromZodErrorOptions): ValidationError;
declare function fromError(err: unknown, options?: FromZodErrorOptions): ValidationError;
type FromZodIssueOptions = {
messageBuilder: MessageBuilder;
} | Partial<Omit<MessageBuilderOptions, 'maxIssuesInMessage'>>;
declare function fromZodIssue(issue: ZodIssue, options?: FromZodIssueOptions): ValidationError;
declare const toValidationError: (options?: FromZodErrorOptions) => (err: unknown) => ValidationError;
export { type ErrorMapOptions, type ErrorOptions, type FromZodErrorOptions, type FromZodIssueOptions, type MessageBuilder, type MessageBuilderOptions, type NonEmptyArray, ValidationError, type ZodError, type ZodIssue, createErrorMap, createMessageBuilder, fromError, fromZodError, fromZodIssue, isValidationError, isValidationErrorLike, isZodErrorLike, toValidationError };

66
node_modules/zod-validation-error/v4/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,66 @@
import * as zod from 'zod/v4/core';
declare const ZOD_VALIDATION_ERROR_NAME = "ZodValidationError";
interface ErrorOptions {
cause?: unknown;
}
declare class ValidationError extends Error {
name: typeof ZOD_VALIDATION_ERROR_NAME;
details: Array<zod.$ZodIssue>;
constructor(message?: string, options?: ErrorOptions);
toString(): string;
}
declare function isValidationError(err: unknown): err is ValidationError;
declare function isValidationErrorLike(err: unknown): err is ValidationError;
declare function isZodErrorLike(err: unknown): err is zod.$ZodError;
type ErrorMapOptions = {
dateLocalization: boolean | Intl.LocalesArgument;
numberLocalization: boolean | Intl.LocalesArgument;
displayInvalidFormatDetails: boolean;
allowedValuesSeparator: string;
allowedValuesLastSeparator: string | undefined;
wrapAllowedValuesInQuote: boolean;
maxAllowedValuesToDisplay: number;
unrecognizedKeysSeparator: string;
unrecognizedKeysLastSeparator: string | undefined;
wrapUnrecognizedKeysInQuote: boolean;
maxUnrecognizedKeysToDisplay: number;
};
declare function createErrorMap(partialOptions?: Partial<ErrorMapOptions>): zod.$ZodErrorMap<zod.$ZodIssue>;
type NonEmptyArray<T> = [T, ...T[]];
type ZodIssue = zod.$ZodIssue;
type MessageBuilder = (issues: NonEmptyArray<ZodIssue>) => string;
type MessageBuilderOptions = {
prefix: string | null | undefined;
prefixSeparator: string;
maxIssuesInMessage: number;
issueSeparator: string;
unionSeparator: string;
includePath: boolean;
forceTitleCase: boolean;
};
declare function createMessageBuilder(partialOptions?: Partial<MessageBuilderOptions>): MessageBuilder;
type ZodError = zod.$ZodError;
type FromZodErrorOptions = {
messageBuilder: MessageBuilder;
} | Partial<MessageBuilderOptions>;
declare function fromZodError(zodError: ZodError, options?: FromZodErrorOptions): ValidationError;
declare function fromError(err: unknown, options?: FromZodErrorOptions): ValidationError;
type FromZodIssueOptions = {
messageBuilder: MessageBuilder;
} | Partial<Omit<MessageBuilderOptions, 'maxIssuesInMessage'>>;
declare function fromZodIssue(issue: ZodIssue, options?: FromZodIssueOptions): ValidationError;
declare const toValidationError: (options?: FromZodErrorOptions) => (err: unknown) => ValidationError;
export { type ErrorMapOptions, type ErrorOptions, type FromZodErrorOptions, type FromZodIssueOptions, type MessageBuilder, type MessageBuilderOptions, type NonEmptyArray, ValidationError, type ZodError, type ZodIssue, createErrorMap, createMessageBuilder, fromError, fromZodError, fromZodIssue, isValidationError, isValidationErrorLike, isZodErrorLike, toValidationError };

725
node_modules/zod-validation-error/v4/index.js generated vendored Normal file
View File

@@ -0,0 +1,725 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// lib/v4/index.ts
var index_exports = {};
__export(index_exports, {
ValidationError: () => ValidationError,
createErrorMap: () => createErrorMap,
createMessageBuilder: () => createMessageBuilder,
fromError: () => fromError,
fromZodError: () => fromZodError,
fromZodIssue: () => fromZodIssue,
isValidationError: () => isValidationError,
isValidationErrorLike: () => isValidationErrorLike,
isZodErrorLike: () => isZodErrorLike,
toValidationError: () => toValidationError
});
module.exports = __toCommonJS(index_exports);
// lib/v4/isZodErrorLike.ts
function isZodErrorLike(err) {
return err instanceof Object && "name" in err && (err.name === "ZodError" || err.name === "$ZodError") && "issues" in err && Array.isArray(err.issues);
}
// lib/v4/ValidationError.ts
var ZOD_VALIDATION_ERROR_NAME = "ZodValidationError";
var ValidationError = class extends Error {
name;
details;
constructor(message, options) {
super(message, options);
this.name = ZOD_VALIDATION_ERROR_NAME;
this.details = getIssuesFromErrorOptions(options);
}
toString() {
return this.message;
}
};
function getIssuesFromErrorOptions(options) {
if (options) {
const cause = options.cause;
if (isZodErrorLike(cause)) {
return cause.issues;
}
}
return [];
}
// lib/v4/isValidationError.ts
function isValidationError(err) {
return err instanceof ValidationError;
}
// lib/v4/isValidationErrorLike.ts
function isValidationErrorLike(err) {
return err instanceof Error && err.name === ZOD_VALIDATION_ERROR_NAME;
}
// lib/v4/errorMap/custom.ts
function parseCustomIssue(issue) {
return {
type: issue.code,
path: issue.path,
message: issue.message ?? "Invalid input"
};
}
// lib/v4/errorMap/invalidElement.ts
function parseInvalidElementIssue(issue) {
return {
type: issue.code,
path: issue.path,
message: `unexpected element in ${issue.origin}`
};
}
// lib/v4/errorMap/invalidKey.ts
function parseInvalidKeyIssue(issue) {
return {
type: issue.code,
path: issue.path,
message: `unexpected key in ${issue.origin}`
};
}
// lib/v4/errorMap/invalidStringFormat.ts
function parseInvalidStringFormatIssue(issue, options = {
displayInvalidFormatDetails: false
}) {
switch (issue.format) {
case "lowercase":
case "uppercase":
return {
type: issue.code,
path: issue.path,
message: `value must be in ${issue.format} format`
};
default: {
if (isZodIssueStringStartsWith(issue)) {
return parseStringStartsWith(issue);
}
if (isZodIssueStringEndsWith(issue)) {
return parseStringEndsWith(issue);
}
if (isZodIssueStringIncludes(issue)) {
return parseStringIncludes(issue);
}
if (isZodIssueStringInvalidRegex(issue)) {
return parseStringInvalidRegex(issue, options);
}
if (isZodIssueStringInvalidJWT(issue)) {
return parseStringInvalidJWT(issue, options);
}
return {
type: issue.code,
path: issue.path,
message: `invalid ${issue.format}`
};
}
}
}
function isZodIssueStringStartsWith(issue) {
return issue.format === "starts_with";
}
function parseStringStartsWith(issue) {
return {
type: issue.code,
path: issue.path,
message: `value must start with "${issue.prefix}"`
};
}
function isZodIssueStringEndsWith(issue) {
return issue.format === "ends_with";
}
function parseStringEndsWith(issue) {
return {
type: issue.code,
path: issue.path,
message: `value must end with "${issue.suffix}"`
};
}
function isZodIssueStringIncludes(issue) {
return issue.format === "includes";
}
function parseStringIncludes(issue) {
return {
type: issue.code,
path: issue.path,
message: `value must include "${issue.includes}"`
};
}
function isZodIssueStringInvalidRegex(issue) {
return issue.format === "regex";
}
function parseStringInvalidRegex(issue, options = {
displayInvalidFormatDetails: false
}) {
let message = "value must match pattern";
if (options.displayInvalidFormatDetails) {
message += ` "${issue.pattern}"`;
}
return {
type: issue.code,
path: issue.path,
message
};
}
function isZodIssueStringInvalidJWT(issue) {
return issue.format === "jwt";
}
function parseStringInvalidJWT(issue, options = {
displayInvalidFormatDetails: false
}) {
return {
type: issue.code,
path: issue.path,
message: options.displayInvalidFormatDetails && issue.algorithm ? `invalid jwt/${issue.algorithm}` : `invalid jwt`
};
}
// lib/v4/errorMap/invalidType.ts
function parseInvalidTypeIssue(issue) {
let message = `expected ${issue.expected}`;
if ("input" in issue) {
message += `, received ${getTypeName(issue.input)}`;
}
return {
type: issue.code,
path: issue.path,
message
};
}
function getTypeName(value) {
if (typeof value === "object") {
if (value === null) {
return "null";
}
if (value === void 0) {
return "undefined";
}
if (Array.isArray(value)) {
return "array";
}
if (value instanceof Date) {
return "date";
}
if (value instanceof RegExp) {
return "regexp";
}
if (value instanceof Map) {
return "map";
}
if (value instanceof Set) {
return "set";
}
if (value instanceof Error) {
return "error";
}
if (value instanceof Function) {
return "function";
}
return "object";
}
return typeof value;
}
// lib/v4/errorMap/invalidUnion.ts
function parseInvalidUnionIssue(issue) {
return {
type: issue.code,
path: issue.path,
message: issue.message ?? "Invalid input"
};
}
// lib/utils/stringify.ts
function stringifySymbol(symbol) {
return symbol.description ?? "";
}
function stringify(value, options = {}) {
switch (typeof value) {
case "symbol":
return stringifySymbol(value);
case "bigint":
case "number": {
switch (options.localization) {
case true:
return value.toLocaleString();
case false:
return value.toString();
default:
return value.toLocaleString(options.localization);
}
}
case "string": {
if (options.wrapStringValueInQuote) {
return `"${value}"`;
}
return value;
}
default: {
if (value instanceof Date) {
switch (options.localization) {
case true:
return value.toLocaleString();
case false:
return value.toISOString();
default:
return value.toLocaleString(options.localization);
}
}
return String(value);
}
}
}
// lib/utils/joinValues.ts
function joinValues(values, options) {
const valuesToDisplay = (options.maxValuesToDisplay ? values.slice(0, options.maxValuesToDisplay) : values).map((value) => {
return stringify(value, {
wrapStringValueInQuote: options.wrapStringValuesInQuote
});
});
if (valuesToDisplay.length < values.length) {
valuesToDisplay.push(
`${values.length - valuesToDisplay.length} more value(s)`
);
}
return valuesToDisplay.reduce((acc, value, index) => {
if (index > 0) {
if (index === valuesToDisplay.length - 1 && options.lastSeparator) {
acc += options.lastSeparator;
} else {
acc += options.separator;
}
}
acc += value;
return acc;
}, "");
}
// lib/v4/errorMap/invalidValue.ts
function parseInvalidValueIssue(issue, options) {
let message;
if (issue.values.length === 0) {
message = "invalid value";
} else if (issue.values.length === 1) {
const valueStr = stringify(issue.values[0], {
wrapStringValueInQuote: true
});
message = `expected value to be ${valueStr}`;
} else {
const valuesStr = joinValues(issue.values, {
separator: options.allowedValuesSeparator,
lastSeparator: options.allowedValuesLastSeparator,
wrapStringValuesInQuote: options.wrapAllowedValuesInQuote,
maxValuesToDisplay: options.maxAllowedValuesToDisplay
});
message = `expected value to be one of ${valuesStr}`;
}
return {
type: issue.code,
path: issue.path,
message
};
}
// lib/v4/errorMap/notMultipleOf.ts
function parseNotMultipleOfIssue(issue) {
return {
type: issue.code,
path: issue.path,
message: `expected multiple of ${issue.divisor}`
};
}
// lib/v4/errorMap/tooBig.ts
function parseTooBigIssue(issue, options) {
const maxValueStr = issue.origin === "date" ? stringify(new Date(issue.maximum), {
localization: options.dateLocalization
}) : stringify(issue.maximum, {
localization: options.numberLocalization
});
switch (issue.origin) {
case "number":
case "int":
case "bigint": {
return {
type: issue.code,
path: issue.path,
message: `number must be less than${issue.inclusive ? " or equal to" : ""} ${maxValueStr}`
};
}
case "string": {
return {
type: issue.code,
path: issue.path,
message: `string must contain at most ${maxValueStr} character(s)`
};
}
case "date": {
return {
type: issue.code,
path: issue.path,
message: `date must be ${issue.inclusive ? "prior or equal to" : "prior to"} "${maxValueStr}"`
};
}
case "array": {
return {
type: issue.code,
path: issue.path,
message: `array must contain at most ${maxValueStr} item(s)`
};
}
case "set": {
return {
type: issue.code,
path: issue.path,
message: `set must contain at most ${maxValueStr} item(s)`
};
}
case "file": {
return {
type: issue.code,
path: issue.path,
message: `file must not exceed ${maxValueStr} byte(s) in size`
};
}
default:
return {
type: issue.code,
path: issue.path,
message: `value must be less than${issue.inclusive ? " or equal to" : ""} ${maxValueStr}`
};
}
}
// lib/v4/errorMap/tooSmall.ts
function parseTooSmallIssue(issue, options) {
const minValueStr = issue.origin === "date" ? stringify(new Date(issue.minimum), {
localization: options.dateLocalization
}) : stringify(issue.minimum, {
localization: options.numberLocalization
});
switch (issue.origin) {
case "number":
case "int":
case "bigint": {
return {
type: issue.code,
path: issue.path,
message: `number must be greater than${issue.inclusive ? " or equal to" : ""} ${minValueStr}`
};
}
case "date": {
return {
type: issue.code,
path: issue.path,
message: `date must be ${issue.inclusive ? "later or equal to" : "later to"} "${minValueStr}"`
};
}
case "string": {
return {
type: issue.code,
path: issue.path,
message: `string must contain at least ${minValueStr} character(s)`
};
}
case "array": {
return {
type: issue.code,
path: issue.path,
message: `array must contain at least ${minValueStr} item(s)`
};
}
case "set": {
return {
type: issue.code,
path: issue.path,
message: `set must contain at least ${minValueStr} item(s)`
};
}
case "file": {
return {
type: issue.code,
path: issue.path,
message: `file must be at least ${minValueStr} byte(s) in size`
};
}
default:
return {
type: issue.code,
path: issue.path,
message: `value must be greater than${issue.inclusive ? " or equal to" : ""} ${minValueStr}`
};
}
}
// lib/v4/errorMap/unrecognizedKeys.ts
function parseUnrecognizedKeysIssue(issue, options) {
const keysStr = joinValues(issue.keys, {
separator: options.unrecognizedKeysSeparator,
lastSeparator: options.unrecognizedKeysLastSeparator,
wrapStringValuesInQuote: options.wrapUnrecognizedKeysInQuote,
maxValuesToDisplay: options.maxUnrecognizedKeysToDisplay
});
return {
type: issue.code,
path: issue.path,
message: `unrecognized key(s) ${keysStr} in object`
};
}
// lib/v4/errorMap/errorMap.ts
var issueParsers = {
invalid_type: parseInvalidTypeIssue,
too_big: parseTooBigIssue,
too_small: parseTooSmallIssue,
invalid_format: parseInvalidStringFormatIssue,
invalid_value: parseInvalidValueIssue,
invalid_element: parseInvalidElementIssue,
not_multiple_of: parseNotMultipleOfIssue,
unrecognized_keys: parseUnrecognizedKeysIssue,
invalid_key: parseInvalidKeyIssue,
custom: parseCustomIssue,
invalid_union: parseInvalidUnionIssue
};
var defaultErrorMapOptions = {
displayInvalidFormatDetails: false,
allowedValuesSeparator: ", ",
allowedValuesLastSeparator: " or ",
wrapAllowedValuesInQuote: true,
maxAllowedValuesToDisplay: 10,
unrecognizedKeysSeparator: ", ",
unrecognizedKeysLastSeparator: " and ",
wrapUnrecognizedKeysInQuote: true,
maxUnrecognizedKeysToDisplay: 5,
dateLocalization: true,
numberLocalization: true
};
function createErrorMap(partialOptions = {}) {
const options = {
...defaultErrorMapOptions,
...partialOptions
};
const errorMap = (issue) => {
if (issue.code === void 0) {
return "Not supported issue type";
}
const parseFunc = issueParsers[issue.code];
const ast = parseFunc(issue, options);
return ast.message;
};
return errorMap;
}
// lib/utils/NonEmptyArray.ts
function isNonEmptyArray(value) {
return value.length !== 0;
}
// lib/utils/joinPath.ts
var identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;
function joinPath(path) {
if (path.length === 1) {
let propertyKey = path[0];
if (typeof propertyKey === "symbol") {
propertyKey = stringifySymbol(propertyKey);
}
return propertyKey.toString() || '""';
}
return path.reduce((acc, propertyKey) => {
if (typeof propertyKey === "number") {
return acc + "[" + propertyKey.toString() + "]";
}
if (typeof propertyKey === "symbol") {
propertyKey = stringifySymbol(propertyKey);
}
if (propertyKey.includes('"')) {
return acc + '["' + escapeQuotes(propertyKey) + '"]';
}
if (!identifierRegex.test(propertyKey)) {
return acc + '["' + propertyKey + '"]';
}
const separator = acc.length === 0 ? "" : ".";
return acc + separator + propertyKey;
}, "");
}
function escapeQuotes(str) {
return str.replace(/"/g, '\\"');
}
// lib/utils/titleCase.ts
function titleCase(value) {
if (value.length === 0) {
return value;
}
return value.charAt(0).toUpperCase() + value.slice(1);
}
// lib/v4/MessageBuilder.ts
var defaultMessageBuilderOptions = {
prefix: "Validation error",
prefixSeparator: ": ",
maxIssuesInMessage: 99,
// I've got 99 problems but the b$tch ain't one
unionSeparator: " or ",
issueSeparator: "; ",
includePath: true,
forceTitleCase: true
};
function createMessageBuilder(partialOptions = {}) {
const options = {
...defaultMessageBuilderOptions,
...partialOptions
};
return function messageBuilder(issues) {
const message = issues.slice(0, options.maxIssuesInMessage).map((issue) => mapIssue(issue, options)).join(options.issueSeparator);
return conditionallyPrefixMessage(message, options);
};
}
function mapIssue(issue, options) {
if (issue.code === "invalid_union" && isNonEmptyArray(issue.errors)) {
const individualMessages = issue.errors.map(
(issues) => issues.map(
(subIssue) => mapIssue(
{
...subIssue,
path: issue.path.concat(subIssue.path)
},
options
)
).join(options.issueSeparator)
);
return Array.from(new Set(individualMessages)).join(options.unionSeparator);
}
const buf = [];
if (options.forceTitleCase) {
buf.push(titleCase(issue.message));
} else {
buf.push(issue.message);
}
pathCondition: if (options.includePath && issue.path !== void 0 && isNonEmptyArray(issue.path)) {
if (issue.path.length === 1) {
const identifier = issue.path[0];
if (typeof identifier === "number") {
buf.push(` at index ${identifier}`);
break pathCondition;
}
}
buf.push(` at "${joinPath(issue.path)}"`);
}
return buf.join("");
}
function conditionallyPrefixMessage(message, options) {
if (options.prefix != null) {
if (message.length > 0) {
return [options.prefix, message].join(options.prefixSeparator);
}
return options.prefix;
}
if (message.length > 0) {
return message;
}
return defaultMessageBuilderOptions.prefix;
}
// lib/v4/fromZodError.ts
function fromZodError(zodError, options = {}) {
if (!isZodErrorLike(zodError)) {
throw new TypeError(
`Invalid zodError param; expected instance of ZodError. Did you mean to use the "${fromError.name}" method instead?`
);
}
return fromZodErrorWithoutRuntimeCheck(zodError, options);
}
function fromZodErrorWithoutRuntimeCheck(zodError, options = {}) {
const zodIssues = zodError.issues;
let message;
if (isNonEmptyArray(zodIssues)) {
const messageBuilder = createMessageBuilderFromOptions(options);
message = messageBuilder(zodIssues);
} else {
message = zodError.message;
}
return new ValidationError(message, { cause: zodError });
}
function createMessageBuilderFromOptions(options) {
if ("messageBuilder" in options) {
return options.messageBuilder;
}
return createMessageBuilder(options);
}
// lib/v4/toValidationError.ts
var toValidationError = (options = {}) => (err) => {
if (isZodErrorLike(err)) {
return fromZodErrorWithoutRuntimeCheck(err, options);
}
if (err instanceof Error) {
return new ValidationError(err.message, { cause: err });
}
return new ValidationError("Unknown error");
};
// lib/v4/fromError.ts
function fromError(err, options = {}) {
return toValidationError(options)(err);
}
// lib/v4/fromZodIssue.ts
var zod = __toESM(require("zod/v4/core"));
function fromZodIssue(issue, options = {}) {
const messageBuilder = createMessageBuilderFromOptions2(options);
const message = messageBuilder([issue]);
return new ValidationError(message, {
cause: new zod.$ZodRealError([issue])
});
}
function createMessageBuilderFromOptions2(options) {
if ("messageBuilder" in options) {
return options.messageBuilder;
}
return createMessageBuilder(options);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ValidationError,
createErrorMap,
createMessageBuilder,
fromError,
fromZodError,
fromZodIssue,
isValidationError,
isValidationErrorLike,
isZodErrorLike,
toValidationError
});
//# sourceMappingURL=index.js.map

1
node_modules/zod-validation-error/v4/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

679
node_modules/zod-validation-error/v4/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,679 @@
// lib/v4/isZodErrorLike.ts
function isZodErrorLike(err) {
return err instanceof Object && "name" in err && (err.name === "ZodError" || err.name === "$ZodError") && "issues" in err && Array.isArray(err.issues);
}
// lib/v4/ValidationError.ts
var ZOD_VALIDATION_ERROR_NAME = "ZodValidationError";
var ValidationError = class extends Error {
name;
details;
constructor(message, options) {
super(message, options);
this.name = ZOD_VALIDATION_ERROR_NAME;
this.details = getIssuesFromErrorOptions(options);
}
toString() {
return this.message;
}
};
function getIssuesFromErrorOptions(options) {
if (options) {
const cause = options.cause;
if (isZodErrorLike(cause)) {
return cause.issues;
}
}
return [];
}
// lib/v4/isValidationError.ts
function isValidationError(err) {
return err instanceof ValidationError;
}
// lib/v4/isValidationErrorLike.ts
function isValidationErrorLike(err) {
return err instanceof Error && err.name === ZOD_VALIDATION_ERROR_NAME;
}
// lib/v4/errorMap/custom.ts
function parseCustomIssue(issue) {
return {
type: issue.code,
path: issue.path,
message: issue.message ?? "Invalid input"
};
}
// lib/v4/errorMap/invalidElement.ts
function parseInvalidElementIssue(issue) {
return {
type: issue.code,
path: issue.path,
message: `unexpected element in ${issue.origin}`
};
}
// lib/v4/errorMap/invalidKey.ts
function parseInvalidKeyIssue(issue) {
return {
type: issue.code,
path: issue.path,
message: `unexpected key in ${issue.origin}`
};
}
// lib/v4/errorMap/invalidStringFormat.ts
function parseInvalidStringFormatIssue(issue, options = {
displayInvalidFormatDetails: false
}) {
switch (issue.format) {
case "lowercase":
case "uppercase":
return {
type: issue.code,
path: issue.path,
message: `value must be in ${issue.format} format`
};
default: {
if (isZodIssueStringStartsWith(issue)) {
return parseStringStartsWith(issue);
}
if (isZodIssueStringEndsWith(issue)) {
return parseStringEndsWith(issue);
}
if (isZodIssueStringIncludes(issue)) {
return parseStringIncludes(issue);
}
if (isZodIssueStringInvalidRegex(issue)) {
return parseStringInvalidRegex(issue, options);
}
if (isZodIssueStringInvalidJWT(issue)) {
return parseStringInvalidJWT(issue, options);
}
return {
type: issue.code,
path: issue.path,
message: `invalid ${issue.format}`
};
}
}
}
function isZodIssueStringStartsWith(issue) {
return issue.format === "starts_with";
}
function parseStringStartsWith(issue) {
return {
type: issue.code,
path: issue.path,
message: `value must start with "${issue.prefix}"`
};
}
function isZodIssueStringEndsWith(issue) {
return issue.format === "ends_with";
}
function parseStringEndsWith(issue) {
return {
type: issue.code,
path: issue.path,
message: `value must end with "${issue.suffix}"`
};
}
function isZodIssueStringIncludes(issue) {
return issue.format === "includes";
}
function parseStringIncludes(issue) {
return {
type: issue.code,
path: issue.path,
message: `value must include "${issue.includes}"`
};
}
function isZodIssueStringInvalidRegex(issue) {
return issue.format === "regex";
}
function parseStringInvalidRegex(issue, options = {
displayInvalidFormatDetails: false
}) {
let message = "value must match pattern";
if (options.displayInvalidFormatDetails) {
message += ` "${issue.pattern}"`;
}
return {
type: issue.code,
path: issue.path,
message
};
}
function isZodIssueStringInvalidJWT(issue) {
return issue.format === "jwt";
}
function parseStringInvalidJWT(issue, options = {
displayInvalidFormatDetails: false
}) {
return {
type: issue.code,
path: issue.path,
message: options.displayInvalidFormatDetails && issue.algorithm ? `invalid jwt/${issue.algorithm}` : `invalid jwt`
};
}
// lib/v4/errorMap/invalidType.ts
function parseInvalidTypeIssue(issue) {
let message = `expected ${issue.expected}`;
if ("input" in issue) {
message += `, received ${getTypeName(issue.input)}`;
}
return {
type: issue.code,
path: issue.path,
message
};
}
function getTypeName(value) {
if (typeof value === "object") {
if (value === null) {
return "null";
}
if (value === void 0) {
return "undefined";
}
if (Array.isArray(value)) {
return "array";
}
if (value instanceof Date) {
return "date";
}
if (value instanceof RegExp) {
return "regexp";
}
if (value instanceof Map) {
return "map";
}
if (value instanceof Set) {
return "set";
}
if (value instanceof Error) {
return "error";
}
if (value instanceof Function) {
return "function";
}
return "object";
}
return typeof value;
}
// lib/v4/errorMap/invalidUnion.ts
function parseInvalidUnionIssue(issue) {
return {
type: issue.code,
path: issue.path,
message: issue.message ?? "Invalid input"
};
}
// lib/utils/stringify.ts
function stringifySymbol(symbol) {
return symbol.description ?? "";
}
function stringify(value, options = {}) {
switch (typeof value) {
case "symbol":
return stringifySymbol(value);
case "bigint":
case "number": {
switch (options.localization) {
case true:
return value.toLocaleString();
case false:
return value.toString();
default:
return value.toLocaleString(options.localization);
}
}
case "string": {
if (options.wrapStringValueInQuote) {
return `"${value}"`;
}
return value;
}
default: {
if (value instanceof Date) {
switch (options.localization) {
case true:
return value.toLocaleString();
case false:
return value.toISOString();
default:
return value.toLocaleString(options.localization);
}
}
return String(value);
}
}
}
// lib/utils/joinValues.ts
function joinValues(values, options) {
const valuesToDisplay = (options.maxValuesToDisplay ? values.slice(0, options.maxValuesToDisplay) : values).map((value) => {
return stringify(value, {
wrapStringValueInQuote: options.wrapStringValuesInQuote
});
});
if (valuesToDisplay.length < values.length) {
valuesToDisplay.push(
`${values.length - valuesToDisplay.length} more value(s)`
);
}
return valuesToDisplay.reduce((acc, value, index) => {
if (index > 0) {
if (index === valuesToDisplay.length - 1 && options.lastSeparator) {
acc += options.lastSeparator;
} else {
acc += options.separator;
}
}
acc += value;
return acc;
}, "");
}
// lib/v4/errorMap/invalidValue.ts
function parseInvalidValueIssue(issue, options) {
let message;
if (issue.values.length === 0) {
message = "invalid value";
} else if (issue.values.length === 1) {
const valueStr = stringify(issue.values[0], {
wrapStringValueInQuote: true
});
message = `expected value to be ${valueStr}`;
} else {
const valuesStr = joinValues(issue.values, {
separator: options.allowedValuesSeparator,
lastSeparator: options.allowedValuesLastSeparator,
wrapStringValuesInQuote: options.wrapAllowedValuesInQuote,
maxValuesToDisplay: options.maxAllowedValuesToDisplay
});
message = `expected value to be one of ${valuesStr}`;
}
return {
type: issue.code,
path: issue.path,
message
};
}
// lib/v4/errorMap/notMultipleOf.ts
function parseNotMultipleOfIssue(issue) {
return {
type: issue.code,
path: issue.path,
message: `expected multiple of ${issue.divisor}`
};
}
// lib/v4/errorMap/tooBig.ts
function parseTooBigIssue(issue, options) {
const maxValueStr = issue.origin === "date" ? stringify(new Date(issue.maximum), {
localization: options.dateLocalization
}) : stringify(issue.maximum, {
localization: options.numberLocalization
});
switch (issue.origin) {
case "number":
case "int":
case "bigint": {
return {
type: issue.code,
path: issue.path,
message: `number must be less than${issue.inclusive ? " or equal to" : ""} ${maxValueStr}`
};
}
case "string": {
return {
type: issue.code,
path: issue.path,
message: `string must contain at most ${maxValueStr} character(s)`
};
}
case "date": {
return {
type: issue.code,
path: issue.path,
message: `date must be ${issue.inclusive ? "prior or equal to" : "prior to"} "${maxValueStr}"`
};
}
case "array": {
return {
type: issue.code,
path: issue.path,
message: `array must contain at most ${maxValueStr} item(s)`
};
}
case "set": {
return {
type: issue.code,
path: issue.path,
message: `set must contain at most ${maxValueStr} item(s)`
};
}
case "file": {
return {
type: issue.code,
path: issue.path,
message: `file must not exceed ${maxValueStr} byte(s) in size`
};
}
default:
return {
type: issue.code,
path: issue.path,
message: `value must be less than${issue.inclusive ? " or equal to" : ""} ${maxValueStr}`
};
}
}
// lib/v4/errorMap/tooSmall.ts
function parseTooSmallIssue(issue, options) {
const minValueStr = issue.origin === "date" ? stringify(new Date(issue.minimum), {
localization: options.dateLocalization
}) : stringify(issue.minimum, {
localization: options.numberLocalization
});
switch (issue.origin) {
case "number":
case "int":
case "bigint": {
return {
type: issue.code,
path: issue.path,
message: `number must be greater than${issue.inclusive ? " or equal to" : ""} ${minValueStr}`
};
}
case "date": {
return {
type: issue.code,
path: issue.path,
message: `date must be ${issue.inclusive ? "later or equal to" : "later to"} "${minValueStr}"`
};
}
case "string": {
return {
type: issue.code,
path: issue.path,
message: `string must contain at least ${minValueStr} character(s)`
};
}
case "array": {
return {
type: issue.code,
path: issue.path,
message: `array must contain at least ${minValueStr} item(s)`
};
}
case "set": {
return {
type: issue.code,
path: issue.path,
message: `set must contain at least ${minValueStr} item(s)`
};
}
case "file": {
return {
type: issue.code,
path: issue.path,
message: `file must be at least ${minValueStr} byte(s) in size`
};
}
default:
return {
type: issue.code,
path: issue.path,
message: `value must be greater than${issue.inclusive ? " or equal to" : ""} ${minValueStr}`
};
}
}
// lib/v4/errorMap/unrecognizedKeys.ts
function parseUnrecognizedKeysIssue(issue, options) {
const keysStr = joinValues(issue.keys, {
separator: options.unrecognizedKeysSeparator,
lastSeparator: options.unrecognizedKeysLastSeparator,
wrapStringValuesInQuote: options.wrapUnrecognizedKeysInQuote,
maxValuesToDisplay: options.maxUnrecognizedKeysToDisplay
});
return {
type: issue.code,
path: issue.path,
message: `unrecognized key(s) ${keysStr} in object`
};
}
// lib/v4/errorMap/errorMap.ts
var issueParsers = {
invalid_type: parseInvalidTypeIssue,
too_big: parseTooBigIssue,
too_small: parseTooSmallIssue,
invalid_format: parseInvalidStringFormatIssue,
invalid_value: parseInvalidValueIssue,
invalid_element: parseInvalidElementIssue,
not_multiple_of: parseNotMultipleOfIssue,
unrecognized_keys: parseUnrecognizedKeysIssue,
invalid_key: parseInvalidKeyIssue,
custom: parseCustomIssue,
invalid_union: parseInvalidUnionIssue
};
var defaultErrorMapOptions = {
displayInvalidFormatDetails: false,
allowedValuesSeparator: ", ",
allowedValuesLastSeparator: " or ",
wrapAllowedValuesInQuote: true,
maxAllowedValuesToDisplay: 10,
unrecognizedKeysSeparator: ", ",
unrecognizedKeysLastSeparator: " and ",
wrapUnrecognizedKeysInQuote: true,
maxUnrecognizedKeysToDisplay: 5,
dateLocalization: true,
numberLocalization: true
};
function createErrorMap(partialOptions = {}) {
const options = {
...defaultErrorMapOptions,
...partialOptions
};
const errorMap = (issue) => {
if (issue.code === void 0) {
return "Not supported issue type";
}
const parseFunc = issueParsers[issue.code];
const ast = parseFunc(issue, options);
return ast.message;
};
return errorMap;
}
// lib/utils/NonEmptyArray.ts
function isNonEmptyArray(value) {
return value.length !== 0;
}
// lib/utils/joinPath.ts
var identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;
function joinPath(path) {
if (path.length === 1) {
let propertyKey = path[0];
if (typeof propertyKey === "symbol") {
propertyKey = stringifySymbol(propertyKey);
}
return propertyKey.toString() || '""';
}
return path.reduce((acc, propertyKey) => {
if (typeof propertyKey === "number") {
return acc + "[" + propertyKey.toString() + "]";
}
if (typeof propertyKey === "symbol") {
propertyKey = stringifySymbol(propertyKey);
}
if (propertyKey.includes('"')) {
return acc + '["' + escapeQuotes(propertyKey) + '"]';
}
if (!identifierRegex.test(propertyKey)) {
return acc + '["' + propertyKey + '"]';
}
const separator = acc.length === 0 ? "" : ".";
return acc + separator + propertyKey;
}, "");
}
function escapeQuotes(str) {
return str.replace(/"/g, '\\"');
}
// lib/utils/titleCase.ts
function titleCase(value) {
if (value.length === 0) {
return value;
}
return value.charAt(0).toUpperCase() + value.slice(1);
}
// lib/v4/MessageBuilder.ts
var defaultMessageBuilderOptions = {
prefix: "Validation error",
prefixSeparator: ": ",
maxIssuesInMessage: 99,
// I've got 99 problems but the b$tch ain't one
unionSeparator: " or ",
issueSeparator: "; ",
includePath: true,
forceTitleCase: true
};
function createMessageBuilder(partialOptions = {}) {
const options = {
...defaultMessageBuilderOptions,
...partialOptions
};
return function messageBuilder(issues) {
const message = issues.slice(0, options.maxIssuesInMessage).map((issue) => mapIssue(issue, options)).join(options.issueSeparator);
return conditionallyPrefixMessage(message, options);
};
}
function mapIssue(issue, options) {
if (issue.code === "invalid_union" && isNonEmptyArray(issue.errors)) {
const individualMessages = issue.errors.map(
(issues) => issues.map(
(subIssue) => mapIssue(
{
...subIssue,
path: issue.path.concat(subIssue.path)
},
options
)
).join(options.issueSeparator)
);
return Array.from(new Set(individualMessages)).join(options.unionSeparator);
}
const buf = [];
if (options.forceTitleCase) {
buf.push(titleCase(issue.message));
} else {
buf.push(issue.message);
}
pathCondition: if (options.includePath && issue.path !== void 0 && isNonEmptyArray(issue.path)) {
if (issue.path.length === 1) {
const identifier = issue.path[0];
if (typeof identifier === "number") {
buf.push(` at index ${identifier}`);
break pathCondition;
}
}
buf.push(` at "${joinPath(issue.path)}"`);
}
return buf.join("");
}
function conditionallyPrefixMessage(message, options) {
if (options.prefix != null) {
if (message.length > 0) {
return [options.prefix, message].join(options.prefixSeparator);
}
return options.prefix;
}
if (message.length > 0) {
return message;
}
return defaultMessageBuilderOptions.prefix;
}
// lib/v4/fromZodError.ts
function fromZodError(zodError, options = {}) {
if (!isZodErrorLike(zodError)) {
throw new TypeError(
`Invalid zodError param; expected instance of ZodError. Did you mean to use the "${fromError.name}" method instead?`
);
}
return fromZodErrorWithoutRuntimeCheck(zodError, options);
}
function fromZodErrorWithoutRuntimeCheck(zodError, options = {}) {
const zodIssues = zodError.issues;
let message;
if (isNonEmptyArray(zodIssues)) {
const messageBuilder = createMessageBuilderFromOptions(options);
message = messageBuilder(zodIssues);
} else {
message = zodError.message;
}
return new ValidationError(message, { cause: zodError });
}
function createMessageBuilderFromOptions(options) {
if ("messageBuilder" in options) {
return options.messageBuilder;
}
return createMessageBuilder(options);
}
// lib/v4/toValidationError.ts
var toValidationError = (options = {}) => (err) => {
if (isZodErrorLike(err)) {
return fromZodErrorWithoutRuntimeCheck(err, options);
}
if (err instanceof Error) {
return new ValidationError(err.message, { cause: err });
}
return new ValidationError("Unknown error");
};
// lib/v4/fromError.ts
function fromError(err, options = {}) {
return toValidationError(options)(err);
}
// lib/v4/fromZodIssue.ts
import * as zod from "zod/v4/core";
function fromZodIssue(issue, options = {}) {
const messageBuilder = createMessageBuilderFromOptions2(options);
const message = messageBuilder([issue]);
return new ValidationError(message, {
cause: new zod.$ZodRealError([issue])
});
}
function createMessageBuilderFromOptions2(options) {
if ("messageBuilder" in options) {
return options.messageBuilder;
}
return createMessageBuilder(options);
}
export {
ValidationError,
createErrorMap,
createMessageBuilder,
fromError,
fromZodError,
fromZodIssue,
isValidationError,
isValidationErrorLike,
isZodErrorLike,
toValidationError
};
//# sourceMappingURL=index.mjs.map

1
node_modules/zod-validation-error/v4/index.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long