{"name":"zod-validation-error","version":"0.1.0","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"}],"publishConfig":{"access":"public"},"sideEffects":false,"types":"./build/index.d.ts","main":"./build/node/cjs/index.js","exports":{".":{"node":{"import":"./build/node/esm/index.js","require":"./build/node/cjs/index.js"},"default":"./build/browser/esm/index.js"}},"engines":{"node":"^14.17 || >=16.0.0"},"scripts":{"build:node-cjs":"swc lib --config-file ./config/node-cjs.json -d build/node/cjs","build:node-esm":"swc lib --config-file ./config/node-esm.json -d build/node/esm","build:browser-esm":"swc lib --config-file ./config/browser-esm.json -d ./build/browser/esm","build":"rimraf build && concurrently \"tsc -p tsconfig.json\" \"yarn build:node-cjs\" \"yarn build:node-esm\" \"yarn build:browser-esm\"","lint":"eslint lib --ext .ts","format":"prettier --config ./.prettierrc --ignore-path .gitignore -w .","test":"jest --config ./config/jest.config.ts","coverage":"jest --config jest.config.ts --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","@swc/cli":"^0.1.55","@swc/core":"^1.2.121","@types/jest":"^27.0.3","@types/node":"^17.0.0","@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":"^27.0.6","lint-staged":"^12.1.2","prettier":"^2.2.1","rimraf":"^3.0.0","ts-jest":"^27.0.5","typescript":"^4.2.3","zod":"^3.18.0"},"peerDependencies":{"@swc/helpers":"^0.3.2","zod":"^3.18.0"},"licenseText":"(The MIT License)\n\nCopyright 2022 Causaly, Inc <front-end@causaly.com>\n\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE 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.\n","_id":"zod-validation-error@0.1.0","dist":{"shasum":"8e5117c1779358530530b703ad6cb01fe61502b1","integrity":"sha512-GP6YgdxNXPx+iBj+jwbaJmnRHQoRUEPL5PWbiwTJX6ayAP+XhN0M9MXBFI1aPy3cJPVjwE+nYr8u95nQJXdCgQ==","tarball":"http://registry-npm.ywwl.com/zod-validation-error/download/zod-validation-error-0.1.0.tgz","fileCount":27,"unpackedSize":14283,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDKhLp6G88ZPzW0Je07lStYji8Je8TmVO5fzZ/6A+WpmAIgWh18zQtpLrS6TpAVOCJGkolQJdoeHMjc2Mk6ZvKxtIU="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjDglGACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmrKeg//T5Gr2irmCmuAehEFU1wbBJsXz8W0z+S6bqqbgjd8XwBZPRrU\r\nfKu8LZsXQGBVU7As/W0dg/EsJT2O2Xd228exq02hgoHjrx0ki7ikuztwSnoo\r\n6fj99uZGzn/u80rxoyaPuzezoa6c8w4jDcNVZMVl0q/ncB2MWo3aZyH+zuyo\r\nKqSx8kGDDExk5gFUvSsIQkj4r53X5Q9kv2LM5A6PomhHMiHB1DQjFovO1HOc\r\n8bL+MYbL9Rx3tQSApfMgYMNCgdrnEyEATqpVMLavd5M1SUb6l66ne/48CMud\r\nAmt5PVJ/RF7qZuE/cCc6hgbg3jgUpjj48cRdpULVhe50IBXdo4DVrCn8eZ9r\r\nwFcAIr0ToJUiyy1/4afN78nFtMGXoTpNUSSTGEkAqYb6LgRP/i3rpWIYJ7HS\r\nq3FjQluv73b2Pj1euzkyUMO+1r4ggdn7BfOerWE/SLlCxSW4lcDrR9F6aSfZ\r\nvl1ydmgCt62Emj+fHhKSEa+N2Cz3Fm10jbAQLkJaTFbnZtJ+p5rXc/x3gkYd\r\nfdPf0hg+KM6XDplusFyT+aApmYd3mUC0NAqqZS8CNaUpJ0TbYe0/Hk188f9o\r\nGGSrmp3OjGi51NZTqpk2UmL/1UvYqto/+TY9HWf6rd1w5I7r8V3h2E8VVeDQ\r\nzXIif61+HAyqn/ACNvSuyYmJdEhRTabumqU=\r\n=pneX\r\n-----END PGP SIGNATURE-----\r\n","size":4655,"noattachment":false,"key":"/zod-validation-error/-/zod-validation-error-0.1.0.tgz"},"_npmUser":{"name":"jmike","email":"dimitris@jmike.gr"},"directories":{},"maintainers":[{"name":"jmike","email":"dimitris@jmike.gr"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/zod-validation-error_0.1.0_1661864261847_0.48306160093749284"},"_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":1661864262050,"_cnpm_publish_time":1661864262050,"dist-tags":{"beta":"4.0.0-beta.2","latest":"5.0.0"}}