@blyp/core 0.1.22 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- 'use strict';var Hn=require('pino'),jiti=require('jiti'),module$1=require('module'),async_hooks=require('async_hooks'),z=require('fs'),Ee=require('path'),ca=require('os'),zod=require('zod'),fflate=require('fflate'),crypto$1=require('crypto'),worker_threads=require('worker_threads');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Hn__default=/*#__PURE__*/_interopDefault(Hn);var z__default=/*#__PURE__*/_interopDefault(z);var Ee__default=/*#__PURE__*/_interopDefault(Ee);var ca__default=/*#__PURE__*/_interopDefault(ca);var Ho=Object.defineProperty;var jo=(e,t,r)=>t in e?Ho(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var g=(e,t,r)=>jo(e,typeof t!="symbol"?t+"":t,r);var Uo=jiti.createJiti(typeof __filename=="string"?__filename:(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)),{interopDefault:false,moduleCache:true,fsCache:false}),Yr=new Map;function $o(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,r="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof r=="string"&&(r.includes("Cannot find module")||r.includes("Cannot find package"))}function j(e,t,r=`@blyp/core/${e}`){let n=`@blyp/core/${e}`,o=`${n}::${r}`,s=Yr.get(o);if(s)return s;try{let a=Uo(r);return Yr.set(o,a),a}catch(a){if(!$o(a))throw a;let i=t.map(u=>`"${u}"`).join(", "),c=t.join(" ");throw new Error(`[Blyp] Optional connector dependencies missing for "${n}". Install ${i} to use this API. Example: bun add ${c}. You can also import directly from "${n}".`,{cause:a instanceof Error?a:void 0})}}var Wo=module$1.createRequire(typeof __filename=="string"?__filename:(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href))),Jt=null;function Jo(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,r="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof r=="string"&&(r.includes("Cannot find module")||r.includes("Cannot find package"))}function Go(e){if(typeof e=="function")return e;if(!e||typeof e!="object")return null;let t="default"in e?e.default:void 0;return typeof t=="function"?t:null}function Xr(){if(Jt)return Jt;let e;try{e=Wo("pino-pretty");}catch(r){throw Jo(r)?new Error('[Blyp] Failed to initialize the pretty logger transport because pretty: true requires "pino-pretty" to be installed.',{cause:r instanceof Error?r:void 0}):new Error('[Blyp] Failed to initialize the pretty logger transport with "pino-pretty".',{cause:r instanceof Error?r:void 0})}let t=Go(e);if(!t)throw new Error('[Blyp] Failed to initialize the pretty logger transport because "pino-pretty" did not expose a callable factory.');return Jt=t,t}var Gt=new async_hooks.AsyncLocalStorage;function Zr(){return {requestScopedLoggerActive:true,structuredCollectorActive:false,structuredLogEmitted:false,mixedLoggerWarningShown:false}}function A(e){return Gt.run(Zr(),e)}function Re(){let e=Zr();return Gt.enterWith(e),e}function ne(){return Gt.getStore()}function Qt(e){let t=ne();t&&(t.activeLogger=e);}function le(){return ne()?.activeLogger}function Ie(e){let t=ne();t&&(t.traceId=e);}function oe(){return ne()?.traceId}function Vt(){let e=ne();e&&(e.structuredCollectorActive=true);}function Yt(){let e=ne();e&&(e.structuredLogEmitted=true);}function Ge(){let e=ne();return !e||!e.requestScopedLoggerActive||!e.structuredCollectorActive?false:(e.mixedLoggerWarningShown||(e.mixedLoggerWarningShown=true,console.warn("[Blyp] Warning: Mixed logger usage detected for this request. The root logger call was ignored because a request-scoped structured logger is active.")),true)}function Qe(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let r=e;return r.cause!==void 0&&(t.cause=Y(r.cause)),t}function Y(e,t=new WeakSet){if(e instanceof Error)return Qe(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e==null)return e;if(Array.isArray(e))return e.map(r=>Y(r,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let r={};for(let[n,o]of Object.entries(e))r[n]=Y(o,t);return t.delete(e),r}return e}function Oe(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=Y(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var tn="[REDACTED]",Vo=["password","passwd","pwd","secret","token","api_key","apikey","api_secret","authorization","auth","x-api-key","private_key","privatekey","access_token","refresh_token","client_secret","session","cookie","set-cookie","ssn","credit_card","card_number","cvv","cvc","otp","pin"],Yo=["authorization","cookie","set-cookie","x-api-key","x-auth-token"],Xo=[{type:"bearer",pattern:/\bBearer\s+(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Za-z0-9._~+/-]{20,})\b/g},{type:"jwt",pattern:/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{type:"api_key",pattern:/\b(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,})\b/g}],Zo=/\b(?:\d[ -]*?){16}\b/g;function en(e){let t=new Set,r=[];for(let n of e)typeof n!="string"||n.length===0||t.has(n)||(t.add(n),r.push(n));return r}function ea(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function ta(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ra(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function na(e){return new Set([...Yo,...e.keys.map(t=>t.toLowerCase())])}function oa(e){return e.split(".").filter(Boolean)}function Xt(e,t,r=0,n=0){if(r===e.length)return n===t.length;let o=e[r];if(o==="**"){if(r===e.length-1)return true;for(let s=n;s<=t.length;s+=1)if(Xt(e,t,r+1,s))return true;return false}return n>=t.length||o!=="*"&&o!==t[n]?false:Xt(e,t,r+1,n+1)}function aa(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(r=>Xt(oa(r),e))}function sa(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let r=0,n=false;for(let o=t.length-1;o>=0;o-=1){let s=Number(t[o]);n&&(s*=2,s>9&&(s-=9)),r+=s,n=!n;}return r%10===0}function Ye(e,t,r){if(r||t.disablePatternScanning)return e;let n=e;for(let{type:o,pattern:s}of Xo)n=n.replace(s,`[REDACTED:${o}]`);n=n.replace(Zo,o=>sa(o)?"[REDACTED:card]":o);for(let o of t.patterns)n=n.replace(ea(o),"[REDACTED:pattern]");return n}function Ve(e,t,r,n){if(typeof e=="string")return Ye(e,t,!!n.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((s,a)=>Ve(s,t,r,{path:[...n.path,String(a)],skipPatternScanning:n.skipPatternScanning}));if(!ta(e))return e;let o={};for(let[s,a]of Object.entries(e)){let i=[...n.path,s];if(r.has(s.toLowerCase())||aa(i,t)){if(a==null||typeof a=="string"||typeof a=="number"||typeof a=="boolean"){o[s]=tn;continue}o[s]=Ve(a,t,r,{path:i,skipPatternScanning:n.skipPatternScanning});continue}o[s]=Ve(a,t,r,{path:i,skipPatternScanning:n.skipPatternScanning});}return o}function W(e,t){return {keys:en([...Vo,...e?.keys??[],...t?.keys??[]]),paths:en([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(r=>r instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function D(e,t,r={path:[]}){let n=Y(e);return Ve(n,t,ra(t),r)}function ge(e,t){return typeof e=="string"?Ye(e,t,false):Oe(D(e,t))}function ia(e){if(!e)return {};if(e instanceof Headers){let t={};return e.forEach((r,n)=>{t[n]=r;}),t}if(typeof e.entries=="function"){let t={};for(let[r,n]of e.entries())t[r]=n;return t}return typeof e.get=="function"?{}:{...e}}function rn(e,t){let r=ia(e),n=na(t),o={};for(let[s,a]of Object.entries(r)){if(n.has(s.toLowerCase())){o[s]=tn;continue}if(Array.isArray(a)){o[s]=a.map(i=>Ye(i,t,false));continue}o[s]=typeof a=="string"?Ye(a,t,false):a;}return o}function J(){return Ee__default.default.join(ca__default.default.homedir(),".blyp","queue.db")}var da=zod.z.string().url().refine(e=>{try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}},{message:"Expected an absolute http(s) URL"}),Be=zod.z.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),er=zod.z.string().trim().min(1);function tr(e){return da.safeParse(e).success}function K(e){return Be.safeParse(e).success}function pe(e){return er.safeParse(e).success}var fe="/inngest";var la=["debug","info","warning","error","critical","success","table"],ga=zod.z.union([zod.z.literal("betterstack"),zod.z.literal("databuddy"),zod.z.literal("posthog"),zod.z.literal("sentry"),zod.z.undefined(),zod.z.object({type:zod.z.literal("otlp"),name:er})]);function pa(e){return typeof e=="string"&&la.includes(e)}function fa(e){return ga.safeParse(e).success}function ma(e){try{return e()}catch{return}}function ya(){return Math.random().toString(36).slice(2,10)}function Xe(){let e=ma(()=>globalThis.crypto),t=e&&typeof e.randomUUID=="function"?e.randomUUID.bind(e):void 0;return t?t():`${Date.now().toString(36)}-${ya()}`}function nn(e){if(!K(e)||e.type!=="client_log"||e.source!=="client"||!pa(e.level)||typeof e.id!="string"||typeof e.message!="string"||typeof e.clientTimestamp!="string")return false;let t=Be.safeParse(e.page),r=Be.safeParse(e.browser),n=Be.safeParse(e.session);return !t.success||!r.success||!n.success||!fa(e.connector)?false:typeof n.data.pageId=="string"&&typeof n.data.sessionId=="string"}function rr(e){return e?e.startsWith("/")?e:`/${e}`:fe}function ha(e,t=new Set){return (r,n,o)=>{if(t.has(r)||typeof console>"u")return;let s=console[e];if(typeof s=="function"){if(t.add(r),o===void 0){s.call(console,n);return}s.call(console,n,o);}}}function se(e){return ha("warn",e)}var wa="@blyp/core",Ra=".gitignore",sn=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],ka="blyp.config.json",Sa="https://us.i.posthog.com",xa="blyp-app",Ta=xa,cn=new Set,ie=se(cn),or={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},ar={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:or},Ze={enabled:true,path:fe},sr=W(),me={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},$={enabled:false,memoryBufferSize:500,durableQueuePath:J(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:me},ir={maxRetries:1,backoffMs:100},un={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:ir},nr={pretty:true,level:"info",destination:"file",file:ar,clientLogging:Ze,redact:sr,connectors:{delivery:$}},ke=null;function Ea(e){let t=e;for(;;){let r=Ee.resolve(t,"package.json");if(z.existsSync(r))try{let o=JSON.parse(z.readFileSync(r,"utf-8"));if(pe(o.name))return o.name}catch{}let n=Ee.dirname(t);if(n===t)return;t=n;}}function cr(e=process.cwd()){return Ea(e)??Ta}function va(){return {pretty:true,level:"info",destination:"file",file:{enabled:true,format:"ndjson",rotation:{enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true}},clientLogging:{enabled:true,path:fe},redact:sr,connectors:{delivery:$}}}function Da(e){let t=Ee.resolve(e,"package.json");if(!z.existsSync(t))return true;try{return JSON.parse(z.readFileSync(t,"utf-8")).name!==wa}catch{return true}}function Pa(e){if(sn.some(r=>z.existsSync(Ee.resolve(e,r))))return;let t=Ee.resolve(e,ka);if(!z.existsSync(t))try{z.writeFileSync(t,`${JSON.stringify(va(),null,2)}
1
+ 'use strict';var Hn=require('pino'),jiti=require('jiti'),module$1=require('module'),async_hooks=require('async_hooks'),z=require('fs'),Ee=require('path'),ca=require('os'),zod=require('zod'),fflate=require('fflate'),crypto$1=require('crypto'),worker_threads=require('worker_threads');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Hn__default=/*#__PURE__*/_interopDefault(Hn);var z__default=/*#__PURE__*/_interopDefault(z);var Ee__default=/*#__PURE__*/_interopDefault(Ee);var ca__default=/*#__PURE__*/_interopDefault(ca);var Ho=Object.defineProperty;var jo=(e,t,r)=>t in e?Ho(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var g=(e,t,r)=>jo(e,typeof t!="symbol"?t+"":t,r);var Uo=jiti.createJiti(typeof __filename=="string"?__filename:(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)),{interopDefault:false,moduleCache:true,fsCache:false}),Yr=new Map;function $o(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,r="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof r=="string"&&(r.includes("Cannot find module")||r.includes("Cannot find package"))}function j(e,t,r=`@blyp/core/${e}`){let n=`@blyp/core/${e}`,o=`${n}::${r}`,i=Yr.get(o);if(i)return i;try{let a=Uo(r);return Yr.set(o,a),a}catch(a){if(!$o(a))throw a;let s=t.map(u=>`"${u}"`).join(", "),c=t.join(" ");throw new Error(`[Blyp] Optional connector dependencies missing for "${n}". Install ${s} to use this API. Example: bun add ${c}. You can also import directly from "${n}".`,{cause:a instanceof Error?a:void 0})}}var Wo=module$1.createRequire(typeof __filename=="string"?__filename:(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href))),Jt=null;function Jo(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,r="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof r=="string"&&(r.includes("Cannot find module")||r.includes("Cannot find package"))}function Go(e){if(typeof e=="function")return e;if(!e||typeof e!="object")return null;let t="default"in e?e.default:void 0;return typeof t=="function"?t:null}function Xr(){if(Jt)return Jt;let e;try{e=Wo("pino-pretty");}catch(r){throw Jo(r)?new Error('[Blyp] Failed to initialize the pretty logger transport because pretty: true requires "pino-pretty" to be installed.',{cause:r instanceof Error?r:void 0}):new Error('[Blyp] Failed to initialize the pretty logger transport with "pino-pretty".',{cause:r instanceof Error?r:void 0})}let t=Go(e);if(!t)throw new Error('[Blyp] Failed to initialize the pretty logger transport because "pino-pretty" did not expose a callable factory.');return Jt=t,t}var Gt=new async_hooks.AsyncLocalStorage;function Zr(){return {requestScopedLoggerActive:true,structuredCollectorActive:false,structuredLogEmitted:false,mixedLoggerWarningShown:false}}function A(e){return Gt.run(Zr(),e)}function Re(){let e=Zr();return Gt.enterWith(e),e}function ne(){return Gt.getStore()}function Qt(e){let t=ne();t&&(t.activeLogger=e);}function le(){return ne()?.activeLogger}function Oe(e){let t=ne();t&&(t.traceId=e);}function oe(){return ne()?.traceId}function Vt(){let e=ne();e&&(e.structuredCollectorActive=true);}function Yt(){let e=ne();e&&(e.structuredLogEmitted=true);}function Ge(){let e=ne();return !e||!e.requestScopedLoggerActive||!e.structuredCollectorActive?false:(e.mixedLoggerWarningShown||(e.mixedLoggerWarningShown=true,console.warn("[Blyp] Warning: Mixed logger usage detected for this request. The root logger call was ignored because a request-scoped structured logger is active.")),true)}function Qe(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let r=e;return r.cause!==void 0&&(t.cause=Y(r.cause)),t}function Y(e,t=new WeakSet){if(e instanceof Error)return Qe(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e==null)return e;if(Array.isArray(e))return e.map(r=>Y(r,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let r={};for(let[n,o]of Object.entries(e))r[n]=Y(o,t);return t.delete(e),r}return e}function Be(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=Y(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var tn="[REDACTED]",Vo=["password","passwd","pwd","secret","token","api_key","apikey","api_secret","authorization","auth","x-api-key","private_key","privatekey","access_token","refresh_token","client_secret","session","cookie","set-cookie","ssn","credit_card","card_number","cvv","cvc","otp","pin"],Yo=["authorization","cookie","set-cookie","x-api-key","x-auth-token"],Xo=[{type:"bearer",pattern:/\bBearer\s+(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Za-z0-9._~+/-]{20,})\b/g},{type:"jwt",pattern:/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{type:"api_key",pattern:/\b(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,})\b/g}],Zo=/\b(?:\d[ -]*?){16}\b/g;function en(e){let t=new Set,r=[];for(let n of e)typeof n!="string"||n.length===0||t.has(n)||(t.add(n),r.push(n));return r}function ea(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function ta(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ra(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function na(e){return new Set([...Yo,...e.keys.map(t=>t.toLowerCase())])}function oa(e){return e.split(".").filter(Boolean)}function Xt(e,t,r=0,n=0){if(r===e.length)return n===t.length;let o=e[r];if(o==="**"){if(r===e.length-1)return true;for(let i=n;i<=t.length;i+=1)if(Xt(e,t,r+1,i))return true;return false}return n>=t.length||o!=="*"&&o!==t[n]?false:Xt(e,t,r+1,n+1)}function aa(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(r=>Xt(oa(r),e))}function ia(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let r=0,n=false;for(let o=t.length-1;o>=0;o-=1){let i=Number(t[o]);n&&(i*=2,i>9&&(i-=9)),r+=i,n=!n;}return r%10===0}function Ye(e,t,r){if(r||t.disablePatternScanning)return e;let n=e;for(let{type:o,pattern:i}of Xo)n=n.replace(i,`[REDACTED:${o}]`);n=n.replace(Zo,o=>ia(o)?"[REDACTED:card]":o);for(let o of t.patterns)n=n.replace(ea(o),"[REDACTED:pattern]");return n}function Ve(e,t,r,n){if(typeof e=="string")return Ye(e,t,!!n.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((i,a)=>Ve(i,t,r,{path:[...n.path,String(a)],skipPatternScanning:n.skipPatternScanning}));if(!ta(e))return e;let o={};for(let[i,a]of Object.entries(e)){let s=[...n.path,i];if(r.has(i.toLowerCase())||aa(s,t)){if(a==null||typeof a=="string"||typeof a=="number"||typeof a=="boolean"){o[i]=tn;continue}o[i]=Ve(a,t,r,{path:s,skipPatternScanning:n.skipPatternScanning});continue}o[i]=Ve(a,t,r,{path:s,skipPatternScanning:n.skipPatternScanning});}return o}function W(e,t){return {keys:en([...Vo,...e?.keys??[],...t?.keys??[]]),paths:en([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(r=>r instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function D(e,t,r={path:[]}){let n=Y(e);return Ve(n,t,ra(t),r)}function ge(e,t){return typeof e=="string"?Ye(e,t,false):Be(D(e,t))}function sa(e){if(!e)return {};if(e instanceof Headers){let t={};return e.forEach((r,n)=>{t[n]=r;}),t}if(typeof e.entries=="function"){let t={};for(let[r,n]of e.entries())t[r]=n;return t}return typeof e.get=="function"?{}:{...e}}function rn(e,t){let r=sa(e),n=na(t),o={};for(let[i,a]of Object.entries(r)){if(n.has(i.toLowerCase())){o[i]=tn;continue}if(Array.isArray(a)){o[i]=a.map(s=>Ye(s,t,false));continue}o[i]=typeof a=="string"?Ye(a,t,false):a;}return o}function J(){return Ee__default.default.join(ca__default.default.homedir(),".blyp","queue.db")}var da=zod.z.string().url().refine(e=>{try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}},{message:"Expected an absolute http(s) URL"}),Ne=zod.z.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),er=zod.z.string().trim().min(1);function tr(e){return da.safeParse(e).success}function K(e){return Ne.safeParse(e).success}function pe(e){return er.safeParse(e).success}var fe="/inngest";var la=["debug","info","warning","error","critical","success","table"],ga=zod.z.union([zod.z.literal("betterstack"),zod.z.literal("databuddy"),zod.z.literal("posthog"),zod.z.literal("sentry"),zod.z.undefined(),zod.z.object({type:zod.z.literal("otlp"),name:er})]);function pa(e){return typeof e=="string"&&la.includes(e)}function fa(e){return ga.safeParse(e).success}function ma(e){try{return e()}catch{return}}function ya(){return Math.random().toString(36).slice(2,10)}function Xe(){let e=ma(()=>globalThis.crypto),t=e&&typeof e.randomUUID=="function"?e.randomUUID.bind(e):void 0;return t?t():`${Date.now().toString(36)}-${ya()}`}function nn(e){if(!K(e)||e.type!=="client_log"||e.source!=="client"||!pa(e.level)||typeof e.id!="string"||typeof e.message!="string"||typeof e.clientTimestamp!="string")return false;let t=Ne.safeParse(e.page),r=Ne.safeParse(e.browser),n=Ne.safeParse(e.session);return !t.success||!r.success||!n.success||!fa(e.connector)?false:typeof n.data.pageId=="string"&&typeof n.data.sessionId=="string"}function rr(e){return e?e.startsWith("/")?e:`/${e}`:fe}function ha(e,t=new Set){return (r,n,o)=>{if(t.has(r)||typeof console>"u")return;let i=console[e];if(typeof i=="function"){if(t.add(r),o===void 0){i.call(console,n);return}i.call(console,n,o);}}}function ie(e){return ha("warn",e)}var wa="@blyp/core",Ra=".gitignore",sn=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],ka="blyp.config.json",Sa="https://us.i.posthog.com",xa="blyp-app",Ta=xa,cn=new Set,se=ie(cn),or={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},ar={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:or},Ze={enabled:true,path:fe},ir=W(),me={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},$={enabled:false,memoryBufferSize:500,durableQueuePath:J(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:me},sr={maxRetries:1,backoffMs:100},un={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:sr},nr={pretty:true,level:"info",destination:"file",file:ar,clientLogging:Ze,redact:ir,connectors:{delivery:$}},ke=null;function Ea(e){let t=e;for(;;){let r=Ee.resolve(t,"package.json");if(z.existsSync(r))try{let o=JSON.parse(z.readFileSync(r,"utf-8"));if(pe(o.name))return o.name}catch{}let n=Ee.dirname(t);if(n===t)return;t=n;}}function cr(e=process.cwd()){return Ea(e)??Ta}function va(){return {pretty:true,level:"info",destination:"file",file:{enabled:true,format:"ndjson",rotation:{enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true}},clientLogging:{enabled:true,path:fe},redact:ir,connectors:{delivery:$}}}function Da(e){let t=Ee.resolve(e,"package.json");if(!z.existsSync(t))return true;try{return JSON.parse(z.readFileSync(t,"utf-8")).name!==wa}catch{return true}}function Pa(e){if(sn.some(r=>z.existsSync(Ee.resolve(e,r))))return;let t=Ee.resolve(e,ka);if(!z.existsSync(t))try{z.writeFileSync(t,`${JSON.stringify(va(),null,2)}
2
2
  `);}catch(r){console.error("[Blyp] Warning: Failed to create blyp.config.json:",r);}}function Aa(e){let t=Ee.resolve(e,Ra);if(!z.existsSync(t)){try{z.writeFileSync(t,`logs
3
3
  .blyp
4
- `);}catch(r){console.error("[Blyp] Warning: Failed to create .gitignore:",r);}return}try{let r=z.readFileSync(t,"utf-8"),n=["logs",".blyp"].filter(s=>{let a=s.replace(".","\\.");return !new RegExp(`^(?:/?${a}/?)\\s*$`,"m").test(r)});if(n.length===0)return;let o=r.endsWith(`
4
+ `);}catch(r){console.error("[Blyp] Warning: Failed to create .gitignore:",r);}return}try{let r=z.readFileSync(t,"utf-8"),n=["logs",".blyp"].filter(i=>{let a=i.replace(".","\\.");return !new RegExp(`^(?:/?${a}/?)\\s*$`,"m").test(r)});if(n.length===0)return;let o=r.endsWith(`
5
5
  `)?"":`
6
6
  `;z.appendFileSync(t,`${o}${n.join(`
7
7
  `)}
8
- `);}catch(r){console.error("[Blyp] Warning: Failed to update .gitignore:",r);}}function _a(){let e=process.cwd();Da(e)&&(Pa(e),Aa(e));}function Ia(){let e=process.cwd(),t=sn.map(n=>Ee.resolve(e,n)).filter(n=>z.existsSync(n));if(t.length===0)return null;if(t.length>1){let n=t[0];ie(`config-multiple:${n}`,`[Blyp] Warning: Multiple config files found. Using ${n} and ignoring ${t.slice(1).join(", ")}.`);}let r=t[0];return {path:r,type:r.endsWith(".json")?"json":"jiti"}}function dn(e,t){let r=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !r||typeof r!="object"||Array.isArray(r)?(ie(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):r}function Oa(e){try{let t=z.readFileSync(e,"utf-8");return dn(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function Ba(e){try{let t=jiti.createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return dn(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function Na(e){return e.type==="json"?Oa(e.path):Ba(e.path)}function on(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function Ma(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function Fa(e,t){return {...ir,...e,...t}}function qa(e,t){return {...un,...e,...t,retry:Fa(e?.retry,t?.retry)}}function Ha(e){let t=e.model??"blypLog",n=e.client?.[t];return !!n&&typeof n.create=="function"}function ja(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function za(e,t){if(!e)return;let r=e.adapter,n=false;t==="json"?ie("database-json-config","[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."):e.dialect!=="postgres"&&e.dialect!=="mysql"?ie(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):r?on(r)?(n=Ha({...r,model:r.model??"blypLog"}),n||ie("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${r.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):Ma(r)&&(n=ja(r),n||ie("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):ie("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let o=on(r)?{...r,model:r.model??"blypLog"}:r;return {dialect:e.dialect,adapter:o,delivery:qa(void 0,e.delivery),ready:n,status:n?"enabled":"missing"}}function Ua(e,t){return {...or,...e,...t}}function $a(e,t){return {...ar,...e,...t,rotation:Ua(e?.rotation,t?.rotation)}}function Ka(e,t){return {...Ze,...e,...t,path:t?.path??e?.path??Ze.path}}function Wa(e,t){return W(e,t)}function Ja(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??me.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??me.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??me.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??me.multiplier),jitter:t?.jitter??e?.jitter??me.jitter}}function Ga(e,t){let r=t?.durableQueuePath??e?.durableQueuePath??$.durableQueuePath;return {enabled:t?.enabled??e?.enabled??$.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??$.memoryBufferSize)),durableQueuePath:pe(r)?r:$.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??$.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??$.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??$.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??$.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??$.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??$.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??$.overflowStrategy,retry:Ja(e?.retry,t?.retry),durableReady:false}}function Qa(e,t,r){if(!(!e&&!t))return za({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},r)}function Va(e,t){let r=t?.enabled??e?.enabled??false,n=t?.projectKey??e?.projectKey,o=e?.enabled===true?e?.errorTracking:void 0,s=t?.errorTracking?.mode??o?.mode??"auto",a=t?.errorTracking?.enabled??o?.enabled??r,i=r&&a&&typeof n=="string"&&n.trim().length>0;return {enabled:r,mode:t?.mode??e?.mode??"auto",projectKey:n,host:t?.host??e?.host??Sa,serviceName:t?.serviceName??e?.serviceName??cr(),errorTracking:{enabled:a,mode:s,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??o?.enableExceptionAutocapture??s==="auto",ready:i,status:i?"enabled":"missing"}}}function Ya(e,t){let r=t?.enabled??e?.enabled??false,n=t?.apiKey??e?.apiKey,o=t?.websiteId??e?.websiteId,s=r&&pe(n)&&pe(o);return {enabled:r,mode:t?.mode??e?.mode??"auto",apiKey:n,websiteId:o,namespace:t?.namespace??e?.namespace,source:t?.source??e?.source,apiUrl:t?.apiUrl??e?.apiUrl,debug:t?.debug??e?.debug??false,enableBatching:t?.enableBatching??e?.enableBatching??true,batchSize:t?.batchSize??e?.batchSize,batchTimeout:t?.batchTimeout??e?.batchTimeout,maxQueueSize:t?.maxQueueSize??e?.maxQueueSize,ready:s,status:s?"enabled":"missing"}}function Xa(e,t){let r=t?.sourceToken??e?.sourceToken,n=t?.ingestingHost??e?.ingestingHost,o=t?.enabled??e?.enabled??false,s=e?.enabled===true?e?.errorTracking:void 0,a=Za(o,s,t?.errorTracking),i=o&&pe(r)&&tr(n);return {enabled:o,mode:t?.mode??e?.mode??"auto",sourceToken:r,ingestingHost:n,serviceName:t?.serviceName??e?.serviceName??cr(),errorTracking:a,ready:i,status:i?"enabled":"missing"}}function Za(e,t,r){let n=r?.dsn??t?.dsn,o=r?.enabled??t?.enabled??e,s=o&&pe(n);return {enabled:o,dsn:n,tracesSampleRate:r?.tracesSampleRate??t?.tracesSampleRate??1,environment:r?.environment??t?.environment,release:r?.release??t?.release,ready:s,status:s?"enabled":"missing"}}function es(e,t){let r=t?.dsn??e?.dsn,n=t?.enabled??e?.enabled??false,o=n&&typeof r=="string"&&r.trim().length>0;return {enabled:n,mode:t?.mode??e?.mode??"auto",dsn:r,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:o,status:o?"enabled":"missing"}}function ts(e,t){let r=t?.endpoint??e?.endpoint,n=t?.enabled??e?.enabled??false,o={...{},...t?.headers??{}},s=n&&tr(r);return {name:t?.name??e?.name??"",enabled:n,mode:t?.mode??e?.mode??"auto",endpoint:r,headers:o,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??cr(),ready:s,status:s?"enabled":"missing"}}function rs(e,t){let r=t??e??[],n=new Map;for(let o of r)!o||typeof o.name!="string"||o.name.length===0||(n.has(o.name)&&ie(`otlp-duplicate:${o.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${o.name}" found. Using the last definition.`),n.set(o.name,ts(void 0,o)));return Array.from(n.values())}function ns(e,t){return {betterstack:Xa(e?.betterstack,t?.betterstack),databuddy:Ya(e?.databuddy,t?.databuddy),posthog:Va(e?.posthog,t?.posthog),sentry:es(e?.sentry,t?.sentry),otlp:rs(e?.otlp,t?.otlp),delivery:Ga(e?.delivery,t?.delivery)}}function et(e,t={},r={}){return {...e,...t,destination:t.destination??e.destination??"file",file:$a(e.file,t.file),database:Qa(e.database,t.database,r.configFileType),clientLogging:Ka(e.clientLogging,t.clientLogging),redact:Wa(e.redact,t.redact),connectors:ns(e.connectors,t.connectors)}}function ur(){if(ke!==null)return ke;_a();let e=Ia();if(e){let t=Na(e);ke=et(nr,t,{configFileType:e.type});}else ke=et(nr);return ke}function Te(e={}){return et(ur(),e)}function os(){return ur()}function as(){ke=null,cn.clear();}var ln={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function rt(e){return e.replace(/\\/g,"/")}function ss(e){let t=rt(e);return t.startsWith("node:")||t.includes("/node_modules/pino")||t.includes("/node_modules/pino-pretty")||t.includes("/node_modules/@blyp/core/")||t.includes("/blyp/src/core/")||t.includes("/blyp/src/frameworks/")||t.includes("/blyp/src/posthog/")||t.includes("/blyp/dist/")}function is(e){let t=rt(e),r=rt(process.cwd());return t.startsWith(`${r}/`)?t.slice(r.length+1):t}function gn(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
9
- `),r=null;for(let n=2;n<t.length;n+=1){let o=t[n];if(!o)continue;let s=o.match(/\((.*):(\d+):\d+\)/)||o.match(/at\s+(.*):(\d+):(\d+)/);if(!s)continue;let a=s[1]||"",i=parseInt(s[2]||"0",10)||null;if(a&&!a.includes("node_modules")&&!ss(a)){let c=is(a);if(!rt(c).startsWith("dist/"))return {file:c,line:i};r??(r={file:c,line:i});}}if(r)return r}catch{return {file:null,line:null}}return {file:null,line:null}}var pn=ge;function fn(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function mn(e,t,r,n,o=W()){let{file:s,line:a}=gn(),i=pn(t,o),c={timestamp:new Date().toISOString(),level:ln[e],message:fn(i)},u=oe();return t instanceof Error&&(c.error=D(Qe(t),o)),s&&(c.caller=a!==null?`${s}:${a}`:s),r.length===1?c.data=D(r[0],o):r.length>1&&(c.data=D(r,o)),Object.keys(n).length>0&&(c.bindings=D(n,o)),u&&(c.traceId=u),c}function yn(e,t,r,n,o=W()){let{file:s,line:a}=gn(),i=D(r,o),c=oe(),u={message:fn(pn(t,o)),...i};return s&&(u.caller=a!==null?`${s}:${a}`:s),Object.keys(n).length>0&&(u.bindings=D(n,o)),c&&u.traceId===void 0&&(u.traceId=c),u.level=typeof i.level=="string"&&i.level.length>0?i.level:ln[e],u.timestamp=typeof i.timestamp=="string"&&i.timestamp.length>0?i.timestamp:new Date().toISOString(),u}function hn(e){switch(e){case "debug":return "debug";case "warning":return "warning";case "warn":return "warn";case "error":return "error";case "success":return "success";case "critical":return "critical";case "table":return "table";default:return "info"}}function us(e){return Buffer.from(fflate.gzipSync(e))}function ds(e,t){console.warn(`[Blyp] Warning: ${e}`,t);}function nt(e){z__default.default.mkdirSync(e,{recursive:true});}function ls(e){try{return z__default.default.statSync(e).size}catch{return 0}}function gs(e){let t=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),n=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),s=String(e.getUTCMinutes()).padStart(2,"0"),a=String(e.getUTCSeconds()).padStart(2,"0");return `${t}${r}${n}T${o}${s}${a}Z`}function ps(e,t){let r=`${e}${t}`,n=1;for(;z__default.default.existsSync(r);)r=`${e}-${n}${t}`,n+=1;return r}function fs(e,t,r,n){let o=`${t}.`;try{let s=z__default.default.readdirSync(e).filter(i=>i.startsWith(o)&&(i.endsWith(".ndjson")||i.endsWith(".ndjson.gz"))).map(i=>Ee__default.default.join(e,i)).sort((i,c)=>z__default.default.statSync(i).mtimeMs-z__default.default.statSync(c).mtimeMs),a=Math.max(s.length-r,0);for(let i=0;i<a;i+=1)z__default.default.rmSync(s[i]);}catch(s){n(`Failed to prune archives for ${t}`,s);}}function ms(){let e=new WeakSet;return (t,r)=>{if(typeof r=="function")return `[Function: ${r.name||"anonymous"}]`;if(r===void 0)return "[undefined]";if(typeof r=="symbol")return r.toString();if(r!==null&&typeof r=="object"){if(e.has(r))return "[Circular]";e.add(r);}return r}}function lr(e){return JSON.stringify(e,ms())}function ys(e){let t=e.file,r=t?.dir||e.logDir||Ee__default.default.join(process.cwd(),"logs"),n=t?.archiveDir||Ee__default.default.join(r,"archive"),o=t?.rotation;return {enabled:t?.enabled??true,dir:r,archiveDir:n,rotationEnabled:o?.enabled??true,maxSizeBytes:o?.maxSizeBytes??10*1024*1024,maxArchives:o?.maxArchives??5,compress:o?.compress??true}}var dr=class{constructor(t,r={}){g(this,"config");g(this,"gzip");g(this,"warn");g(this,"combined");g(this,"error");this.config=ys(t),this.gzip=r.gzip??us,this.warn=r.warn??ds,this.combined={activePath:Ee__default.default.join(this.config.dir,"log.ndjson"),archivePrefix:"log",bytes:0,queue:[],processing:false},this.error={activePath:Ee__default.default.join(this.config.dir,"log.error.ndjson"),archivePrefix:"log.error",bytes:0,queue:[],processing:false},this.config.enabled&&(nt(this.config.dir),nt(this.config.archiveDir),this.seedStream(this.combined),this.seedStream(this.error));}write(t){if(!this.config.enabled)return;let r=`${lr(t)}
10
- `;this.enqueue(this.combined,r),(t.level==="error"||t.level==="critical")&&this.enqueue(this.error,r);}enqueue(t,r){t.queue.push(r),this.processQueue(t);}processQueue(t){if(!t.processing){t.processing=true;try{for(;t.queue.length>0;){let r=t.queue.shift();if(r!==void 0)try{this.append(t,r);}catch(n){this.warn(`Failed writing log line for ${t.archivePrefix}`,n);}}}finally{t.processing=false;}}}seedStream(t){t.bytes=ls(t.activePath),this.config.rotationEnabled&&t.bytes>this.config.maxSizeBytes&&t.bytes>0&&(this.rotate(t),z__default.default.closeSync(z__default.default.openSync(t.activePath,"a")),t.bytes=0);}append(t,r){nt(this.config.dir);let n=Buffer.byteLength(r,"utf8");this.config.rotationEnabled&&t.bytes>0&&t.bytes+n>this.config.maxSizeBytes&&this.rotate(t),z__default.default.appendFileSync(t.activePath,r,"utf8"),t.bytes+=n;}rotate(t){if(nt(this.config.archiveDir),!z__default.default.existsSync(t.activePath)||t.bytes===0){t.bytes=0;return}let r=gs(new Date),n=Ee__default.default.join(this.config.archiveDir,`${t.archivePrefix}.${r}`),o=ps(n,".ndjson");if(z__default.default.renameSync(t.activePath,o),this.config.compress)try{let s=`${o}.gz`,a=this.gzip(z__default.default.readFileSync(o));z__default.default.writeFileSync(s,a),z__default.default.rmSync(o);}catch(s){this.warn(`Failed to gzip archive ${o}`,s);}t.bytes=0,fs(this.config.archiveDir,t.archivePrefix,this.config.maxArchives,this.warn);}};function Cn(e){return new dr(e)}var gr=class{constructor(t){this.logger=t;g(this,"isAsync",false);g(this,"isReady",true);}write(t){this.logger.write(t);}async flush(){}async shutdown(){}};function Ln(e){return new gr(Cn(e))}function bn(e){return {type:"drizzle",db:e.db,table:e.table}}function wn(e){let t=e.db;if(typeof t?.insert!="function"||e.table===void 0)throw new Error("[Blyp] Drizzle database adapter is missing a db.insert function or table reference.");return {async insert(r){r.length!==0&&await t.insert(e.table).values(r);}}}function hs(e){let t=String(e??"");return t.includes("createMany")||t.includes("Unknown argument")||t.includes("not supported")||t.includes("is not a function")}function Rn(e){return {type:"prisma",client:e.client,model:e.model??"blypLog"}}function kn(e){let t=e.client,r=e.model??"blypLog",n=t[r];if(!n||typeof n.create!="function")throw new Error(`[Blyp] Prisma database adapter is missing the "${r}" delegate or its create method.`);let o=n,s=typeof o.createMany=="function";async function a(i){if(typeof t.$transaction=="function"){await t.$transaction(i.map(c=>o.create({data:c})));return}for(let c of i)await o.create({data:c});}return {async insert(i){if(i.length!==0){if(i.length===1){await o.create({data:i[0]});return}if(!s||typeof o.createMany!="function"){await a(i);return}try{await o.createMany({data:i});}catch(c){if(!hs(c))throw c;s=false,await a(i);}}}}}function Sn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ve(e){return typeof e=="string"&&e.length>0?e:null}function Ls(e){if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function xn(e){let t=Y(e);return {id:crypto$1.randomUUID(),timestamp:Ls(e.timestamp),level:e.level,message:e.message,caller:ve(e.caller),type:ve(e.type),traceId:ve(e.traceId),groupId:ve(e.groupId),method:ve(e.method),path:ve(e.path),status:Sn(e.status),duration:Sn(e.duration),hasError:t.error!=null,data:t.data??null,bindings:t.bindings??null,error:t.error??null,events:t.events??null,record:t,createdAt:new Date}}function bs(e){return !!e&&e.type==="prisma"}function ws(e){return !!e&&e.type==="drizzle"}function Tn(e){if(bs(e.adapter))return kn(e.adapter);if(ws(e.adapter))return wn(e.adapter);throw new Error("[Blyp] Unsupported database adapter configuration.")}function Rs(e){return new Promise(t=>{setTimeout(t,e);})}var ot=class{constructor(t){this.config=t;g(this,"isAsync",true);g(this,"isReady",true);g(this,"warnOnce",se(new Set));g(this,"queue",[]);g(this,"writer");g(this,"timer",null);g(this,"processing",false);g(this,"closed",false);g(this,"terminalError",null);g(this,"activeDispatch",null);this.writer=Tn(t);}write(t){this.closed||(this.enqueue(xn(t)),this.scheduleDispatch());}async flush(){this.timer&&(clearTimeout(this.timer),this.timer=null);let t=(async()=>{if(await this.drain(),this.terminalError)throw this.terminalError})(),r=null;try{await Promise.race([t,new Promise((n,o)=>{r=setTimeout(()=>{this.warnOnce("database-flush-timeout",`[Blyp] Warning: Timed out flushing database logs after ${this.config.delivery.flushTimeoutMs}ms.`),o(new Error("[Blyp] Timed out flushing database logs."));},this.config.delivery.flushTimeoutMs);})]);}finally{r&&clearTimeout(r);}}async shutdown(){this.closed=true,await this.flush();}enqueue(t){this.queue.push(t);let r=this.queue.length-this.config.delivery.maxQueueSize;if(!(r<=0)){if(this.warnOnce("database-overflow",`[Blyp] Warning: Database log queue exceeded ${this.config.delivery.maxQueueSize} entries. Applying ${this.config.delivery.overflowStrategy} overflow handling.`),this.config.delivery.overflowStrategy==="drop-new"){this.queue.splice(this.config.delivery.maxQueueSize);return}this.queue.splice(0,r);}}scheduleDispatch(){if(!this.processing){if(this.config.delivery.strategy==="immediate"){this.drain();return}if(this.queue.length>=this.config.delivery.batchSize){this.drain();return}this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.drain();},this.config.delivery.flushIntervalMs));}}async drain(){if(this.processing){this.activeDispatch&&await this.activeDispatch;return}this.processing=true,this.activeDispatch=this.processQueue();try{await this.activeDispatch;}finally{this.processing=false,this.activeDispatch=null;}}async processQueue(){for(;this.queue.length>0;){let t=this.config.delivery.strategy==="batch"?Math.max(1,this.config.delivery.batchSize):1,r=this.queue.splice(0,t);try{await this.insertWithRetry(r);}catch(n){let o=n instanceof Error?n:new Error(String(n??"Unknown database logging failure"));throw this.terminalError=o,this.warnOnce("database-insert-failure",`[Blyp] Warning: Failed to persist logs to the ${this.config.dialect??"database"} database.`,o),o}}}async insertWithRetry(t){let r=Math.max(1,this.config.delivery.retry.maxRetries+1),n=0;for(;n<r;){n+=1;try{await this.writer.insert(t);return}catch(o){if(n>=r)throw o;await Rs(this.config.delivery.retry.backoffMs);}}}};var pr=class{constructor(){g(this,"isAsync",false);g(this,"isReady",false);}write(t){}async flush(){}async shutdown(){}},ks=se(new Set);function En(e){if(e.destination!=="database")return Ln(e);let t=e.database;return t?.ready?new ot(t):(ks("database-sink-disabled","[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."),new pr)}function fr(e){return K(e.data)?e.data:e}function ce(e,t){if(t in e){let o=e[t];if(typeof o=="string"||typeof o=="number")return o}let n=fr(e)[t];if(typeof n=="string"||typeof n=="number")return n}function mr(e,t){let r=fr(e),o=(K(r.page)?r.page:void 0)?.[t];return typeof o=="string"?o:void 0}function yr(e,t){let r=fr(e),o=(K(r.session)?r.session:void 0)?.[t];return typeof o=="string"?o:void 0}function at(e){return ce(e,"type")}function vn(e,t){let r=Math.max(1,Math.floor(e)),n=Math.pow(t.multiplier,r-1),o=Math.min(Math.max(0,Math.floor(t.initialBackoffMs*n)),Math.max(0,t.maxBackoffMs));return t.jitter?Math.floor(Math.random()*(o+1)):o}var Dn="bun:sqlite";var Pn="node:sqlite";function An(){return `
8
+ `);}catch(r){console.error("[Blyp] Warning: Failed to update .gitignore:",r);}}function _a(){let e=process.cwd();Da(e)&&(Pa(e),Aa(e));}function Ia(){let e=process.cwd(),t=sn.map(n=>Ee.resolve(e,n)).filter(n=>z.existsSync(n));if(t.length===0)return null;if(t.length>1){let n=t[0];se(`config-multiple:${n}`,`[Blyp] Warning: Multiple config files found. Using ${n} and ignoring ${t.slice(1).join(", ")}.`);}let r=t[0];return {path:r,type:r.endsWith(".json")?"json":"jiti"}}function dn(e,t){let r=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !r||typeof r!="object"||Array.isArray(r)?(se(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):r}function Oa(e){try{let t=z.readFileSync(e,"utf-8");return dn(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function Ba(e){try{let t=jiti.createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return dn(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function Na(e){return e.type==="json"?Oa(e.path):Ba(e.path)}function on(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function Ma(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function Fa(e,t){return {...sr,...e,...t}}function qa(e,t){return {...un,...e,...t,retry:Fa(e?.retry,t?.retry)}}function Ha(e){let t=e.model??"blypLog",n=e.client?.[t];return !!n&&typeof n.create=="function"}function ja(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function za(e,t){if(!e)return;let r=e.adapter,n=false;t==="json"?se("database-json-config","[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."):e.dialect!=="postgres"&&e.dialect!=="mysql"?se(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):r?on(r)?(n=Ha({...r,model:r.model??"blypLog"}),n||se("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${r.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):Ma(r)&&(n=ja(r),n||se("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):se("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let o=on(r)?{...r,model:r.model??"blypLog"}:r;return {dialect:e.dialect,adapter:o,delivery:qa(void 0,e.delivery),ready:n,status:n?"enabled":"missing"}}function Ua(e,t){return {...or,...e,...t}}function $a(e,t){return {...ar,...e,...t,rotation:Ua(e?.rotation,t?.rotation)}}function Ka(e,t){return {...Ze,...e,...t,path:t?.path??e?.path??Ze.path}}function Wa(e,t){return W(e,t)}function Ja(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??me.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??me.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??me.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??me.multiplier),jitter:t?.jitter??e?.jitter??me.jitter}}function Ga(e,t){let r=t?.durableQueuePath??e?.durableQueuePath??$.durableQueuePath;return {enabled:t?.enabled??e?.enabled??$.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??$.memoryBufferSize)),durableQueuePath:pe(r)?r:$.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??$.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??$.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??$.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??$.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??$.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??$.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??$.overflowStrategy,retry:Ja(e?.retry,t?.retry),durableReady:false}}function Qa(e,t,r){if(!(!e&&!t))return za({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},r)}function Va(e,t){let r=t?.enabled??e?.enabled??false,n=t?.projectKey??e?.projectKey,o=e?.enabled===true?e?.errorTracking:void 0,i=t?.errorTracking?.mode??o?.mode??"auto",a=t?.errorTracking?.enabled??o?.enabled??r,s=r&&a&&typeof n=="string"&&n.trim().length>0;return {enabled:r,mode:t?.mode??e?.mode??"auto",projectKey:n,host:t?.host??e?.host??Sa,serviceName:t?.serviceName??e?.serviceName??cr(),errorTracking:{enabled:a,mode:i,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??o?.enableExceptionAutocapture??i==="auto",ready:s,status:s?"enabled":"missing"}}}function Ya(e,t){let r=t?.enabled??e?.enabled??false,n=t?.apiKey??e?.apiKey,o=t?.websiteId??e?.websiteId,i=r&&pe(n)&&pe(o);return {enabled:r,mode:t?.mode??e?.mode??"auto",apiKey:n,websiteId:o,namespace:t?.namespace??e?.namespace,source:t?.source??e?.source,apiUrl:t?.apiUrl??e?.apiUrl,debug:t?.debug??e?.debug??false,enableBatching:t?.enableBatching??e?.enableBatching??true,batchSize:t?.batchSize??e?.batchSize,batchTimeout:t?.batchTimeout??e?.batchTimeout,maxQueueSize:t?.maxQueueSize??e?.maxQueueSize,ready:i,status:i?"enabled":"missing"}}function Xa(e,t){let r=t?.sourceToken??e?.sourceToken,n=t?.ingestingHost??e?.ingestingHost,o=t?.enabled??e?.enabled??false,i=e?.enabled===true?e?.errorTracking:void 0,a=Za(o,i,t?.errorTracking),s=o&&pe(r)&&tr(n);return {enabled:o,mode:t?.mode??e?.mode??"auto",sourceToken:r,ingestingHost:n,serviceName:t?.serviceName??e?.serviceName??cr(),errorTracking:a,ready:s,status:s?"enabled":"missing"}}function Za(e,t,r){let n=r?.dsn??t?.dsn,o=r?.enabled??t?.enabled??e,i=o&&pe(n);return {enabled:o,dsn:n,tracesSampleRate:r?.tracesSampleRate??t?.tracesSampleRate??1,environment:r?.environment??t?.environment,release:r?.release??t?.release,ready:i,status:i?"enabled":"missing"}}function ei(e,t){let r=t?.dsn??e?.dsn,n=t?.enabled??e?.enabled??false,o=n&&typeof r=="string"&&r.trim().length>0;return {enabled:n,mode:t?.mode??e?.mode??"auto",dsn:r,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:o,status:o?"enabled":"missing"}}function ti(e,t){let r=t?.endpoint??e?.endpoint,n=t?.enabled??e?.enabled??false,o={...{},...t?.headers??{}},i=n&&tr(r);return {name:t?.name??e?.name??"",enabled:n,mode:t?.mode??e?.mode??"auto",endpoint:r,headers:o,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??cr(),ready:i,status:i?"enabled":"missing"}}function ri(e,t){let r=t??e??[],n=new Map;for(let o of r)!o||typeof o.name!="string"||o.name.length===0||(n.has(o.name)&&se(`otlp-duplicate:${o.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${o.name}" found. Using the last definition.`),n.set(o.name,ti(void 0,o)));return Array.from(n.values())}function ni(e,t){return {betterstack:Xa(e?.betterstack,t?.betterstack),databuddy:Ya(e?.databuddy,t?.databuddy),posthog:Va(e?.posthog,t?.posthog),sentry:ei(e?.sentry,t?.sentry),otlp:ri(e?.otlp,t?.otlp),delivery:Ga(e?.delivery,t?.delivery)}}function et(e,t={},r={}){return {...e,...t,destination:t.destination??e.destination??"file",file:$a(e.file,t.file),database:Qa(e.database,t.database,r.configFileType),clientLogging:Ka(e.clientLogging,t.clientLogging),redact:Wa(e.redact,t.redact),connectors:ni(e.connectors,t.connectors)}}function ur(){if(ke!==null)return ke;_a();let e=Ia();if(e){let t=Na(e);ke=et(nr,t,{configFileType:e.type});}else ke=et(nr);return ke}function Te(e={}){return et(ur(),e)}function oi(){return ur()}function ai(){ke=null,cn.clear();}var ln={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function rt(e){return e.replace(/\\/g,"/")}function ii(e){let t=rt(e);return t.startsWith("node:")||t.includes("/node_modules/pino")||t.includes("/node_modules/pino-pretty")||t.includes("/node_modules/@blyp/core/")||t.includes("/blyp/src/core/")||t.includes("/blyp/src/frameworks/")||t.includes("/blyp/src/posthog/")||t.includes("/blyp/dist/")}function si(e){let t=rt(e),r=rt(process.cwd());return t.startsWith(`${r}/`)?t.slice(r.length+1):t}function gn(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
9
+ `),r=null;for(let n=2;n<t.length;n+=1){let o=t[n];if(!o)continue;let i=o.match(/\((.*):(\d+):\d+\)/)||o.match(/at\s+(.*):(\d+):(\d+)/);if(!i)continue;let a=i[1]||"",s=parseInt(i[2]||"0",10)||null;if(a&&!a.includes("node_modules")&&!ii(a)){let c=si(a);if(!rt(c).startsWith("dist/"))return {file:c,line:s};r??(r={file:c,line:s});}}if(r)return r}catch{return {file:null,line:null}}return {file:null,line:null}}var pn=ge;function fn(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function mn(e,t,r,n,o=W()){let{file:i,line:a}=gn(),s=pn(t,o),c={timestamp:new Date().toISOString(),level:ln[e],message:fn(s)},u=oe();return t instanceof Error&&(c.error=D(Qe(t),o)),i&&(c.caller=a!==null?`${i}:${a}`:i),r.length===1?c.data=D(r[0],o):r.length>1&&(c.data=D(r,o)),Object.keys(n).length>0&&(c.bindings=D(n,o)),u&&(c.traceId=u),c}function yn(e,t,r,n,o=W()){let{file:i,line:a}=gn(),s=D(r,o),c=oe(),u={message:fn(pn(t,o)),...s};return i&&(u.caller=a!==null?`${i}:${a}`:i),Object.keys(n).length>0&&(u.bindings=D(n,o)),c&&u.traceId===void 0&&(u.traceId=c),u.level=typeof s.level=="string"&&s.level.length>0?s.level:ln[e],u.timestamp=typeof s.timestamp=="string"&&s.timestamp.length>0?s.timestamp:new Date().toISOString(),u}function hn(e){switch(e){case "debug":return "debug";case "warning":return "warning";case "warn":return "warn";case "error":return "error";case "success":return "success";case "critical":return "critical";case "table":return "table";default:return "info"}}function ui(e){return Buffer.from(fflate.gzipSync(e))}function di(e,t){console.warn(`[Blyp] Warning: ${e}`,t);}function nt(e){z__default.default.mkdirSync(e,{recursive:true});}function li(e){try{return z__default.default.statSync(e).size}catch{return 0}}function gi(e){let t=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),n=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),i=String(e.getUTCMinutes()).padStart(2,"0"),a=String(e.getUTCSeconds()).padStart(2,"0");return `${t}${r}${n}T${o}${i}${a}Z`}function pi(e,t){let r=`${e}${t}`,n=1;for(;z__default.default.existsSync(r);)r=`${e}-${n}${t}`,n+=1;return r}function fi(e,t,r,n){let o=`${t}.`;try{let i=z__default.default.readdirSync(e).filter(s=>s.startsWith(o)&&(s.endsWith(".ndjson")||s.endsWith(".ndjson.gz"))).map(s=>Ee__default.default.join(e,s)).sort((s,c)=>z__default.default.statSync(s).mtimeMs-z__default.default.statSync(c).mtimeMs),a=Math.max(i.length-r,0);for(let s=0;s<a;s+=1)z__default.default.rmSync(i[s]);}catch(i){n(`Failed to prune archives for ${t}`,i);}}function mi(){let e=new WeakSet;return (t,r)=>{if(typeof r=="function")return `[Function: ${r.name||"anonymous"}]`;if(r===void 0)return "[undefined]";if(typeof r=="symbol")return r.toString();if(r!==null&&typeof r=="object"){if(e.has(r))return "[Circular]";e.add(r);}return r}}function lr(e){return JSON.stringify(e,mi())}function yi(e){let t=e.file,r=t?.dir||e.logDir||Ee__default.default.join(process.cwd(),"logs"),n=t?.archiveDir||Ee__default.default.join(r,"archive"),o=t?.rotation;return {enabled:t?.enabled??true,dir:r,archiveDir:n,rotationEnabled:o?.enabled??true,maxSizeBytes:o?.maxSizeBytes??10*1024*1024,maxArchives:o?.maxArchives??5,compress:o?.compress??true}}var dr=class{constructor(t,r={}){g(this,"config");g(this,"gzip");g(this,"warn");g(this,"combined");g(this,"error");this.config=yi(t),this.gzip=r.gzip??ui,this.warn=r.warn??di,this.combined={activePath:Ee__default.default.join(this.config.dir,"log.ndjson"),archivePrefix:"log",bytes:0,queue:[],processing:false},this.error={activePath:Ee__default.default.join(this.config.dir,"log.error.ndjson"),archivePrefix:"log.error",bytes:0,queue:[],processing:false},this.config.enabled&&(nt(this.config.dir),nt(this.config.archiveDir),this.seedStream(this.combined),this.seedStream(this.error));}write(t){if(!this.config.enabled)return;let r=`${lr(t)}
10
+ `;this.enqueue(this.combined,r),(t.level==="error"||t.level==="critical")&&this.enqueue(this.error,r);}enqueue(t,r){t.queue.push(r),this.processQueue(t);}processQueue(t){if(!t.processing){t.processing=true;try{for(;t.queue.length>0;){let r=t.queue.shift();if(r!==void 0)try{this.append(t,r);}catch(n){this.warn(`Failed writing log line for ${t.archivePrefix}`,n);}}}finally{t.processing=false;}}}seedStream(t){t.bytes=li(t.activePath),this.config.rotationEnabled&&t.bytes>this.config.maxSizeBytes&&t.bytes>0&&(this.rotate(t),z__default.default.closeSync(z__default.default.openSync(t.activePath,"a")),t.bytes=0);}append(t,r){nt(this.config.dir);let n=Buffer.byteLength(r,"utf8");this.config.rotationEnabled&&t.bytes>0&&t.bytes+n>this.config.maxSizeBytes&&this.rotate(t),z__default.default.appendFileSync(t.activePath,r,"utf8"),t.bytes+=n;}rotate(t){if(nt(this.config.archiveDir),!z__default.default.existsSync(t.activePath)||t.bytes===0){t.bytes=0;return}let r=gi(new Date),n=Ee__default.default.join(this.config.archiveDir,`${t.archivePrefix}.${r}`),o=pi(n,".ndjson");if(z__default.default.renameSync(t.activePath,o),this.config.compress)try{let i=`${o}.gz`,a=this.gzip(z__default.default.readFileSync(o));z__default.default.writeFileSync(i,a),z__default.default.rmSync(o);}catch(i){this.warn(`Failed to gzip archive ${o}`,i);}t.bytes=0,fi(this.config.archiveDir,t.archivePrefix,this.config.maxArchives,this.warn);}};function Cn(e){return new dr(e)}var gr=class{constructor(t){this.logger=t;g(this,"isAsync",false);g(this,"isReady",true);}write(t){this.logger.write(t);}async flush(){}async shutdown(){}};function Ln(e){return new gr(Cn(e))}function bn(e){return {type:"drizzle",db:e.db,table:e.table}}function wn(e){let t=e.db;if(typeof t?.insert!="function"||e.table===void 0)throw new Error("[Blyp] Drizzle database adapter is missing a db.insert function or table reference.");return {async insert(r){r.length!==0&&await t.insert(e.table).values(r);}}}function hi(e){let t=String(e??"");return t.includes("createMany")||t.includes("Unknown argument")||t.includes("not supported")||t.includes("is not a function")}function Rn(e){return {type:"prisma",client:e.client,model:e.model??"blypLog"}}function kn(e){let t=e.client,r=e.model??"blypLog",n=t[r];if(!n||typeof n.create!="function")throw new Error(`[Blyp] Prisma database adapter is missing the "${r}" delegate or its create method.`);let o=n,i=typeof o.createMany=="function";async function a(s){if(typeof t.$transaction=="function"){await t.$transaction(s.map(c=>o.create({data:c})));return}for(let c of s)await o.create({data:c});}return {async insert(s){if(s.length!==0){if(s.length===1){await o.create({data:s[0]});return}if(!i||typeof o.createMany!="function"){await a(s);return}try{await o.createMany({data:s});}catch(c){if(!hi(c))throw c;i=false,await a(s);}}}}}function Sn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ve(e){return typeof e=="string"&&e.length>0?e:null}function Li(e){if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function xn(e){let t=Y(e);return {id:crypto$1.randomUUID(),timestamp:Li(e.timestamp),level:e.level,message:e.message,caller:ve(e.caller),type:ve(e.type),traceId:ve(e.traceId),groupId:ve(e.groupId),method:ve(e.method),path:ve(e.path),status:Sn(e.status),duration:Sn(e.duration),hasError:t.error!=null,data:t.data??null,bindings:t.bindings??null,error:t.error??null,events:t.events??null,record:t,createdAt:new Date}}function bi(e){return !!e&&e.type==="prisma"}function wi(e){return !!e&&e.type==="drizzle"}function Tn(e){if(bi(e.adapter))return kn(e.adapter);if(wi(e.adapter))return wn(e.adapter);throw new Error("[Blyp] Unsupported database adapter configuration.")}function Ri(e){return new Promise(t=>{setTimeout(t,e);})}var ot=class{constructor(t){this.config=t;g(this,"isAsync",true);g(this,"isReady",true);g(this,"warnOnce",ie(new Set));g(this,"queue",[]);g(this,"writer");g(this,"timer",null);g(this,"processing",false);g(this,"closed",false);g(this,"terminalError",null);g(this,"activeDispatch",null);this.writer=Tn(t);}write(t){this.closed||(this.enqueue(xn(t)),this.scheduleDispatch());}async flush(){this.timer&&(clearTimeout(this.timer),this.timer=null);let t=(async()=>{if(await this.drain(),this.terminalError)throw this.terminalError})(),r=null;try{await Promise.race([t,new Promise((n,o)=>{r=setTimeout(()=>{this.warnOnce("database-flush-timeout",`[Blyp] Warning: Timed out flushing database logs after ${this.config.delivery.flushTimeoutMs}ms.`),o(new Error("[Blyp] Timed out flushing database logs."));},this.config.delivery.flushTimeoutMs);})]);}finally{r&&clearTimeout(r);}}async shutdown(){this.closed=true,await this.flush();}enqueue(t){this.queue.push(t);let r=this.queue.length-this.config.delivery.maxQueueSize;if(!(r<=0)){if(this.warnOnce("database-overflow",`[Blyp] Warning: Database log queue exceeded ${this.config.delivery.maxQueueSize} entries. Applying ${this.config.delivery.overflowStrategy} overflow handling.`),this.config.delivery.overflowStrategy==="drop-new"){this.queue.splice(this.config.delivery.maxQueueSize);return}this.queue.splice(0,r);}}scheduleDispatch(){if(!this.processing){if(this.config.delivery.strategy==="immediate"){this.drain();return}if(this.queue.length>=this.config.delivery.batchSize){this.drain();return}this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.drain();},this.config.delivery.flushIntervalMs));}}async drain(){if(this.processing){this.activeDispatch&&await this.activeDispatch;return}this.processing=true,this.activeDispatch=this.processQueue();try{await this.activeDispatch;}finally{this.processing=false,this.activeDispatch=null;}}async processQueue(){for(;this.queue.length>0;){let t=this.config.delivery.strategy==="batch"?Math.max(1,this.config.delivery.batchSize):1,r=this.queue.splice(0,t);try{await this.insertWithRetry(r);}catch(n){let o=n instanceof Error?n:new Error(String(n??"Unknown database logging failure"));throw this.terminalError=o,this.warnOnce("database-insert-failure",`[Blyp] Warning: Failed to persist logs to the ${this.config.dialect??"database"} database.`,o),o}}}async insertWithRetry(t){let r=Math.max(1,this.config.delivery.retry.maxRetries+1),n=0;for(;n<r;){n+=1;try{await this.writer.insert(t);return}catch(o){if(n>=r)throw o;await Ri(this.config.delivery.retry.backoffMs);}}}};var pr=class{constructor(){g(this,"isAsync",false);g(this,"isReady",false);}write(t){}async flush(){}async shutdown(){}},ki=ie(new Set);function En(e){if(e.destination!=="database")return Ln(e);let t=e.database;return t?.ready?new ot(t):(ki("database-sink-disabled","[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."),new pr)}function fr(e){return K(e.data)?e.data:e}function ce(e,t){if(t in e){let o=e[t];if(typeof o=="string"||typeof o=="number")return o}let n=fr(e)[t];if(typeof n=="string"||typeof n=="number")return n}function mr(e,t){let r=fr(e),o=(K(r.page)?r.page:void 0)?.[t];return typeof o=="string"?o:void 0}function yr(e,t){let r=fr(e),o=(K(r.session)?r.session:void 0)?.[t];return typeof o=="string"?o:void 0}function at(e){return ce(e,"type")}function vn(e,t){let r=Math.max(1,Math.floor(e)),n=Math.pow(t.multiplier,r-1),o=Math.min(Math.max(0,Math.floor(t.initialBackoffMs*n)),Math.max(0,t.maxBackoffMs));return t.jitter?Math.floor(Math.random()*(o+1)):o}var Dn="bun:sqlite";var Pn="node:sqlite";function An(){return `
11
11
  const { parentPort } = require('node:worker_threads');
12
12
  const fs = require('node:fs');
13
13
  const path = require('node:path');
@@ -697,7 +697,7 @@ parentPort.on('message', async (message) => {
697
697
  });
698
698
  }
699
699
  });
700
- `}var De=class{constructor(t){this.path=t;g(this,"worker");g(this,"pending",new Map);g(this,"nextId",1);this.worker=new worker_threads.Worker(An(),{eval:true}),this.worker.on("message",r=>{let n=this.pending.get(r.id);if(n){if(this.pending.delete(r.id),r.ok){n.resolve(r.result);return}n.reject(new Error(r.error??"SQLite worker request failed."));}}),this.worker.on("error",r=>{for(let n of this.pending.values())n.reject(r instanceof Error?r:new Error(String(r)));this.pending.clear();});}request(t,r={}){let n=this.nextId++;return new Promise((o,s)=>{this.pending.set(n,{resolve:o,reject:s}),this.worker.postMessage({id:n,type:t,payload:r});})}async init(){await this.request("init",{path:this.path});}async insert(t){await this.request("insert",{jobs:t});}async claimDue(t,r){return this.request("claimDue",{limit:t,now:r})}async ack(t){await this.request("ack",{ids:t});}async reschedule(t,r){await this.request("reschedule",{items:t,now:r});}async deadLetter(t){await this.request("deadLetter",{items:t});}async markSuccess(t){await this.request("markSuccess",{items:t});}async markFailure(t){await this.request("markFailure",{items:t});}async getStatusSummary(){return this.request("getStatusSummary")}async listDeadLetters(t){return this.request("listDeadLetters",t)}async retryDeadLetters(t,r){return this.request("retryDeadLetters",{ids:t,now:r})}async clearDeadLetters(t){return this.request("clearDeadLetters",{ids:t})}async count(){return this.request("count")}async shutdown(){try{await this.request("shutdown");}finally{await this.worker.terminate();}}};var _n=Symbol("blyp.connector.batch-dispatch"),Ne=Symbol("blyp.connector.delivery-binder");function Me(e){return new Promise(t=>{setTimeout(t,e);})}function xs(e){return e.data===void 0||typeof e.data!="object"||e.data===null||e.data.type!=="client_log"}function In(e){return JSON.stringify(e)}function Ts(e){try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.jobId!="string"?null:t}catch{return null}}function On(e){let t=new Map;for(let r of e){let n=`${r.connectorType}:${r.connectorTarget??""}`;t.has(n)||t.set(n,{connectorType:r.connectorType,connectorTarget:r.connectorTarget});}return [...t.values()]}var st=class{constructor(t){this.config=t;g(this,"warnOnce",se(new Set));g(this,"memoryQueue",[]);g(this,"durableStaging",[]);g(this,"dispatchers",new Map);g(this,"activeDispatches",0);g(this,"flushPromise",null);g(this,"durableFlushPromise",null);g(this,"pollTimer",null);g(this,"durablePollRunning",false);g(this,"closed",false);g(this,"durableClient",null);g(this,"durableReady",false);g(this,"durableInitPromise",null);t.enabled&&(this.durableInitPromise=this.initializeDurableQueue());}bindTarget(t){typeof t[Ne]=="function"&&t[Ne](this);let r=t[_n];r&&this.dispatchers.set(r.dispatchKey,r);}unbindTarget(t){typeof t[Ne]=="function"&&t[Ne](null);}enqueue(t,r,n,o){this.closed||!xs(r)||(this.dispatchers.set(n.dispatchKey,n),this.memoryQueue.push({id:Xe(),connectorType:t,connectorTarget:o,source:"server",record:r,attemptCount:0,maxAttempts:this.config.retry.maxAttempts,nextAttemptAt:Date.now(),createdAt:Date.now(),dispatchKey:n.dispatchKey,dispatcher:n}),this.enforceMemoryCapacity(),this.scheduleDispatch());}async flush(){await this.durableInitPromise?.catch(()=>{}),await this.processUntilIdle(),await this.flushDurableStaging(),await this.drainDurableQueueForFlush(),await this.flushDurableStaging(),await this.processUntilIdle();}async shutdown(){if(this.closed=true,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),await this.durableInitPromise?.catch(()=>{}),this.durableReady){let t=this.memoryQueue.splice(0,this.memoryQueue.length);for(let r of t)this.stageDurableJob(r,r.attemptCount,Math.max(r.nextAttemptAt,Date.now()));await this.flushDurableStaging();}await this.processUntilIdle(),this.durableClient&&(await this.durableClient.shutdown().catch(()=>{}),this.durableClient=null);}async getDurableCountForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?0:this.durableClient.count()}async getStatusSummaryForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:this.durableClient.getStatusSummary()}async listDeadLettersForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:(await this.durableClient.listDeadLetters({limit:1e3,offset:0})).items}async initializeDurableQueue(){try{let t=new De(this.config.durableQueuePath);await t.init(),this.durableClient=t,this.durableReady=!0,this.scheduleDurablePoll();}catch(t){this.durableReady=false,this.durableClient=null,this.warnOnce("connector-durable-disabled",`[Blyp] Warning: Failed to initialize the connector SQLite queue at ${this.config.durableQueuePath}. Falling back to in-memory retries.`,t);}}scheduleDispatch(){this.flushPromise||(this.flushPromise=(async()=>{try{await this.pumpMemoryQueue();}finally{this.flushPromise=null,!this.closed&&this.hasReadyMemoryJobs()&&this.scheduleDispatch();}})());}async pumpMemoryQueue(){for(;!this.closed;){for(;this.activeDispatches<this.config.dispatchConcurrency;){let t=this.takeNextMemoryBatch();if(t.length===0)break;this.activeDispatches+=1,this.dispatchMemoryBatch(t).finally(()=>{this.activeDispatches-=1,this.closed||this.scheduleDispatch();});}if(this.activeDispatches===0||!this.hasReadyMemoryJobs())break;await Me(10);}}takeNextMemoryBatch(){let t=Date.now(),r=this.memoryQueue.findIndex(s=>s.nextAttemptAt<=t);if(r===-1)return [];let n=this.memoryQueue[r],o=[n];this.memoryQueue.splice(r,1);for(let s=this.memoryQueue.length-1;s>=0;s-=1){let a=this.memoryQueue[s];a.dispatchKey===n.dispatchKey&&a.connectorTarget===n.connectorTarget&&a.nextAttemptAt<=t&&o.length<this.config.memoryBatchSize&&(o.push(a),this.memoryQueue.splice(s,1));}return o}async dispatchMemoryBatch(t){let r=t[0].dispatcher,n=Date.now(),o=await r.dispatch(t.map(s=>s.record),{source:"server",target:t[0].connectorTarget}).catch(s=>({ok:false,retryable:true,error:s instanceof Error?s.message:String(s)}));if(o.ok){await this.recordSuccessfulDispatch(t,n);return}await this.handleRetryableFailure(t,o,false,n);}async handleRetryableFailure(t,r,n,o){n||await this.durableInitPromise?.catch(()=>{});let s=[],a=[];await this.recordFailedDispatch(t,r,o);for(let i of t){let c=i.attemptCount+1;if(!r.retryable||c>=i.maxAttempts){a.push({id:i.id,connectorType:i.connectorType,connectorTarget:i.connectorTarget,operation:"send",payloadJson:In({jobId:i.id,connectorType:i.connectorType,connectorTarget:i.connectorTarget,source:i.source,record:i.record,createdAt:i.createdAt}),attemptCount:c,maxAttempts:i.maxAttempts,lastError:r.error,firstEnqueuedAt:i.createdAt,deadLetteredAt:o,lastAttemptAt:o}),this.warnOnce(`connector-drop:${i.connectorType}:${i.connectorTarget??"default"}:${i.id}`,n&&this.durableReady?`[Blyp] Warning: Dead-lettered ${i.connectorType} connector job after ${c} failed attempt(s). ${r.error??"Connector delivery failed."}`:`[Blyp] Warning: Dropped ${i.connectorType} connector job after ${c} failed attempt(s). ${r.error??"Connector delivery failed."}`);continue}let u=o+vn(c,this.config.retry);if(n){s.push({id:i.id,attemptCount:c,nextAttemptAt:u,lastError:r.error});continue}if(this.durableReady&&this.config.durableSpillStrategy==="after-first-failure"){this.stageDurableJob(i,c,u,r.error);continue}this.memoryQueue.push({...i,attemptCount:c,nextAttemptAt:u});}a.length>0&&await this.durableClient?.deadLetter(a).catch(i=>{this.warnOnce("connector-dead-letter-failure","[Blyp] Warning: Failed to persist dead-lettered connector queue jobs.",i);}),s.length>0&&await this.durableClient?.reschedule(s,o).catch(i=>{this.warnOnce("connector-reschedule-failure","[Blyp] Warning: Failed to reschedule durable connector queue jobs.",i);});}async recordSuccessfulDispatch(t,r){if(!this.durableReady||!this.durableClient||t.length===0)return;let n=On(t).map(o=>({connectorType:o.connectorType,connectorTarget:o.connectorTarget,timestamp:r}));await this.durableClient.markSuccess(n).catch(o=>{this.warnOnce("connector-status-success-failure","[Blyp] Warning: Failed to record connector delivery success state.",o);});}async recordFailedDispatch(t,r,n){if(!this.durableReady||!this.durableClient||t.length===0)return;let o=On(t).map(s=>({connectorType:s.connectorType,connectorTarget:s.connectorTarget,timestamp:n,lastError:r.error}));await this.durableClient.markFailure(o).catch(s=>{this.warnOnce("connector-status-failure-failure","[Blyp] Warning: Failed to record connector delivery failure state.",s);});}stageDurableJob(t,r,n,o){let s=In({jobId:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,source:t.source,record:t.record,createdAt:t.createdAt});this.durableStaging.push({id:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,operation:"send",payloadJson:s,attemptCount:r,maxAttempts:t.maxAttempts,nextAttemptAt:n,state:"pending",lastError:o,createdAt:t.createdAt,updatedAt:Date.now()}),this.flushDurableStaging();}async flushDurableStaging(){if(!(!this.durableReady||!this.durableClient||this.durableStaging.length===0)){if(this.durableFlushPromise){await this.durableFlushPromise;return}this.durableFlushPromise=(async()=>{for(;this.durableStaging.length>0;){let t=this.durableStaging.splice(0,this.config.sqliteWriteBatchSize);try{await this.durableClient.insert(t);}catch(r){this.warnOnce("connector-durable-insert-failure","[Blyp] Warning: Failed to persist connector jobs into the durable SQLite queue.",r),this.durableStaging.unshift(...t);break}}})();try{await this.durableFlushPromise;}finally{this.durableFlushPromise=null;}}}async processDurableQueueOnce(){if(!(!this.durableReady||!this.durableClient||this.durablePollRunning)){this.durablePollRunning=true;try{for(;!this.closed;){let t=await this.durableClient.claimDue(this.config.sqliteReadBatchSize,Date.now());if(t.length===0)break;let r=new Map,n=[];for(let o of t){let s=Ts(o.payloadJson);if(!s){n.push(o.id);continue}let a=o.connectorType==="otlp"?`otlp:${o.connectorTarget??""}`:o.connectorType,i=this.dispatchers.get(a);if(!i){n.push(o.id);continue}let c={id:o.id,connectorType:o.connectorType,connectorTarget:o.connectorTarget,source:s.source,record:s.record,attemptCount:o.attemptCount,maxAttempts:o.maxAttempts,nextAttemptAt:o.nextAttemptAt,createdAt:o.createdAt,dispatchKey:a,dispatcher:i},u=r.get(a)??[];u.push(c),r.set(a,u);}n.length>0&&await this.durableClient.ack(n);for(let o of r.values()){let a=await o[0].dispatcher.dispatch(o.map(i=>i.record),{source:"server",target:o[0].connectorTarget}).catch(i=>({ok:!1,retryable:!0,error:i instanceof Error?i.message:String(i)}));if(a.ok){await this.recordSuccessfulDispatch(o,Date.now()),await this.durableClient.ack(o.map(i=>i.id));continue}await this.handleRetryableFailure(o,a,!0,Date.now());}}}finally{this.durablePollRunning=false;}}}async drainDurableQueueForFlush(){if(!(!this.durableReady||!this.durableClient)){this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null);try{for(;!this.closed;){for(;this.durablePollRunning;)await Me(10);if(await this.processDurableQueueOnce(),await this.flushDurableStaging(),await this.durableClient.count().catch(()=>0)===0&&!this.durablePollRunning&&this.durableStaging.length===0)break;await Me(10);}}finally{this.closed||this.scheduleDurablePoll();}}}scheduleDurablePoll(){this.closed||!this.durableReady||this.pollTimer||(this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.flushDurableStaging(),await this.processDurableQueueOnce(),this.scheduleDurablePoll();},this.config.pollIntervalMs));}enforceMemoryCapacity(){for(;this.memoryQueue.length>this.config.memoryBufferSize;){let t=this.config.overflowStrategy==="drop-new"?this.memoryQueue.length-1:0,[r]=this.memoryQueue.splice(t,1);if(!r)break;if(this.durableReady){this.stageDurableJob(r,r.attemptCount,Math.max(Date.now(),r.nextAttemptAt),"spilled from in-memory buffer");continue}this.warnOnce(`connector-overflow:${r.connectorType}:${r.connectorTarget??"default"}:${t}`,`[Blyp] Warning: Connector queue overflow reached ${this.config.memoryBufferSize}. Dropping queued ${r.connectorType} job.`);}}hasReadyMemoryJobs(){let t=Date.now();return this.memoryQueue.some(r=>r.nextAttemptAt<=t)}async processUntilIdle(){for(;this.activeDispatches>0||this.memoryQueue.length>0||this.durableStaging.length>0||this.flushPromise!==null||this.durableFlushPromise!==null;){if(this.scheduleDispatch(),await this.flushPromise?.catch(()=>{}),await this.flushDurableStaging(),this.memoryQueue.some(t=>t.nextAttemptAt>Date.now())||await this.processDurableQueueOnce(),this.activeDispatches===0&&this.memoryQueue.length>0&&!this.hasReadyMemoryJobs()){let t=Math.min(...this.memoryQueue.map(r=>r.nextAttemptAt));await Me(Math.max(t-Date.now(),0));}else await Me(10);if(this.activeDispatches===0&&this.memoryQueue.length===0&&this.durableStaging.length===0)break}}};var ye=class ye{constructor(){g(this,"_type",null);}static getInstance(){return ye.instance||(ye.instance=new ye),ye.instance}get type(){return this._type===null&&(this._type=this.detectRuntime()),this._type}get isBun(){return this.type==="bun"}get isNode(){return this.type==="node"}detectRuntime(){return typeof Bun<"u"&&typeof Bun.file=="function"?"bun":"node"}};g(ye,"instance");var hr=ye,Cr=class{constructor(){g(this,"type","bun");g(this,"isBun",true);g(this,"isNode",false);g(this,"file",{existsSync:t=>{try{let r=Bun.file(t);return r.size>0||r.name!==""}catch{return false}},mkdirSync:(t,r)=>{try{z__default.default.mkdirSync(t,r);}catch{}},writeFileSync:(t,r)=>{Bun.write(t,r);}});g(this,"path",{join:(...t)=>Ee__default.default.join(...t)});g(this,"env",{get:t=>Bun.env[t]});g(this,"cwd",()=>process.cwd());}},Lr=class{constructor(){g(this,"type","node");g(this,"isBun",false);g(this,"isNode",true);g(this,"file",{existsSync:t=>z__default.default.existsSync(t),mkdirSync:(t,r)=>{z__default.default.mkdirSync(t,r);},writeFileSync:(t,r)=>{z__default.default.writeFileSync(t,r);}});g(this,"path",{join:(...t)=>Ee__default.default.join(...t)});g(this,"env",{get:t=>process.env[t]});g(this,"cwd",()=>process.cwd());}};function Nn(){return hr.getInstance().isBun?new Cr:new Lr}var he=Nn();function Es(e){let t=e??he.path.join(he.cwd(),"logs");return he.file.existsSync(t)||he.file.mkdirSync(t,{recursive:true}),t}function Mn(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let r=[e,...t];return r.length===1?r[0]:r}function Fn(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function vs(e,t){if(e==null)return t===void 0||t<400?void 0:{message:`HTTP ${t}`,code:t,type:"HttpError"};if(e instanceof Error){let r=e;return {message:e.message,code:r.code,type:r.type??e.name??e.constructor?.name,stack:e.stack,why:r.why,fix:r.fix,link:r.link,details:Fn(r.details),cause:r.cause}}if(typeof e=="object"){let r=e,n=typeof r.statusCode=="number"?r.statusCode:typeof r.status=="number"?r.status:t;return {message:typeof r.message=="string"?r.message:`HTTP ${n??500}`,code:typeof r.code=="string"||typeof r.code=="number"?r.code:n,type:typeof r.type=="string"?r.type:typeof r.name=="string"?r.name:"Error",stack:typeof r.stack=="string"?r.stack:void 0,why:typeof r.why=="string"?r.why:void 0,fix:typeof r.fix=="string"?r.fix:void 0,link:typeof r.link=="string"?r.link:void 0,details:Fn(r.details),cause:r.cause}}return {message:String(e),code:t,type:typeof e}}function Ds(e){return e.response&&typeof e.response.status=="number"?e.response.status:typeof e.status=="number"?e.status:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.statusCode=="number"?e.error.statusCode:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.status=="number"?e.error.status:e.error?500:void 0}function qn(e,t){let r=t.redact??W(),n=performance.now(),o=D(t.initialFields??{},r),s=[],a;t.onCreate?.();let i=(u,d,l)=>(s.push({level:u,message:ge(d,r),timestamp:new Date().toISOString(),...Mn(d,l)===void 0?{}:{data:D(Mn(d,l),r)}}),c),c={set(u){return Object.assign(o,D(u,r)),c},debug(u,...d){return i("debug",u,d)},info(u,...d){return i("info",u,d)},warn(u,...d){return i("warn",u,d)},warning(u,...d){return i("warning",u,d)},error(u,...d){return i("error",u,d)},success(u,...d){return i("success",u,d)},critical(u,...d){return i("critical",u,d)},table(u,d){return i("table",u,d===void 0?[]:[d])},emit(u={}){if(a)return a;let d=D(t.resolveDefaultFields?.()??{},r),l=Ds(u),f=D(vs(u.error,l),r),h=u.level??(f?"error":"info"),y=D({...d,...o,groupId:e,timestamp:new Date().toISOString(),level:h,duration:Math.round(performance.now()-n),...typeof l=="number"?{status:l}:{},...s.length>0?{events:[...s]}:{},...f?{error:f}:{}},r);return t.write(y,ge(u.message??"structured_log",r)),a=y,t.onEmit?.(y),y}};return c}var kr=Symbol("blyp.logger.factory"),wr={success:25,info:30,debug:35,table:37,warning:40,error:50,critical:60},jn={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warn",table:"debug"},Ps="\x1B[35m",As="\x1B[0m";function Fe(e){return at(e)==="client_log"}function _s(){return {enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",ingestingHost:void 0,status:"missing",errorTracking:{enabled:false,ready:false,status:"missing",dsn:void 0,tracesSampleRate:1,environment:void 0,release:void 0},shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function Is(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function Os(){return {enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",host:"https://us.i.posthog.com",status:"missing",errorTracking:{enabled:false,ready:false,mode:"auto",status:"missing",enableExceptionAutocapture:false},shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function Bs(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,send:()=>{},flush:async()=>{}}}function Ns(e){return {name:e,enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",endpoint:void 0,status:"missing",send:()=>{},flush:async()=>{}}}function Ms(){return {get:e=>Ns(e),getAutoForwardTargets:()=>[],send:()=>{},flush:async()=>{}}}function Fs(e){return e.connectors?.betterstack?.enabled?j("betterstack",["@logtail/node","@sentry/node"],"../connectors/betterstack/sender").createBetterStackSender(e):_s()}function qs(e){return e.connectors?.databuddy?.enabled?j("databuddy",["@databuddy/sdk"],"../connectors/databuddy/sender").createDatabuddySender(e):Is()}function Hs(e){return e.connectors?.posthog?.enabled?j("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/posthog/sender").createPostHogSender(e):Os()}function js(e){return e.connectors?.sentry?.enabled?j("sentry",["@sentry/node"],"../connectors/sentry/sender").createSentrySender(e):Bs()}function zs(e){return e.connectors?.otlp?.some(t=>t.enabled)?j("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/otlp/sender").createOTLPRegistry(e):Ms()}function Us(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};t.data!==void 0&&(r.data=t.data);let n=typeof t.page?.pathname=="string"?t.page.pathname:void 0,o=typeof t.page?.url=="string"?t.page.url:void 0;return (n||o)&&(r.page=n??o),t.metadata!==void 0&&(r.metadata=t.metadata),Object.keys(r).length>0?r:null}function $s(e){if(!e||typeof e!="object"||Array.isArray(e))return {hidden:false,value:e};let t=e;if(t.type==="http_request"||t.type==="http_error")return {hidden:true};if(t.type==="client_log"){let r=Us(e);return r?{hidden:false,value:r}:{hidden:true}}return {hidden:false,value:e}}function Ks(e){if(e.pretty){let r=Xr()({colorize:true,translateTime:"SYS:HH:MM:ss",ignore:"pid,hostname,caller",customColors:{success:"green",critical:"red bold",info:"blue",warning:"yellow",error:"red",debug:"cyan",table:"cyan"},messageFormat:(n,o)=>{let s=String(n[o]??""),a=typeof n.caller=="string"?n.caller.trim():"";return a?`${s} ${Ps}${a}${As}`:s}});return Hn__default.default({level:e.level,customLevels:wr},r)}return Hn__default.default({level:e.level,customLevels:wr})}function X(e){let t=e[kr];if(!t)throw new Error("Unsupported Blyp logger instance");return t}function Sr(e){return X(e).posthog}function xr(e){return X(e).betterstack}function Tr(e){return X(e).databuddy}function ct(e){try{return Sr(e)}catch{return null}}function ut(e){try{return xr(e)}catch{return null}}function dt(e){try{return Tr(e)}catch{return null}}function Jn(e){return X(e).sentry}function Gn(e){return X(e).otlp}function lt(e){try{return X(e).redact}catch{return Te().redact}}function qe(e,t){let r=X(t);return Object.defineProperty(e,kr,{value:r,enumerable:false,configurable:false,writable:false}),e}function Qn(e,t){let r=X(e);return r.create(t,r.bindings)}function Er(e,t,r={}){let n=X(e);return qn(t,{initialFields:r.initialFields,resolveDefaultFields:()=>({...n.bindings,...r.resolveDefaultFields?.()??{}}),write:(o,s)=>{n.writeStructured(o,s,"structured-flush");},onCreate:r.onCreate,onEmit:r.onEmit,redact:r.redact??n.redact})}function zn(e,t){if(!Fe(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Un(e,t){if(!Fe(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function $n(e,t){if(!Fe(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Kn(e,t){if(!Fe(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Wn(e,t){if(!Fe(t))for(let r of e.getAutoForwardTargets())r.send(t,{source:"server",warnIfUnavailable:true});}function Rr(e,t,r,n,o,s,a,i,c,u={},d="root"){let l=Object.keys(u).length>0?e.child(u):e,f=(m,p,b,O=d)=>{if(O==="root"&&Ge())return;let w=mn(m,p,b,u,c),Ae=w.message,_e={caller:w.caller},Je=$s(w.data);!Je.hidden&&Je.value!==void 0&&(_e.data=Je.value);let Vr=jn[m],Wt=l;(Wt[Vr]??Wt.info??((tc,rc)=>{})).call(l,_e,Ae),t.write(w),Un(n,w),$n(o,w),zn(s,w),Kn(a,w),Wn(i,w);},h=(m,p,b="structured-flush")=>{let O=hn(m.level),w=yn(O,p,m,u,c),Ae=jn[O],_e=l;(_e[Ae]??_e.info??((Vr,Wt)=>{})).call(l,{caller:w.caller,...w},w.message),(b!=="root"||!Ge())&&t.write(w),Un(n,w),$n(o,w),zn(s,w),Kn(a,w),Wn(i,w);},y={success:(m,...p)=>{f("success",m,p);},critical:(m,...p)=>{f("critical",m,p);},warning:(m,...p)=>{f("warning",m,p);},info:(m,...p)=>{f("info",m,p);},debug:(m,...p)=>{f("debug",m,p);},error:(m,...p)=>{f("error",m,p);},warn:(m,...p)=>{f("warn",m,p);},table:(m,p)=>{p&&typeof p=="object"&&he.env.get("NODE_ENV")!=="production"&&(console.log("TABLE:",m),console.table(D(p,c))),f("table",m,p===void 0?[]:[p]);},flush:async()=>{await t.flush(),r&&await r.flush(),await Promise.allSettled([n.flush(),o.flush(),s.flush(),a.flush(),i.flush()]);},shutdown:async()=>{await t.shutdown(),r&&await r.shutdown(),await Promise.allSettled([n.flush(),o.flush(),s.flush(),a.flush(),i.flush()]);},createStructuredLog:(m,p)=>Er(y,m,{initialFields:p}),child:m=>{let p={...u,...m};return Rr(e,t,r,n,o,s,a,i,c,p,d)},[kr]:{bindings:u,betterstack:n,databuddy:o,posthog:s,sentry:a,otlp:i,redact:c,sink:t,create:(m,p=u)=>Rr(e,t,r,n,o,s,a,i,c,p,m),writeStructured:(m,p,b="structured-flush")=>{h(m,p,b);}}};return y}var br=null;function Pe(e){if(e===void 0&&br)return br;let t=Te(e),r=Ks(t),n=En(t),o=Fs(t),s=qs(t),a=Hs(t),i=js(t),c=zs(t),u=t.connectors.delivery.enabled?new st(t.connectors.delivery):null;if(u){u.bindTarget(o),u.bindTarget(s),u.bindTarget(a),u.bindTarget(i);for(let l of c.getAutoForwardTargets())u.bindTarget(l);}let d=Rr(r,n,u,o,s,a,i,c,t.redact);return e===void 0&&(br=d),d}var Z=Pe();function Ce(e,t){let r=Ws(e);return typeof e=="string"?{text:r,data:t}:{text:r,data:[e,...t]}}function Ws(e){return Oe(e)}function Vn(e,t){return qe({debug:(r,...n)=>{let{text:o,data:s}=Ce(r,n);e.debug(o,...s);},info:(r,...n)=>{let{text:o,data:s}=Ce(r,n);e.info(o,...s);},error:(r,...n)=>{let{text:o,data:s}=Ce(r,n);e.error(o,...s);},warn:(r,...n)=>{let{text:o,data:s}=Ce(r,n);e.warn(o,...s);},warning:(r,...n)=>{let{text:o,data:s}=Ce(r,n);e.warning(o,...s);},success:(r,n)=>{let{text:o,data:s}=Ce(r,n===void 0?[]:[n]);n?e.success(o,...s):e.success(o);},critical:(r,n)=>{let{text:o,data:s}=Ce(r,n===void 0?[]:[n]);n?e.critical(o,...s):e.critical(o);},table:(r,n)=>{e.table(r,n);},flush:()=>e.flush(),shutdown:()=>e.shutdown(),createStructuredLog:(r,n)=>e.createStructuredLog(r,n),child:r=>Vn(e.child(r))},e)}function vr(e={}){let t=Pe(e);return Vn(t)}var Js=vr();function U(){return Js}function Gs(){return qe({debug:(e,...t)=>{U().debug(e,...t);},info:(e,...t)=>{U().info(e,...t);},error:(e,...t)=>{U().error(e,...t);},warn:(e,...t)=>{U().warn(e,...t);},warning:(e,...t)=>{U().warning(e,...t);},success:(e,t)=>{if(t===void 0){U().success(e);return}U().success(e,t);},critical:(e,t)=>{if(t===void 0){U().critical(e);return}U().critical(e,t);},table:(e,t)=>{U().table(e,t);},flush:()=>U().flush(),shutdown:()=>U().shutdown(),createStructuredLog:(e,t)=>U().createStructuredLog(e,t),child:e=>U().child(e)},U())}var gt=Gs();var Qs={CONTINUE:{status:100,message:"Continue"},SWITCHING_PROTOCOLS:{status:101,message:"Switching Protocols"},PROCESSING:{status:102,message:"Processing"},EARLY_HINTS:{status:103,message:"Early Hints"},OK:{status:200,message:"OK"},CREATED:{status:201,message:"Created"},ACCEPTED:{status:202,message:"Accepted"},NON_AUTHORITATIVE_INFORMATION:{status:203,message:"Non-Authoritative Information"},NO_CONTENT:{status:204,message:"No Content"},RESET_CONTENT:{status:205,message:"Reset Content"},PARTIAL_CONTENT:{status:206,message:"Partial Content"},MULTI_STATUS:{status:207,message:"Multi-Status"},ALREADY_REPORTED:{status:208,message:"Already Reported"},IM_USED:{status:226,message:"IM Used"},MULTIPLE_CHOICES:{status:300,message:"Multiple Choices"},MOVED_PERMANENTLY:{status:301,message:"Moved Permanently"},FOUND:{status:302,message:"Found"},SEE_OTHER:{status:303,message:"See Other"},NOT_MODIFIED:{status:304,message:"Not Modified"},USE_PROXY:{status:305,message:"Use Proxy"},TEMPORARY_REDIRECT:{status:307,message:"Temporary Redirect"},PERMANENT_REDIRECT:{status:308,message:"Permanent Redirect"},BAD_REQUEST:{status:400,message:"Bad Request"},UNAUTHORIZED:{status:401,message:"Unauthorized"},PAYMENT_REQUIRED:{status:402,message:"Payment Required"},FORBIDDEN:{status:403,message:"Forbidden"},NOT_FOUND:{status:404,message:"Not Found"},METHOD_NOT_ALLOWED:{status:405,message:"Method Not Allowed"},NOT_ACCEPTABLE:{status:406,message:"Not Acceptable"},PROXY_AUTHENTICATION_REQUIRED:{status:407,message:"Proxy Authentication Required"},REQUEST_TIMEOUT:{status:408,message:"Request Timeout"},CONFLICT:{status:409,message:"Conflict"},GONE:{status:410,message:"Gone"},LENGTH_REQUIRED:{status:411,message:"Length Required"},PRECONDITION_FAILED:{status:412,message:"Precondition Failed"},PAYLOAD_TOO_LARGE:{status:413,message:"Payload Too Large"},URI_TOO_LONG:{status:414,message:"URI Too Long"},UNSUPPORTED_MEDIA_TYPE:{status:415,message:"Unsupported Media Type"},RANGE_NOT_SATISFIABLE:{status:416,message:"Range Not Satisfiable"},EXPECTATION_FAILED:{status:417,message:"Expectation Failed"},IM_A_TEAPOT:{status:418,message:"I'm a Teapot"},MISDIRECTED_REQUEST:{status:421,message:"Misdirected Request"},UNPROCESSABLE_ENTITY:{status:422,message:"Unprocessable Entity"},LOCKED:{status:423,message:"Locked"},FAILED_DEPENDENCY:{status:424,message:"Failed Dependency"},TOO_EARLY:{status:425,message:"Too Early"},UPGRADE_REQUIRED:{status:426,message:"Upgrade Required"},PRECONDITION_REQUIRED:{status:428,message:"Precondition Required"},TOO_MANY_REQUESTS:{status:429,message:"Too Many Requests"},REQUEST_HEADER_FIELDS_TOO_LARGE:{status:431,message:"Request Header Fields Too Large"},UNAVAILABLE_FOR_LEGAL_REASONS:{status:451,message:"Unavailable For Legal Reasons"},INTERNAL_SERVER_ERROR:{status:500,message:"Internal Server Error"},NOT_IMPLEMENTED:{status:501,message:"Not Implemented"},BAD_GATEWAY:{status:502,message:"Bad Gateway"},SERVICE_UNAVAILABLE:{status:503,message:"Service Unavailable"},GATEWAY_TIMEOUT:{status:504,message:"Gateway Timeout"},HTTP_VERSION_NOT_SUPPORTED:{status:505,message:"HTTP Version Not Supported"},VARIANT_ALSO_NEGOTIATES:{status:506,message:"Variant Also Negotiates"},INSUFFICIENT_STORAGE:{status:507,message:"Insufficient Storage"},LOOP_DETECTED:{status:508,message:"Loop Detected"},BANDWIDTH_LIMIT_EXCEEDED:{status:509,message:"Bandwidth Limit Exceeded"},NOT_EXTENDED:{status:510,message:"Not Extended"},NETWORK_AUTHENTICATION_REQUIRED:{status:511,message:"Network Authentication Required"}},Vs=["status","statusCode","code","message","stack","why","fix","link","details","cause","title","detail","logLevel","error","data"];function Ys(e){return e==="debug"||e==="info"||e==="warning"||e==="error"||e==="critical"}function Yn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&/^\d+$/.test(e.trim()))return Number.parseInt(e,10)}function Xs(e){return K(e)?e:void 0}function Xn(e){return e.status!==void 0||e.statusCode!==void 0||e.code!==void 0||e.message!==void 0||e.stack!==void 0||e.why!==void 0||e.fix!==void 0||e.link!==void 0||e.details!==void 0||e.cause!==void 0||e.logLevel!==void 0}function to(e){let t=typeof e.title=="string"?e.title:void 0,r=typeof e.detail=="string"?e.detail:void 0;return {status:Yn(e.status),statusCode:Yn(e.statusCode),code:typeof e.code=="string"||typeof e.code=="number"?e.code:void 0,message:typeof e.message=="string"?e.message:t??r,stack:typeof e.stack=="string"?e.stack:void 0,why:typeof e.why=="string"?e.why:void 0,fix:typeof e.fix=="string"?e.fix:void 0,link:typeof e.link=="string"?e.link:void 0,details:Xs(e.details),cause:e.cause,logLevel:Ys(e.logLevel)?e.logLevel:void 0}}function Dr(e,t){let r=to(e);return t===void 0?Xn(r)?r:void 0:typeof t=="string"?Xn(r)?{...r,message:r.message??t}:t:{status:r.status??t.status,statusCode:r.statusCode??t.statusCode,code:r.code??t.code,message:r.message??t.message,stack:r.stack??t.stack,why:r.why??t.why,fix:r.fix??t.fix,link:r.link??t.link,details:r.details??t.details,cause:r.cause??t.cause,logLevel:r.logLevel??t.logLevel}}function Zn(e){return Vs.some(t=>e[t]!==void 0)}function Zs(e){return typeof Response<"u"&&e instanceof Response?true:K(e)&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.clone=="function"&&typeof e.text=="function"}var Le=class e extends Error{constructor(r){super(r.message);g(this,"name","BlypError");g(this,"status");g(this,"statusCode");g(this,"code");g(this,"why");g(this,"fix");g(this,"link");g(this,"details");g(this,"cause");g(this,"logLevel");Object.setPrototypeOf(this,new.target.prototype),this.status=r.status,this.statusCode=r.statusCode,this.code=r.code,this.why=r.why,this.fix=r.fix,this.link=r.link,this.details=r.details,this.cause=r.cause,this.logLevel=r.logLevel,r.stack?this.stack=r.stack:typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,e);}toJSON(){return {name:"BlypError",message:this.message,status:this.status,statusCode:this.statusCode,...this.code!==void 0?{code:this.code}:{},...this.why!==void 0?{why:this.why}:{},...this.fix!==void 0?{fix:this.fix}:{},...this.link!==void 0?{link:this.link}:{},...this.details!==void 0?{details:this.details}:{}}}};function ro(e,t){return t||(e>=500?"critical":e>=400?"error":"warning")}function ei(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{}}:e}function He(e,t,r){let n=ro(t.status,r??t.logLevel);(()=>{switch(n){case "debug":return e.debug;case "info":return e.info;case "warning":return e.warning;case "critical":return e.critical;default:return e.error}})()(t.message,{type:"application_error",status:t.status,statusCode:t.statusCode,code:t.code,why:t.why,fix:t.fix,link:t.link,details:t.details,cause:ei(t.cause)});}function Ar(e,t={}){let n=e.status??e.statusCode??t.status??t.statusCode??500,o=pt(n),s=e.message??t.message??o?.message??`HTTP ${n}`;return {status:n,statusCode:n,message:s,code:e.code??t.code??o?.code,why:e.why??t.why??o?.why,fix:e.fix??t.fix??o?.fix,link:e.link??t.link??o?.link,details:e.details??t.details??o?.details,cause:e.cause??t.cause,stack:e.stack??t.stack,logLevel:ro(n,e.logLevel??t.logLevel??o?.logLevel)}}function no(e,t={}){let r=new Le(Ar(e,t));return e.skipLogging!==true&&e.logger&&He(e.logger,r,e.logLevel),r}function oo(e,t){let r={...e,statusCode:e.status,create(n={}){return t?t(e,n):no({status:e.status,message:e.message,code:n.code??e.code,why:n.why??e.why,fix:n.fix??e.fix,link:n.link??e.link,details:n.details??e.details,cause:n.cause,stack:n.stack,logLevel:n.logLevel??e.logLevel,logger:n.logger,skipLogging:n.skipLogging})},extend(n){return oo({key:n.code,status:e.status,message:n.message??e.message,code:n.code,why:n.why??e.why,fix:n.fix??e.fix,link:n.link??e.link,details:n.details??e.details,logLevel:n.logLevel??e.logLevel},t)}};return Object.freeze(r)}function _r(e){let t=Object.entries(Qs).map(([r,n])=>[r,oo({key:r,...n},e)]);return Object.freeze(Object.fromEntries(t))}var ti=_r(),ri=new Map(Object.values(ti).map(e=>[e.status,e]));function pt(e){return ri.get(e)}function Pr(e){if(typeof e=="string")return e;if(K(e)){if(e.error!==void 0){let t=e.error;if(typeof t=="string")return Dr(e,t);if(K(t))return Dr(e,Pr(t))}if(K(e.data)){let t=e.data;if(t.error!==void 0||Zn(t))return Dr(e,Pr(t))}if(Zn(e))return to(e)}}function eo(e,t={},r={}){if(e instanceof Le)return e;let n=(()=>{if(e instanceof Error){let u=e;return {status:u.status,statusCode:u.statusCode,code:u.code,message:e.message,stack:e.stack,why:u.why,fix:u.fix,link:u.link,details:u.details,cause:u.cause,logLevel:u.logLevel}}return Pr(e)})(),o=r.status&&r.status>0?r.status:void 0,s=typeof n=="string"?void 0:n?.status??n?.statusCode,a=o??s??t.fallbackStatus??500,i=typeof n=="string"&&n.trim()||void 0,c=r.statusText?.trim()||void 0;return no(typeof n=="string"?{message:i,...o!==void 0?{status:o}:{}}:{...n??{},...o!==void 0?{status:o,statusCode:o}:{}},{status:a,message:(typeof n=="string"?i:n?.message)??c??pt(a)?.message??`HTTP ${a}`})}async function ni(e){let t=e.headers.get("content-type")?.toLowerCase();if(t?.includes("application/json")||t?.includes("+json"))try{return await e.clone().json()}catch{try{return await e.clone().text()}catch{return}}try{return await e.clone().text()}catch{return}}function oi(e,t={}){if(Zs(e))return (async()=>{let n=await ni(e).catch(()=>{}),o=eo(n,t,{status:e.status,statusText:e.statusText});return t.logger&&He(t.logger,o,t.logLevel),o})();let r=eo(e,t);return t.logger&&He(t.logger,r,t.logLevel),r}function ao(e){let t=new Le(Ar(e));if(e.skipLogging!==true){He(e.logger??Z,t,e.logLevel);let r=ct(e.logger??Z);r?.shouldAutoCaptureExceptions()&&r.captureException(t,{source:"server",warnIfUnavailable:true,properties:{"blyp.type":"application_error",status:t.status,statusCode:t.statusCode,...t.code!==void 0?{code:t.code}:{},...t.why!==void 0?{why:t.why}:{},...t.fix!==void 0?{fix:t.fix}:{},...t.link!==void 0?{link:t.link}:{},...t.details!==void 0?{details:t.details}:{}}});let n=ut(e.logger??Z);n?.shouldAutoCaptureExceptions()&&n.captureException(t,{source:"server",warnIfUnavailable:true,context:{"blyp.type":"application_error",status:t.status,statusCode:t.statusCode,...t.code!==void 0?{code:t.code}:{},...t.why!==void 0?{why:t.why}:{},...t.fix!==void 0?{fix:t.fix}:{},...t.link!==void 0?{link:t.link}:{},...t.details!==void 0?{details:t.details}:{}}});let o=dt(e.logger??Z);o?.shouldAutoCaptureExceptions()&&o.captureException(t,{source:"server",warnIfUnavailable:true,properties:{blyp_type:"application_error",status:t.status,status_code:t.statusCode,...t.code!==void 0?{code:t.code}:{},...t.why!==void 0?{why:t.why}:{},...t.fix!==void 0?{fix:t.fix}:{},...t.link!==void 0?{link:t.link}:{},...t.details!==void 0?{details:t.details}:{}}});}return t}var so=_r((e,t={})=>ao({status:e.status,message:e.message,code:e.code,why:e.why,fix:e.fix,link:e.link,details:e.details,...t})),ai=new Map(Object.values(so).map(e=>[e.status,e]));function si(e){return ai.get(e)??pt(e)}async function ft(e,t=J()){let r=new De(t);try{return await r.init(),await e(r)}finally{await r.shutdown().catch(()=>{});}}function ci(){return J()}function ui(e=J()){return z__default.default.existsSync(e)}async function di(e=J()){return ft(t=>t.getStatusSummary(),e)}async function li(e={},t=J()){return ft(r=>r.listDeadLetters({limit:e.limit??100,offset:e.offset??0,connectorType:e.connectorType,connectorTarget:e.connectorTarget}),t)}async function gi(e,t=J()){return ft(r=>r.retryDeadLetters(e,Date.now()),t)}async function pi(e,t=J()){return ft(r=>r.clearDeadLetters(e),t)}function yi(e){return {timestamp:"",level:"unknown",message:e}}function hi(e){try{return JSON.parse(e)}catch{return yi(e)}}function Ci(e){let t=z__default.default.readFileSync(e);return e.endsWith(".gz")?Buffer.from(fflate.gunzipSync(t)).toString("utf8"):t.toString("utf8")}function io(e){let t=e.timestamp?`[${e.timestamp}] `:"",r=e.level?e.level.toUpperCase():"UNKNOWN",n=e.caller?` (${e.caller})`:"";return `${t}${r} ${e.message}${n}`.trim()}async function Li(e,t={}){let{format:r="pretty",limit:n}=t,s=Ci(e).split(`
701
- `).map(c=>c.trim()).filter(c=>c.length>0),i=(typeof n=="number"&&n>=0?s.slice(-n):s).map(hi);return r==="json"?i:i.map(io).join(`
702
- `)}function bi(e,t=200,r=500,n=false){if(n&&e.error)return e.error.status?e.error.status:e.error.statusCode?e.error.statusCode:e.code&&parseInt(e.code,10)||r;if(e.set?.status){let o=e.set.status;return typeof o=="number"?o:parseInt(o,10)||t}return t}function fd(){return process.env.NODE_ENV!=="production"}function wi(e){let t=e.indexOf("?"),r=t>=0?e.substring(0,t):e;return r.endsWith("/")&&r.length>1&&(r=r.slice(0,-1)),r.startsWith("/")||(r="/"+r),r}function Ri(e){let t=e.indexOf("?"),r=t>=0?e.substring(0,t):e;return r.endsWith("/")&&r.length>1&&(r=r.slice(0,-1)),r.startsWith("/")||(r="/"+r),r}function Ir(e,t){if(!t||t.length===0)return false;let r=wi(e);return t.some(n=>{let o=Ri(n);if(o===r||o==="/**"||o==="**")return true;if(o==="/*")return r.split("/").filter(a=>a.length>0).length===1;if(o.endsWith("/*")&&!o.includes("**")){let s=o.slice(0,-1);return r.startsWith(s)?r.slice(s.length).split("/").filter(c=>c.length>0).length===1:false}if(o.includes("**")){if(o==="/**")return true;if(o.startsWith("/")&&o.endsWith("**")){let c=o.slice(0,-2);return c.endsWith("/")&&c.length>1&&(c=c.slice(0,-1)),c===r?true:r.startsWith(c+"/")}let s=o.indexOf("**"),a=o.substring(0,s),i=o.substring(s+2);return a.endsWith("/")&&a.length>1&&(a=a.slice(0,-1)),a===""&&i===""?true:a!==""&&i===""?r.startsWith(a+"/"):a===""&&i!==""?r.endsWith(i)||r.includes(i+"/"):a!==""&&i!==""?r.startsWith(a)&&(r.endsWith(i)||r.includes(i+"/")):false}if(o.includes("*")){let s=o.lastIndexOf("."),a=o.lastIndexOf("*");if(s>a&&a>0&&o[a-1]==="/"){let d=o.slice(a),l=r.slice(r.lastIndexOf("/")+1),f=l.lastIndexOf(".");if(f>0)return l.slice(f)===d}let i=o.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*");return new RegExp("^"+i+"$").test(r)}return false})}function mt(e){return `${{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[33m",PATCH:"\x1B[34m",DELETE:"\x1B[31m"}[e.toUpperCase()]||""}${e}\x1B[0m`}function yt(e){let t="\x1B[0m";return e>=500?`\x1B[31m${e}${t}`:e>=400?`\x1B[33m${e}${t}`:e>=300?`\x1B[36m${e}${t}`:e>=200?`\x1B[32m${e}${t}`:`\x1B[37m${e}${t}`}function co(e){return {GET:"\u2192",POST:"\u2191",PUT:"\u21D1",PATCH:"\u2197",DELETE:"\u2715"}[e.toUpperCase()]||"\u2022"}function ht(e){let t="\x1B[0m";return e<100?`\x1B[32m${e}ms${t}`:e<300?`\x1B[33m${e}ms${t}`:e<1e3?`\x1B[31m${e}ms${t}`:`\x1B[41m\x1B[37m${e}ms${t}`}function yd(e){return `${{error:"\x1B[31m",critical:"\x1B[35m",warning:"\x1B[33m",info:"\x1B[34m",success:"\x1B[32m",debug:"\x1B[36m"}[e.toLowerCase()]||""}${e.toUpperCase()}\x1B[0m`}var hd={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m"};function k(e,t){if(!e)return;if(e instanceof Headers||typeof e.get=="function")return e.get(t)??e.get(t.toLowerCase())??void 0;let r=e,n=r[t]??r[t.toLowerCase()];return Array.isArray(n)?n[0]:n}function ki(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>t.match(/for="?(\[[^\]]+\]|[^;,\s"]+)/i)?.[1]?.replace(/^"|"$/g,"")??"").map(t=>t.replace(/^\[|\]$/g,"")).filter(Boolean):[]}function Si(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function xi(e){if(e.startsWith("[")){let t=e.indexOf("]");return t>=0?e.slice(1,t):e}return e.replace(/:\d+$/,"")}function Ti(e){return /edg\//i.test(e)?"Edge":/opr\//i.test(e)||/opera/i.test(e)?"Opera":/chrome\//i.test(e)&&!/edg\//i.test(e)?"Chrome":/firefox\//i.test(e)?"Firefox":/safari\//i.test(e)&&!/chrome\//i.test(e)?"Safari":/curl\//i.test(e)?"curl":/postmanruntime/i.test(e)?"Postman":"Unknown"}function Ei(e){return /windows/i.test(e)?"Windows":/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/mac os x|macintosh/i.test(e)?"macOS":/linux/i.test(e)?"Linux":"Unknown"}function vi(e){return e?/bot|crawler|spider|curl|wget|postmanruntime/i.test(e)?"bot":/ipad|tablet/i.test(e)?"tablet":/mobi|iphone|android/i.test(e)?"mobile":"desktop":"unknown"}function P(e,t="/"){if(!e)return t;if(e.startsWith("http://")||e.startsWith("https://"))try{return new URL(e).pathname||t}catch{return t}if(e.startsWith("/")){let r=e.indexOf("?");return r>=0?e.slice(0,r):e}try{return new URL(e,"http://localhost").pathname||t}catch{return t}}function S(e,t,r){return {method:e,url:t,headers:r}}function Or(e,t,r=W()){let n=t??P(e.url),o=(()=>{try{return new URL(e.url)}catch{try{return new URL(n,"http://localhost")}catch{return null}}})(),s=k(e.headers,"x-forwarded-host")??k(e.headers,"host")??o?.host??void 0,a=s?xi(s):o?.hostname,i=s?.match(/:(\d+)$/)?.[1]??(o?.port||void 0),c=Si(k(e.headers,"x-forwarded-for")),u=ki(k(e.headers,"forwarded")),d=[k(e.headers,"cf-connecting-ip"),k(e.headers,"true-client-ip"),k(e.headers,"fly-client-ip"),k(e.headers,"x-real-ip"),k(e.headers,"x-client-ip"),c[0],u[0]].filter(y=>!!y),l=k(e.headers,"user-agent"),f=k(e.headers,"sec-ch-ua-platform")?.replace(/^"|"$/g,"")??void 0,h=vi(l??"");return {hostname:a,ip:d[0],forwardedFor:[...c,...u].filter((y,m,p)=>p.indexOf(y)===m),protocol:k(e.headers,"x-forwarded-proto")??(o?.protocol?o.protocol.replace(/:$/,""):void 0),port:i,userAgent:l,origin:k(e.headers,"origin"),referer:k(e.headers,"referer"),acceptLanguage:k(e.headers,"accept-language"),headers:rn(e.headers,r),client:{ip:d[0],hostname:a,browser:l?Ti(l):void 0,os:l?Ei(l):void 0,deviceType:h,platform:f,isMobile:h==="mobile"}}}function Ct(e,t,r,n,o,s={},a=W()){return {type:t,method:e.method,url:r,statusCode:n,responseTime:o,...Or(e,r,a),...s}}function Lt(e,t,r,n){let o=mt(e),s=yt(t),a=ht(n),i=co(e);return `${o} ${i} ${s} ${r} ${a}`}function R(e,t){if(e==null)return t===void 0?void 0:{statusCode:t,message:`HTTP ${t}`};if(e instanceof Error){let r=e;return {status:r.status,statusCode:r.statusCode??t,code:r.code,message:e.message,stack:e.stack,why:r.why,fix:r.fix,link:r.link,details:r.details,cause:r.cause}}if(typeof e=="object"){let r=e;return {status:typeof r.status=="number"?r.status:void 0,statusCode:typeof r.statusCode=="number"?r.statusCode:t,code:typeof r.code=="string"||typeof r.code=="number"?r.code:void 0,message:typeof r.message=="string"?r.message:`HTTP ${t??500}`,stack:typeof r.stack=="string"?r.stack:void 0,why:typeof r.why=="string"?r.why:void 0,fix:typeof r.fix=="string"?r.fix:void 0,link:typeof r.link=="string"?r.link:void 0,details:r.details!==null&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:void 0,cause:r.cause}}return {statusCode:t,message:typeof e=="string"?e:`HTTP ${t??500}`}}function B(e){return e>=400}function Di(e,t){let r=at(e),n=typeof e.caller=="string"?e.caller:void 0,o=ce(e,"groupId"),s=ce(e,"traceId"),a=ce(e,"method"),i=ce(e,"path"),c=ce(e,"status"),u=ce(e,"duration"),d=mr(e,"pathname"),l=mr(e,"url"),f=yr(e,"sessionId"),h=yr(e,"pageId"),y={"blyp.level":e.level,"blyp.source":t,"blyp.payload":lr(e)},m=[["blyp.type",r],["blyp.caller",n],["blyp.group_id",o],["blyp.trace_id",s],["http.method",a],["url.path",i],["client.page_path",d],["client.page_url",l],["client.session_id",f],["client.page_id",h]],p=[["http.status_code",c],["blyp.duration_ms",u]];for(let[b,O]of m)O&&(y[b]=O);for(let[b,O]of p)O!==void 0&&(y[b]=O);return y}function Br(e,t,r={}){return {...Di(e,t),...r}}function uo(e,t,r,n){let o=mt(e),s=yt(t),a=ht(n);return `${o} ${r} ${s} ${a}`}function Pi(e,t){let r=rr(t?.path??fe),n=t?.enabled===false?null:{path:r};return e===false?null:e===void 0?n:e===true?{path:r}:{...n,...e,path:rr(e.path??r)}}function _(e={},t){let r=Te({...e.level!==void 0?{level:e.level}:{},...e.pretty!==void 0?{pretty:e.pretty}:{},...e.destination!==void 0?{destination:e.destination}:{},...e.logDir!==void 0?{logDir:e.logDir}:{},...e.file!==void 0?{file:e.file}:{},...e.database!==void 0?{database:e.database}:{},...e.redact!==void 0?{redact:e.redact}:{},...e.connectors!==void 0?{connectors:e.connectors}:{}}),{level:n=r.level,pretty:o=r.pretty,destination:s=r.destination,logDir:a=r.logDir,file:i=r.file,database:c=r.database,autoLogging:u=true,customProps:d,logErrors:l=true,includePaths:f,ignorePaths:h,clientLogging:y,connectors:m}=e,p=t??Pe({level:n,pretty:o,destination:s,logDir:a,file:i,database:c,connectors:m}),b=Pi(y,r.clientLogging),O=b?.path??fe,w=f,Ae=b?Array.from(new Set([...h??[],O])):h;return {logger:p,betterstack:xr(p),databuddy:Tr(p),posthog:Sr(p),sentry:Jn(p),otlp:Gn(p),resolvedConfig:r,level:n,pretty:o,logDir:a,file:i,autoLogging:u,customProps:d,logErrors:l,resolvedIncludePaths:w,resolvedIgnorePaths:Ae,resolvedClientLogging:b,ingestionPath:O}}function Ai(e,t){return !t||t.length===0?true:Ir(e,t)}function lo(e,t,r){return Ai(e,t)?Ir(e,r):true}function M(e,t,r){return e.autoLogging===false||typeof e.autoLogging=="object"&&e.autoLogging.ignore?.(t)?true:lo(r,e.resolvedIncludePaths,e.resolvedIgnorePaths)}function x(e,t){return e.logErrors?lo(t,e.resolvedIncludePaths,e.resolvedIgnorePaths):true}function C(e,t){return e.customProps?e.customProps(t):{}}function F(e,t,r,n,o,s,a={}){let i=Ct(r,"http_request",n,o,s,a,lt(e));return t==="info"?e.info(Lt(r.method,o,n,s),i):(e.info(uo(r.method,o,n,s),i),Object.keys(a).length>0&&e.debug("Request context",a)),i}function T(e,t,r,n,o,s,a,i={},c={}){let u=Ct(r,"http_error",n,o,s,{error:a?.message??`HTTP ${o}`,stack:a?.stack,code:a?.code,why:a?.why,fix:a?.fix,link:a?.link,details:a?.details,...i},lt(e)),d=t==="info"?Lt(r.method,o,n,s):uo(r.method,o,n,s);e.error(d,u);let l=ct(e);l?.shouldAutoCaptureExceptions()&&l.captureException(c.error??a??d,{source:"server",warnIfUnavailable:true,distinctId:c.distinctId??k(r.headers,"x-posthog-distinct-id"),properties:Br({timestamp:new Date().toISOString(),level:"error",message:d,data:u},"server",{$request_method:r.method,$request_path:n,$current_url:r.url,$response_status_code:o,...k(r.headers,"user-agent")?{$user_agent:k(r.headers,"user-agent")}:{},...u.ip?{$ip:u.ip}:{}})});let f=ut(e);f?.shouldAutoCaptureExceptions()&&f.captureException(c.error??a??d,{source:"server",warnIfUnavailable:true,context:{timestamp:new Date().toISOString(),level:"error",message:d,status:o,path:n,data:u}});let h=dt(e);return h?.shouldAutoCaptureExceptions()&&h.captureException(c.error??a??d,{source:"server",warnIfUnavailable:true,properties:{method:r.method,path:n,status_code:o,...r.url?{current_url:r.url}:{},...k(r.headers,"user-agent")?{user_agent:k(r.headers,"user-agent")}:{},...u.ip?{ip:u.ip}:{},payload:u}}),u}async function _i(e,t){if(t!==void 0)return typeof t=="string"?JSON.parse(t):t;if(typeof e.json=="function")return await e.json();throw new Error("Unable to parse client log payload")}function Ii(e,t){switch(t){case "debug":return e.debug;case "info":return e.info;case "warning":return e.warning;case "error":return e.error;case "critical":return e.critical;case "success":return e.success}}async function q(e){let{config:t,ctx:r,request:n,body:o,deliveryPath:s}=e;if(!t.resolvedClientLogging)return {status:404};let a;try{a=await _i(n,o);}catch{return {status:400}}if(!nn(a))return {status:400};if(!(t.resolvedClientLogging.validate?await t.resolvedClientLogging.validate(r,a):true))return {status:403};let c=t.resolvedClientLogging.enrich?await t.resolvedClientLogging.enrich(r,a):void 0,u=lt(t.logger),d=D(a,u),l=D({...d,receivedAt:new Date().toISOString(),delivery:Or(n,s??P(n.url),u)},u);c!==void 0&&(l.serverContext=D(c,u));let f=ge(`[client] ${d.message}`,u),h=oe(),y=typeof d.traceId=="string"&&d.traceId.length>0?d.traceId:h;try{y&&Ie(y),d.level==="table"?t.logger.table(f,l):Ii(t.logger,d.level)(f,l);}finally{Ie(h);}let m={};if(d.connector==="betterstack"){if(m["x-blyp-betterstack-status"]=t.betterstack.ready?"enabled":"missing",t.betterstack.ready){let p={timestamp:l.receivedAt,level:d.level,message:f,data:l};if(t.betterstack.send(p,{source:"client"}),(d.level==="error"||d.level==="critical")&&t.betterstack.shouldAutoCaptureExceptions()){let b=d.data&&typeof d.data=="object"&&!Array.isArray(d.data)&&typeof d.data.message=="string"?d.data:d.message;t.betterstack.captureException(b,{source:"client",warnIfUnavailable:true,context:{sessionId:d.session.sessionId,pageUrl:d.page.url,pagePath:d.page.pathname,metadata:d.metadata,payload:l}});}}}else if(d.connector==="databuddy"){if(m["x-blyp-databuddy-status"]=t.databuddy.ready?"enabled":"missing",t.databuddy.ready){let p={timestamp:l.receivedAt,level:d.level,message:f,data:l};if(t.databuddy.send(p,{source:"client"}),(d.level==="error"||d.level==="critical")&&t.databuddy.shouldAutoCaptureExceptions()){let b=d.data&&typeof d.data=="object"&&!Array.isArray(d.data)&&typeof d.data.message=="string"?d.data:d.message;t.databuddy.captureException(b,{source:"client",warnIfUnavailable:true,sessionId:d.session.sessionId,properties:{page_url:d.page.url,page_path:d.page.pathname,client_runtime:d.device?.runtime,metadata:d.metadata,payload:l}});}}}else if(d.connector==="posthog"){if(m["x-blyp-posthog-status"]=t.posthog.ready?"enabled":"missing",t.posthog.ready){let p={timestamp:l.receivedAt,level:d.level,message:f,data:l};if(t.posthog.send(p,{source:"client"}),(d.level==="error"||d.level==="critical")&&t.posthog.shouldAutoCaptureExceptions()){let b=l.metadata,O=b&&typeof b=="object"&&!Array.isArray(b)&&typeof b.posthogDistinctId=="string"&&b.posthogDistinctId?String(b.posthogDistinctId):void 0,w=d.data&&typeof d.data=="object"&&!Array.isArray(d.data)&&typeof d.data.message=="string"?d.data:d.message;t.posthog.captureException(w,{source:"client",warnIfUnavailable:true,distinctId:O,properties:Br(p,"client",{$session_id:d.session.sessionId,$current_url:d.page.url,$request_path:d.page.pathname,"client.runtime":d.device?.runtime,"client.metadata":d.metadata})});}}}else if(d.connector==="sentry")m["x-blyp-sentry-status"]=t.sentry.ready?"enabled":"missing",t.sentry.ready&&t.sentry.send({timestamp:l.receivedAt,level:d.level,message:f,data:l},{source:"client"});else if(d.connector?.type==="otlp"){let p=t.otlp.get(d.connector.name);m["x-blyp-otlp-status"]=p.ready?"enabled":"missing",p.ready&&p.send({timestamp:l.receivedAt,level:d.level,message:f,data:l},{source:"client"});}return Object.keys(m).length>0?{status:204,headers:m}:{status:204}}async function bt(e){let t=[];for await(let r of e)t.push(Buffer.isBuffer(r)?r:Buffer.from(r));return Buffer.concat(t).toString("utf8")}function je(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return e;let r=k(t,"x-forwarded-proto")??"http",n=k(t,"host")??"localhost";return `${r}://${n}${e.startsWith("/")?e:`/${e}`}`}function Oi(e){return e.resolvedConfig.destination==="database"}async function L(e){if(Oi(e))try{await e.logger.flush();}catch(t){console.warn("[Blyp] Warning: Failed to flush database logs.",t);}}function N(e,t={}){let r=Qn(e,"request-scoped"),n=qe({...r,createStructuredLog:(o,s)=>Er(n,o,{initialFields:s,resolveDefaultFields:()=>{let a=oe();return {...t.resolveStructuredFields?.()??{},...a?{traceId:a}:{}}},onCreate:()=>{Vt();},onEmit:()=>{Yt(),t.onStructuredEmit?.();}}),child(o){return N(r.child(o),t)}},r);return Qt(n),n}var Nr="x-blyp-trace-id",Bi="trace_";function E(){return `${Bi}${Xe().replace(/[^a-z0-9]/gi,"").toLowerCase().slice(0,12)}`}function v(e){Ie(e);}function I(e,t){let r=new Headers(e.headers);return r.set(Nr,t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}function go(e={}){let t=_(e);return async(r,n)=>A(async()=>{let o=performance.now(),s=E(),a=false;v(s),r.set("blypLog",N(t.logger,{resolveStructuredFields:()=>({method:r.req.method,path:r.req.path||P(r.req.url),...C(t,r)}),onStructuredEmit:()=>{a=true;}})),r.set("blypTraceId",s),r.set("blypStartTime",o);let i=r.req.path||P(r.req.url);if(t.resolvedClientLogging&&r.req.method==="POST"&&i===t.ingestionPath){let u=await q({config:t,ctx:r,request:r.req.raw,deliveryPath:t.ingestionPath});return await L(t),new Response(null,{status:u.status,headers:{...u.headers,"x-blyp-trace-id":s}})}let c;try{await n();}catch(u){throw c=u,u}finally{if(a){await L(t),r.res=I(r.res,s);return}let u=Math.round(performance.now()-o),d=S(r.req.method,r.req.url,r.req.raw.headers),l=r.res?.status??(c?500:200);if(c||B(l)){x(t,i)||T(t.logger,t.level,d,i,l,u,R(c,l),C(t,r),{error:c}),await L(t);return}M(t,r,i)||F(t.logger,t.level,d,i,l,u,C(t,r)),await L(t),r.res=I(r.res,s);}})}function Mr(e,t,r){return {req:e,res:t,error:r}}function po(e={}){let t=_(e);return (r,n,o)=>{Re();let s=E();v(s);let a=false;r.blypTraceId=s,n.setHeader(Nr,s),r.blypLog=N(t.logger,{resolveStructuredFields:()=>({method:r.method,path:P(r.originalUrl||r.url||"/"),...C(t,Mr(r,n,n.locals.blypError))}),onStructuredEmit:()=>{a=true;}}),n.locals.blypStartTime=performance.now(),n.on("finish",()=>{let c=P(r.originalUrl||r.url||"/"),u=S(r.method,je(r.originalUrl||r.url||"/",r.headers),r.headers),d=Math.round(performance.now()-(n.locals.blypStartTime??performance.now())),l=Mr(r,n,n.locals.blypError);if(!a){if(n.locals.blypError||B(n.statusCode)){x(t,c)||T(t.logger,t.level,u,c,n.statusCode,d,R(n.locals.blypError,n.statusCode),C(t,l),{error:n.locals.blypError});return}M(t,l,c)||F(t.logger,t.level,u,c,n.statusCode,d,C(t,l));}});let i=P(r.originalUrl||r.url||"/");if(t.resolvedClientLogging&&r.method.toUpperCase()==="POST"&&i===t.ingestionPath){(async()=>{let c=r.body===void 0?await bt(r):r.body,u=await q({config:t,ctx:Mr(r,n),request:S(r.method,je(r.originalUrl||r.url||"/",r.headers),r.headers),body:c,deliveryPath:t.ingestionPath});if(u.headers)for(let[d,l]of Object.entries(u.headers))n.setHeader(d,l);n.status(u.status).end();})().catch(o);return}o();}}function fo(e={}){return (t,r,n,o)=>{n.locals.blypError=t,o(t);}}function wt(e,t,r,n){return {request:e,context:t,response:r,error:n}}function mo(e={}){let t=_(e);return {logger:t.logger,withLogger:r=>async(n,o)=>A(async()=>{let s=performance.now(),a=P(n.url),i=E(),c=false;v(i);let u=N(t.logger,{resolveStructuredFields:()=>({method:n.method,path:a,...C(t,wt(n,o))}),onStructuredEmit:()=>{c=true;}});try{let d=await r(n,o,{log:u,traceId:i});if(c)return await L(t),I(d,i);let l=d.status,f=S(n.method,n.url,n.headers),h=wt(n,o,d),y=Math.round(performance.now()-s);return B(l)?x(t,a)||T(t.logger,t.level,f,a,l,y,R(void 0,l),C(t,h)):M(t,h,a)||F(t.logger,t.level,f,a,l,y,C(t,h)),await L(t),I(d,i)}catch(d){throw !c&&!x(t,a)&&T(t.logger,t.level,S(n.method,n.url,n.headers),a,500,Math.round(performance.now()-s),R(d,500),C(t,wt(n,o,void 0,d)),{error:d}),await L(t),d}}),clientLogHandler:async r=>A(async()=>{let n=E();v(n);let o=P(r.url);if(o!==t.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${o} does not match configured client logging path ${t.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":n}});let s=await q({config:t,ctx:wt(r),request:r,deliveryPath:o});return await L(t),new Response(null,{status:s.status,headers:{...s.headers,"x-blyp-trace-id":n}})})}}var kt=Symbol.for("blyp.react-router.logger"),St="__blypLog",xt=Symbol.for("blyp.react-router.trace-id"),Tt="__blypTraceId";function Rt(e,t,r){return {request:e.request,params:e.params,context:e.context,response:t,error:r}}function Ni(e){if(typeof e.get=="function"){let t=e.get(kt);return t||e.get(St)}return e[kt]??e[St]}function Mi(e,t){if(typeof e.set=="function"){e.set(kt,t),e.set(St,t);return}e[kt]=t,e[St]=t;}function Fi(e){if(typeof e.get=="function"){let t=e.get(xt);return t||e.get(Tt)}return e[xt]??e[Tt]}function qi(e,t){if(typeof e.set=="function"){e.set(xt,t),e.set(Tt,t);return}e[xt]=t,e[Tt]=t;}function Hi(e){let t=R(e);return t?.status??t?.statusCode??500}function yo(e={}){let t=_(e),r=(a,i)=>{Mi(a,i);},n=a=>{let i=Ni(a);return i&&typeof i=="object"?i:t.logger},o=(a,i)=>{qi(a,i);},s=a=>{let i=Fi(a);return typeof i=="string"?i:void 0};return {logger:t.logger,setLogger:r,getLogger:n,setTraceId:o,getTraceId:s,middleware:async(a,i)=>A(async()=>{let c=performance.now(),u=P(a.request.url),d=E(),l=false;v(d);let f=N(t.logger,{resolveStructuredFields:()=>({method:a.request.method,path:u,...C(t,Rt(a))}),onStructuredEmit:()=>{l=true;}});r(a.context,f),o(a.context,d);try{let h=await i();if(l)return await L(t),I(h,d);let y=h.status,m=Rt(a,h),p=Math.round(performance.now()-c),b=S(a.request.method,a.request.url,a.request.headers);return B(y)?x(t,u)||T(t.logger,t.level,b,u,y,p,R(void 0,y),C(t,m)):M(t,m,u)||F(t.logger,t.level,b,u,y,p,C(t,m)),await L(t),I(h,d)}catch(h){if(!l&&!x(t,u)){let y=Hi(h);T(t.logger,t.level,S(a.request.method,a.request.url,a.request.headers),u,y,Math.round(performance.now()-c),R(h,y),C(t,Rt(a,void 0,h)),{error:h});}throw await L(t),h}}),clientLogHandler:async a=>A(async()=>{let i=E();v(i);let c=P(a.url);if(c!==t.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${c} does not match configured client logging path ${t.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":i}});let d=await q({config:t,ctx:Rt({request:a,context:{}}),request:a,deliveryPath:c});return await L(t),new Response(null,{status:d.status,headers:{...d.headers,"x-blyp-trace-id":i}})})}}function Et(e,t,r,n){return {request:e,context:t,response:r,error:n}}function ho(e={}){let t=_(e);return {logger:t.logger,requestMiddleware:async({request:r,context:n,next:o})=>A(async()=>{let s=performance.now(),a=P(r.url),i=E(),c=false,u={...n,blypTraceId:i};v(i);let d=N(t.logger,{resolveStructuredFields:()=>({method:r.method,path:a,...C(t,Et(r,u))}),onStructuredEmit:()=>{c=true;}});u.blypLog=d;try{let l=await o({context:u});if(c)return await L(t),I(l,i);let f=l.status,h=Et(r,u,l),y=Math.round(performance.now()-s);return B(f)?x(t,a)||T(t.logger,t.level,S(r.method,r.url,r.headers),a,f,y,R(void 0,f),C(t,h)):M(t,h,a)||F(t.logger,t.level,S(r.method,r.url,r.headers),a,f,y,C(t,h)),await L(t),I(l,i)}catch(l){throw !c&&!x(t,a)&&T(t.logger,t.level,S(r.method,r.url,r.headers),a,500,Math.round(performance.now()-s),R(l,500),C(t,Et(r,u,void 0,l)),{error:l}),await L(t),l}}),clientLogHandlers:{POST:async r=>A(async()=>{let n=E();v(n);let o=P(r.url);if(o!==t.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${o} does not match configured client logging path ${t.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":n}});let s=await q({config:t,ctx:Et(r,{blypTraceId:n}),request:r,deliveryPath:o});return await L(t),new Response(null,{status:s.status,headers:{...s.headers,"x-blyp-trace-id":n}})})}}}function vt(e,t,r){return {event:e,response:t,error:r}}function Co(e={}){let t=_(e),r=async({event:n,resolve:o})=>A(async()=>{let s=E(),a=false;v(s),n.locals.blypTraceId=s,n.locals.blypLog=N(t.logger,{resolveStructuredFields:()=>({method:n.request.method,path:n.url.pathname,...C(t,vt(n))}),onStructuredEmit:()=>{a=true;}});let i=performance.now(),c=n.url.pathname,u=S(n.request.method,n.request.url,n.request.headers);try{let d=await o(n);if(a)return await L(t),I(d,s);let l=d.status,f=vt(n,d),h=Math.round(performance.now()-i);return B(l)?x(t,c)||T(t.logger,t.level,u,c,l,h,R(void 0,l),C(t,f)):M(t,f,c)||F(t.logger,t.level,u,c,l,h,C(t,f)),await L(t),I(d,s)}catch(d){throw !a&&!x(t,c)&&T(t.logger,t.level,u,c,500,Math.round(performance.now()-i),R(d,500),C(t,vt(n,void 0,d)),{error:d}),await L(t),d}});return {logger:t.logger,handle:r,clientLogHandler:async n=>A(async()=>{let o=E();v(o),n.locals.blypTraceId=o;let s=n.url.pathname;if(s!==t.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${s} does not match configured client logging path ${t.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":o}});let a=await q({config:t,ctx:vt(n),request:n.request,deliveryPath:s});return await L(t),new Response(null,{status:a.status,headers:{...a.headers,"x-blyp-trace-id":o}})})}}function Dt(e,t,r){return {context:e,response:t,error:r}}function Lo(e={}){let t=_(e);return {logger:t.logger,onRequest:async(r,n)=>A(async()=>{let o=E(),s=false;v(o),r.locals.blypTraceId=o,r.locals.blypLog=N(t.logger,{resolveStructuredFields:()=>({method:r.request.method,path:r.url.pathname,...C(t,Dt(r))}),onStructuredEmit:()=>{s=true;}});let a=performance.now(),i=r.url.pathname,c=S(r.request.method,r.request.url,r.request.headers);try{let u=await n();if(s)return await L(t),I(u,o);let d=u.status,l=Dt(r,u),f=Math.round(performance.now()-a);return B(d)?x(t,i)||T(t.logger,t.level,c,i,d,f,R(void 0,d),C(t,l)):M(t,l,i)||F(t.logger,t.level,c,i,d,f,C(t,l)),await L(t),I(u,o)}catch(u){throw !s&&!x(t,i)&&T(t.logger,t.level,c,i,500,Math.round(performance.now()-a),R(u,500),C(t,Dt(r,void 0,u)),{error:u}),await L(t),u}}),clientLogHandler:async r=>A(async()=>{let n=E();v(n),r.locals.blypTraceId=n;let o=r.url.pathname;if(o!==t.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${o} does not match configured client logging path ${t.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":n}});let s=await q({config:t,ctx:Dt(r),request:r.request,deliveryPath:o});return await L(t),new Response(null,{status:s.status,headers:{...s.headers,"x-blyp-trace-id":n}})})}}var bo=Symbol.for("blyp.nitro.state");function ze(e){return e.context[bo]}function wo(e,t){return e.context[bo]=t,t}function Fr(e){return e.method??e.node?.req?.method??e.request?.method??"GET"}function Ro(e){return e.headers??e.node?.req?.headers??e.request?.headers}function ji(e){if(e.request?.url)return e.request.url;let t=e.url??e.path??e.node?.req?.url??"/";return je(t,Ro(e))}function qr(e){if(typeof e.path=="string"&&e.path.length>0)return e.path;if(e.request?.url)return new URL(e.request.url).pathname;let t=e.url??e.node?.req?.url??"/";if(t.startsWith("http://")||t.startsWith("https://"))return new URL(t).pathname;let r=t.indexOf("?");return r>=0?t.slice(0,r):t}function Pt(e){return S(Fr(e),ji(e),Ro(e))}function Hr(e,t,r=200){return t instanceof Response||typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:typeof e.node?.res?.statusCode=="number"&&e.node.res.statusCode>0?e.node.res.statusCode:r}async function ko(e){if(e.body!==void 0)return e.body;if(e.request){if((e.request.headers.get("content-type")??"").includes("application/json")){let r=e.request.clone();try{return await e.request.json()}catch{return await r.text()}}return await e.request.text()}if(e.node?.req)return await bt(e.node.req);throw new Error("Unable to parse Nitro request body")}function At(e,t,r){return {event:e,response:t,error:r}}function jr(e){let t=o=>o.context.blypLog??e.logger,r=async(o,s)=>{let a=ze(o);if(!a||a.structuredLogEmitted||a.errorLogged)return;let i=Pt(o),c=Hr(o,s),u=Math.round(performance.now()-a.startTime),d=At(o,s);B(c)?x(e,a.path)||T(e.logger,e.level,i,a.path,c,u,R(void 0,c),C(e,d)):M(e,d,a.path)||F(e.logger,e.level,i,a.path,c,u,C(e,d));},n=async(o,s,a)=>{let i=ze(o);!i||i.structuredLogEmitted||i.errorLogged||x(e,i.path)||(i.errorLogged=true,T(e.logger,e.level,Pt(o),i.path,Hr(o,a,500),Math.round(performance.now()-i.startTime),R(s,500),C(e,At(o,a,s)),{error:s}));};return {logger:e.logger,getLogger:t,plugin:async o=>{await o.hooks.hook("request",async s=>{let a=s;Re();let i=E();v(i),typeof a.node?.res=="object"&&a.node.res&&"setHeader"in a.node.res&&a.node.res.setHeader?.("x-blyp-trace-id",i);let c=qr(a),u=wo(a,{startTime:performance.now(),path:c,structuredLogEmitted:false});a.context.blypTraceId=i;let d=N(e.logger,{resolveStructuredFields:()=>({method:Fr(a),path:c,...C(e,At(a))}),onStructuredEmit:()=>{let l=ze(a);l&&(l.structuredLogEmitted=true);}});a.context.blypLog=d,u.scopedLogger=d;}),await o.hooks.hook("beforeResponse",async(s,a)=>{await r(s,a);}),await o.hooks.hook("afterResponse",async s=>{await L(e);let a=ze(s);a&&(a.errorLogged=true);}),await o.hooks.hook("error",async(s,a)=>{a&&typeof a=="object"&&(await n(a,s),await L(e));});},clientLogHandler:async o=>{Re();let s=E();v(s),o.context.blypTraceId=s;let a=qr(o);if(a!==e.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${a} does not match configured client logging path ${e.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":s}});let i=await ko(o),c=await q({config:e,ctx:At(o),request:{...Pt(o),json:async()=>i},body:i,deliveryPath:a});return await L(e),new Response(null,{status:c.status,headers:{...c.headers,"x-blyp-trace-id":s}})}}}function So(e={}){let t=_(e);return jr(t)}function xo(e={}){let t=jr(_(e));return {logger:t.logger,serverPlugin:t.plugin,clientLogHandler:t.clientLogHandler,getLogger:r=>t.getLogger(r)}}var zi=new TextEncoder;function _t(e){return zi.encode(e).length}function Ui(e){if(!e||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function H(e,t=new WeakSet){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(e instanceof Date)return e.toISOString();if(e instanceof Error)return {name:e.name,message:e.message,stack:e.stack};if(Array.isArray(e))return e.map(r=>H(r,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";if(t.add(e),!Ui(e)){let r=e.constructor?.name;return r?`[${r}]`:"[Object]"}return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,H(n,t)]))}return String(e)}function ee(e,t){if(t.length===0)return e;let r=H(e);for(let n of t){let o=n.split(".").filter(Boolean);if(o.length===0)continue;let s=r;for(let a=0;a<o.length-1;a+=1){if(!s||typeof s!="object"){s=void 0;break}s=s[o[a]];}s&&typeof s=="object"&&delete s[o[o.length-1]];}return r}function It(e,t){let r=H(e);if(t<=0)return {value:"[Truncated]",truncated:true};if(typeof r=="string"){if(_t(r)<=t)return {value:r,truncated:false};let s=r;for(;s.length>0&&_t(`${s}\u2026[truncated]`)>t;)s=s.slice(0,Math.max(1,Math.floor(s.length*.8)));return {value:`${s}\u2026[truncated]`,truncated:true}}let n=JSON.stringify(r);if(n===void 0||_t(n)<=t)return {value:r,truncated:false};let o=n;for(;o.length>0&&_t(`${o}\u2026[truncated]`)>t;)o=o.slice(0,Math.max(1,Math.floor(o.length*.8)));return {value:{truncated:true,preview:`${o}\u2026[truncated]`},truncated:true}}function be(e){if(!e)return;let t={inputTokens:typeof e.inputTokens=="number"?e.inputTokens:void 0,outputTokens:typeof e.outputTokens=="number"?e.outputTokens:void 0,totalTokens:typeof e.totalTokens=="number"?e.totalTokens:void 0,reasoningTokens:typeof e.reasoningTokens=="number"?e.reasoningTokens:void 0,cachedInputTokens:typeof e.cachedInputTokens=="number"?e.cachedInputTokens:void 0};if(t.totalTokens===void 0&&(t.inputTokens!==void 0||t.outputTokens!==void 0)&&(t.totalTokens=(t.inputTokens??0)+(t.outputTokens??0)),!Object.values(t).every(r=>r===void 0))return t}function te(e){if(typeof e=="string"&&e.length>0)return e;if(e&&typeof e=="object"){let t=e;for(let r of ["type","reason","stop_reason","finish_reason","raw","unified"]){let n=t[r];if(typeof n=="string"&&n.length>0)return n}}}function Ue(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function zr(e){return {toolName:e.name,toolCallId:e.id,status:e.status}}function To(e){if(!e)return {};if(e instanceof Error){let t=e;return {errorType:e.name,errorCode:t.code}}if(typeof e=="object"){let t=e;return {errorType:typeof t.type=="string"?t.type:typeof t.name=="string"?t.name:"Error",errorCode:typeof t.code=="string"||typeof t.code=="number"?t.code:void 0}}return {errorType:typeof e}}function Eo(e){return H(e)}var Ur={input:false,output:false,toolInputs:false,toolOutputs:false,reasoning:false,streamEvents:false,streamChunks:false,rawProviderPayload:false},$e={providerOptions:false,requestPaths:[],responsePaths:[],metadataPaths:[],toolNames:[]},$r={maxContentBytes:16384,maxEvents:200,maxToolCalls:50};function $i(){return `ai_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`}function Ki(){return new Date().toISOString()}function vo(e){return H(e)}function Kr(){return new Date().toISOString()}function Wi(e={}){return {logger:e.logger,provider:e.provider,operation:e.operation,metadata:{...e.metadata??{}},capture:{...Ur,...e.capture??{},streamEvents:e.capture?.streamEvents??e.capture?.streamChunks??Ur.streamEvents,streamChunks:e.capture?.streamChunks??e.capture?.streamEvents??Ur.streamChunks},exclude:{providerOptions:e.exclude?.providerOptions??$e.providerOptions,requestPaths:[...e.exclude?.requestPaths??$e.requestPaths],responsePaths:[...e.exclude?.responsePaths??$e.responsePaths],metadataPaths:[...e.exclude?.metadataPaths??$e.metadataPaths],toolNames:[...e.exclude?.toolNames??$e.toolNames]},limits:{maxContentBytes:e.limits?.maxContentBytes??$r.maxContentBytes,maxEvents:e.limits?.maxEvents??$r.maxEvents,maxToolCalls:e.limits?.maxToolCalls??$r.maxToolCalls},hooks:e.hooks??{}}}function Ot(e={}){return Wi(e)}function Bt(e){let t=e.config.logger??le()??Z,r=$i(),n=Kr(),o={traceId:r,provider:e.provider,sdk:e.sdk,operation:e.operation??e.config.operation??e.method,method:e.method,model:e.model,logger:t,metadata:{...e.config.metadata},request:e.request,toolCalls:[],events:[],startedAt:n,startedAtMs:performance.now(),options:e.config,capture:{...e.config.capture},streamed:e.streamed,truncated:false},s={traceId:r,provider:o.provider,sdk:o.sdk,operation:o.operation,method:o.method,logger:t,metadata:o.metadata,request:o.request,get response(){return o.response},get usage(){return o.usage},get finishReason(){return o.finishReason},get input(){return o.input},get output(){return o.output},get toolCalls(){return o.toolCalls.length>0?o.toolCalls:void 0},get startedAt(){return o.startedAt},get firstChunkAt(){return o.firstChunkAt},get endedAt(){return o.endedAt},get error(){return o.error},setMetadata(a){Object.assign(o.metadata,a);},disableCapture(a){o.capture[a]=false;}};return {state:o,context:s}}function re(e,t){e.usage=be(t);}function ue(e,t){e.finishReason=te(t);}function Nt(e,t){e.response=t;}function Mt(e,t){e.input=t;}function de(e,t){e.output=t;}function Ft(e,t){e.rawProviderPayload=Eo(t);}async function qt(e,t){e.firstChunkAt||(e.firstChunkAt=Kr(),e.firstChunkAtMs=performance.now(),await G(e,t,{type:"ai.first_chunk",timestamp:e.firstChunkAt}));}async function Ht(e,t,r){e.capture.streamEvents&&await G(e,t,{type:"ai.chunk",data:r});}function Q(e,t){let r=t.id??`${t.name}:${e.toolCalls.length}`,n=e.toolCalls.findIndex((o,s)=>(o.id??`${o.name}:${s}`)===r);if(n===-1&&e.toolCalls.length>=e.options.limits.maxToolCalls){e.truncated=true;return}if(n===-1){e.toolCalls.push(t);return}e.toolCalls[n]={...e.toolCalls[n],...t};}async function We(e,t,r){Q(e,r),await G(e,t,{type:"ai.tool_call.start",data:zr(r)});}async function Do(e,t,r){Q(e,r),await G(e,t,{type:"ai.tool_call.result",data:zr(r)});}function Ji(e){let t=e.toolCalls.filter(r=>!e.options.exclude.toolNames.includes(r.name)).map(r=>{let n={id:r.id,name:r.name,status:r.status};if(e.capture.toolInputs&&r.input!==void 0){let o=Ke(r.input,e.options.limits.maxContentBytes);n.input=o.value,e.truncated||(e.truncated=o.truncated);}if(e.capture.toolOutputs&&r.output!==void 0){let o=Ke(r.output,e.options.limits.maxContentBytes);n.output=o.value,e.truncated||(e.truncated=o.truncated);}return r.providerFormat!==void 0&&(n.providerFormat=H(r.providerFormat)),n});return t.length>0?t:void 0}async function V(e,t,r){if(e.emitted)return;e.emitted=true,r?.error!==void 0&&(e.error=r.error,await G(e,t,{type:"ai.error",data:{error:H(r.error)}}),await we(e.options.hooks.onError,[t])),e.endedAt=Kr(),await G(e,t,{type:"ai.finish",timestamp:e.endedAt}),e.error||await we(e.options.hooks.onFinish,[t]);let n={startedAt:e.startedAt,endedAt:e.endedAt,durationMs:Math.max(0,Math.round(performance.now()-e.startedAtMs))};e.firstChunkAt&&e.firstChunkAtMs!==void 0&&(n.firstChunkAt=e.firstChunkAt,n.msToFirstChunk=Math.max(0,Math.round(e.firstChunkAtMs-e.startedAtMs)));let o={provider:e.provider,sdk:e.sdk,model:e.model,operation:e.operation,method:e.method,streamed:e.streamed,timing:n,metadata:ee(e.metadata,e.options.exclude.metadataPaths)};if(e.usage&&(o.usage=e.usage),e.finishReason&&(o.finishReason=e.finishReason),e.capture.input&&e.input!==void 0){let i=Ke(ee(H(e.input),e.options.exclude.requestPaths),e.options.limits.maxContentBytes);o.input=i.value,e.truncated||(e.truncated=i.truncated);}if(e.capture.output&&e.output!==void 0){let i=H(e.output),c=Ke(typeof i=="object"&&i!==null&&!Array.isArray(i)?ee(i,e.options.exclude.responsePaths):i,e.options.limits.maxContentBytes);o.output=c.value,e.truncated||(e.truncated=c.truncated);}let s=Ji(e);if(s&&(o.tools=s),e.capture.rawProviderPayload&&e.rawProviderPayload!==void 0){let i=Ke(e.rawProviderPayload,e.options.limits.maxContentBytes);o.rawProviderPayload=i.value,e.truncated||(e.truncated=i.truncated);}e.truncated&&o.metadata&&(o.metadata={...o.metadata,truncated:true});let a={...o};if(e.error!==void 0){let{errorType:i,errorCode:c}=To(e.error);i&&(a.errorType=i),c!==void 0&&(a.errorCode=c);}try{e.logger.createStructuredLog(e.traceId,{type:"ai_trace",ai:a,events:e.events}).emit({message:"ai_trace",level:e.error===void 0?"info":"error",...e.error===void 0?{}:{error:e.error}});}catch(i){console.warn("[Blyp] Failed to emit AI trace.",vo(i));}}async function we(e,t){if(e)try{await e(...t);}catch(r){console.warn("[Blyp] AI middleware hook failed.",vo(r));}}async function G(e,t,r){e.events.length<e.options.limits.maxEvents?e.events.push({...r,timestamp:r.timestamp??Ki()}):e.truncated=true,await we(e.options.hooks.onEvent,[e.events[e.events.length-1],t]);}function Ke(e,t){return It(e,t)}function jt(e){return !!e&&typeof e[Symbol.asyncIterator]=="function"}function zt(e,t){return {[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]();return {async next(){try{let n=await r.next();return n.done?(await t.onReturn?.(),n):(await t.onChunk?.(n.value),n)}catch(n){throw await t.onError?.(n),n}},async return(n){try{return typeof r.return=="function"?await r.return(n):{done:!0,value:n}}finally{await t.onReturn?.();}},async throw(n){try{if(typeof r.throw=="function")return await r.throw(n);throw n}catch(o){throw await t.onError?.(o),o}}}}}}function Gi(e){let t=e.output;if(!Array.isArray(t))return;let r=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n.content;if(Array.isArray(s))for(let a of s){if(!a||typeof a!="object")continue;let c=a.text;typeof c=="string"&&r.push(c);}}return r.length>0?r.join(""):void 0}function Qi(e){let t=e.output;if(!Array.isArray(t))return [];let r=[];for(let n of t){if(!n||typeof n!="object")continue;let o=n,s=o.type;s==="function_call"&&r.push({id:typeof o.call_id=="string"?o.call_id:void 0,name:typeof o.name=="string"?o.name:"unknown",input:Ue(o.arguments),status:"started"}),s==="function_call_output"&&r.push({id:typeof o.call_id=="string"?o.call_id:void 0,name:typeof o.name=="string"?o.name:"unknown",output:o.output,status:"completed"});}return r}function Vi(e){let t=e.choices;if(Array.isArray(t))return t.map(r=>{if(!r||typeof r!="object")return "";let n=r.message;return !n||typeof n!="object"?"":typeof n.content=="string"?n.content:""}).join("")}function Yi(e){let t=e.choices;if(!Array.isArray(t))return [];let r=[];for(let n of t){if(!n||typeof n!="object")continue;let o=n.message;if(!o||typeof o!="object")continue;let a=o.tool_calls;if(Array.isArray(a))for(let i of a){if(!i||typeof i!="object")continue;let c=i,u=c.function,d=u&&typeof u=="object"?u:{};r.push({id:typeof c.id=="string"?c.id:void 0,name:typeof d.name=="string"?d.name:"unknown",input:Ue(d.arguments),providerFormat:c,status:"started"});}}return r}function Po(e,t){if(!e||typeof e!="object")return {toolCalls:[]};let r=e,n=r.usage&&typeof r.usage=="object"?r.usage:void 0,o=t==="chat.completions.create"?be({inputTokens:typeof n?.prompt_tokens=="number"?n.prompt_tokens:void 0,outputTokens:typeof n?.completion_tokens=="number"?n.completion_tokens:void 0,totalTokens:typeof n?.total_tokens=="number"?n.total_tokens:void 0,reasoningTokens:n?.completion_tokens_details&&typeof n.completion_tokens_details=="object"&&typeof n.completion_tokens_details.reasoning_tokens=="number"?n.completion_tokens_details.reasoning_tokens:void 0,cachedInputTokens:n?.prompt_tokens_details&&typeof n.prompt_tokens_details=="object"&&typeof n.prompt_tokens_details.cached_tokens=="number"?n.prompt_tokens_details.cached_tokens:void 0}):be({inputTokens:typeof n?.input_tokens=="number"?n.input_tokens:void 0,outputTokens:typeof n?.output_tokens=="number"?n.output_tokens:void 0,totalTokens:typeof n?.total_tokens=="number"?n.total_tokens:void 0,reasoningTokens:n?.output_tokens_details&&typeof n.output_tokens_details=="object"&&typeof n.output_tokens_details.reasoning_tokens=="number"?n.output_tokens_details.reasoning_tokens:void 0,cachedInputTokens:n?.input_tokens_details&&typeof n.input_tokens_details=="object"&&typeof n.input_tokens_details.cached_tokens=="number"?n.input_tokens_details.cached_tokens:void 0}),s=t==="chat.completions.create"?te(Array.isArray(r.choices)&&r.choices[0]&&typeof r.choices[0]=="object"?r.choices[0].finish_reason:void 0):te(r.status),a=t==="chat.completions.create"?Yi(r):Qi(r),i={};return typeof r.id=="string"&&(i.responseId=r.id),typeof r.created_at=="number"&&(i.createdAt=r.created_at),typeof r.provider=="string"&&(i.upstreamProvider=r.provider),{model:typeof r.model=="string"?r.model:void 0,usage:o,finishReason:s,output:t==="chat.completions.create"?Vi(r):Gi(r),toolCalls:a,metadata:Object.keys(i).length>0?i:void 0}}async function Ao(e,t,r){if(!r||typeof r!="object")return;await qt(e,t);let n=r,o=n.type;if(typeof o=="string"&&await Ht(e,t,{type:o}),o==="response.output_text.delta"&&typeof n.delta=="string"){let s=`${typeof e.output=="string"?e.output:""}${n.delta}`;de(e,s);}if(o==="response.function_call_arguments.delta"){let s=typeof n.item_id=="string"?n.item_id:void 0,a=typeof n.name=="string"?n.name:"unknown",i=e.toolCalls.find(d=>d.id===s),c=`${typeof i?.input=="string"?i.input:""}${typeof n.delta=="string"?n.delta:""}`,u={id:s,name:a,input:c,status:"started"};i?Q(e,u):await We(e,t,u);}if(o==="response.output_item.done"){let s=n.item;if(s&&typeof s=="object"){let a=s;if(a.type==="function_call"){let i={id:typeof a.call_id=="string"?a.call_id:void 0,name:typeof a.name=="string"?a.name:"unknown",input:Ue(a.arguments),status:"started"};await We(e,t,i);}if(a.type==="function_call_output"){let i={id:typeof a.call_id=="string"?a.call_id:void 0,name:typeof a.name=="string"?a.name:"unknown",output:a.output,status:"completed"};await Do(e,t,i);}}}if(o==="response.completed"){let s=n.response;if(s&&typeof s=="object"){let a=s;if(ue(e,te(a.status)),a.usage&&typeof a.usage=="object"){let i=a.usage;re(e,{inputTokens:typeof i.input_tokens=="number"?i.input_tokens:void 0,outputTokens:typeof i.output_tokens=="number"?i.output_tokens:void 0,totalTokens:typeof i.total_tokens=="number"?i.total_tokens:void 0});}}}}async function _o(e,t,r,n,o){let s=Ot({...o,provider:o.provider??"openai"}),{state:a,context:i}=Bt({provider:o.provider??"openai",sdk:"openai-sdk",operation:o.operation,method:t,model:typeof r.model=="string"?r.model:"unknown",request:r,streamed:r.stream===true,config:s});Mt(a,t==="chat.completions.create"?r.messages:r.input??r),await G(a,i,{type:"ai.start"}),await we(s.hooks.onStart,[i]);try{let c=await e(r,...n);if(r.stream===!0&&jt(c))return zt(c,{onChunk:async l=>{await Ao(a,i,l);},onReturn:async()=>{await V(a,i);},onError:async l=>{await V(a,i,{error:l});}});let u=Po(c,t);Nt(a,c),Ft(a,c),u.metadata&&i.setMetadata(u.metadata),u.usage&&re(a,u.usage),u.finishReason&&ue(a,u.finishReason),u.output!==void 0&&de(a,u.output);for(let d of u.toolCalls)Q(a,d);return await V(a,i),c}catch(c){throw await V(a,i,{error:c}),c}}function Wr(e,t,r){return Object.assign(Object.create(Object.getPrototypeOf(e)),e,{[t]:r})}function Io(e,t={}){let r=Object.create(Object.getPrototypeOf(e));if(Object.assign(r,e),e.responses?.create){let n=e.responses,o=Wr(n,"create",(async(s,...a)=>_o(n.create.bind(n),"responses.create",s??{},a,t)));r.responses=o;}if(e.chat?.completions?.create){let n=e.chat,o=n.completions,s=Wr(o,"create",(async(a,...i)=>_o(o.create.bind(o),"chat.completions.create",a??{},i,t)));r.chat=Wr(n,"completions",s);}return r}function Oo(e={}){return {...e,provider:e.provider??"openai"}}function Jr(e,t={}){let r=t.logger??le()??Z,n={...t.metadata??{}},o=t.limits?.maxContentBytes??16384,s=t.exclude?.requestPaths??[],a=t.exclude?.responsePaths??[],i=(async(c,u)=>{let d=performance.now(),l=new Date().toISOString(),f=u?.method??(c instanceof Request?c.method:"GET"),h=typeof c=="string"?c:c instanceof URL?c.toString():c.url;try{let y=await e(c,u),m=new Date().toISOString(),p=r.createStructuredLog(`fetch_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`,{type:"fetch_trace",fetch:{url:h,method:f,status:y.status,startedAt:l,endedAt:m,durationMs:Math.max(0,Math.round(performance.now()-d)),requestId:y.headers.get("x-request-id")??y.headers.get("request-id")??y.headers.get("cf-ray")??void 0,metadata:ee(n,t.exclude?.metadataPaths??[])}});if(t.inspectJsonBody===!0&&!y.bodyUsed&&y.headers.get("content-type")?.includes("application/json"))try{let O=await y.clone().json(),w=It({request:ee(H(u??{}),s),response:ee(H(O),a)},o);p.set({fetchBody:w.value});}catch{}return p.emit({message:"fetch_trace",level:y.ok?"info":"error"}),y}catch(y){throw r.createStructuredLog(`fetch_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`,{type:"fetch_trace",fetch:{url:h,method:f,startedAt:l,endedAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-d)),metadata:ee(n,t.exclude?.metadataPaths??[])}}).emit({message:"fetch_trace",level:"error",error:H(y)}),y}});return "preconnect"in e&&(i.preconnect=e.preconnect),i}function Bo(e){if(!e||typeof e!="object")return {toolCalls:[]};let t=e,r=t.usage&&typeof t.usage=="object"?be({inputTokens:typeof t.usage.input_tokens=="number"?t.usage.input_tokens:void 0,outputTokens:typeof t.usage.output_tokens=="number"?t.usage.output_tokens:void 0,cachedInputTokens:typeof t.usage.cache_read_input_tokens=="number"?t.usage.cache_read_input_tokens:void 0}):void 0,n=Array.isArray(t.content)?t.content:[],o=n.filter(a=>!!a&&typeof a=="object").filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(""),s=n.filter(a=>!!a&&typeof a=="object").filter(a=>a.type==="tool_use").map(a=>({id:typeof a.id=="string"?a.id:void 0,name:typeof a.name=="string"?a.name:"unknown",input:a.input,status:"started"}));return {model:typeof t.model=="string"?t.model:void 0,usage:r,finishReason:te(t.stop_reason),output:o||void 0,toolCalls:s}}async function No(e,t,r){if(!r||typeof r!="object")return;let n=r,o=n.type;if(typeof o=="string"){if(await qt(e,t),await Ht(e,t,{type:o}),o==="content_block_delta"){let s=n.delta;if(s&&typeof s=="object"){let a=s;if(a.type==="text_delta"&&typeof a.text=="string"&&de(e,`${typeof e.output=="string"?e.output:""}${a.text}`),a.type==="input_json_delta"&&typeof a.partial_json=="string"){let i=typeof n.index=="number"?n.index:0,c=e.toolCalls[i];Q(e,{id:c?.id,name:c?.name??"unknown",input:`${typeof c?.input=="string"?c.input:""}${a.partial_json}`,status:c?.status??"started"});}}}if(o==="content_block_start"){let s=n.content_block;if(s&&typeof s=="object"){let a=s;a.type==="tool_use"&&await We(e,t,{id:typeof a.id=="string"?a.id:void 0,name:typeof a.name=="string"?a.name:"unknown",input:a.input,status:"started"});}}if(o==="message_delta"&&(ue(e,n.stop_reason),n.usage&&typeof n.usage=="object")){let s=n.usage;re(e,{outputTokens:typeof s.output_tokens=="number"?s.output_tokens:void 0});}if(o==="message_stop"&&n.usage&&typeof n.usage=="object"){let s=n.usage;re(e,{inputTokens:typeof s.input_tokens=="number"?s.input_tokens:void 0,outputTokens:typeof s.output_tokens=="number"?s.output_tokens:void 0});}}}function Xi(e,t,r){return Object.assign(Object.create(Object.getPrototypeOf(e)),e,{[t]:r})}function Mo(e,t={}){let r=Object.create(Object.getPrototypeOf(e));if(Object.assign(r,e),!e.messages?.create)return r;let n=async(o,...s)=>{let a=Ot({...t,provider:"anthropic"}),{state:i,context:c}=Bt({provider:"anthropic",sdk:"anthropic-sdk",operation:t.operation,method:"messages.create",model:typeof o?.model=="string"?o.model:"unknown",request:o,streamed:o?.stream===true,config:a});Mt(i,o?.messages??o),await G(i,c,{type:"ai.start"}),await we(a.hooks.onStart,[c]);try{let u=await e.messages.create(o,...s);if(o?.stream===!0&&jt(u))return zt(u,{onChunk:async l=>{await No(i,c,l);},onReturn:async()=>{await V(i,c);},onError:async l=>{await V(i,c,{error:l});}});let d=Bo(u);Nt(i,u),Ft(i,u),d.usage&&re(i,d.usage),d.finishReason&&ue(i,d.finishReason),d.output!==void 0&&de(i,d.output);for(let l of d.toolCalls)Q(i,l);return await V(i,c),u}catch(u){throw await V(i,c,{error:u}),u}};return r.messages=Xi(e.messages,"create",n),r}function Og(e,t){return (le()??gt).createStructuredLog(e,t)}function Bg(e={}){return qo().createElysiaLogger(e)}function Ng(e={}){return qo().createLogger(e)}function Mg(e={}){return Zi().createFastifyLogger(e)}function Fg(e={}){return Gr().createNestLogger(e)}var qg=new Proxy(function(){},{get(e,t,r){return Reflect.get(Gr().BlypModule,t,r)},construct(e,t,r){return Reflect.construct(Gr().BlypModule,t,r)}});function Ut(){return j("betterstack",["@logtail/node","@sentry/node"])}function $t(){return j("databuddy",["@databuddy/sdk"])}function Kt(){return j("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"])}function Qr(){return j("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"])}function Fo(){return j("sentry",["@sentry/node"])}function qo(){return j("elysia",["elysia"])}function Zi(){return j("fastify",["fastify","fastify-plugin"])}function Gr(){return j("nestjs",["@nestjs/common","@nestjs/core","@nestjs/platform-express","@nestjs/platform-fastify","rxjs"])}function Hg(e,t,r){return Qr().normalizeOTLPRecord(e,t,r)}function jg(e={}){return Ut().createBetterStackLogger(e)}function zg(e={}){return Ut().createBetterStackErrorTracker(e)}function Ug(e,t={},r={}){return Ut().captureBetterStackException(e,t,r)}function $g(e,t,r={}){return Ut().createStructuredBetterStackLogger(e,t,r)}function Kg(e={}){return $t().createDatabuddyLogger(e)}function Wg(e={}){return $t().createDatabuddyErrorTracker(e)}function Jg(e,t={},r={}){return $t().captureDatabuddyException(e,t,r)}function Gg(e,t,r={}){return $t().createStructuredDatabuddyLogger(e,t,r)}function Qg(e={}){return Kt().createPosthogLogger(e)}function Vg(e={}){return Kt().createPosthogErrorTracker(e)}function Yg(e,t={},r={}){return Kt().capturePosthogException(e,t,r)}function Xg(e,t,r={}){return Kt().createStructuredPosthogLogger(e,t,r)}function Zg(e={}){return Fo().createSentryLogger(e)}function ep(e,t,r={}){return Fo().createStructuredSentryLogger(e,t,r)}function tp(e={name:""}){return Qr().createOtlpLogger(e)}function rp(e,t,r){return Qr().createStructuredOtlpLogger(e,t,r)}
703
- exports.BlypError=Le;exports.BlypModule=qg;exports.CUSTOM_LEVELS=wr;exports.DEFAULT_CLIENT_LOGGING_CONFIG=Ze;exports.DEFAULT_CONFIG=nr;exports.DEFAULT_CONNECTOR_DELIVERY_CONFIG=$;exports.DEFAULT_CONNECTOR_RETRY_CONFIG=me;exports.DEFAULT_DATABASE_DELIVERY_CONFIG=un;exports.DEFAULT_DATABASE_RETRY_CONFIG=ir;exports.DEFAULT_FILE_CONFIG=ar;exports.DEFAULT_REDACTION_CONFIG=sr;exports.DEFAULT_ROTATION_CONFIG=or;exports.HTTP_CODES=so;exports.blypFetch=Jr;exports.captureBetterStackException=Ug;exports.captureDatabuddyException=Jg;exports.capturePosthogException=Yg;exports.clearConnectorDeadLetters=pi;exports.colors=hd;exports.connectorQueueExists=ui;exports.createAstroLogger=Lo;exports.createBaseLogger=Pe;exports.createBetterStackErrorTracker=zg;exports.createBetterStackLogger=jg;exports.createDatabuddyErrorTracker=Wg;exports.createDatabuddyLogger=Kg;exports.createDrizzleDatabaseAdapter=bn;exports.createElysiaLogger=Bg;exports.createError=ao;exports.createExpressErrorLogger=fo;exports.createExpressLogger=po;exports.createFastifyLogger=Mg;exports.createHonoLogger=go;exports.createLogDir=Es;exports.createLogger=Ng;exports.createNestLogger=Fg;exports.createNextJsLogger=mo;exports.createNitroLogger=So;exports.createNuxtLogger=xo;exports.createOpenAITracker=Oo;exports.createOtlpLogger=tp;exports.createPosthogErrorTracker=Vg;exports.createPosthogLogger=Qg;exports.createPrismaDatabaseAdapter=Rn;exports.createReactRouterLogger=yo;exports.createRuntimeAdapter=Nn;exports.createSentryLogger=Zg;exports.createStandaloneLogger=vr;exports.createStructuredBetterStackLogger=$g;exports.createStructuredDatabuddyLogger=Gg;exports.createStructuredLog=Og;exports.createStructuredOtlpLogger=rp;exports.createStructuredPosthogLogger=Xg;exports.createStructuredSentryLogger=ep;exports.createSvelteKitLogger=Co;exports.createTanStackStartLogger=ho;exports.formatLogRecord=io;exports.getArrowForMethod=co;exports.getColoredLevel=yd;exports.getConfig=os;exports.getConnectorDeliveryStatusSummary=di;exports.getConnectorQueuePath=ci;exports.getHttpCode=si;exports.getMethodColor=mt;exports.getResponseTimeColor=ht;exports.getStatusColor=yt;exports.listConnectorDeadLetters=li;exports.loadConfig=ur;exports.logger=gt;exports.mergeBlypConfig=et;exports.normalizeOTLPRecord=Hg;exports.parseError=oi;exports.readLogFile=Li;exports.resetConfigCache=as;exports.resolveConfig=Te;exports.resolveStatusCode=bi;exports.retryConnectorDeadLetters=gi;exports.runtime=he;exports.shouldIgnorePath=Ir;exports.shouldLogTable=fd;exports.wrapAnthropic=Mo;exports.wrapOpenAI=Io;
700
+ `}var De=class{constructor(t){this.path=t;g(this,"worker");g(this,"pending",new Map);g(this,"nextId",1);this.worker=new worker_threads.Worker(An(),{eval:true}),this.worker.on("message",r=>{let n=this.pending.get(r.id);if(n){if(this.pending.delete(r.id),r.ok){n.resolve(r.result);return}n.reject(new Error(r.error??"SQLite worker request failed."));}}),this.worker.on("error",r=>{for(let n of this.pending.values())n.reject(r instanceof Error?r:new Error(String(r)));this.pending.clear();});}request(t,r={}){let n=this.nextId++;return new Promise((o,i)=>{this.pending.set(n,{resolve:o,reject:i}),this.worker.postMessage({id:n,type:t,payload:r});})}async init(){await this.request("init",{path:this.path});}async insert(t){await this.request("insert",{jobs:t});}async claimDue(t,r){return this.request("claimDue",{limit:t,now:r})}async ack(t){await this.request("ack",{ids:t});}async reschedule(t,r){await this.request("reschedule",{items:t,now:r});}async deadLetter(t){await this.request("deadLetter",{items:t});}async markSuccess(t){await this.request("markSuccess",{items:t});}async markFailure(t){await this.request("markFailure",{items:t});}async getStatusSummary(){return this.request("getStatusSummary")}async listDeadLetters(t){return this.request("listDeadLetters",t)}async retryDeadLetters(t,r){return this.request("retryDeadLetters",{ids:t,now:r})}async clearDeadLetters(t){return this.request("clearDeadLetters",{ids:t})}async count(){return this.request("count")}async shutdown(){try{await this.request("shutdown");}finally{await this.worker.terminate();}}};var _n=Symbol("blyp.connector.batch-dispatch"),Me=Symbol("blyp.connector.delivery-binder");function Fe(e){return new Promise(t=>{setTimeout(t,e);})}function xi(e){return e.data===void 0||typeof e.data!="object"||e.data===null||e.data.type!=="client_log"}function In(e){return JSON.stringify(e)}function Ti(e){try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.jobId!="string"?null:t}catch{return null}}function On(e){let t=new Map;for(let r of e){let n=`${r.connectorType}:${r.connectorTarget??""}`;t.has(n)||t.set(n,{connectorType:r.connectorType,connectorTarget:r.connectorTarget});}return [...t.values()]}var it=class{constructor(t){this.config=t;g(this,"warnOnce",ie(new Set));g(this,"memoryQueue",[]);g(this,"durableStaging",[]);g(this,"dispatchers",new Map);g(this,"activeDispatches",0);g(this,"flushPromise",null);g(this,"durableFlushPromise",null);g(this,"pollTimer",null);g(this,"durablePollRunning",false);g(this,"closed",false);g(this,"durableClient",null);g(this,"durableReady",false);g(this,"durableInitPromise",null);t.enabled&&(this.durableInitPromise=this.initializeDurableQueue());}bindTarget(t){typeof t[Me]=="function"&&t[Me](this);let r=t[_n];r&&this.dispatchers.set(r.dispatchKey,r);}unbindTarget(t){typeof t[Me]=="function"&&t[Me](null);}enqueue(t,r,n,o){this.closed||!xi(r)||(this.dispatchers.set(n.dispatchKey,n),this.memoryQueue.push({id:Xe(),connectorType:t,connectorTarget:o,source:"server",record:r,attemptCount:0,maxAttempts:this.config.retry.maxAttempts,nextAttemptAt:Date.now(),createdAt:Date.now(),dispatchKey:n.dispatchKey,dispatcher:n}),this.enforceMemoryCapacity(),this.scheduleDispatch());}async flush(){await this.durableInitPromise?.catch(()=>{}),await this.processUntilIdle(),await this.flushDurableStaging(),await this.drainDurableQueueForFlush(),await this.flushDurableStaging(),await this.processUntilIdle();}async shutdown(){if(this.closed=true,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),await this.durableInitPromise?.catch(()=>{}),this.durableReady){let t=this.memoryQueue.splice(0,this.memoryQueue.length);for(let r of t)this.stageDurableJob(r,r.attemptCount,Math.max(r.nextAttemptAt,Date.now()));await this.flushDurableStaging();}await this.processUntilIdle(),this.durableClient&&(await this.durableClient.shutdown().catch(()=>{}),this.durableClient=null);}async getDurableCountForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?0:this.durableClient.count()}async getStatusSummaryForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:this.durableClient.getStatusSummary()}async listDeadLettersForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:(await this.durableClient.listDeadLetters({limit:1e3,offset:0})).items}async initializeDurableQueue(){try{let t=new De(this.config.durableQueuePath);await t.init(),this.durableClient=t,this.durableReady=!0,this.scheduleDurablePoll();}catch(t){this.durableReady=false,this.durableClient=null,this.warnOnce("connector-durable-disabled",`[Blyp] Warning: Failed to initialize the connector SQLite queue at ${this.config.durableQueuePath}. Falling back to in-memory retries.`,t);}}scheduleDispatch(){this.flushPromise||(this.flushPromise=(async()=>{try{await this.pumpMemoryQueue();}finally{this.flushPromise=null,!this.closed&&this.hasReadyMemoryJobs()&&this.scheduleDispatch();}})());}async pumpMemoryQueue(){for(;!this.closed;){for(;this.activeDispatches<this.config.dispatchConcurrency;){let t=this.takeNextMemoryBatch();if(t.length===0)break;this.activeDispatches+=1,this.dispatchMemoryBatch(t).finally(()=>{this.activeDispatches-=1,this.closed||this.scheduleDispatch();});}if(this.activeDispatches===0||!this.hasReadyMemoryJobs())break;await Fe(10);}}takeNextMemoryBatch(){let t=Date.now(),r=this.memoryQueue.findIndex(i=>i.nextAttemptAt<=t);if(r===-1)return [];let n=this.memoryQueue[r],o=[n];this.memoryQueue.splice(r,1);for(let i=this.memoryQueue.length-1;i>=0;i-=1){let a=this.memoryQueue[i];a.dispatchKey===n.dispatchKey&&a.connectorTarget===n.connectorTarget&&a.nextAttemptAt<=t&&o.length<this.config.memoryBatchSize&&(o.push(a),this.memoryQueue.splice(i,1));}return o}async dispatchMemoryBatch(t){let r=t[0].dispatcher,n=Date.now(),o=await r.dispatch(t.map(i=>i.record),{source:"server",target:t[0].connectorTarget}).catch(i=>({ok:false,retryable:true,error:i instanceof Error?i.message:String(i)}));if(o.ok){await this.recordSuccessfulDispatch(t,n);return}await this.handleRetryableFailure(t,o,false,n);}async handleRetryableFailure(t,r,n,o){n||await this.durableInitPromise?.catch(()=>{});let i=[],a=[];await this.recordFailedDispatch(t,r,o);for(let s of t){let c=s.attemptCount+1;if(!r.retryable||c>=s.maxAttempts){a.push({id:s.id,connectorType:s.connectorType,connectorTarget:s.connectorTarget,operation:"send",payloadJson:In({jobId:s.id,connectorType:s.connectorType,connectorTarget:s.connectorTarget,source:s.source,record:s.record,createdAt:s.createdAt}),attemptCount:c,maxAttempts:s.maxAttempts,lastError:r.error,firstEnqueuedAt:s.createdAt,deadLetteredAt:o,lastAttemptAt:o}),this.warnOnce(`connector-drop:${s.connectorType}:${s.connectorTarget??"default"}:${s.id}`,n&&this.durableReady?`[Blyp] Warning: Dead-lettered ${s.connectorType} connector job after ${c} failed attempt(s). ${r.error??"Connector delivery failed."}`:`[Blyp] Warning: Dropped ${s.connectorType} connector job after ${c} failed attempt(s). ${r.error??"Connector delivery failed."}`);continue}let u=o+vn(c,this.config.retry);if(n){i.push({id:s.id,attemptCount:c,nextAttemptAt:u,lastError:r.error});continue}if(this.durableReady&&this.config.durableSpillStrategy==="after-first-failure"){this.stageDurableJob(s,c,u,r.error);continue}this.memoryQueue.push({...s,attemptCount:c,nextAttemptAt:u});}a.length>0&&await this.durableClient?.deadLetter(a).catch(s=>{this.warnOnce("connector-dead-letter-failure","[Blyp] Warning: Failed to persist dead-lettered connector queue jobs.",s);}),i.length>0&&await this.durableClient?.reschedule(i,o).catch(s=>{this.warnOnce("connector-reschedule-failure","[Blyp] Warning: Failed to reschedule durable connector queue jobs.",s);});}async recordSuccessfulDispatch(t,r){if(!this.durableReady||!this.durableClient||t.length===0)return;let n=On(t).map(o=>({connectorType:o.connectorType,connectorTarget:o.connectorTarget,timestamp:r}));await this.durableClient.markSuccess(n).catch(o=>{this.warnOnce("connector-status-success-failure","[Blyp] Warning: Failed to record connector delivery success state.",o);});}async recordFailedDispatch(t,r,n){if(!this.durableReady||!this.durableClient||t.length===0)return;let o=On(t).map(i=>({connectorType:i.connectorType,connectorTarget:i.connectorTarget,timestamp:n,lastError:r.error}));await this.durableClient.markFailure(o).catch(i=>{this.warnOnce("connector-status-failure-failure","[Blyp] Warning: Failed to record connector delivery failure state.",i);});}stageDurableJob(t,r,n,o){let i=In({jobId:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,source:t.source,record:t.record,createdAt:t.createdAt});this.durableStaging.push({id:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,operation:"send",payloadJson:i,attemptCount:r,maxAttempts:t.maxAttempts,nextAttemptAt:n,state:"pending",lastError:o,createdAt:t.createdAt,updatedAt:Date.now()}),this.flushDurableStaging();}async flushDurableStaging(){if(!(!this.durableReady||!this.durableClient||this.durableStaging.length===0)){if(this.durableFlushPromise){await this.durableFlushPromise;return}this.durableFlushPromise=(async()=>{for(;this.durableStaging.length>0;){let t=this.durableStaging.splice(0,this.config.sqliteWriteBatchSize);try{await this.durableClient.insert(t);}catch(r){this.warnOnce("connector-durable-insert-failure","[Blyp] Warning: Failed to persist connector jobs into the durable SQLite queue.",r),this.durableStaging.unshift(...t);break}}})();try{await this.durableFlushPromise;}finally{this.durableFlushPromise=null;}}}async processDurableQueueOnce(){if(!(!this.durableReady||!this.durableClient||this.durablePollRunning)){this.durablePollRunning=true;try{for(;!this.closed;){let t=await this.durableClient.claimDue(this.config.sqliteReadBatchSize,Date.now());if(t.length===0)break;let r=new Map,n=[];for(let o of t){let i=Ti(o.payloadJson);if(!i){n.push(o.id);continue}let a=o.connectorType==="otlp"?`otlp:${o.connectorTarget??""}`:o.connectorType,s=this.dispatchers.get(a);if(!s){n.push(o.id);continue}let c={id:o.id,connectorType:o.connectorType,connectorTarget:o.connectorTarget,source:i.source,record:i.record,attemptCount:o.attemptCount,maxAttempts:o.maxAttempts,nextAttemptAt:o.nextAttemptAt,createdAt:o.createdAt,dispatchKey:a,dispatcher:s},u=r.get(a)??[];u.push(c),r.set(a,u);}n.length>0&&await this.durableClient.ack(n);for(let o of r.values()){let a=await o[0].dispatcher.dispatch(o.map(s=>s.record),{source:"server",target:o[0].connectorTarget}).catch(s=>({ok:!1,retryable:!0,error:s instanceof Error?s.message:String(s)}));if(a.ok){await this.recordSuccessfulDispatch(o,Date.now()),await this.durableClient.ack(o.map(s=>s.id));continue}await this.handleRetryableFailure(o,a,!0,Date.now());}}}finally{this.durablePollRunning=false;}}}async drainDurableQueueForFlush(){if(!(!this.durableReady||!this.durableClient)){this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null);try{for(;!this.closed;){for(;this.durablePollRunning;)await Fe(10);if(await this.processDurableQueueOnce(),await this.flushDurableStaging(),await this.durableClient.count().catch(()=>0)===0&&!this.durablePollRunning&&this.durableStaging.length===0)break;await Fe(10);}}finally{this.closed||this.scheduleDurablePoll();}}}scheduleDurablePoll(){this.closed||!this.durableReady||this.pollTimer||(this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.flushDurableStaging(),await this.processDurableQueueOnce(),this.scheduleDurablePoll();},this.config.pollIntervalMs));}enforceMemoryCapacity(){for(;this.memoryQueue.length>this.config.memoryBufferSize;){let t=this.config.overflowStrategy==="drop-new"?this.memoryQueue.length-1:0,[r]=this.memoryQueue.splice(t,1);if(!r)break;if(this.durableReady){this.stageDurableJob(r,r.attemptCount,Math.max(Date.now(),r.nextAttemptAt),"spilled from in-memory buffer");continue}this.warnOnce(`connector-overflow:${r.connectorType}:${r.connectorTarget??"default"}:${t}`,`[Blyp] Warning: Connector queue overflow reached ${this.config.memoryBufferSize}. Dropping queued ${r.connectorType} job.`);}}hasReadyMemoryJobs(){let t=Date.now();return this.memoryQueue.some(r=>r.nextAttemptAt<=t)}async processUntilIdle(){for(;this.activeDispatches>0||this.memoryQueue.length>0||this.durableStaging.length>0||this.flushPromise!==null||this.durableFlushPromise!==null;){if(this.scheduleDispatch(),await this.flushPromise?.catch(()=>{}),await this.flushDurableStaging(),this.memoryQueue.some(t=>t.nextAttemptAt>Date.now())||await this.processDurableQueueOnce(),this.activeDispatches===0&&this.memoryQueue.length>0&&!this.hasReadyMemoryJobs()){let t=Math.min(...this.memoryQueue.map(r=>r.nextAttemptAt));await Fe(Math.max(t-Date.now(),0));}else await Fe(10);if(this.activeDispatches===0&&this.memoryQueue.length===0&&this.durableStaging.length===0)break}}};var ye=class ye{constructor(){g(this,"_type",null);}static getInstance(){return ye.instance||(ye.instance=new ye),ye.instance}get type(){return this._type===null&&(this._type=this.detectRuntime()),this._type}get isBun(){return this.type==="bun"}get isNode(){return this.type==="node"}detectRuntime(){return typeof Bun<"u"&&typeof Bun.file=="function"?"bun":"node"}};g(ye,"instance");var hr=ye,Cr=class{constructor(){g(this,"type","bun");g(this,"isBun",true);g(this,"isNode",false);g(this,"file",{existsSync:t=>{try{let r=Bun.file(t);return r.size>0||r.name!==""}catch{return false}},mkdirSync:(t,r)=>{try{z__default.default.mkdirSync(t,r);}catch{}},writeFileSync:(t,r)=>{Bun.write(t,r);}});g(this,"path",{join:(...t)=>Ee__default.default.join(...t)});g(this,"env",{get:t=>Bun.env[t]});g(this,"cwd",()=>process.cwd());}},Lr=class{constructor(){g(this,"type","node");g(this,"isBun",false);g(this,"isNode",true);g(this,"file",{existsSync:t=>z__default.default.existsSync(t),mkdirSync:(t,r)=>{z__default.default.mkdirSync(t,r);},writeFileSync:(t,r)=>{z__default.default.writeFileSync(t,r);}});g(this,"path",{join:(...t)=>Ee__default.default.join(...t)});g(this,"env",{get:t=>process.env[t]});g(this,"cwd",()=>process.cwd());}};function Nn(){return hr.getInstance().isBun?new Cr:new Lr}var he=Nn();function Ei(e){let t=e??he.path.join(he.cwd(),"logs");return he.file.existsSync(t)||he.file.mkdirSync(t,{recursive:true}),t}function Mn(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let r=[e,...t];return r.length===1?r[0]:r}function Fn(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function vi(e,t){if(e==null)return t===void 0||t<400?void 0:{message:`HTTP ${t}`,code:t,type:"HttpError"};if(e instanceof Error){let r=e;return {message:e.message,code:r.code,type:r.type??e.name??e.constructor?.name,stack:e.stack,why:r.why,fix:r.fix,link:r.link,details:Fn(r.details),cause:r.cause}}if(typeof e=="object"){let r=e,n=typeof r.statusCode=="number"?r.statusCode:typeof r.status=="number"?r.status:t;return {message:typeof r.message=="string"?r.message:`HTTP ${n??500}`,code:typeof r.code=="string"||typeof r.code=="number"?r.code:n,type:typeof r.type=="string"?r.type:typeof r.name=="string"?r.name:"Error",stack:typeof r.stack=="string"?r.stack:void 0,why:typeof r.why=="string"?r.why:void 0,fix:typeof r.fix=="string"?r.fix:void 0,link:typeof r.link=="string"?r.link:void 0,details:Fn(r.details),cause:r.cause}}return {message:String(e),code:t,type:typeof e}}function Di(e){return e.response&&typeof e.response.status=="number"?e.response.status:typeof e.status=="number"?e.status:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.statusCode=="number"?e.error.statusCode:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.status=="number"?e.error.status:e.error?500:void 0}function qn(e,t){let r=t.redact??W(),n=performance.now(),o=D(t.initialFields??{},r),i=[],a;t.onCreate?.();let s=(u,d,l)=>(i.push({level:u,message:ge(d,r),timestamp:new Date().toISOString(),...Mn(d,l)===void 0?{}:{data:D(Mn(d,l),r)}}),c),c={set(u){return Object.assign(o,D(u,r)),c},debug(u,...d){return s("debug",u,d)},info(u,...d){return s("info",u,d)},warn(u,...d){return s("warn",u,d)},warning(u,...d){return s("warning",u,d)},error(u,...d){return s("error",u,d)},success(u,...d){return s("success",u,d)},critical(u,...d){return s("critical",u,d)},table(u,d){return s("table",u,d===void 0?[]:[d])},emit(u={}){if(a)return a;let d=D(t.resolveDefaultFields?.()??{},r),l=Di(u),f=D(vi(u.error,l),r),h=u.level??(f?"error":"info"),y=D({...d,...o,groupId:e,timestamp:new Date().toISOString(),level:h,duration:Math.round(performance.now()-n),...typeof l=="number"?{status:l}:{},...i.length>0?{events:[...i]}:{},...f?{error:f}:{}},r);return t.write(y,ge(u.message??"structured_log",r)),a=y,t.onEmit?.(y),y}};return c}var kr=Symbol("blyp.logger.factory"),wr={success:25,info:30,debug:35,table:37,warning:40,error:50,critical:60},jn={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warn",table:"debug"},Pi="\x1B[35m",Ai="\x1B[0m";function qe(e){return at(e)==="client_log"}function _i(){return {enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",ingestingHost:void 0,status:"missing",errorTracking:{enabled:false,ready:false,status:"missing",dsn:void 0,tracesSampleRate:1,environment:void 0,release:void 0},shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function Ii(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function Oi(){return {enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",host:"https://us.i.posthog.com",status:"missing",errorTracking:{enabled:false,ready:false,mode:"auto",status:"missing",enableExceptionAutocapture:false},shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function Bi(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,send:()=>{},flush:async()=>{}}}function Ni(e){return {name:e,enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",endpoint:void 0,status:"missing",send:()=>{},flush:async()=>{}}}function Mi(){return {get:e=>Ni(e),getAutoForwardTargets:()=>[],send:()=>{},flush:async()=>{}}}function Fi(e){return e.connectors?.betterstack?.enabled?j("betterstack",["@logtail/node","@sentry/node"],"../connectors/betterstack/sender").createBetterStackSender(e):_i()}function qi(e){return e.connectors?.databuddy?.enabled?j("databuddy",["@databuddy/sdk"],"../connectors/databuddy/sender").createDatabuddySender(e):Ii()}function Hi(e){return e.connectors?.posthog?.enabled?j("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/posthog/sender").createPostHogSender(e):Oi()}function ji(e){return e.connectors?.sentry?.enabled?j("sentry",["@sentry/node"],"../connectors/sentry/sender").createSentrySender(e):Bi()}function zi(e){return e.connectors?.otlp?.some(t=>t.enabled)?j("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/otlp/sender").createOTLPRegistry(e):Mi()}function Ui(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};t.data!==void 0&&(r.data=t.data);let n=typeof t.page?.pathname=="string"?t.page.pathname:void 0,o=typeof t.page?.url=="string"?t.page.url:void 0;return (n||o)&&(r.page=n??o),t.metadata!==void 0&&(r.metadata=t.metadata),Object.keys(r).length>0?r:null}function $i(e){if(!e||typeof e!="object"||Array.isArray(e))return {hidden:false,value:e};let t=e;if(t.type==="http_request"||t.type==="http_error")return {hidden:true};if(t.type==="client_log"){let r=Ui(e);return r?{hidden:false,value:r}:{hidden:true}}return {hidden:false,value:e}}function Ki(e){if(e.pretty){let r=Xr()({colorize:true,translateTime:"SYS:HH:MM:ss",ignore:"pid,hostname,caller",customColors:{success:"green",critical:"red bold",info:"blue",warning:"yellow",error:"red",debug:"cyan",table:"cyan"},messageFormat:(n,o)=>{let i=String(n[o]??""),a=typeof n.caller=="string"?n.caller.trim():"";return a?`${i} ${Pi}${a}${Ai}`:i}});return Hn__default.default({level:e.level,customLevels:wr},r)}return Hn__default.default({level:e.level,customLevels:wr})}function X(e){let t=e[kr];if(!t)throw new Error("Unsupported Blyp logger instance");return t}function Sr(e){return X(e).posthog}function xr(e){return X(e).betterstack}function Tr(e){return X(e).databuddy}function ct(e){try{return Sr(e)}catch{return null}}function ut(e){try{return xr(e)}catch{return null}}function dt(e){try{return Tr(e)}catch{return null}}function Jn(e){return X(e).sentry}function Gn(e){return X(e).otlp}function lt(e){try{return X(e).redact}catch{return Te().redact}}function He(e,t){let r=X(t);return Object.defineProperty(e,kr,{value:r,enumerable:false,configurable:false,writable:false}),e}function Qn(e,t){let r=X(e);return r.create(t,r.bindings)}function Er(e,t,r={}){let n=X(e);return qn(t,{initialFields:r.initialFields,resolveDefaultFields:()=>({...n.bindings,...r.resolveDefaultFields?.()??{}}),write:(o,i)=>{n.writeStructured(o,i,"structured-flush");},onCreate:r.onCreate,onEmit:r.onEmit,redact:r.redact??n.redact})}function zn(e,t){if(!qe(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Un(e,t){if(!qe(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function $n(e,t){if(!qe(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Kn(e,t){if(!qe(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Wn(e,t){if(!qe(t))for(let r of e.getAutoForwardTargets())r.send(t,{source:"server",warnIfUnavailable:true});}function Rr(e,t,r,n,o,i,a,s,c,u={},d="root"){let l=Object.keys(u).length>0?e.child(u):e,f=(m,p,b,O=d)=>{if(O==="root"&&Ge())return;let w=mn(m,p,b,u,c),_e=w.message,Ie={caller:w.caller},Je=$i(w.data);!Je.hidden&&Je.value!==void 0&&(Ie.data=Je.value);let Vr=jn[m],Wt=l;(Wt[Vr]??Wt.info??((tc,rc)=>{})).call(l,Ie,_e),t.write(w),Un(n,w),$n(o,w),zn(i,w),Kn(a,w),Wn(s,w);},h=(m,p,b="structured-flush")=>{let O=hn(m.level),w=yn(O,p,m,u,c),_e=jn[O],Ie=l;(Ie[_e]??Ie.info??((Vr,Wt)=>{})).call(l,{caller:w.caller,...w},w.message),(b!=="root"||!Ge())&&t.write(w),Un(n,w),$n(o,w),zn(i,w),Kn(a,w),Wn(s,w);},y={success:(m,...p)=>{f("success",m,p);},critical:(m,...p)=>{f("critical",m,p);},warning:(m,...p)=>{f("warning",m,p);},info:(m,...p)=>{f("info",m,p);},debug:(m,...p)=>{f("debug",m,p);},error:(m,...p)=>{f("error",m,p);},warn:(m,...p)=>{f("warn",m,p);},table:(m,p)=>{p&&typeof p=="object"&&he.env.get("NODE_ENV")!=="production"&&(console.log("TABLE:",m),console.table(D(p,c))),f("table",m,p===void 0?[]:[p]);},flush:async()=>{await t.flush(),r&&await r.flush(),await Promise.allSettled([n.flush(),o.flush(),i.flush(),a.flush(),s.flush()]);},shutdown:async()=>{await t.shutdown(),r&&await r.shutdown(),await Promise.allSettled([n.flush(),o.flush(),i.flush(),a.flush(),s.flush()]);},createStructuredLog:(m,p)=>Er(y,m,{initialFields:p}),child:m=>{let p={...u,...m};return Rr(e,t,r,n,o,i,a,s,c,p,d)},[kr]:{bindings:u,betterstack:n,databuddy:o,posthog:i,sentry:a,otlp:s,redact:c,sink:t,create:(m,p=u)=>Rr(e,t,r,n,o,i,a,s,c,p,m),writeStructured:(m,p,b="structured-flush")=>{h(m,p,b);}}};return y}var br=null;function Pe(e){if(e===void 0&&br)return br;let t=Te(e),r=Ki(t),n=En(t),o=Fi(t),i=qi(t),a=Hi(t),s=ji(t),c=zi(t),u=t.connectors.delivery.enabled?new it(t.connectors.delivery):null;if(u){u.bindTarget(o),u.bindTarget(i),u.bindTarget(a),u.bindTarget(s);for(let l of c.getAutoForwardTargets())u.bindTarget(l);}let d=Rr(r,n,u,o,i,a,s,c,t.redact);return e===void 0&&(br=d),d}var Z=Pe();function Ce(e,t){let r=Wi(e);return typeof e=="string"?{text:r,data:t}:{text:r,data:[e,...t]}}function Wi(e){return Be(e)}function Vn(e,t){return He({debug:(r,...n)=>{let{text:o,data:i}=Ce(r,n);e.debug(o,...i);},info:(r,...n)=>{let{text:o,data:i}=Ce(r,n);e.info(o,...i);},error:(r,...n)=>{let{text:o,data:i}=Ce(r,n);e.error(o,...i);},warn:(r,...n)=>{let{text:o,data:i}=Ce(r,n);e.warn(o,...i);},warning:(r,...n)=>{let{text:o,data:i}=Ce(r,n);e.warning(o,...i);},success:(r,n)=>{let{text:o,data:i}=Ce(r,n===void 0?[]:[n]);n?e.success(o,...i):e.success(o);},critical:(r,n)=>{let{text:o,data:i}=Ce(r,n===void 0?[]:[n]);n?e.critical(o,...i):e.critical(o);},table:(r,n)=>{e.table(r,n);},flush:()=>e.flush(),shutdown:()=>e.shutdown(),createStructuredLog:(r,n)=>e.createStructuredLog(r,n),child:r=>Vn(e.child(r))},e)}function vr(e={}){let t=Pe(e);return Vn(t)}var Ji=vr();function U(){return Ji}function Gi(){return He({debug:(e,...t)=>{U().debug(e,...t);},info:(e,...t)=>{U().info(e,...t);},error:(e,...t)=>{U().error(e,...t);},warn:(e,...t)=>{U().warn(e,...t);},warning:(e,...t)=>{U().warning(e,...t);},success:(e,t)=>{if(t===void 0){U().success(e);return}U().success(e,t);},critical:(e,t)=>{if(t===void 0){U().critical(e);return}U().critical(e,t);},table:(e,t)=>{U().table(e,t);},flush:()=>U().flush(),shutdown:()=>U().shutdown(),createStructuredLog:(e,t)=>U().createStructuredLog(e,t),child:e=>U().child(e)},U())}var gt=Gi();var Qi={CONTINUE:{status:100,message:"Continue"},SWITCHING_PROTOCOLS:{status:101,message:"Switching Protocols"},PROCESSING:{status:102,message:"Processing"},EARLY_HINTS:{status:103,message:"Early Hints"},OK:{status:200,message:"OK"},CREATED:{status:201,message:"Created"},ACCEPTED:{status:202,message:"Accepted"},NON_AUTHORITATIVE_INFORMATION:{status:203,message:"Non-Authoritative Information"},NO_CONTENT:{status:204,message:"No Content"},RESET_CONTENT:{status:205,message:"Reset Content"},PARTIAL_CONTENT:{status:206,message:"Partial Content"},MULTI_STATUS:{status:207,message:"Multi-Status"},ALREADY_REPORTED:{status:208,message:"Already Reported"},IM_USED:{status:226,message:"IM Used"},MULTIPLE_CHOICES:{status:300,message:"Multiple Choices"},MOVED_PERMANENTLY:{status:301,message:"Moved Permanently"},FOUND:{status:302,message:"Found"},SEE_OTHER:{status:303,message:"See Other"},NOT_MODIFIED:{status:304,message:"Not Modified"},USE_PROXY:{status:305,message:"Use Proxy"},TEMPORARY_REDIRECT:{status:307,message:"Temporary Redirect"},PERMANENT_REDIRECT:{status:308,message:"Permanent Redirect"},BAD_REQUEST:{status:400,message:"Bad Request"},UNAUTHORIZED:{status:401,message:"Unauthorized"},PAYMENT_REQUIRED:{status:402,message:"Payment Required"},FORBIDDEN:{status:403,message:"Forbidden"},NOT_FOUND:{status:404,message:"Not Found"},METHOD_NOT_ALLOWED:{status:405,message:"Method Not Allowed"},NOT_ACCEPTABLE:{status:406,message:"Not Acceptable"},PROXY_AUTHENTICATION_REQUIRED:{status:407,message:"Proxy Authentication Required"},REQUEST_TIMEOUT:{status:408,message:"Request Timeout"},CONFLICT:{status:409,message:"Conflict"},GONE:{status:410,message:"Gone"},LENGTH_REQUIRED:{status:411,message:"Length Required"},PRECONDITION_FAILED:{status:412,message:"Precondition Failed"},PAYLOAD_TOO_LARGE:{status:413,message:"Payload Too Large"},URI_TOO_LONG:{status:414,message:"URI Too Long"},UNSUPPORTED_MEDIA_TYPE:{status:415,message:"Unsupported Media Type"},RANGE_NOT_SATISFIABLE:{status:416,message:"Range Not Satisfiable"},EXPECTATION_FAILED:{status:417,message:"Expectation Failed"},IM_A_TEAPOT:{status:418,message:"I'm a Teapot"},MISDIRECTED_REQUEST:{status:421,message:"Misdirected Request"},UNPROCESSABLE_ENTITY:{status:422,message:"Unprocessable Entity"},LOCKED:{status:423,message:"Locked"},FAILED_DEPENDENCY:{status:424,message:"Failed Dependency"},TOO_EARLY:{status:425,message:"Too Early"},UPGRADE_REQUIRED:{status:426,message:"Upgrade Required"},PRECONDITION_REQUIRED:{status:428,message:"Precondition Required"},TOO_MANY_REQUESTS:{status:429,message:"Too Many Requests"},REQUEST_HEADER_FIELDS_TOO_LARGE:{status:431,message:"Request Header Fields Too Large"},UNAVAILABLE_FOR_LEGAL_REASONS:{status:451,message:"Unavailable For Legal Reasons"},INTERNAL_SERVER_ERROR:{status:500,message:"Internal Server Error"},NOT_IMPLEMENTED:{status:501,message:"Not Implemented"},BAD_GATEWAY:{status:502,message:"Bad Gateway"},SERVICE_UNAVAILABLE:{status:503,message:"Service Unavailable"},GATEWAY_TIMEOUT:{status:504,message:"Gateway Timeout"},HTTP_VERSION_NOT_SUPPORTED:{status:505,message:"HTTP Version Not Supported"},VARIANT_ALSO_NEGOTIATES:{status:506,message:"Variant Also Negotiates"},INSUFFICIENT_STORAGE:{status:507,message:"Insufficient Storage"},LOOP_DETECTED:{status:508,message:"Loop Detected"},BANDWIDTH_LIMIT_EXCEEDED:{status:509,message:"Bandwidth Limit Exceeded"},NOT_EXTENDED:{status:510,message:"Not Extended"},NETWORK_AUTHENTICATION_REQUIRED:{status:511,message:"Network Authentication Required"}},Vi=["status","statusCode","code","message","stack","why","fix","link","details","cause","title","detail","logLevel","error","data"];function Yi(e){return e==="debug"||e==="info"||e==="warning"||e==="error"||e==="critical"}function Yn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&/^\d+$/.test(e.trim()))return Number.parseInt(e,10)}function Xi(e){return K(e)?e:void 0}function Xn(e){return e.status!==void 0||e.statusCode!==void 0||e.code!==void 0||e.message!==void 0||e.stack!==void 0||e.why!==void 0||e.fix!==void 0||e.link!==void 0||e.details!==void 0||e.cause!==void 0||e.logLevel!==void 0}function to(e){let t=typeof e.title=="string"?e.title:void 0,r=typeof e.detail=="string"?e.detail:void 0;return {status:Yn(e.status),statusCode:Yn(e.statusCode),code:typeof e.code=="string"||typeof e.code=="number"?e.code:void 0,message:typeof e.message=="string"?e.message:t??r,stack:typeof e.stack=="string"?e.stack:void 0,why:typeof e.why=="string"?e.why:void 0,fix:typeof e.fix=="string"?e.fix:void 0,link:typeof e.link=="string"?e.link:void 0,details:Xi(e.details),cause:e.cause,logLevel:Yi(e.logLevel)?e.logLevel:void 0}}function Dr(e,t){let r=to(e);return t===void 0?Xn(r)?r:void 0:typeof t=="string"?Xn(r)?{...r,message:r.message??t}:t:{status:r.status??t.status,statusCode:r.statusCode??t.statusCode,code:r.code??t.code,message:r.message??t.message,stack:r.stack??t.stack,why:r.why??t.why,fix:r.fix??t.fix,link:r.link??t.link,details:r.details??t.details,cause:r.cause??t.cause,logLevel:r.logLevel??t.logLevel}}function Zn(e){return Vi.some(t=>e[t]!==void 0)}function Zi(e){return typeof Response<"u"&&e instanceof Response?true:K(e)&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.clone=="function"&&typeof e.text=="function"}var Le=class e extends Error{constructor(r){super(r.message);g(this,"name","BlypError");g(this,"status");g(this,"statusCode");g(this,"code");g(this,"why");g(this,"fix");g(this,"link");g(this,"details");g(this,"cause");g(this,"logLevel");Object.setPrototypeOf(this,new.target.prototype),this.status=r.status,this.statusCode=r.statusCode,this.code=r.code,this.why=r.why,this.fix=r.fix,this.link=r.link,this.details=r.details,this.cause=r.cause,this.logLevel=r.logLevel,r.stack?this.stack=r.stack:typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,e);}toJSON(){return {name:"BlypError",message:this.message,status:this.status,statusCode:this.statusCode,...this.code!==void 0?{code:this.code}:{},...this.why!==void 0?{why:this.why}:{},...this.fix!==void 0?{fix:this.fix}:{},...this.link!==void 0?{link:this.link}:{},...this.details!==void 0?{details:this.details}:{}}}};function ro(e,t){return t||(e>=500?"critical":e>=400?"error":"warning")}function es(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{}}:e}function je(e,t,r){let n=ro(t.status,r??t.logLevel);(()=>{switch(n){case "debug":return e.debug;case "info":return e.info;case "warning":return e.warning;case "critical":return e.critical;default:return e.error}})()(t.message,{type:"application_error",status:t.status,statusCode:t.statusCode,code:t.code,why:t.why,fix:t.fix,link:t.link,details:t.details,cause:es(t.cause)});}function Ar(e,t={}){let n=e.status??e.statusCode??t.status??t.statusCode??500,o=pt(n),i=e.message??t.message??o?.message??`HTTP ${n}`;return {status:n,statusCode:n,message:i,code:e.code??t.code??o?.code,why:e.why??t.why??o?.why,fix:e.fix??t.fix??o?.fix,link:e.link??t.link??o?.link,details:e.details??t.details??o?.details,cause:e.cause??t.cause,stack:e.stack??t.stack,logLevel:ro(n,e.logLevel??t.logLevel??o?.logLevel)}}function no(e,t={}){let r=new Le(Ar(e,t));return e.skipLogging!==true&&e.logger&&je(e.logger,r,e.logLevel),r}function oo(e,t){let r={...e,statusCode:e.status,create(n={}){return t?t(e,n):no({status:e.status,message:e.message,code:n.code??e.code,why:n.why??e.why,fix:n.fix??e.fix,link:n.link??e.link,details:n.details??e.details,cause:n.cause,stack:n.stack,logLevel:n.logLevel??e.logLevel,logger:n.logger,skipLogging:n.skipLogging})},extend(n){return oo({key:n.code,status:e.status,message:n.message??e.message,code:n.code,why:n.why??e.why,fix:n.fix??e.fix,link:n.link??e.link,details:n.details??e.details,logLevel:n.logLevel??e.logLevel},t)}};return Object.freeze(r)}function _r(e){let t=Object.entries(Qi).map(([r,n])=>[r,oo({key:r,...n},e)]);return Object.freeze(Object.fromEntries(t))}var ts=_r(),rs=new Map(Object.values(ts).map(e=>[e.status,e]));function pt(e){return rs.get(e)}function Pr(e){if(typeof e=="string")return e;if(K(e)){if(e.error!==void 0){let t=e.error;if(typeof t=="string")return Dr(e,t);if(K(t))return Dr(e,Pr(t))}if(K(e.data)){let t=e.data;if(t.error!==void 0||Zn(t))return Dr(e,Pr(t))}if(Zn(e))return to(e)}}function eo(e,t={},r={}){if(e instanceof Le)return e;let n=(()=>{if(e instanceof Error){let u=e;return {status:u.status,statusCode:u.statusCode,code:u.code,message:e.message,stack:e.stack,why:u.why,fix:u.fix,link:u.link,details:u.details,cause:u.cause,logLevel:u.logLevel}}return Pr(e)})(),o=r.status&&r.status>0?r.status:void 0,i=typeof n=="string"?void 0:n?.status??n?.statusCode,a=o??i??t.fallbackStatus??500,s=typeof n=="string"&&n.trim()||void 0,c=r.statusText?.trim()||void 0;return no(typeof n=="string"?{message:s,...o!==void 0?{status:o}:{}}:{...n??{},...o!==void 0?{status:o,statusCode:o}:{}},{status:a,message:(typeof n=="string"?s:n?.message)??c??pt(a)?.message??`HTTP ${a}`})}async function ns(e){let t=e.headers.get("content-type")?.toLowerCase();if(t?.includes("application/json")||t?.includes("+json"))try{return await e.clone().json()}catch{try{return await e.clone().text()}catch{return}}try{return await e.clone().text()}catch{return}}function os(e,t={}){if(Zi(e))return (async()=>{let n=await ns(e).catch(()=>{}),o=eo(n,t,{status:e.status,statusText:e.statusText});return t.logger&&je(t.logger,o,t.logLevel),o})();let r=eo(e,t);return t.logger&&je(t.logger,r,t.logLevel),r}function ao(e){let t=new Le(Ar(e));if(e.skipLogging!==true){je(e.logger??Z,t,e.logLevel);let r=ct(e.logger??Z);r?.shouldAutoCaptureExceptions()&&r.captureException(t,{source:"server",warnIfUnavailable:true,properties:{"blyp.type":"application_error",status:t.status,statusCode:t.statusCode,...t.code!==void 0?{code:t.code}:{},...t.why!==void 0?{why:t.why}:{},...t.fix!==void 0?{fix:t.fix}:{},...t.link!==void 0?{link:t.link}:{},...t.details!==void 0?{details:t.details}:{}}});let n=ut(e.logger??Z);n?.shouldAutoCaptureExceptions()&&n.captureException(t,{source:"server",warnIfUnavailable:true,context:{"blyp.type":"application_error",status:t.status,statusCode:t.statusCode,...t.code!==void 0?{code:t.code}:{},...t.why!==void 0?{why:t.why}:{},...t.fix!==void 0?{fix:t.fix}:{},...t.link!==void 0?{link:t.link}:{},...t.details!==void 0?{details:t.details}:{}}});let o=dt(e.logger??Z);o?.shouldAutoCaptureExceptions()&&o.captureException(t,{source:"server",warnIfUnavailable:true,properties:{blyp_type:"application_error",status:t.status,status_code:t.statusCode,...t.code!==void 0?{code:t.code}:{},...t.why!==void 0?{why:t.why}:{},...t.fix!==void 0?{fix:t.fix}:{},...t.link!==void 0?{link:t.link}:{},...t.details!==void 0?{details:t.details}:{}}});}return t}var io=_r((e,t={})=>ao({status:e.status,message:e.message,code:e.code,why:e.why,fix:e.fix,link:e.link,details:e.details,...t})),as=new Map(Object.values(io).map(e=>[e.status,e]));function is(e){return as.get(e)??pt(e)}async function ft(e,t=J()){let r=new De(t);try{return await r.init(),await e(r)}finally{await r.shutdown().catch(()=>{});}}function cs(){return J()}function us(e=J()){return z__default.default.existsSync(e)}async function ds(e=J()){return ft(t=>t.getStatusSummary(),e)}async function ls(e={},t=J()){return ft(r=>r.listDeadLetters({limit:e.limit??100,offset:e.offset??0,connectorType:e.connectorType,connectorTarget:e.connectorTarget}),t)}async function gs(e,t=J()){return ft(r=>r.retryDeadLetters(e,Date.now()),t)}async function ps(e,t=J()){return ft(r=>r.clearDeadLetters(e),t)}function ys(e){return {timestamp:"",level:"unknown",message:e}}function hs(e){try{return JSON.parse(e)}catch{return ys(e)}}function Cs(e){let t=z__default.default.readFileSync(e);return e.endsWith(".gz")?Buffer.from(fflate.gunzipSync(t)).toString("utf8"):t.toString("utf8")}function so(e){let t=e.timestamp?`[${e.timestamp}] `:"",r=e.level?e.level.toUpperCase():"UNKNOWN",n=e.caller?` (${e.caller})`:"";return `${t}${r} ${e.message}${n}`.trim()}async function Ls(e,t={}){let{format:r="pretty",limit:n}=t,i=Cs(e).split(`
701
+ `).map(c=>c.trim()).filter(c=>c.length>0),s=(typeof n=="number"&&n>=0?i.slice(-n):i).map(hs);return r==="json"?s:s.map(so).join(`
702
+ `)}function bs(e,t=200,r=500,n=false){if(n&&e.error)return e.error.status?e.error.status:e.error.statusCode?e.error.statusCode:e.code&&parseInt(e.code,10)||r;if(e.set?.status){let o=e.set.status;return typeof o=="number"?o:parseInt(o,10)||t}return t}function fd(){return process.env.NODE_ENV!=="production"}function ws(e){let t=e.indexOf("?"),r=t>=0?e.substring(0,t):e;return r.endsWith("/")&&r.length>1&&(r=r.slice(0,-1)),r.startsWith("/")||(r="/"+r),r}function Rs(e){let t=e.indexOf("?"),r=t>=0?e.substring(0,t):e;return r.endsWith("/")&&r.length>1&&(r=r.slice(0,-1)),r.startsWith("/")||(r="/"+r),r}function Ir(e,t){if(!t||t.length===0)return false;let r=ws(e);return t.some(n=>{let o=Rs(n);if(o===r||o==="/**"||o==="**")return true;if(o==="/*")return r.split("/").filter(a=>a.length>0).length===1;if(o.endsWith("/*")&&!o.includes("**")){let i=o.slice(0,-1);return r.startsWith(i)?r.slice(i.length).split("/").filter(c=>c.length>0).length===1:false}if(o.includes("**")){if(o==="/**")return true;if(o.startsWith("/")&&o.endsWith("**")){let c=o.slice(0,-2);return c.endsWith("/")&&c.length>1&&(c=c.slice(0,-1)),c===r?true:r.startsWith(c+"/")}let i=o.indexOf("**"),a=o.substring(0,i),s=o.substring(i+2);return a.endsWith("/")&&a.length>1&&(a=a.slice(0,-1)),a===""&&s===""?true:a!==""&&s===""?r.startsWith(a+"/"):a===""&&s!==""?r.endsWith(s)||r.includes(s+"/"):a!==""&&s!==""?r.startsWith(a)&&(r.endsWith(s)||r.includes(s+"/")):false}if(o.includes("*")){let i=o.lastIndexOf("."),a=o.lastIndexOf("*");if(i>a&&a>0&&o[a-1]==="/"){let d=o.slice(a),l=r.slice(r.lastIndexOf("/")+1),f=l.lastIndexOf(".");if(f>0)return l.slice(f)===d}let s=o.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*");return new RegExp("^"+s+"$").test(r)}return false})}function mt(e){return `${{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[33m",PATCH:"\x1B[34m",DELETE:"\x1B[31m"}[e.toUpperCase()]||""}${e}\x1B[0m`}function yt(e){let t="\x1B[0m";return e>=500?`\x1B[31m${e}${t}`:e>=400?`\x1B[33m${e}${t}`:e>=300?`\x1B[36m${e}${t}`:e>=200?`\x1B[32m${e}${t}`:`\x1B[37m${e}${t}`}function co(e){return {GET:"\u2192",POST:"\u2191",PUT:"\u21D1",PATCH:"\u2197",DELETE:"\u2715"}[e.toUpperCase()]||"\u2022"}function ht(e){let t="\x1B[0m";return e<100?`\x1B[32m${e}ms${t}`:e<300?`\x1B[33m${e}ms${t}`:e<1e3?`\x1B[31m${e}ms${t}`:`\x1B[41m\x1B[37m${e}ms${t}`}function yd(e){return `${{error:"\x1B[31m",critical:"\x1B[35m",warning:"\x1B[33m",info:"\x1B[34m",success:"\x1B[32m",debug:"\x1B[36m"}[e.toLowerCase()]||""}${e.toUpperCase()}\x1B[0m`}var hd={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m"};function k(e,t){if(!e)return;if(e instanceof Headers||typeof e.get=="function")return e.get(t)??e.get(t.toLowerCase())??void 0;let r=e,n=r[t]??r[t.toLowerCase()];return Array.isArray(n)?n[0]:n}function ks(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>t.match(/for="?(\[[^\]]+\]|[^;,\s"]+)/i)?.[1]?.replace(/^"|"$/g,"")??"").map(t=>t.replace(/^\[|\]$/g,"")).filter(Boolean):[]}function Ss(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function xs(e){if(e.startsWith("[")){let t=e.indexOf("]");return t>=0?e.slice(1,t):e}return e.replace(/:\d+$/,"")}function Ts(e){return /edg\//i.test(e)?"Edge":/opr\//i.test(e)||/opera/i.test(e)?"Opera":/chrome\//i.test(e)&&!/edg\//i.test(e)?"Chrome":/firefox\//i.test(e)?"Firefox":/safari\//i.test(e)&&!/chrome\//i.test(e)?"Safari":/curl\//i.test(e)?"curl":/postmanruntime/i.test(e)?"Postman":"Unknown"}function Es(e){return /windows/i.test(e)?"Windows":/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/mac os x|macintosh/i.test(e)?"macOS":/linux/i.test(e)?"Linux":"Unknown"}function vs(e){return e?/bot|crawler|spider|curl|wget|postmanruntime/i.test(e)?"bot":/ipad|tablet/i.test(e)?"tablet":/mobi|iphone|android/i.test(e)?"mobile":"desktop":"unknown"}function P(e,t="/"){if(!e)return t;if(e.startsWith("http://")||e.startsWith("https://"))try{return new URL(e).pathname||t}catch{return t}if(e.startsWith("/")){let r=e.indexOf("?");return r>=0?e.slice(0,r):e}try{return new URL(e,"http://localhost").pathname||t}catch{return t}}function S(e,t,r){return {method:e,url:t,headers:r}}function Or(e,t,r=W()){let n=t??P(e.url),o=(()=>{try{return new URL(e.url)}catch{try{return new URL(n,"http://localhost")}catch{return null}}})(),i=k(e.headers,"x-forwarded-host")??k(e.headers,"host")??o?.host??void 0,a=i?xs(i):o?.hostname,s=i?.match(/:(\d+)$/)?.[1]??(o?.port||void 0),c=Ss(k(e.headers,"x-forwarded-for")),u=ks(k(e.headers,"forwarded")),d=[k(e.headers,"cf-connecting-ip"),k(e.headers,"true-client-ip"),k(e.headers,"fly-client-ip"),k(e.headers,"x-real-ip"),k(e.headers,"x-client-ip"),c[0],u[0]].filter(y=>!!y),l=k(e.headers,"user-agent"),f=k(e.headers,"sec-ch-ua-platform")?.replace(/^"|"$/g,"")??void 0,h=vs(l??"");return {hostname:a,ip:d[0],forwardedFor:[...c,...u].filter((y,m,p)=>p.indexOf(y)===m),protocol:k(e.headers,"x-forwarded-proto")??(o?.protocol?o.protocol.replace(/:$/,""):void 0),port:s,userAgent:l,origin:k(e.headers,"origin"),referer:k(e.headers,"referer"),acceptLanguage:k(e.headers,"accept-language"),headers:rn(e.headers,r),client:{ip:d[0],hostname:a,browser:l?Ts(l):void 0,os:l?Es(l):void 0,deviceType:h,platform:f,isMobile:h==="mobile"}}}function Ct(e,t,r,n,o,i={},a=W()){return {type:t,method:e.method,url:r,statusCode:n,responseTime:o,...Or(e,r,a),...i}}function Lt(e,t,r,n){let o=mt(e),i=yt(t),a=ht(n),s=co(e);return `${o} ${s} ${i} ${r} ${a}`}function R(e,t){if(e==null)return t===void 0?void 0:{statusCode:t,message:`HTTP ${t}`};if(e instanceof Error){let r=e;return {status:r.status,statusCode:r.statusCode??t,code:r.code,message:e.message,stack:e.stack,why:r.why,fix:r.fix,link:r.link,details:r.details,cause:r.cause}}if(typeof e=="object"){let r=e;return {status:typeof r.status=="number"?r.status:void 0,statusCode:typeof r.statusCode=="number"?r.statusCode:t,code:typeof r.code=="string"||typeof r.code=="number"?r.code:void 0,message:typeof r.message=="string"?r.message:`HTTP ${t??500}`,stack:typeof r.stack=="string"?r.stack:void 0,why:typeof r.why=="string"?r.why:void 0,fix:typeof r.fix=="string"?r.fix:void 0,link:typeof r.link=="string"?r.link:void 0,details:r.details!==null&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:void 0,cause:r.cause}}return {statusCode:t,message:typeof e=="string"?e:`HTTP ${t??500}`}}function B(e){return e>=400}function Ds(e,t){let r=at(e),n=typeof e.caller=="string"?e.caller:void 0,o=ce(e,"groupId"),i=ce(e,"traceId"),a=ce(e,"method"),s=ce(e,"path"),c=ce(e,"status"),u=ce(e,"duration"),d=mr(e,"pathname"),l=mr(e,"url"),f=yr(e,"sessionId"),h=yr(e,"pageId"),y={"blyp.level":e.level,"blyp.source":t,"blyp.payload":lr(e)},m=[["blyp.type",r],["blyp.caller",n],["blyp.group_id",o],["blyp.trace_id",i],["http.method",a],["url.path",s],["client.page_path",d],["client.page_url",l],["client.session_id",f],["client.page_id",h]],p=[["http.status_code",c],["blyp.duration_ms",u]];for(let[b,O]of m)O&&(y[b]=O);for(let[b,O]of p)O!==void 0&&(y[b]=O);return y}function Br(e,t,r={}){return {...Ds(e,t),...r}}function uo(e,t,r,n){let o=mt(e),i=yt(t),a=ht(n);return `${o} ${r} ${i} ${a}`}function Ps(e,t){let r=rr(t?.path??fe),n=t?.enabled===false?null:{path:r};return e===false?null:e===void 0?n:e===true?{path:r}:{...n,...e,path:rr(e.path??r)}}function _(e={},t){let r=Te({...e.level!==void 0?{level:e.level}:{},...e.pretty!==void 0?{pretty:e.pretty}:{},...e.destination!==void 0?{destination:e.destination}:{},...e.logDir!==void 0?{logDir:e.logDir}:{},...e.file!==void 0?{file:e.file}:{},...e.database!==void 0?{database:e.database}:{},...e.redact!==void 0?{redact:e.redact}:{},...e.connectors!==void 0?{connectors:e.connectors}:{}}),{level:n=r.level,pretty:o=r.pretty,destination:i=r.destination,logDir:a=r.logDir,file:s=r.file,database:c=r.database,autoLogging:u=true,customProps:d,logErrors:l=true,includePaths:f,ignorePaths:h,clientLogging:y,connectors:m}=e,p=t??Pe({level:n,pretty:o,destination:i,logDir:a,file:s,database:c,connectors:m}),b=Ps(y,r.clientLogging),O=b?.path??fe,w=f,_e=b?Array.from(new Set([...h??[],O])):h;return {logger:p,betterstack:xr(p),databuddy:Tr(p),posthog:Sr(p),sentry:Jn(p),otlp:Gn(p),resolvedConfig:r,level:n,pretty:o,logDir:a,file:s,autoLogging:u,customProps:d,logErrors:l,resolvedIncludePaths:w,resolvedIgnorePaths:_e,resolvedClientLogging:b,ingestionPath:O}}function As(e,t){return !t||t.length===0?true:Ir(e,t)}function lo(e,t,r){return As(e,t)?Ir(e,r):true}function F(e,t,r){return e.autoLogging===false||typeof e.autoLogging=="object"&&e.autoLogging.ignore?.(t)?true:lo(r,e.resolvedIncludePaths,e.resolvedIgnorePaths)}function x(e,t){return e.logErrors?lo(t,e.resolvedIncludePaths,e.resolvedIgnorePaths):true}function C(e,t){return e.customProps?e.customProps(t):{}}function q(e,t,r,n,o,i,a={}){let s=Ct(r,"http_request",n,o,i,a,lt(e));return t==="info"?e.info(Lt(r.method,o,n,i),s):(e.info(uo(r.method,o,n,i),s),Object.keys(a).length>0&&e.debug("Request context",a)),s}function T(e,t,r,n,o,i,a,s={},c={}){let u=Ct(r,"http_error",n,o,i,{error:a?.message??`HTTP ${o}`,stack:a?.stack,code:a?.code,why:a?.why,fix:a?.fix,link:a?.link,details:a?.details,...s},lt(e)),d=t==="info"?Lt(r.method,o,n,i):uo(r.method,o,n,i);e.error(d,u);let l=ct(e);l?.shouldAutoCaptureExceptions()&&l.captureException(c.error??a??d,{source:"server",warnIfUnavailable:true,distinctId:c.distinctId??k(r.headers,"x-posthog-distinct-id"),properties:Br({timestamp:new Date().toISOString(),level:"error",message:d,data:u},"server",{$request_method:r.method,$request_path:n,$current_url:r.url,$response_status_code:o,...k(r.headers,"user-agent")?{$user_agent:k(r.headers,"user-agent")}:{},...u.ip?{$ip:u.ip}:{}})});let f=ut(e);f?.shouldAutoCaptureExceptions()&&f.captureException(c.error??a??d,{source:"server",warnIfUnavailable:true,context:{timestamp:new Date().toISOString(),level:"error",message:d,status:o,path:n,data:u}});let h=dt(e);return h?.shouldAutoCaptureExceptions()&&h.captureException(c.error??a??d,{source:"server",warnIfUnavailable:true,properties:{method:r.method,path:n,status_code:o,...r.url?{current_url:r.url}:{},...k(r.headers,"user-agent")?{user_agent:k(r.headers,"user-agent")}:{},...u.ip?{ip:u.ip}:{},payload:u}}),u}async function _s(e,t){if(t!==void 0)return typeof t=="string"?JSON.parse(t):t;if(typeof e.json=="function")return await e.json();throw new Error("Unable to parse client log payload")}function Is(e,t){switch(t){case "debug":return e.debug;case "info":return e.info;case "warning":return e.warning;case "error":return e.error;case "critical":return e.critical;case "success":return e.success}}async function H(e){let{config:t,ctx:r,request:n,body:o,deliveryPath:i}=e;if(!t.resolvedClientLogging)return {status:404};let a;try{a=await _s(n,o);}catch{return {status:400}}if(!nn(a))return {status:400};if(!(t.resolvedClientLogging.validate?await t.resolvedClientLogging.validate(r,a):true))return {status:403};let c=t.resolvedClientLogging.enrich?await t.resolvedClientLogging.enrich(r,a):void 0,u=lt(t.logger),d=D(a,u),l=D({...d,receivedAt:new Date().toISOString(),delivery:Or(n,i??P(n.url),u)},u);c!==void 0&&(l.serverContext=D(c,u));let f=ge(`[client] ${d.message}`,u),h=oe(),y=typeof d.traceId=="string"&&d.traceId.length>0?d.traceId:h;try{y&&Oe(y),d.level==="table"?t.logger.table(f,l):Is(t.logger,d.level)(f,l);}finally{Oe(h);}let m={};if(d.connector==="betterstack"){if(m["x-blyp-betterstack-status"]=t.betterstack.ready?"enabled":"missing",t.betterstack.ready){let p={timestamp:l.receivedAt,level:d.level,message:f,data:l};if(t.betterstack.send(p,{source:"client"}),(d.level==="error"||d.level==="critical")&&t.betterstack.shouldAutoCaptureExceptions()){let b=d.data&&typeof d.data=="object"&&!Array.isArray(d.data)&&typeof d.data.message=="string"?d.data:d.message;t.betterstack.captureException(b,{source:"client",warnIfUnavailable:true,context:{sessionId:d.session.sessionId,pageUrl:d.page.url,pagePath:d.page.pathname,metadata:d.metadata,payload:l}});}}}else if(d.connector==="databuddy"){if(m["x-blyp-databuddy-status"]=t.databuddy.ready?"enabled":"missing",t.databuddy.ready){let p={timestamp:l.receivedAt,level:d.level,message:f,data:l};if(t.databuddy.send(p,{source:"client"}),(d.level==="error"||d.level==="critical")&&t.databuddy.shouldAutoCaptureExceptions()){let b=d.data&&typeof d.data=="object"&&!Array.isArray(d.data)&&typeof d.data.message=="string"?d.data:d.message;t.databuddy.captureException(b,{source:"client",warnIfUnavailable:true,sessionId:d.session.sessionId,properties:{page_url:d.page.url,page_path:d.page.pathname,client_runtime:d.device?.runtime,metadata:d.metadata,payload:l}});}}}else if(d.connector==="posthog"){if(m["x-blyp-posthog-status"]=t.posthog.ready?"enabled":"missing",t.posthog.ready){let p={timestamp:l.receivedAt,level:d.level,message:f,data:l};if(t.posthog.send(p,{source:"client"}),(d.level==="error"||d.level==="critical")&&t.posthog.shouldAutoCaptureExceptions()){let b=l.metadata,O=b&&typeof b=="object"&&!Array.isArray(b)&&typeof b.posthogDistinctId=="string"&&b.posthogDistinctId?String(b.posthogDistinctId):void 0,w=d.data&&typeof d.data=="object"&&!Array.isArray(d.data)&&typeof d.data.message=="string"?d.data:d.message;t.posthog.captureException(w,{source:"client",warnIfUnavailable:true,distinctId:O,properties:Br(p,"client",{$session_id:d.session.sessionId,$current_url:d.page.url,$request_path:d.page.pathname,"client.runtime":d.device?.runtime,"client.metadata":d.metadata})});}}}else if(d.connector==="sentry")m["x-blyp-sentry-status"]=t.sentry.ready?"enabled":"missing",t.sentry.ready&&t.sentry.send({timestamp:l.receivedAt,level:d.level,message:f,data:l},{source:"client"});else if(d.connector?.type==="otlp"){let p=t.otlp.get(d.connector.name);m["x-blyp-otlp-status"]=p.ready?"enabled":"missing",p.ready&&p.send({timestamp:l.receivedAt,level:d.level,message:f,data:l},{source:"client"});}return Object.keys(m).length>0?{status:204,headers:m}:{status:204}}async function bt(e){let t=[];for await(let r of e)t.push(Buffer.isBuffer(r)?r:Buffer.from(r));return Buffer.concat(t).toString("utf8")}function ze(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return e;let r=k(t,"x-forwarded-proto")??"http",n=k(t,"host")??"localhost";return `${r}://${n}${e.startsWith("/")?e:`/${e}`}`}function Os(e){return e.resolvedConfig.destination==="database"}async function L(e){if(Os(e))try{await e.logger.flush();}catch(t){console.warn("[Blyp] Warning: Failed to flush database logs.",t);}}function N(e,t={}){let r=Qn(e,"request-scoped"),n=He({...r,createStructuredLog:(o,i)=>Er(n,o,{initialFields:i,resolveDefaultFields:()=>{let a=oe();return {...t.resolveStructuredFields?.()??{},...a?{traceId:a}:{}}},onCreate:()=>{Vt();},onEmit:()=>{Yt(),t.onStructuredEmit?.();}}),child(o){return N(r.child(o),t)}},r);return Qt(n),n}var Nr="x-blyp-trace-id",Bs="trace_";function E(){return `${Bs}${Xe().replace(/[^a-z0-9]/gi,"").toLowerCase().slice(0,12)}`}function v(e){Oe(e);}function I(e,t){let r=new Headers(e.headers);return r.set(Nr,t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}function go(e={}){let t=_(e);return async(r,n)=>A(async()=>{let o=performance.now(),i=E(),a=false;v(i),r.set("blypLog",N(t.logger,{resolveStructuredFields:()=>({method:r.req.method,path:r.req.path||P(r.req.url),...C(t,r)}),onStructuredEmit:()=>{a=true;}})),r.set("blypTraceId",i),r.set("blypStartTime",o);let s=r.req.path||P(r.req.url);if(t.resolvedClientLogging&&r.req.method==="POST"&&s===t.ingestionPath){let u=await H({config:t,ctx:r,request:r.req.raw,deliveryPath:t.ingestionPath});return await L(t),new Response(null,{status:u.status,headers:{...u.headers,"x-blyp-trace-id":i}})}let c;try{await n();}catch(u){throw c=u,u}finally{if(a){await L(t),r.res=I(r.res,i);return}let u=Math.round(performance.now()-o),d=S(r.req.method,r.req.url,r.req.raw.headers),l=r.res?.status??(c?500:200);if(c||B(l)){x(t,s)||T(t.logger,t.level,d,s,l,u,R(c,l),C(t,r),{error:c}),await L(t);return}F(t,r,s)||q(t.logger,t.level,d,s,l,u,C(t,r)),await L(t),r.res=I(r.res,i);}})}function Mr(e,t,r){return {req:e,res:t,error:r}}function po(e={}){let t=_(e);return (r,n,o)=>{Re();let i=E();v(i);let a=false;r.blypTraceId=i,n.setHeader(Nr,i),r.blypLog=N(t.logger,{resolveStructuredFields:()=>({method:r.method,path:P(r.originalUrl||r.url||"/"),...C(t,Mr(r,n,n.locals.blypError))}),onStructuredEmit:()=>{a=true;}}),n.locals.blypStartTime=performance.now(),n.on("finish",()=>{let c=P(r.originalUrl||r.url||"/"),u=S(r.method,ze(r.originalUrl||r.url||"/",r.headers),r.headers),d=Math.round(performance.now()-(n.locals.blypStartTime??performance.now())),l=Mr(r,n,n.locals.blypError);if(!a){if(n.locals.blypError||B(n.statusCode)){x(t,c)||T(t.logger,t.level,u,c,n.statusCode,d,R(n.locals.blypError,n.statusCode),C(t,l),{error:n.locals.blypError});return}F(t,l,c)||q(t.logger,t.level,u,c,n.statusCode,d,C(t,l));}});let s=P(r.originalUrl||r.url||"/");if(t.resolvedClientLogging&&r.method.toUpperCase()==="POST"&&s===t.ingestionPath){(async()=>{let c=r.body===void 0?await bt(r):r.body,u=await H({config:t,ctx:Mr(r,n),request:S(r.method,ze(r.originalUrl||r.url||"/",r.headers),r.headers),body:c,deliveryPath:t.ingestionPath});if(u.headers)for(let[d,l]of Object.entries(u.headers))n.setHeader(d,l);n.status(u.status).end();})().catch(o);return}o();}}function fo(e={}){return (t,r,n,o)=>{n.locals.blypError=t,o(t);}}function wt(e,t,r,n){return {request:e,context:t,response:r,error:n}}function mo(e={}){let t=_(e);return {logger:t.logger,withLogger:r=>async(n,o)=>A(async()=>{let i=performance.now(),a=P(n.url),s=E(),c=false;v(s);let u=N(t.logger,{resolveStructuredFields:()=>({method:n.method,path:a,...C(t,wt(n,o))}),onStructuredEmit:()=>{c=true;}});try{let d=await r(n,o,{log:u,traceId:s});if(c)return await L(t),I(d,s);let l=d.status,f=S(n.method,n.url,n.headers),h=wt(n,o,d),y=Math.round(performance.now()-i);return B(l)?x(t,a)||T(t.logger,t.level,f,a,l,y,R(void 0,l),C(t,h)):F(t,h,a)||q(t.logger,t.level,f,a,l,y,C(t,h)),await L(t),I(d,s)}catch(d){throw !c&&!x(t,a)&&T(t.logger,t.level,S(n.method,n.url,n.headers),a,500,Math.round(performance.now()-i),R(d,500),C(t,wt(n,o,void 0,d)),{error:d}),await L(t),d}}),clientLogHandler:async r=>A(async()=>{let n=E();v(n);let o=P(r.url);if(o!==t.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${o} does not match configured client logging path ${t.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":n}});let i=await H({config:t,ctx:wt(r),request:r,deliveryPath:o});return await L(t),new Response(null,{status:i.status,headers:{...i.headers,"x-blyp-trace-id":n}})})}}var kt=Symbol.for("blyp.react-router.logger"),St="__blypLog",xt=Symbol.for("blyp.react-router.trace-id"),Tt="__blypTraceId";function Rt(e,t,r){return {request:e.request,params:e.params,context:e.context,response:t,error:r}}function Ns(e){if(typeof e.get=="function"){let t=e.get(kt);return t||e.get(St)}return e[kt]??e[St]}function Ms(e,t){if(typeof e.set=="function"){e.set(kt,t),e.set(St,t);return}e[kt]=t,e[St]=t;}function Fs(e){if(typeof e.get=="function"){let t=e.get(xt);return t||e.get(Tt)}return e[xt]??e[Tt]}function qs(e,t){if(typeof e.set=="function"){e.set(xt,t),e.set(Tt,t);return}e[xt]=t,e[Tt]=t;}function Hs(e){let t=R(e);return t?.status??t?.statusCode??500}function yo(e={}){let t=_(e),r=(a,s)=>{Ms(a,s);},n=a=>{let s=Ns(a);return s&&typeof s=="object"?s:t.logger},o=(a,s)=>{qs(a,s);},i=a=>{let s=Fs(a);return typeof s=="string"?s:void 0};return {logger:t.logger,setLogger:r,getLogger:n,setTraceId:o,getTraceId:i,middleware:async(a,s)=>A(async()=>{let c=performance.now(),u=P(a.request.url),d=E(),l=false;v(d);let f=N(t.logger,{resolveStructuredFields:()=>({method:a.request.method,path:u,...C(t,Rt(a))}),onStructuredEmit:()=>{l=true;}});r(a.context,f),o(a.context,d);try{let h=await s();if(l)return await L(t),I(h,d);let y=h.status,m=Rt(a,h),p=Math.round(performance.now()-c),b=S(a.request.method,a.request.url,a.request.headers);return B(y)?x(t,u)||T(t.logger,t.level,b,u,y,p,R(void 0,y),C(t,m)):F(t,m,u)||q(t.logger,t.level,b,u,y,p,C(t,m)),await L(t),I(h,d)}catch(h){if(!l&&!x(t,u)){let y=Hs(h);T(t.logger,t.level,S(a.request.method,a.request.url,a.request.headers),u,y,Math.round(performance.now()-c),R(h,y),C(t,Rt(a,void 0,h)),{error:h});}throw await L(t),h}}),clientLogHandler:async a=>A(async()=>{let s=E();v(s);let c=P(a.url);if(c!==t.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${c} does not match configured client logging path ${t.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":s}});let d=await H({config:t,ctx:Rt({request:a,context:{}}),request:a,deliveryPath:c});return await L(t),new Response(null,{status:d.status,headers:{...d.headers,"x-blyp-trace-id":s}})})}}function Et(e,t,r,n){return {request:e,context:t,response:r,error:n}}function ho(e={}){let t=_(e);return {logger:t.logger,requestMiddleware:async({request:r,context:n,next:o})=>A(async()=>{let i=performance.now(),a=P(r.url),s=E(),c=false,u={...n,blypTraceId:s};v(s);let d=N(t.logger,{resolveStructuredFields:()=>({method:r.method,path:a,...C(t,Et(r,u))}),onStructuredEmit:()=>{c=true;}});u.blypLog=d;try{let l=await o({context:u});if(c)return await L(t),I(l,s);let f=l.status,h=Et(r,u,l),y=Math.round(performance.now()-i);return B(f)?x(t,a)||T(t.logger,t.level,S(r.method,r.url,r.headers),a,f,y,R(void 0,f),C(t,h)):F(t,h,a)||q(t.logger,t.level,S(r.method,r.url,r.headers),a,f,y,C(t,h)),await L(t),I(l,s)}catch(l){throw !c&&!x(t,a)&&T(t.logger,t.level,S(r.method,r.url,r.headers),a,500,Math.round(performance.now()-i),R(l,500),C(t,Et(r,u,void 0,l)),{error:l}),await L(t),l}}),clientLogHandlers:{POST:async r=>A(async()=>{let n=E();v(n);let o=P(r.url);if(o!==t.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${o} does not match configured client logging path ${t.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":n}});let i=await H({config:t,ctx:Et(r,{blypTraceId:n}),request:r,deliveryPath:o});return await L(t),new Response(null,{status:i.status,headers:{...i.headers,"x-blyp-trace-id":n}})})}}}function vt(e,t,r){return {event:e,response:t,error:r}}function Co(e={}){let t=_(e),r=async({event:n,resolve:o})=>A(async()=>{let i=E(),a=false;v(i),n.locals.blypTraceId=i,n.locals.blypLog=N(t.logger,{resolveStructuredFields:()=>({method:n.request.method,path:n.url.pathname,...C(t,vt(n))}),onStructuredEmit:()=>{a=true;}});let s=performance.now(),c=n.url.pathname,u=S(n.request.method,n.request.url,n.request.headers);try{let d=await o(n);if(a)return await L(t),I(d,i);let l=d.status,f=vt(n,d),h=Math.round(performance.now()-s);return B(l)?x(t,c)||T(t.logger,t.level,u,c,l,h,R(void 0,l),C(t,f)):F(t,f,c)||q(t.logger,t.level,u,c,l,h,C(t,f)),await L(t),I(d,i)}catch(d){throw !a&&!x(t,c)&&T(t.logger,t.level,u,c,500,Math.round(performance.now()-s),R(d,500),C(t,vt(n,void 0,d)),{error:d}),await L(t),d}});return {logger:t.logger,handle:r,clientLogHandler:async n=>A(async()=>{let o=E();v(o),n.locals.blypTraceId=o;let i=n.url.pathname;if(i!==t.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${i} does not match configured client logging path ${t.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":o}});let a=await H({config:t,ctx:vt(n),request:n.request,deliveryPath:i});return await L(t),new Response(null,{status:a.status,headers:{...a.headers,"x-blyp-trace-id":o}})})}}function Dt(e,t,r){return {context:e,response:t,error:r}}function Lo(e={}){let t=_(e);return {logger:t.logger,onRequest:async(r,n)=>A(async()=>{let o=E(),i=false;v(o),r.locals.blypTraceId=o,r.locals.blypLog=N(t.logger,{resolveStructuredFields:()=>({method:r.request.method,path:r.url.pathname,...C(t,Dt(r))}),onStructuredEmit:()=>{i=true;}});let a=performance.now(),s=r.url.pathname,c=S(r.request.method,r.request.url,r.request.headers);try{let u=await n();if(i)return await L(t),I(u,o);let d=u.status,l=Dt(r,u),f=Math.round(performance.now()-a);return B(d)?x(t,s)||T(t.logger,t.level,c,s,d,f,R(void 0,d),C(t,l)):F(t,l,s)||q(t.logger,t.level,c,s,d,f,C(t,l)),await L(t),I(u,o)}catch(u){throw !i&&!x(t,s)&&T(t.logger,t.level,c,s,500,Math.round(performance.now()-a),R(u,500),C(t,Dt(r,void 0,u)),{error:u}),await L(t),u}}),clientLogHandler:async r=>A(async()=>{let n=E();v(n),r.locals.blypTraceId=n;let o=r.url.pathname;if(o!==t.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${o} does not match configured client logging path ${t.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":n}});let i=await H({config:t,ctx:Dt(r),request:r.request,deliveryPath:o});return await L(t),new Response(null,{status:i.status,headers:{...i.headers,"x-blyp-trace-id":n}})})}}var bo=Symbol.for("blyp.nitro.state");function Ue(e){return e.context[bo]}function wo(e,t){return e.context[bo]=t,t}function Fr(e){return e.method??e.node?.req?.method??e.request?.method??"GET"}function Ro(e){return e.headers??e.node?.req?.headers??e.request?.headers}function js(e){if(e.request?.url)return e.request.url;let t=e.url??e.path??e.node?.req?.url??"/";return ze(t,Ro(e))}function qr(e){if(typeof e.path=="string"&&e.path.length>0)return e.path;if(e.request?.url)return new URL(e.request.url).pathname;let t=e.url??e.node?.req?.url??"/";if(t.startsWith("http://")||t.startsWith("https://"))return new URL(t).pathname;let r=t.indexOf("?");return r>=0?t.slice(0,r):t}function Pt(e){return S(Fr(e),js(e),Ro(e))}function Hr(e,t,r=200){return t instanceof Response||typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:typeof e.node?.res?.statusCode=="number"&&e.node.res.statusCode>0?e.node.res.statusCode:r}async function ko(e){if(e.body!==void 0)return e.body;if(e.request){if((e.request.headers.get("content-type")??"").includes("application/json")){let r=e.request.clone();try{return await e.request.json()}catch{return await r.text()}}return await e.request.text()}if(e.node?.req)return await bt(e.node.req);throw new Error("Unable to parse Nitro request body")}function At(e,t,r){return {event:e,response:t,error:r}}function jr(e){let t=o=>o.context.blypLog??e.logger,r=async(o,i)=>{let a=Ue(o);if(!a||a.structuredLogEmitted||a.errorLogged)return;let s=Pt(o),c=Hr(o,i),u=Math.round(performance.now()-a.startTime),d=At(o,i);B(c)?x(e,a.path)||T(e.logger,e.level,s,a.path,c,u,R(void 0,c),C(e,d)):F(e,d,a.path)||q(e.logger,e.level,s,a.path,c,u,C(e,d));},n=async(o,i,a)=>{let s=Ue(o);!s||s.structuredLogEmitted||s.errorLogged||x(e,s.path)||(s.errorLogged=true,T(e.logger,e.level,Pt(o),s.path,Hr(o,a,500),Math.round(performance.now()-s.startTime),R(i,500),C(e,At(o,a,i)),{error:i}));};return {logger:e.logger,getLogger:t,plugin:async o=>{await o.hooks.hook("request",async i=>{let a=i;Re();let s=E();v(s),typeof a.node?.res=="object"&&a.node.res&&"setHeader"in a.node.res&&a.node.res.setHeader?.("x-blyp-trace-id",s);let c=qr(a),u=wo(a,{startTime:performance.now(),path:c,structuredLogEmitted:false});a.context.blypTraceId=s;let d=N(e.logger,{resolveStructuredFields:()=>({method:Fr(a),path:c,...C(e,At(a))}),onStructuredEmit:()=>{let l=Ue(a);l&&(l.structuredLogEmitted=true);}});a.context.blypLog=d,u.scopedLogger=d;}),await o.hooks.hook("beforeResponse",async(i,a)=>{await r(i,a);}),await o.hooks.hook("afterResponse",async i=>{await L(e);let a=Ue(i);a&&(a.errorLogged=true);}),await o.hooks.hook("error",async(i,a)=>{a&&typeof a=="object"&&(await n(a,i),await L(e));});},clientLogHandler:async o=>{Re();let i=E();v(i),o.context.blypTraceId=i;let a=qr(o);if(a!==e.ingestionPath)return new Response(JSON.stringify({error:`Mounted route path ${a} does not match configured client logging path ${e.ingestionPath}`}),{status:500,headers:{"content-type":"application/json","x-blyp-trace-id":i}});let s=await ko(o),c=await H({config:e,ctx:At(o),request:{...Pt(o),json:async()=>s},body:s,deliveryPath:a});return await L(e),new Response(null,{status:c.status,headers:{...c.headers,"x-blyp-trace-id":i}})}}}function So(e={}){let t=_(e);return jr(t)}function xo(e={}){let t=jr(_(e));return {logger:t.logger,serverPlugin:t.plugin,clientLogHandler:t.clientLogHandler,getLogger:r=>t.getLogger(r)}}var zs=new TextEncoder;function _t(e){return zs.encode(e).length}function Us(e){if(!e||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function M(e,t=new WeakSet){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(e instanceof Date)return e.toISOString();if(e instanceof Error)return {name:e.name,message:e.message,stack:e.stack};if(Array.isArray(e))return e.map(r=>M(r,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";if(t.add(e),!Us(e)){let r=e.constructor?.name;return r?`[${r}]`:"[Object]"}return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,M(n,t)]))}return String(e)}function ee(e,t){if(t.length===0)return e;let r=M(e);for(let n of t){let o=n.split(".").filter(Boolean);if(o.length===0)continue;let i=r;for(let a=0;a<o.length-1;a+=1){if(!i||typeof i!="object"){i=void 0;break}i=i[o[a]];}i&&typeof i=="object"&&delete i[o[o.length-1]];}return r}function It(e,t){let r=M(e);if(t<=0)return {value:"[Truncated]",truncated:true};if(typeof r=="string"){if(_t(r)<=t)return {value:r,truncated:false};let i=r;for(;i.length>0&&_t(`${i}\u2026[truncated]`)>t;)i=i.slice(0,Math.max(1,Math.floor(i.length*.8)));return {value:`${i}\u2026[truncated]`,truncated:true}}let n=JSON.stringify(r);if(n===void 0||_t(n)<=t)return {value:r,truncated:false};let o=n;for(;o.length>0&&_t(`${o}\u2026[truncated]`)>t;)o=o.slice(0,Math.max(1,Math.floor(o.length*.8)));return {value:{truncated:true,preview:`${o}\u2026[truncated]`},truncated:true}}function be(e){if(!e)return;let t={inputTokens:typeof e.inputTokens=="number"?e.inputTokens:void 0,outputTokens:typeof e.outputTokens=="number"?e.outputTokens:void 0,totalTokens:typeof e.totalTokens=="number"?e.totalTokens:void 0,reasoningTokens:typeof e.reasoningTokens=="number"?e.reasoningTokens:void 0,cachedInputTokens:typeof e.cachedInputTokens=="number"?e.cachedInputTokens:void 0};if(t.totalTokens===void 0&&(t.inputTokens!==void 0||t.outputTokens!==void 0)&&(t.totalTokens=(t.inputTokens??0)+(t.outputTokens??0)),!Object.values(t).every(r=>r===void 0))return t}function te(e){if(typeof e=="string"&&e.length>0)return e;if(e&&typeof e=="object"){let t=e;for(let r of ["type","reason","stop_reason","finish_reason","raw","unified"]){let n=t[r];if(typeof n=="string"&&n.length>0)return n}}}function $e(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function zr(e){return {toolName:e.name,toolCallId:e.id,status:e.status}}function To(e){if(!e)return {};if(e instanceof Error){let t=e;return {errorType:e.name,errorCode:t.code}}if(typeof e=="object"){let t=e;return {errorType:typeof t.type=="string"?t.type:typeof t.name=="string"?t.name:"Error",errorCode:typeof t.code=="string"||typeof t.code=="number"?t.code:void 0}}return {errorType:typeof e}}function Eo(e){return M(e)}var Ur={input:false,output:false,toolInputs:false,toolOutputs:false,reasoning:false,streamEvents:false,streamChunks:false,rawProviderPayload:false},Ke={providerOptions:false,requestPaths:[],responsePaths:[],metadataPaths:[],toolNames:[]},$r={maxContentBytes:16384,maxEvents:200,maxToolCalls:50};function $s(){return `ai_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`}function Ks(){return new Date().toISOString()}function vo(e){return M(e)}function Kr(){return new Date().toISOString()}function Ws(e={}){return {logger:e.logger,provider:e.provider,operation:e.operation,metadata:{...e.metadata??{}},capture:{...Ur,...e.capture??{},streamEvents:e.capture?.streamEvents??e.capture?.streamChunks??Ur.streamEvents,streamChunks:e.capture?.streamChunks??e.capture?.streamEvents??Ur.streamChunks},exclude:{providerOptions:e.exclude?.providerOptions??Ke.providerOptions,requestPaths:[...e.exclude?.requestPaths??Ke.requestPaths],responsePaths:[...e.exclude?.responsePaths??Ke.responsePaths],metadataPaths:[...e.exclude?.metadataPaths??Ke.metadataPaths],toolNames:[...e.exclude?.toolNames??Ke.toolNames]},limits:{maxContentBytes:e.limits?.maxContentBytes??$r.maxContentBytes,maxEvents:e.limits?.maxEvents??$r.maxEvents,maxToolCalls:e.limits?.maxToolCalls??$r.maxToolCalls},hooks:e.hooks??{}}}function Ot(e={}){return Ws(e)}function Bt(e){let t=e.config.logger??le()??Z,r=$s(),n=Kr(),o={traceId:r,provider:e.provider,sdk:e.sdk,operation:e.operation??e.config.operation??e.method,method:e.method,model:e.model,logger:t,metadata:{...e.config.metadata},request:e.request,toolCalls:[],events:[],startedAt:n,startedAtMs:performance.now(),options:e.config,capture:{...e.config.capture},streamed:e.streamed,truncated:false},i={traceId:r,provider:o.provider,sdk:o.sdk,operation:o.operation,method:o.method,logger:t,metadata:o.metadata,request:o.request,get response(){return o.response},get usage(){return o.usage},get finishReason(){return o.finishReason},get input(){return o.input},get output(){return o.output},get reasoning(){return o.reasoning},get toolCalls(){return o.toolCalls.length>0?o.toolCalls:void 0},get startedAt(){return o.startedAt},get firstChunkAt(){return o.firstChunkAt},get endedAt(){return o.endedAt},get error(){return o.error},setMetadata(a){Object.assign(o.metadata,a);},disableCapture(a){o.capture[a]=false;}};return {state:o,context:i}}function re(e,t){e.usage=be(t);}function ue(e,t){e.finishReason=te(t);}function Nt(e,t){e.response=t;}function Mt(e,t){e.input=t;}function de(e,t){e.output=t;}function Ft(e,t){e.rawProviderPayload=Eo(t);}async function qt(e,t){e.firstChunkAt||(e.firstChunkAt=Kr(),e.firstChunkAtMs=performance.now(),await G(e,t,{type:"ai.first_chunk",timestamp:e.firstChunkAt}));}async function Ht(e,t,r){e.capture.streamEvents&&await G(e,t,{type:"ai.chunk",data:r});}function Q(e,t){let r=t.id??`${t.name}:${e.toolCalls.length}`,n=e.toolCalls.findIndex((o,i)=>(o.id??`${o.name}:${i}`)===r);if(n===-1&&e.toolCalls.length>=e.options.limits.maxToolCalls){e.truncated=true;return}if(n===-1){e.toolCalls.push(t);return}e.toolCalls[n]={...e.toolCalls[n],...t};}async function We(e,t,r){Q(e,r),await G(e,t,{type:"ai.tool_call.start",data:zr(r)});}async function Do(e,t,r){Q(e,r),await G(e,t,{type:"ai.tool_call.result",data:zr(r)});}function Js(e){let t=e.toolCalls.filter(r=>!e.options.exclude.toolNames.includes(r.name)).map(r=>{let n={id:r.id,name:r.name,status:r.status};if(e.capture.toolInputs&&r.input!==void 0){let o=Ae(r.input,e.options.limits.maxContentBytes);n.input=o.value,e.truncated||(e.truncated=o.truncated);}if(e.capture.toolOutputs&&r.output!==void 0){let o=Ae(r.output,e.options.limits.maxContentBytes);n.output=o.value,e.truncated||(e.truncated=o.truncated);}return r.providerFormat!==void 0&&(n.providerFormat=M(r.providerFormat)),n});return t.length>0?t:void 0}async function V(e,t,r){if(e.emitted)return;e.emitted=true,r?.error!==void 0&&(e.error=r.error,await G(e,t,{type:"ai.error",data:{error:M(r.error)}}),await we(e.options.hooks.onError,[t])),e.endedAt=Kr(),await G(e,t,{type:"ai.finish",timestamp:e.endedAt}),e.error||await we(e.options.hooks.onFinish,[t]);let n={startedAt:e.startedAt,endedAt:e.endedAt,durationMs:Math.max(0,Math.round(performance.now()-e.startedAtMs))};e.firstChunkAt&&e.firstChunkAtMs!==void 0&&(n.firstChunkAt=e.firstChunkAt,n.msToFirstChunk=Math.max(0,Math.round(e.firstChunkAtMs-e.startedAtMs)));let o={provider:e.provider,sdk:e.sdk,model:e.model,operation:e.operation,method:e.method,streamed:e.streamed,timing:n,metadata:ee(e.metadata,e.options.exclude.metadataPaths)};if(e.usage&&(o.usage=e.usage),e.finishReason&&(o.finishReason=e.finishReason),e.capture.input&&e.input!==void 0){let s=Ae(ee(M(e.input),e.options.exclude.requestPaths),e.options.limits.maxContentBytes);o.input=s.value,e.truncated||(e.truncated=s.truncated);}if(e.capture.output&&e.output!==void 0){let s=M(e.output),c=Ae(typeof s=="object"&&s!==null&&!Array.isArray(s)?ee(s,e.options.exclude.responsePaths):s,e.options.limits.maxContentBytes);o.output=c.value,e.truncated||(e.truncated=c.truncated);}if(e.capture.reasoning&&e.reasoning!==void 0){let s=M(e.reasoning),c=Ae(s,e.options.limits.maxContentBytes);o.reasoning=c.value,e.truncated||(e.truncated=c.truncated);}let i=Js(e);if(i&&(o.tools=i,o.toolCalls=i),e.capture.rawProviderPayload&&e.rawProviderPayload!==void 0){let s=Ae(e.rawProviderPayload,e.options.limits.maxContentBytes);o.rawProviderPayload=s.value,e.truncated||(e.truncated=s.truncated);}e.truncated&&o.metadata&&(o.metadata={...o.metadata,truncated:true});let a={...o};if(e.error!==void 0){let{errorType:s,errorCode:c}=To(e.error);s&&(a.errorType=s),c!==void 0&&(a.errorCode=c);}try{e.logger.createStructuredLog(e.traceId,{type:"ai_trace",ai:a,events:e.events}).emit({message:"ai_trace",level:e.error===void 0?"info":"error",...e.error===void 0?{}:{error:e.error}});}catch(s){console.warn("[Blyp] Failed to emit AI trace.",vo(s));}}async function we(e,t){if(e)try{await e(...t);}catch(r){console.warn("[Blyp] AI middleware hook failed.",vo(r));}}async function G(e,t,r){e.events.length<e.options.limits.maxEvents?e.events.push({...r,timestamp:r.timestamp??Ks()}):e.truncated=true,await we(e.options.hooks.onEvent,[e.events[e.events.length-1],t]);}function Ae(e,t){return It(e,t)}function jt(e){return !!e&&typeof e[Symbol.asyncIterator]=="function"}function zt(e,t){return {[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]();return {async next(){try{let n=await r.next();return n.done?(await t.onReturn?.(),n):(await t.onChunk?.(n.value),n)}catch(n){throw await t.onError?.(n),n}},async return(n){try{return typeof r.return=="function"?await r.return(n):{done:!0,value:n}}finally{await t.onReturn?.();}},async throw(n){try{if(typeof r.throw=="function")return await r.throw(n);throw n}catch(o){throw await t.onError?.(o),o}}}}}}function Gs(e){let t=e.output;if(!Array.isArray(t))return;let r=[];for(let n of t){if(!n||typeof n!="object")continue;let i=n.content;if(Array.isArray(i))for(let a of i){if(!a||typeof a!="object")continue;let c=a.text;typeof c=="string"&&r.push(c);}}return r.length>0?r.join(""):void 0}function Qs(e){let t=e.output;if(!Array.isArray(t))return [];let r=[];for(let n of t){if(!n||typeof n!="object")continue;let o=n,i=o.type;i==="function_call"&&r.push({id:typeof o.call_id=="string"?o.call_id:void 0,name:typeof o.name=="string"?o.name:"unknown",input:$e(o.arguments),status:"started"}),i==="function_call_output"&&r.push({id:typeof o.call_id=="string"?o.call_id:void 0,name:typeof o.name=="string"?o.name:"unknown",output:o.output,status:"completed"});}return r}function Vs(e){let t=e.choices;if(Array.isArray(t))return t.map(r=>{if(!r||typeof r!="object")return "";let n=r.message;return !n||typeof n!="object"?"":typeof n.content=="string"?n.content:""}).join("")}function Ys(e){let t=e.choices;if(!Array.isArray(t))return [];let r=[];for(let n of t){if(!n||typeof n!="object")continue;let o=n.message;if(!o||typeof o!="object")continue;let a=o.tool_calls;if(Array.isArray(a))for(let s of a){if(!s||typeof s!="object")continue;let c=s,u=c.function,d=u&&typeof u=="object"?u:{};r.push({id:typeof c.id=="string"?c.id:void 0,name:typeof d.name=="string"?d.name:"unknown",input:$e(d.arguments),providerFormat:c,status:"started"});}}return r}function Po(e,t){if(!e||typeof e!="object")return {toolCalls:[]};let r=e,n=r.usage&&typeof r.usage=="object"?r.usage:void 0,o=t==="chat.completions.create"?be({inputTokens:typeof n?.prompt_tokens=="number"?n.prompt_tokens:void 0,outputTokens:typeof n?.completion_tokens=="number"?n.completion_tokens:void 0,totalTokens:typeof n?.total_tokens=="number"?n.total_tokens:void 0,reasoningTokens:n?.completion_tokens_details&&typeof n.completion_tokens_details=="object"&&typeof n.completion_tokens_details.reasoning_tokens=="number"?n.completion_tokens_details.reasoning_tokens:void 0,cachedInputTokens:n?.prompt_tokens_details&&typeof n.prompt_tokens_details=="object"&&typeof n.prompt_tokens_details.cached_tokens=="number"?n.prompt_tokens_details.cached_tokens:void 0}):be({inputTokens:typeof n?.input_tokens=="number"?n.input_tokens:void 0,outputTokens:typeof n?.output_tokens=="number"?n.output_tokens:void 0,totalTokens:typeof n?.total_tokens=="number"?n.total_tokens:void 0,reasoningTokens:n?.output_tokens_details&&typeof n.output_tokens_details=="object"&&typeof n.output_tokens_details.reasoning_tokens=="number"?n.output_tokens_details.reasoning_tokens:void 0,cachedInputTokens:n?.input_tokens_details&&typeof n.input_tokens_details=="object"&&typeof n.input_tokens_details.cached_tokens=="number"?n.input_tokens_details.cached_tokens:void 0}),i=t==="chat.completions.create"?te(Array.isArray(r.choices)&&r.choices[0]&&typeof r.choices[0]=="object"?r.choices[0].finish_reason:void 0):te(r.status),a=t==="chat.completions.create"?Ys(r):Qs(r),s={};return typeof r.id=="string"&&(s.responseId=r.id),typeof r.created_at=="number"&&(s.createdAt=r.created_at),typeof r.provider=="string"&&(s.upstreamProvider=r.provider),{model:typeof r.model=="string"?r.model:void 0,usage:o,finishReason:i,output:t==="chat.completions.create"?Vs(r):Gs(r),toolCalls:a,metadata:Object.keys(s).length>0?s:void 0}}async function Ao(e,t,r){if(!r||typeof r!="object")return;await qt(e,t);let n=r,o=n.type;if(typeof o=="string"&&await Ht(e,t,{type:o}),o==="response.output_text.delta"&&typeof n.delta=="string"){let i=`${typeof e.output=="string"?e.output:""}${n.delta}`;de(e,i);}if(o==="response.function_call_arguments.delta"){let i=typeof n.item_id=="string"?n.item_id:void 0,a=typeof n.name=="string"?n.name:"unknown",s=e.toolCalls.find(d=>d.id===i),c=`${typeof s?.input=="string"?s.input:""}${typeof n.delta=="string"?n.delta:""}`,u={id:i,name:a,input:c,status:"started"};s?Q(e,u):await We(e,t,u);}if(o==="response.output_item.done"){let i=n.item;if(i&&typeof i=="object"){let a=i;if(a.type==="function_call"){let s={id:typeof a.call_id=="string"?a.call_id:void 0,name:typeof a.name=="string"?a.name:"unknown",input:$e(a.arguments),status:"started"};await We(e,t,s);}if(a.type==="function_call_output"){let s={id:typeof a.call_id=="string"?a.call_id:void 0,name:typeof a.name=="string"?a.name:"unknown",output:a.output,status:"completed"};await Do(e,t,s);}}}if(o==="response.completed"){let i=n.response;if(i&&typeof i=="object"){let a=i;if(ue(e,te(a.status)),a.usage&&typeof a.usage=="object"){let s=a.usage;re(e,{inputTokens:typeof s.input_tokens=="number"?s.input_tokens:void 0,outputTokens:typeof s.output_tokens=="number"?s.output_tokens:void 0,totalTokens:typeof s.total_tokens=="number"?s.total_tokens:void 0});}}}}async function _o(e,t,r,n,o){let i=Ot({...o,provider:o.provider??"openai"}),{state:a,context:s}=Bt({provider:o.provider??"openai",sdk:"openai-sdk",operation:o.operation,method:t,model:typeof r.model=="string"?r.model:"unknown",request:r,streamed:r.stream===true,config:i});Mt(a,t==="chat.completions.create"?r.messages:r.input??r),await G(a,s,{type:"ai.start"}),await we(i.hooks.onStart,[s]);try{let c=await e(r,...n);if(r.stream===!0&&jt(c))return zt(c,{onChunk:async l=>{await Ao(a,s,l);},onReturn:async()=>{await V(a,s);},onError:async l=>{await V(a,s,{error:l});}});let u=Po(c,t);Nt(a,c),Ft(a,c),u.metadata&&s.setMetadata(u.metadata),u.usage&&re(a,u.usage),u.finishReason&&ue(a,u.finishReason),u.output!==void 0&&de(a,u.output);for(let d of u.toolCalls)Q(a,d);return await V(a,s),c}catch(c){throw await V(a,s,{error:c}),c}}function Wr(e,t,r){return Object.assign(Object.create(Object.getPrototypeOf(e)),e,{[t]:r})}function Io(e,t={}){let r=Object.create(Object.getPrototypeOf(e));if(Object.assign(r,e),e.responses?.create){let n=e.responses,o=Wr(n,"create",(async(i,...a)=>_o(n.create.bind(n),"responses.create",i??{},a,t)));r.responses=o;}if(e.chat?.completions?.create){let n=e.chat,o=n.completions,i=Wr(o,"create",(async(a,...s)=>_o(o.create.bind(o),"chat.completions.create",a??{},s,t)));r.chat=Wr(n,"completions",i);}return r}function Oo(e={}){return {...e,provider:e.provider??"openai"}}function Jr(e,t={}){let r=t.logger??le()??Z,n={...t.metadata??{}},o=t.limits?.maxContentBytes??16384,i=t.exclude?.requestPaths??[],a=t.exclude?.responsePaths??[],s=(async(c,u)=>{let d=performance.now(),l=new Date().toISOString(),f=u?.method??(c instanceof Request?c.method:"GET"),h=typeof c=="string"?c:c instanceof URL?c.toString():c.url;try{let y=await e(c,u),m=new Date().toISOString(),p=r.createStructuredLog(`fetch_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`,{type:"fetch_trace",fetch:{url:h,method:f,status:y.status,startedAt:l,endedAt:m,durationMs:Math.max(0,Math.round(performance.now()-d)),requestId:y.headers.get("x-request-id")??y.headers.get("request-id")??y.headers.get("cf-ray")??void 0,metadata:ee(n,t.exclude?.metadataPaths??[])}});if(t.inspectJsonBody===!0&&!y.bodyUsed&&y.headers.get("content-type")?.includes("application/json"))try{let O=await y.clone().json(),w=It({request:ee(M(u??{}),i),response:ee(M(O),a)},o);p.set({fetchBody:w.value});}catch{}return p.emit({message:"fetch_trace",level:y.ok?"info":"error"}),y}catch(y){throw r.createStructuredLog(`fetch_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`,{type:"fetch_trace",fetch:{url:h,method:f,startedAt:l,endedAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-d)),metadata:ee(n,t.exclude?.metadataPaths??[])}}).emit({message:"fetch_trace",level:"error",error:M(y)}),y}});return "preconnect"in e&&(s.preconnect=e.preconnect),s}function Bo(e){if(!e||typeof e!="object")return {toolCalls:[]};let t=e,r=t.usage&&typeof t.usage=="object"?be({inputTokens:typeof t.usage.input_tokens=="number"?t.usage.input_tokens:void 0,outputTokens:typeof t.usage.output_tokens=="number"?t.usage.output_tokens:void 0,cachedInputTokens:typeof t.usage.cache_read_input_tokens=="number"?t.usage.cache_read_input_tokens:void 0}):void 0,n=Array.isArray(t.content)?t.content:[],o=n.filter(a=>!!a&&typeof a=="object").filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(""),i=n.filter(a=>!!a&&typeof a=="object").filter(a=>a.type==="tool_use").map(a=>({id:typeof a.id=="string"?a.id:void 0,name:typeof a.name=="string"?a.name:"unknown",input:a.input,status:"started"}));return {model:typeof t.model=="string"?t.model:void 0,usage:r,finishReason:te(t.stop_reason),output:o||void 0,toolCalls:i}}async function No(e,t,r){if(!r||typeof r!="object")return;let n=r,o=n.type;if(typeof o=="string"){if(await qt(e,t),await Ht(e,t,{type:o}),o==="content_block_delta"){let i=n.delta;if(i&&typeof i=="object"){let a=i;if(a.type==="text_delta"&&typeof a.text=="string"&&de(e,`${typeof e.output=="string"?e.output:""}${a.text}`),a.type==="input_json_delta"&&typeof a.partial_json=="string"){let s=typeof n.index=="number"?n.index:0,c=e.toolCalls[s];Q(e,{id:c?.id,name:c?.name??"unknown",input:`${typeof c?.input=="string"?c.input:""}${a.partial_json}`,status:c?.status??"started"});}}}if(o==="content_block_start"){let i=n.content_block;if(i&&typeof i=="object"){let a=i;a.type==="tool_use"&&await We(e,t,{id:typeof a.id=="string"?a.id:void 0,name:typeof a.name=="string"?a.name:"unknown",input:a.input,status:"started"});}}if(o==="message_delta"&&(ue(e,n.stop_reason),n.usage&&typeof n.usage=="object")){let i=n.usage;re(e,{outputTokens:typeof i.output_tokens=="number"?i.output_tokens:void 0});}if(o==="message_stop"&&n.usage&&typeof n.usage=="object"){let i=n.usage;re(e,{inputTokens:typeof i.input_tokens=="number"?i.input_tokens:void 0,outputTokens:typeof i.output_tokens=="number"?i.output_tokens:void 0});}}}function Xs(e,t,r){return Object.assign(Object.create(Object.getPrototypeOf(e)),e,{[t]:r})}function Mo(e,t={}){let r=Object.create(Object.getPrototypeOf(e));if(Object.assign(r,e),!e.messages?.create)return r;let n=async(o,...i)=>{let a=Ot({...t,provider:"anthropic"}),{state:s,context:c}=Bt({provider:"anthropic",sdk:"anthropic-sdk",operation:t.operation,method:"messages.create",model:typeof o?.model=="string"?o.model:"unknown",request:o,streamed:o?.stream===true,config:a});Mt(s,o?.messages??o),await G(s,c,{type:"ai.start"}),await we(a.hooks.onStart,[c]);try{let u=await e.messages.create(o,...i);if(o?.stream===!0&&jt(u))return zt(u,{onChunk:async l=>{await No(s,c,l);},onReturn:async()=>{await V(s,c);},onError:async l=>{await V(s,c,{error:l});}});let d=Bo(u);Nt(s,u),Ft(s,u),d.usage&&re(s,d.usage),d.finishReason&&ue(s,d.finishReason),d.output!==void 0&&de(s,d.output);for(let l of d.toolCalls)Q(s,l);return await V(s,c),u}catch(u){throw await V(s,c,{error:u}),u}};return r.messages=Xs(e.messages,"create",n),r}function Og(e,t){return (le()??gt).createStructuredLog(e,t)}function Bg(e={}){return qo().createElysiaLogger(e)}function Ng(e={}){return qo().createLogger(e)}function Mg(e={}){return Zs().createFastifyLogger(e)}function Fg(e={}){return Gr().createNestLogger(e)}var qg=new Proxy(function(){},{get(e,t,r){return Reflect.get(Gr().BlypModule,t,r)},construct(e,t,r){return Reflect.construct(Gr().BlypModule,t,r)}});function Ut(){return j("betterstack",["@logtail/node","@sentry/node"])}function $t(){return j("databuddy",["@databuddy/sdk"])}function Kt(){return j("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"])}function Qr(){return j("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"])}function Fo(){return j("sentry",["@sentry/node"])}function qo(){return j("elysia",["elysia"])}function Zs(){return j("fastify",["fastify","fastify-plugin"])}function Gr(){return j("nestjs",["@nestjs/common","@nestjs/core","@nestjs/platform-express","@nestjs/platform-fastify","rxjs"])}function Hg(e,t,r){return Qr().normalizeOTLPRecord(e,t,r)}function jg(e={}){return Ut().createBetterStackLogger(e)}function zg(e={}){return Ut().createBetterStackErrorTracker(e)}function Ug(e,t={},r={}){return Ut().captureBetterStackException(e,t,r)}function $g(e,t,r={}){return Ut().createStructuredBetterStackLogger(e,t,r)}function Kg(e={}){return $t().createDatabuddyLogger(e)}function Wg(e={}){return $t().createDatabuddyErrorTracker(e)}function Jg(e,t={},r={}){return $t().captureDatabuddyException(e,t,r)}function Gg(e,t,r={}){return $t().createStructuredDatabuddyLogger(e,t,r)}function Qg(e={}){return Kt().createPosthogLogger(e)}function Vg(e={}){return Kt().createPosthogErrorTracker(e)}function Yg(e,t={},r={}){return Kt().capturePosthogException(e,t,r)}function Xg(e,t,r={}){return Kt().createStructuredPosthogLogger(e,t,r)}function Zg(e={}){return Fo().createSentryLogger(e)}function ep(e,t,r={}){return Fo().createStructuredSentryLogger(e,t,r)}function tp(e={name:""}){return Qr().createOtlpLogger(e)}function rp(e,t,r){return Qr().createStructuredOtlpLogger(e,t,r)}
703
+ exports.BlypError=Le;exports.BlypModule=qg;exports.CUSTOM_LEVELS=wr;exports.DEFAULT_CLIENT_LOGGING_CONFIG=Ze;exports.DEFAULT_CONFIG=nr;exports.DEFAULT_CONNECTOR_DELIVERY_CONFIG=$;exports.DEFAULT_CONNECTOR_RETRY_CONFIG=me;exports.DEFAULT_DATABASE_DELIVERY_CONFIG=un;exports.DEFAULT_DATABASE_RETRY_CONFIG=sr;exports.DEFAULT_FILE_CONFIG=ar;exports.DEFAULT_REDACTION_CONFIG=ir;exports.DEFAULT_ROTATION_CONFIG=or;exports.HTTP_CODES=io;exports.blypFetch=Jr;exports.captureBetterStackException=Ug;exports.captureDatabuddyException=Jg;exports.capturePosthogException=Yg;exports.clearConnectorDeadLetters=ps;exports.colors=hd;exports.connectorQueueExists=us;exports.createAstroLogger=Lo;exports.createBaseLogger=Pe;exports.createBetterStackErrorTracker=zg;exports.createBetterStackLogger=jg;exports.createDatabuddyErrorTracker=Wg;exports.createDatabuddyLogger=Kg;exports.createDrizzleDatabaseAdapter=bn;exports.createElysiaLogger=Bg;exports.createError=ao;exports.createExpressErrorLogger=fo;exports.createExpressLogger=po;exports.createFastifyLogger=Mg;exports.createHonoLogger=go;exports.createLogDir=Ei;exports.createLogger=Ng;exports.createNestLogger=Fg;exports.createNextJsLogger=mo;exports.createNitroLogger=So;exports.createNuxtLogger=xo;exports.createOpenAITracker=Oo;exports.createOtlpLogger=tp;exports.createPosthogErrorTracker=Vg;exports.createPosthogLogger=Qg;exports.createPrismaDatabaseAdapter=Rn;exports.createReactRouterLogger=yo;exports.createRuntimeAdapter=Nn;exports.createSentryLogger=Zg;exports.createStandaloneLogger=vr;exports.createStructuredBetterStackLogger=$g;exports.createStructuredDatabuddyLogger=Gg;exports.createStructuredLog=Og;exports.createStructuredOtlpLogger=rp;exports.createStructuredPosthogLogger=Xg;exports.createStructuredSentryLogger=ep;exports.createSvelteKitLogger=Co;exports.createTanStackStartLogger=ho;exports.formatLogRecord=so;exports.getArrowForMethod=co;exports.getColoredLevel=yd;exports.getConfig=oi;exports.getConnectorDeliveryStatusSummary=ds;exports.getConnectorQueuePath=cs;exports.getHttpCode=is;exports.getMethodColor=mt;exports.getResponseTimeColor=ht;exports.getStatusColor=yt;exports.listConnectorDeadLetters=ls;exports.loadConfig=ur;exports.logger=gt;exports.mergeBlypConfig=et;exports.normalizeOTLPRecord=Hg;exports.parseError=os;exports.readLogFile=Ls;exports.resetConfigCache=ai;exports.resolveConfig=Te;exports.resolveStatusCode=bs;exports.retryConnectorDeadLetters=gs;exports.runtime=he;exports.shouldIgnorePath=Ir;exports.shouldLogTable=fd;exports.wrapAnthropic=Mo;exports.wrapOpenAI=Io;