@fajarnugraha37/error
Version:
Runtime-agnostic error handling library with structured errors, adapters, and validation support for Bun, Node.js, and browsers
5 lines (4 loc) • 2.8 kB
JavaScript
var p=Object.defineProperty;var o=(r,t)=>p(r,"name",{value:t,configurable:!0});var d=[/at Object\.<anonymous>/,/at Module\._compile/,/at Module\.load/,/at Function\.Module\._load/,/at Module\.require/,/at require \(node:internal/,/node_modules/,/\/error\/dist/];function l(){return typeof globalThis<"u"&&"Bun"in globalThis?{type:"bun",version:globalThis.Bun?.version}:typeof process<"u"&&process.versions?.node?{type:"node",version:process.versions.node}:typeof window<"u"?{type:"browser"}:{type:"unknown"}}o(l,"detectRuntime");function c(r){let t=l(),e=r.replace(/\r\n/g,`
`),n=e.split(`
`),i=[],s=0;for(let u of n){if(!u.trim().startsWith("at ")){i.push(u);continue}if(!d.some(f=>f.test(u))){if(s>=50){i.push(" ... (truncated)");break}i.push(u),s++}}return e=i.join(`
`),(t.type==="browser"||t.type==="bun")&&(e=m(e)),e}o(c,"normalizeStack");function m(r){if(typeof globalThis<"u"&&"__stackTraceMapper"in globalThis)try{let t=globalThis.__stackTraceMapper;if(typeof t=="function")return t(r)||r}catch{}return r}o(m,"applySourceMaps");var a=class r extends Error{static{o(this,"AppError")}code;cause;data;status;tags;severity;retryable;id;timestamp;constructor(t,e,n={}){super(e||t),this.name="AppError",this.code=t,this.cause=n.cause,this.data=n.data,this.tags=Object.freeze(n.tags||[]),this.severity=n.severity||"error",this.status=n.status,this.retryable=n.retryable??!1,this.id=h(),this.timestamp=Date.now(),n.captureStack!==!1&&(Error.captureStackTrace&&Error.captureStackTrace(this,r),this.stack&&(this.stack=c(this.stack))),Object.freeze(this)}toJSON(){return{name:this.name,code:this.code,message:this.message,severity:this.severity,status:this.status,retryable:this.retryable,id:this.id,timestamp:this.timestamp,tags:this.tags,data:this.data,stack:this.stack,cause:this.cause instanceof Error?this.cause.message:this.cause}}};function g(r){if(y(r))return r;if(r instanceof Error)return new a("error/from-unknown",r.message,{cause:r,data:{originalName:r.name}});if(typeof r=="string")return new a("error/from-unknown",r);if(typeof r=="object"&&r!==null){let t=r,e=String(t.message||t.error||"Unknown error");return new a("error/from-unknown",e,{data:t})}return new a("error/from-unknown",String(r),{data:{originalValue:r}})}o(g,"fromUnknown");function y(r){return r instanceof a}o(y,"isAppError");function h(){let r=Date.now(),t=new Uint8Array(10);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(t);else for(let s=0;s<10;s++)t[s]=Math.floor(Math.random()*256);let e=o((s,u)=>s.toString(16).padStart(u,"0"),"hex"),n=Math.floor(r/4294967296),i=r&4294967295;return[e(n,8),e(i>>>16&65535,4),e(i&65535&4095|28672,4),e((t[0]<<8|t[1])&16383|32768,4),e(t[2]<<24|t[3]<<16|t[4]<<8|t[5],8)+e(t[6]<<8|t[7],4)].join("-")}o(h,"generateUUIDv7");export{g as fromUnknown};