{"name":"errs","version":"1.0.0","description":"Simple error creation, boundaries, and formatting utilities","type":"module","exports":{".":{"types":"./src/errs.d.ts","import":"./src/errs.js"},"./boundary":{"types":"./src/boundary.d.ts","import":"./src/boundary.js"},"./format":{"types":"./src/format.d.ts","import":"./src/format.js"},"./package.json":"./package.json"},"main":"./src/errs.js","types":"./src/errs.d.ts","scripts":{"test":"node --test test/**/*.test.js","test:coverage":"node --test --experimental-test-coverage test/**/*.test.js","test:watch":"node --test --watch test/**/*.test.js","test:examples":"bash test/examples.test.sh","build:types":"tsc","lint":"biome lint src test examples","lint:fix":"biome lint --write src test examples","format":"biome format --write src test examples","format:check":"biome format src test examples","check":"biome check src test examples && pnpm run build:types","check:fix":"biome check --write src test examples","prepublishOnly":"pnpm run build:types"},"repository":{"type":"git","url":"git+https://github.com/indexzero/errs.git"},"bugs":{"url":"https://github.com/indexzero/errs/issues"},"homepage":"https://github.com/indexzero/errs#readme","keywords":["errors","error","utilities","aggregate-error","error-boundary","error-cause","formatting"],"author":{"name":"Charlie Robbins","email":"charlie.robbins@gmail.com"},"contributors":[{"name":"Nuno Job","email":"nuno@nodejitsu.com"}],"license":"MIT","sideEffects":false,"engines":{"node":">=22.0.0"},"devDependencies":{"@biomejs/biome":"^2.3.8","@types/node":"^22.10.2","typescript":"^5.7.2"},"packageManager":"pnpm@10.25.0","_id":"errs@1.0.0","gitHead":"7beaa613ca7e6dbae9e2b26f6205f531397e035e","_nodeVersion":"22.20.0","_npmVersion":"11.4.2","dist":{"integrity":"sha512-bv8LOhoorYBHcsOuUyKOwZsIuUfpyb0TanHI13Dm7IRa1A4o+vHs1jcfc21Uy9tr5gwe7eLshMoAHVd6y/ydag==","shasum":"6e3bd1fda3bb96825c1e4c6aaec4a917bed14e96","tarball":"http://registry-npm.ywwl.com/errs/download/errs-1.0.0.tgz","fileCount":9,"unpackedSize":35891,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCmP1YklZtcOEnMpJOAzT2/ua/9ClXycDZUHkeDX5QfTQIgcKfwRdhtdLN1xucZ57mFplYgG5MKcAEy28yt1ysm7VA="}],"size":9805,"noattachment":false,"key":"/errs/-/errs-1.0.0.tgz"},"_npmUser":{"name":"indexzero","email":"charlie.robbins@gmail.com"},"directories":{},"maintainers":[{"name":"indexzero","email":"charlie.robbins@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/errs_1.0.0_1770324657799_0.6720944633645083"},"_hasShrinkwrap":false,"readme":"# errs\n\nSimple error creation, boundaries, and formatting utilities for modern Node.js applications.\n\n## Features\n\n- **Simple Error Creation** - Create errors with custom properties in one line\n- **Error Boundaries** - Collect errors without immediate throwing\n- **Type Guards** - Runtime type checking for errors with TypeScript support\n- **Result Pattern** - Rust-style `tryCatch` for exception-free error handling\n- **Multi-Format Output** - Format errors for terminal, JSON, or HTML\n- **Native Cause Chains** - Built-in support for ES2022 `Error.cause`\n- **Error Type Registration** - Register and reuse custom error types\n- **Zero Dependencies** - No runtime dependencies\n\n## Installation\n\n```sh\nnpm install errs\n```\n\n## Quick Start\n\n```js\nimport errs from 'errs'\n\n// Create errors with custom properties\nconst err = errs.create({\n  message: 'User not found',\n  status: 404,\n  code: 'USER_NOT_FOUND'\n})\n\n// Collect multiple errors without throwing\nconst boundary = errs.boundary()\nboundary.add(new Error('Validation failed'))\nboundary.add(new Error('Invalid email'))\nif (boundary.hasErrors()) {\n  boundary.throwIfErrors()\n}\n\n// Format errors for different outputs\nconsole.log(errs.format(err, { format: 'terminal' }))\n```\n\n## API Reference\n\n### Creating Errors\n\n#### `errs.create(opts)`\n\nCreates a new error with custom properties.\n\n```js\n// From a string\nconst err = errs.create('Something went wrong')\n\n// From an object\nconst err = errs.create({\n  message: 'Database connection failed',\n  status: 500,\n  code: 'DB_ERROR'\n})\n\n// From an array (joined with spaces)\nconst err = errs.create(['Invalid', 'request', 'parameters'])\n\n// From a function\nconst err = errs.create(() => ({\n  message: 'Dynamic error',\n  timestamp: Date.now()\n}))\n```\n\n#### `errs.create(type, opts)`\n\nCreates an error of a registered type.\n\n```js\nclass ValidationError extends Error {\n  name = 'ValidationError'\n}\n\nerrs.register('validation', ValidationError)\n\nconst err = errs.create('validation', {\n  message: 'Invalid input',\n  field: 'email'\n})\n```\n\n### Merging Errors\n\n#### `errs.merge(error, opts)`\n\nMerges an existing error with new properties and sets native cause chain.\n\n```js\ntry {\n  await fetchData()\n} catch (original) {\n  throw errs.merge(original, {\n    message: 'Failed to load user data',\n    userId: 123\n  })\n  // merged.cause === original\n}\n```\n\n### Error Boundaries\n\n#### `errs.boundary(options)`\n\nCreates an ErrorBoundary for collecting errors without immediate throwing.\n\n```js\nconst boundary = errs.boundary({\n  maxErrors: 100,      // Maximum errors to collect (default: 1000)\n  captureStack: true   // Capture creation point (default: true)\n})\n\n// Collect errors\ntry {\n  validateEmail(data.email)\n} catch (e) {\n  boundary.add(e)\n}\n\ntry {\n  validateAge(data.age)\n} catch (e) {\n  boundary.add(e)\n}\n\n// Check and throw if errors exist\nif (boundary.hasErrors()) {\n  console.log(`Collected ${boundary.count} errors`)\n  boundary.throwIfErrors('Validation failed')\n}\n\n// Or get as AggregateError\nconst aggregate = boundary.toAggregateError()\n\n// Clear and reuse\nboundary.clear()\n```\n\n#### ErrorBoundary Methods\n\n- `add(error)` - Add an error to the boundary\n- `hasErrors()` - Check if any errors collected\n- `count` - Get number of errors\n- `errors` - Get copy of all errors\n- `toAggregateError(message)` - Convert to AggregateError\n- `throwIfErrors(message)` - Throw if errors exist\n- `clear()` - Remove all errors\n- `trap(fn)` - Execute sync function, trap errors to boundary\n- `trapAsync(fn)` - Execute async function, trap errors to boundary\n\n#### `boundary.trap(fn)` / `boundary.trapAsync(fn)`\n\nExecute functions and automatically collect errors without throwing.\n\n```js\nconst boundary = errs.boundary()\n\n// Sync operations\nconst result = boundary.trap(() => JSON.parse(userInput))\nif (result.ok) {\n  console.log('Parsed:', result.value)\n} else {\n  console.log('Parse failed, error collected')\n}\n\n// Async operations\nconst fetched = await boundary.trapAsync(() => fetch(url))\nif (fetched.ok) {\n  const data = await fetched.value.json()\n}\n\n// Process multiple and handle all errors at once\nitems.forEach(item => boundary.trap(() => processItem(item)))\nboundary.throwIfErrors('Batch processing failed')\n```\n\n### Type Guards\n\n#### `errs.isErrorType(error, ErrorClass)`\n\nType guard that checks if an error is an instance of a specific class.\n\n```js\ntry {\n  await fetchData()\n} catch (err) {\n  if (errs.isErrorType(err, TypeError)) {\n    // TypeScript knows err is TypeError here\n    console.log('Type error occurred')\n  }\n}\n```\n\n#### `errs.isRegisteredType(error, typeName)`\n\nCheck if an error matches a registered type name.\n\n```js\nerrs.register('validation', ValidationError)\n\nif (errs.isRegisteredType(err, 'validation')) {\n  // Handle validation error\n}\n```\n\n#### `errs.assertErrorType(error, ErrorClass, message?)`\n\nAssert error is a specific type, throws TypeError if not.\n\n```js\nfunction handleHttpError(err) {\n  // Throws TypeError if err is not HttpError\n  const httpErr = errs.assertErrorType(err, HttpError)\n  return httpErr.status // TypeScript knows this is HttpError\n}\n```\n\n### Result Pattern\n\n#### `errs.tryCatch(fn)`\n\nWraps a sync function to return a Result instead of throwing.\n\n```js\nconst result = errs.tryCatch(() => JSON.parse(input))\nif (result.ok) {\n  console.log(result.value)\n} else {\n  console.log('Parse error:', result.error.message)\n}\n```\n\n#### `errs.tryCatchAsync(fn)`\n\nWraps an async function to return a Result instead of throwing.\n\n```js\nconst result = await errs.tryCatchAsync(() => fetch(url))\nif (result.ok) {\n  const data = await result.value.json()\n} else {\n  console.log('Fetch failed:', result.error.message)\n}\n```\n\n### Parallel Operations\n\n#### `errs.parallel(promises, options)`\n\nRun multiple promises and collect all errors.\n\n```js\nconst { results, boundary } = await errs.parallel([\n  fetchUser(1),\n  fetchUser(2),\n  fetchUser(3)\n])\n\n// Get successful values\nconst users = results\n  .filter(r => r.status === 'fulfilled')\n  .map(r => r.value)\n\n// Check for errors\nif (boundary.hasErrors()) {\n  console.error(`${boundary.count} requests failed`)\n}\n```\n\n### Error Formatting\n\n#### `errs.format(error, options)`\n\nFormat errors for different output targets.\n\n```js\n// Terminal output with colors\nconsole.log(errs.format(error, { format: 'terminal', colors: true }))\n\n// JSON for logging\nlogger.error(errs.format(error, { format: 'json', indent: 2 }))\n\n// HTML for error pages\nres.send(errs.format(error, { format: 'html' }))\n```\n\n**Terminal Output:**\n\n```\n╭─ TypeError: Cannot read property 'x' of undefined\n│\n│  at processUser (src/users.js:42:15)\n│  at async main (src/index.js:10:3)\n│\n├─ Caused by: NetworkError: Connection refused\n│\n│  at fetch (src/api.js:23:9)\n│\n╰─ 2 errors in chain\n```\n\n### Error Handling\n\n#### `errs.handle(error, callback, stream)`\n\nUnified error handling for callbacks and EventEmitters.\n\n```js\n// With callback\nerrs.handle(err, (e) => console.error(e))\n\n// With EventEmitter\nerrs.handle(err, emitter)\n\n// With both\nerrs.handle(err, callback, emitter)\n\n// Returns emitter if no callback\nconst emitter = errs.handle(err)\nemitter.on('error', handleError)\n```\n\n### Type Registration\n\n#### `errs.register(type, ErrorClass)`\n\nRegister a custom error type.\n\n```js\nclass HttpError extends Error {\n  name = 'HttpError'\n  constructor(message, status) {\n    super(message)\n    this.status = status\n  }\n}\n\nerrs.register('http', HttpError)\n\n// Use registered type\nconst err = errs.create('http', {\n  message: 'Not found',\n  status: 404\n})\n```\n\n#### `errs.unregister(type)`\n\nUnregister an error type.\n\n```js\nerrs.unregister('http')\n```\n\n### JSON Conversion\n\n#### `errs.toJSON(error)`\n\nConvert error to JSON-serializable object.\n\n```js\nconst err = new Error('Test error')\nerr.code = 'TEST_CODE'\n\nconst json = errs.toJSON(err)\n// { message: 'Test error', stack: '...', code: 'TEST_CODE' }\n```\n\n## Named Exports\n\nAll functions are available as named exports:\n\n```js\nimport {\n  create,\n  boundary,\n  format,\n  parallel,\n  isErrorType,\n  isRegisteredType,\n  assertErrorType,\n  tryCatch,\n  tryCatchAsync\n} from 'errs'\n\nconst err = create('Error message')\nconst bound = boundary()\nconst result = tryCatch(() => JSON.parse(data))\n```\n\n## Subpath Exports\n\nImport specific modules directly:\n\n```js\nimport { ErrorBoundary } from 'errs/boundary'\nimport { format } from 'errs/format'\n```\n\n## Use Cases\n\n### Form Validation\n\n```js\nconst boundary = errs.boundary()\n\nif (!email.includes('@')) {\n  boundary.add(new Error('Invalid email'))\n}\nif (password.length < 8) {\n  boundary.add(new Error('Password too short'))\n}\n\nboundary.throwIfErrors('Validation failed')\n```\n\n### Batch Processing\n\n```js\nconst boundary = errs.boundary()\n\nfor (const item of items) {\n  try {\n    await processItem(item)\n  } catch (err) {\n    boundary.add(err)\n  }\n}\n\nif (boundary.hasErrors()) {\n  console.error(`${boundary.count} items failed`)\n  await logErrors(boundary.errors)\n}\n```\n\n### API Error Formatting\n\n```js\napp.use((err, req, res, next) => {\n  res.status(err.status || 500).send(\n    errs.format(err, { format: 'json' })\n  )\n})\n```\n\n## Requirements\n\n- Node.js >= 20.0.0\n\n## Migration from v0.x\n\nSee [MIGRATION.md](./MIGRATION.md) for detailed migration guide.\n\n## License\n\nMIT\n\n## Contributors\n\n- [Charlie Robbins](http://github.com/indexzero)\n- [Nuno Job](http://github.com/dscape)\n","publish_time":1770324657950,"_cnpm_publish_time":1770324657950,"dist-tags":{"latest":"1.0.0"}}