{"name":"zod-validation-error","version":"0.2.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":"Causaly Team","email":"front-end@causaly.com","url":"https://www.causaly.com"},"contributors":[{"name":"Dimitrios C. Michalakos","email":"dimitris@jmike.gr","url":"https://github.com/jmike"}],"main":"./dist/cjs/index.js","module":"./dist/esm/index.js","types":"./dist/types/index.d.ts","publishConfig":{"access":"public"},"sideEffects":false,"engines":{"node":"^14.17 || >=16.0.0"},"scripts":{"typecheck":"tsc --noEmit","build:cjs":"tsc -p ./tsconfig.build-cjs.json","build:esm":"tsc -p ./tsconfig.build-esm.json","build:types":"tsc -p ./tsconfig.build-types.json","build":"rimraf dist && concurrently \"yarn build:types\" \"yarn build:esm\" \"yarn build:cjs\"","lint":"eslint lib --ext .ts","format":"prettier --config ./.prettierrc --ignore-path .gitignore -w .","test":"jest","coverage":"jest --coverage","changeset":"changeset","prerelease":"yarn build && yarn test","release":"changeset publish"},"husky":{"hooks":{"commit-msg":"commitlint -E HUSKY_GIT_PARAMS","pre-commit":"lint-staged"}},"lint-staged":{"*.{js,jsx,ts,tsx}":["eslint --fix","prettier --config ./.prettierrc --write"]},"devDependencies":{"@changesets/changelog-github":"^0.4.2","@changesets/cli":"^2.18.1","@commitlint/cli":"^15.0.0","@commitlint/config-conventional":"^15.0.0","@types/jest":"^29.2.4","@types/node":"^18.11.13","@typescript-eslint/eslint-plugin":"^5.7.0","@typescript-eslint/parser":"^5.7.0","concurrently":"^6.5.1","eslint":"^8.4.1","eslint-config-prettier":"^8.1.0","eslint-plugin-prettier":"^4.0.0","eslint-plugin-simple-import-sort":"^7.0.0","husky":"4","jest":"^29.3.1","lint-staged":"^12.1.2","prettier":"^2.2.1","rimraf":"^3.0.0","ts-jest":"^29.0.3","typescript":"^4.9.4","zod":"^3.20.0"},"peerDependencies":{"zod":"^3.18.0"},"gitHead":"0c73aa8fffb234278fbe8050c3aef9271a028821","bugs":{"url":"https://github.com/causaly/zod-validation-error/issues"},"homepage":"https://github.com/causaly/zod-validation-error#readme","_id":"zod-validation-error@0.2.2","_nodeVersion":"16.18.1","_npmVersion":"8.19.2","dist":{"integrity":"sha512-CD7i+LIxdskkgxhVOsCr5F1Q4kbnbpgQGBQXdNdFxKCecS4OFseekJ5gOkNu/Y6rapQ4Rj7XBYMckBhyOZm+lQ==","shasum":"934a7275f8b0977613ddf74731c4da519330802a","tarball":"http://registry-npm.ywwl.com/zod-validation-error/download/zod-validation-error-0.2.2.tgz","fileCount":15,"unpackedSize":13186,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQD1Y1WFi5cmvdCvAqOkm7dSyydDnD4N5AReQPUSPV+fOwIhAO452jV+HkVJ9qrwS9OalhB1Mq4reXTVzhwEtiQHy7sA"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjmaX0ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmqwIhAAnRwArft2F+oEj7GdOt1He4yBhWmh2jWu8S5CQx63IFq3Awnc\r\nfN+1PLEtDyeWkqcS9MAukXxivvcfrjMTCxQgrS6YxKTpKftojmfo750e9o5S\r\nzfzqFD2uqNYwJnWSYtHxeGM2s4uCyRo4XHK49yQkiYDhy88lWGJMvCPKUicR\r\nl7tOErojzmdlU27lxdVL5dAZ3yn03aljhd+LPhTKIxA+a+BgvMTDP2p2WYxb\r\ngRRKfWsM6ecsHOvNF61v79sUl/i7AXNcS2JNNmm8FBeAsqQIi6j7KChvmst/\r\nuL+0rUOM5RQvWgCNd8WXwBIPXEkh0zUS7BzVCze9H2OGfGOQdIGOKq5w1FPZ\r\nvtrSmbHcuedU0vzd/PKXj4bj68QGh6pLqEPXNoc9LODwlTEr5+Soo77TTK2+\r\n28VRlYHUZ3PNL1dxkv2uXzi6XaFCqwlNUb1d0DbxlDXoB6eYnmXh6Ug9G5g+\r\n6NSwaYfWIwGPSd6MoaxUvqW6oYZg77qqX3RtXMsIjRnApqAgCUUxm99fwSPs\r\nyo5XuEocn5bk2qrWtfV8b86r6jjHxx/DhtkKCZp4CE9wiYIfPjcVJkRdUszi\r\n+OFz0gw/Lna5Jz7Z6kjc/quMJGt5HhlhrdDTPxutTZl+v68AzhXN7KobfE6+\r\nsSsX77Nthvh3qS73w71+wwfjF5uYHTnH4qg=\r\n=Twwv\r\n-----END PGP SIGNATURE-----\r\n","size":4795,"noattachment":false,"key":"/zod-validation-error/-/zod-validation-error-0.2.2.tgz"},"_npmUser":{"name":"jmike","email":"dimitris@jmike.gr"},"directories":{},"maintainers":[{"name":"nikoskalogridis","email":"nikos.kalogridis@gmail.com"},{"name":"dnlytras","email":"dnlytras@gmail.com"},{"name":"jmike","email":"dimitris@jmike.gr"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/zod-validation-error_0.2.2_1671013876493_0.06907084860744805"},"_hasShrinkwrap":false,"readme":"# zod-validation-error\n\nWrap zod validation errors in user-friendly readable messages.\n\n[![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)\n\n#### Features\n\n- User-friendly readable messages, configurable via options;\n- Maintain original issues under `error.details`;\n- Extensive tests.\n\n## Installation\n\n```bash\nnpm install zod-validation-error\n```\n\n#### Requirements\n\n- Node.js v.18+\n- TypeScript v.4.5+\n\n## Quick start\n\n```typescript\nimport { z as zod } from 'zod';\nimport { fromError } from 'zod-validation-error';\n\n// create zod schema\nconst zodSchema = zod.object({\n  id: zod.number().int().positive(),\n  email: zod.string().email(),\n});\n\n// parse some invalid value\ntry {\n  zodSchema.parse({\n    id: 1,\n    email: 'foobar', // note: invalid email\n  });\n} catch (err) {\n  const validationError = fromError(err);\n  // the error is now readable by the user\n  // you may print it to console\n  console.log(validationError.toString());\n  // or return it as an actual error\n  return validationError;\n}\n```\n\n## Motivation\n\nZod 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.\n\n### Example\n\n#### Input (from Zod)\n\n```json\n[\n  {\n    \"code\": \"too_small\",\n    \"inclusive\": false,\n    \"message\": \"Number must be greater than 0\",\n    \"minimum\": 0,\n    \"path\": [\"id\"],\n    \"type\": \"number\"\n  },\n  {\n    \"code\": \"invalid_string\",\n    \"message\": \"Invalid email\",\n    \"path\": [\"email\"],\n    \"validation\": \"email\"\n  }\n]\n```\n\n#### Output\n\n```\nValidation error: Number must be greater than 0 at \"id\"; Invalid email at \"email\"\n```\n\n## API\n\n- [ValidationError(message[, options])](#validationerror)\n- [errorMap](#errormap)\n- [isValidationError(error)](#isvalidationerror)\n- [isValidationErrorLike(error)](#isvalidationerrorlike)\n- [fromError(error[, options])](#fromerror)\n- [fromZodIssue(zodIssue[, options])](#fromzodissue)\n- [fromZodError(zodError[, options])](#fromzoderror)\n- [toValidationError([options]) => (error) => ValidationError](#tovalidationerror)\n\n### ValidationError\n\nMain `ValidationError` class, extending native JavaScript `Error`.\n\n#### Arguments\n\n- `message` - _string_; error message (required)\n- `options` - _ErrorOptions_; error options as per [JavaScript definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error#options) (optional)\n  - `options.cause` - _any_; can be used to hold the original zod error (optional)\n\n#### Example 1: construct new ValidationError with `message`\n\n```typescript\nconst { ValidationError } = require('zod-validation-error');\n\nconst error = new ValidationError('foobar');\nconsole.log(error instanceof Error); // prints true\n```\n\n#### Example 2: construct new ValidationError with `message` and `options.cause`\n\n```typescript\nimport { z as zod } from 'zod';\nconst { ValidationError } = require('zod-validation-error');\n\nconst error = new ValidationError('foobar', {\n  cause: new zod.ZodError([\n    {\n      code: 'invalid_string',\n      message: 'Invalid email',\n      path: ['email'],\n      validation: 'email',\n    },\n  ]),\n});\n\nconsole.log(error.details); // prints issues from zod error\n```\n\n### errorMap\n\nA custom error map to use with zod's `setErrorMap` method and get user-friendly messages automatically.\n\n#### Example\n\n```typescript\nimport { z as zod } from 'zod';\nimport { errorMap } from 'zod-validation-error';\n\nzod.setErrorMap(errorMap);\n```\n\n### isValidationError\n\nA [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on `instanceof` comparison.\n\n#### Arguments\n\n- `error` - error instance (required)\n\n#### Example\n\n```typescript\nimport { z as zod } from 'zod';\nimport { ValidationError, isValidationError } from 'zod-validation-error';\n\nconst err = new ValidationError('foobar');\nisValidationError(err); // returns true\n\nconst invalidErr = new Error('foobar');\nisValidationError(err); // returns false\n```\n\n### isValidationErrorLike\n\nA [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on heuristics comparison.\n\n_Why do we need heuristics if we have `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.\n\nIn most cases, it is safer to use `isValidationErrorLike` than `isValidationError`.\n\n#### Arguments\n\n- `error` - error instance (required)\n\n#### Example\n\n```typescript\nimport { ValidationError, isValidationErrorLike } from 'zod-validation-error';\n\nconst err = new ValidationError('foobar');\nisValidationErrorLike(err); // returns true\n\nconst invalidErr = new Error('foobar');\nisValidationErrorLike(err); // returns false\n```\n\n### fromError\n\nConverts an error to `ValidationError`.\n\n_Why is the difference between `fromError` and `fromZodError`?_ The `fromError` is a less strict version of `fromZodError` that can accept an unknown error and attempt to convert it to a `ValidationError`.\n\n#### Arguments\n\n- `error` - _unknown_; an error (required)\n- `options` - _Object_; formatting options (optional)\n  - `maxIssuesInMessage` - _number_; max issues to include in user-friendly message (optional, defaults to 99)\n  - `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to \";\")\n  - `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to \", or\")\n  - `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to \"Validation error\"). Pass `null` to disable prefix completely.\n  - `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to \": \"). Not used when `prefix` is `null`.\n  - `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).\n\n### fromZodIssue\n\nConverts a single zod issue to `ValidationError`.\n\n#### Arguments\n\n- `zodIssue` - _zod.ZodIssue_; a ZodIssue instance (required)\n- `options` - _Object_; formatting options (optional)\n  - `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to \";\")\n  - `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to \", or\")\n  - `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to \"Validation error\"). Pass `null` to disable prefix completely.\n  - `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to \": \"). Not used when `prefix` is `null`.\n  - `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).\n\n### fromZodError\n\nConverts zod error to `ValidationError`.\n\n_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()`.\n\n#### Arguments\n\n- `zodError` - _zod.ZodError_; a ZodError instance (required)\n- `options` - _Object_; formatting options (optional)\n  - `maxIssuesInMessage` - _number_; max issues to include in user-friendly message (optional, defaults to 99)\n  - `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to \";\")\n  - `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to \", or\")\n  - `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to \"Validation error\"). Pass `null` to disable prefix completely.\n  - `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to \": \"). Not used when `prefix` is `null`.\n  - `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).\n\n### toValidationError\n\nA 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\n\n```js\ntoValidationError(options) => (zodError) => ValidationError\n```\n\n#### Example using fp-ts\n\n```typescript\nimport * as Either from 'fp-ts/Either';\nimport { z as zod } from 'zod';\nimport { toValidationError, ValidationError } from 'zod-validation-error';\n\n// create zod schema\nconst zodSchema = zod\n  .object({\n    id: zod.number().int().positive(),\n    email: zod.string().email(),\n  })\n  .brand<'User'>();\n\nexport type User = zod.infer<typeof zodSchema>;\n\nexport function parse(\n  value: zod.input<typeof zodSchema>\n): Either.Either<ValidationError, User> {\n  return Either.tryCatch(() => schema.parse(value), toValidationError());\n}\n```\n\n## FAQ\n\n### How to distinguish between errors\n\nUse the `isValidationErrorLike` type guard.\n\n#### Example\n\nScenario: Distinguish between `ValidationError` VS generic `Error` in order to respond with 400 VS 500 HTTP status code respectively.\n\n```typescript\nimport * as Either from 'fp-ts/Either';\nimport { z as zod } from 'zod';\nimport { isValidationErrorLike } from 'zod-validation-error';\n\ntry {\n  func(); // throws Error - or - ValidationError\n} catch (err) {\n  if (isValidationErrorLike(err)) {\n    return 400; // Bad Data (this is a client error)\n  }\n\n  return 500; // Server Error\n}\n```\n\n### How to use `ValidationError` outside `zod`\n\nIt's possible to implement custom validation logic outside `zod` and throw a `ValidationError`.\n\n#### Example 1: passing custom message\n\n```typescript\nimport { ValidationError } from 'zod-validation-error';\nimport { Buffer } from 'node:buffer';\n\nfunction parseBuffer(buf: unknown): Buffer {\n  if (!Buffer.isBuffer(buf)) {\n    throw new ValidationError('Invalid argument; expected buffer');\n  }\n\n  return buf;\n}\n```\n\n#### Example 2: passing custom message and original error as cause\n\n```typescript\nimport { ValidationError } from 'zod-validation-error';\n\ntry {\n  // do something that throws an error\n} catch (err) {\n  throw new ValidationError('Something went deeply wrong', { cause: err });\n}\n```\n\n### How to use `ValidationError` with custom \"error map\"\n\nZod supports customizing error messages by providing a custom \"error map\". You may combine this with `zod-validation-error` to produce user-friendly messages.\n\n#### Example 1: produce user-friendly error messages using the `errorMap` property\n\nIf all you need is to produce user-friendly error messages you may use the `errorMap` property.\n\n```typescript\nimport { z as zod } from 'zod';\nimport { errorMap } from 'zod-validation-error';\n\nzod.setErrorMap(errorMap);\n```\n\n#### Example 2: extra customization using `fromZodIssue`\n\nIf you need to customize some error code, you may use the `fromZodIssue` function.\n\n```typescript\nimport { z as zod } from 'zod';\nimport { fromZodIssue } from 'zod-validation-error';\n\nconst customErrorMap: zod.ZodErrorMap = (issue, ctx) => {\n  switch (issue.code) {\n    case ZodIssueCode.invalid_type: {\n      return {\n        message:\n          'Custom error message of your preference for invalid_type errors',\n      };\n    }\n    default: {\n      const validationError = fromZodIssue({\n        ...issue,\n        // fallback to the default error message\n        // when issue does not have a message\n        message: issue.message ?? ctx.defaultError,\n      });\n\n      return {\n        message: validationError.message,\n      };\n    }\n  }\n};\n\nzod.setErrorMap(customErrorMap);\n```\n\n### How to use `zod-validation-error` with `react-hook-form`?\n\n```typescript\nimport { useForm } from 'react-hook-form';\nimport { zodResolver } from '@hookform/resolvers/zod';\nimport { errorMap } from 'zod-validation-error';\n\nuseForm({\n  resolver: zodResolver(schema, { errorMap }),\n});\n```\n\n### Does `zod-validation-error` support CommonJS\n\nYes, `zod-validation-error` supports CommonJS out-of-the-box. All you need to do is import it using `require`.\n\n#### Example\n\n```typescript\nconst { ValidationError } = require('zod-validation-error');\n```\n\n## Contribute\n\nSource code contributions are most welcome. Please open a PR, ensure the linter is satisfied and all tests pass.\n\n#### We are hiring\n\nCausaly 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://apply.workable.com/causaly/.\n\n## License\n\nMIT\n","publish_time":1671013876686,"_cnpm_publish_time":1671013876686,"dist-tags":{"beta":"4.0.0-beta.2","latest":"5.0.0"}}