@blyp/core 0.1.21 → 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/README.md +54 -522
- package/STABILITY.md +56 -0
- package/dist/ai/anthropic/index.d.ts +3 -0
- package/dist/ai/anthropic/normalize.d.ts +9 -0
- package/dist/ai/anthropic/stream.d.ts +3 -0
- package/dist/ai/anthropic/wrap.d.ts +13 -0
- package/dist/ai/anthropic.js +701 -0
- package/dist/ai/anthropic.mjs +701 -0
- package/dist/ai/better-agent/index.d.ts +3 -0
- package/dist/ai/better-agent/normalize.d.ts +18 -0
- package/dist/ai/better-agent/plugin.d.ts +3 -0
- package/dist/ai/better-agent/tracker.d.ts +35 -0
- package/dist/ai/better-agent.js +701 -0
- package/dist/ai/better-agent.mjs +701 -0
- package/dist/ai/fetch.js +701 -0
- package/dist/ai/fetch.mjs +701 -0
- package/dist/ai/openai/index.d.ts +3 -0
- package/dist/ai/openai/normalize.d.ts +10 -0
- package/dist/ai/openai/stream.d.ts +3 -0
- package/dist/ai/openai/wrap.d.ts +24 -0
- package/dist/ai/openai.js +701 -0
- package/dist/ai/openai.mjs +701 -0
- package/dist/ai/shared/fetch.d.ts +5 -0
- package/dist/ai/shared/index.d.ts +2 -0
- package/dist/ai/shared/normalize.d.ts +17 -0
- package/dist/ai/shared/redaction.d.ts +6 -0
- package/dist/ai/shared/stream.d.ts +7 -0
- package/dist/ai/shared/trace.d.ts +119 -0
- package/dist/ai/shared/types.d.ts +171 -0
- package/dist/ai/shared.js +701 -0
- package/dist/ai/shared.mjs +701 -0
- package/dist/ai/vercel/index.d.ts +3 -0
- package/dist/ai/vercel/middleware.d.ts +3 -0
- package/dist/ai/vercel/model.d.ts +3 -0
- package/dist/ai/vercel.js +701 -0
- package/dist/ai/vercel.mjs +701 -0
- package/dist/astro.js +618 -4519
- package/dist/astro.mjs +618 -4491
- package/dist/client.js +1 -1139
- package/dist/client.mjs +1 -1132
- package/dist/connectors/betterstack.js +9 -1532
- package/dist/connectors/betterstack.mjs +9 -1507
- package/dist/connectors/databuddy.js +9 -1456
- package/dist/connectors/databuddy.mjs +9 -1451
- package/dist/connectors/delivery/backoff.d.ts +2 -0
- package/dist/connectors/delivery/manager.d.ts +44 -0
- package/dist/connectors/delivery/queue-path.d.ts +1 -0
- package/dist/connectors/delivery/sqlite-adapter-bun.d.ts +1 -0
- package/dist/connectors/delivery/sqlite-adapter-node.d.ts +1 -0
- package/dist/connectors/delivery/sqlite-client.d.ts +37 -0
- package/dist/connectors/delivery/sqlite-worker.d.ts +1 -0
- package/dist/connectors/delivery/studio-queue.d.ts +12 -0
- package/dist/connectors/delivery/types.d.ts +98 -0
- package/dist/connectors/otlp/index.d.ts +1 -0
- package/dist/connectors/otlp.js +9 -1371
- package/dist/connectors/otlp.mjs +9 -1368
- package/dist/connectors/posthog/properties.d.ts +4 -0
- package/dist/connectors/posthog/sender.d.ts +0 -1
- package/dist/connectors/posthog.js +10 -1527
- package/dist/connectors/posthog.mjs +10 -1522
- package/dist/connectors/sentry.js +9 -1380
- package/dist/connectors/sentry.mjs +9 -1357
- package/dist/core/config.d.ts +7 -2
- package/dist/core/log-record.d.ts +5 -4
- package/dist/core/logger.d.ts +2 -0
- package/dist/core/optional-module.d.ts +1 -0
- package/dist/core/pino-pretty-loader.d.ts +4 -0
- package/dist/database.js +1 -24
- package/dist/database.mjs +1 -21
- package/dist/elysia.js +613 -4517
- package/dist/elysia.mjs +615 -4491
- package/dist/expo.js +1 -726
- package/dist/expo.mjs +1 -724
- package/dist/express.js +613 -4507
- package/dist/express.mjs +615 -4480
- package/dist/fastify.js +615 -4526
- package/dist/fastify.mjs +617 -4499
- package/dist/frameworks/elysia/index.d.ts +1 -1
- package/dist/frameworks/elysia/logger.d.ts +2 -35
- package/dist/frameworks/nestjs/helpers.d.ts +2 -0
- package/dist/frameworks/shared/http.d.ts +3 -2
- package/dist/frameworks/shared/index.d.ts +2 -1
- package/dist/frameworks/shared/logger.d.ts +2 -0
- package/dist/frameworks/shared/request-context.d.ts +2 -0
- package/dist/frameworks/shared/trace.d.ts +6 -0
- package/dist/hono.js +616 -4496
- package/dist/hono.mjs +618 -4470
- package/dist/index.d.ts +49 -19
- package/dist/index.js +615 -7557
- package/dist/index.mjs +618 -7465
- package/dist/nestjs.js +626 -4999
- package/dist/nestjs.mjs +621 -4966
- package/dist/nextjs.js +618 -4525
- package/dist/nextjs.mjs +620 -4499
- package/dist/nitro.js +617 -4642
- package/dist/nitro.mjs +619 -4616
- package/dist/nuxt.js +617 -4649
- package/dist/nuxt.mjs +619 -4623
- package/dist/react-router.js +616 -4559
- package/dist/react-router.mjs +618 -4533
- package/dist/shared/redaction.d.ts +17 -0
- package/dist/standalone.js +606 -3628
- package/dist/standalone.mjs +610 -3603
- package/dist/sveltekit.js +617 -4523
- package/dist/sveltekit.mjs +619 -4497
- package/dist/tanstack-start.js +616 -4522
- package/dist/tanstack-start.mjs +618 -4496
- package/dist/types/core/config.d.ts +57 -0
- package/dist/types/core/logger.d.ts +3 -0
- package/dist/types/core/structured-log.d.ts +2 -0
- package/dist/types/database.d.ts +1 -0
- package/dist/types/frameworks/astro.d.ts +1 -0
- package/dist/types/frameworks/client.d.ts +2 -0
- package/dist/types/frameworks/elysia.d.ts +2 -0
- package/dist/types/frameworks/express.d.ts +1 -0
- package/dist/types/frameworks/fastify.d.ts +1 -0
- package/dist/types/frameworks/hono.d.ts +1 -0
- package/dist/types/frameworks/http.d.ts +1 -0
- package/dist/types/frameworks/nestjs.d.ts +2 -0
- package/dist/types/frameworks/nextjs.d.ts +1 -0
- package/dist/types/frameworks/nitro.d.ts +1 -0
- package/dist/types/frameworks/react-router.d.ts +2 -0
- package/dist/types/frameworks/request-context.d.ts +1 -0
- package/dist/types/frameworks/shared.d.ts +4 -1
- package/dist/types/frameworks/standalone.d.ts +3 -2
- package/dist/types/frameworks/sveltekit.d.ts +1 -0
- package/dist/types/frameworks/tanstack-start.d.ts +9 -3
- package/dist/types/frameworks/workers.d.ts +3 -0
- package/dist/types/shared/client-log.d.ts +1 -0
- package/dist/workers.js +2 -626
- package/dist/workers.mjs +2 -623
- package/package.json +259 -173
- package/dist/astro.js.map +0 -1
- package/dist/astro.mjs.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/client.mjs.map +0 -1
- package/dist/connectors/betterstack.js.map +0 -1
- package/dist/connectors/betterstack.mjs.map +0 -1
- package/dist/connectors/databuddy.js.map +0 -1
- package/dist/connectors/databuddy.mjs.map +0 -1
- package/dist/connectors/otlp.js.map +0 -1
- package/dist/connectors/otlp.mjs.map +0 -1
- package/dist/connectors/posthog.js.map +0 -1
- package/dist/connectors/posthog.mjs.map +0 -1
- package/dist/connectors/sentry.js.map +0 -1
- package/dist/connectors/sentry.mjs.map +0 -1
- package/dist/database.js.map +0 -1
- package/dist/database.mjs.map +0 -1
- package/dist/elysia.js.map +0 -1
- package/dist/elysia.mjs.map +0 -1
- package/dist/expo.js.map +0 -1
- package/dist/expo.mjs.map +0 -1
- package/dist/express.js.map +0 -1
- package/dist/express.mjs.map +0 -1
- package/dist/fastify.js.map +0 -1
- package/dist/fastify.mjs.map +0 -1
- package/dist/hono.js.map +0 -1
- package/dist/hono.mjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/nestjs.js.map +0 -1
- package/dist/nestjs.mjs.map +0 -1
- package/dist/nextjs.js.map +0 -1
- package/dist/nextjs.mjs.map +0 -1
- package/dist/nitro.js.map +0 -1
- package/dist/nitro.mjs.map +0 -1
- package/dist/nuxt.js.map +0 -1
- package/dist/nuxt.mjs.map +0 -1
- package/dist/react-router.js.map +0 -1
- package/dist/react-router.mjs.map +0 -1
- package/dist/standalone.js.map +0 -1
- package/dist/standalone.mjs.map +0 -1
- package/dist/sveltekit.js.map +0 -1
- package/dist/sveltekit.mjs.map +0 -1
- package/dist/tanstack-start.js.map +0 -1
- package/dist/tanstack-start.mjs.map +0 -1
- package/dist/workers.js.map +0 -1
- package/dist/workers.mjs.map +0 -1
- package/exports/client.js +0 -3
- package/exports/client.mjs +0 -3
- package/exports/connectors/betterstack.js +0 -1
- package/exports/connectors/betterstack.mjs +0 -1
- package/exports/connectors/databuddy.js +0 -1
- package/exports/connectors/databuddy.mjs +0 -1
- package/exports/connectors/otlp.js +0 -1
- package/exports/connectors/otlp.mjs +0 -1
- package/exports/connectors/posthog.js +0 -1
- package/exports/connectors/posthog.mjs +0 -1
- package/exports/connectors/sentry.js +0 -1
- package/exports/connectors/sentry.mjs +0 -1
- package/exports/database.js +0 -1
- package/exports/database.mjs +0 -1
- package/exports/expo.js +0 -1
- package/exports/expo.mjs +0 -1
- package/exports/frameworks/astro.js +0 -1
- package/exports/frameworks/astro.mjs +0 -1
- package/exports/frameworks/elysia.js +0 -1
- package/exports/frameworks/elysia.mjs +0 -1
- package/exports/frameworks/express.js +0 -1
- package/exports/frameworks/express.mjs +0 -1
- package/exports/frameworks/fastify.js +0 -1
- package/exports/frameworks/fastify.mjs +0 -1
- package/exports/frameworks/hono.js +0 -1
- package/exports/frameworks/hono.mjs +0 -1
- package/exports/frameworks/nestjs.js +0 -1
- package/exports/frameworks/nestjs.mjs +0 -1
- package/exports/frameworks/nextjs.js +0 -1
- package/exports/frameworks/nextjs.mjs +0 -1
- package/exports/frameworks/nitro.js +0 -1
- package/exports/frameworks/nitro.mjs +0 -1
- package/exports/frameworks/nuxt.js +0 -1
- package/exports/frameworks/nuxt.mjs +0 -1
- package/exports/frameworks/react-router.js +0 -1
- package/exports/frameworks/react-router.mjs +0 -1
- package/exports/frameworks/standalone.js +0 -1
- package/exports/frameworks/standalone.mjs +0 -1
- package/exports/frameworks/sveltekit.js +0 -1
- package/exports/frameworks/sveltekit.mjs +0 -1
- package/exports/frameworks/tanstack-start.js +0 -1
- package/exports/frameworks/tanstack-start.mjs +0 -1
- package/exports/workers.js +0 -1
- package/exports/workers.mjs +0 -1
- package/types/client.d.ts +0 -34
- package/types/connectors/betterstack.d.ts +0 -1
- package/types/connectors/databuddy.d.ts +0 -1
- package/types/connectors/otlp.d.ts +0 -1
- package/types/connectors/posthog.d.ts +0 -1
- package/types/connectors/sentry.d.ts +0 -1
- package/types/database.d.ts +0 -1
- package/types/expo.d.ts +0 -17
- package/types/frameworks/astro.d.ts +0 -1
- package/types/frameworks/client.d.ts +0 -160
- package/types/frameworks/elysia.d.ts +0 -1
- package/types/frameworks/expo.d.ts +0 -50
- package/types/frameworks/express.d.ts +0 -1
- package/types/frameworks/fastify.d.ts +0 -1
- package/types/frameworks/hono.d.ts +0 -1
- package/types/frameworks/nestjs.d.ts +0 -1
- package/types/frameworks/nextjs.d.ts +0 -1
- package/types/frameworks/nitro.d.ts +0 -1
- package/types/frameworks/nuxt.d.ts +0 -1
- package/types/frameworks/react-router.d.ts +0 -1
- package/types/frameworks/standalone.d.ts +0 -1
- package/types/frameworks/sveltekit.d.ts +0 -1
- package/types/frameworks/tanstack-start.d.ts +0 -1
- package/types/frameworks/workers.d.ts +0 -115
- package/types/index.d.ts +0 -1
- package/types/workers.d.ts +0 -13
|
@@ -0,0 +1,701 @@
|
|
|
1
|
+
'use strict';var Ot=require('pino'),jiti=require('jiti'),module$1=require('module'),async_hooks=require('async_hooks'),w=require('fs'),F=require('path'),xn=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 Ot__default=/*#__PURE__*/_interopDefault(Ot);var w__default=/*#__PURE__*/_interopDefault(w);var F__default=/*#__PURE__*/_interopDefault(F);var xn__default=/*#__PURE__*/_interopDefault(xn);var sn=Object.defineProperty;var cn=(e,t,n)=>t in e?sn(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var l=(e,t,n)=>cn(e,typeof t!="symbol"?t+"":t,n);var ln=jiti.createJiti(typeof __filename=="string"?__filename:(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('anthropic.js', document.baseURI).href)),{interopDefault:false,moduleCache:true,fsCache:false}),Ke=new Map;function dn(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,n="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof n=="string"&&(n.includes("Cannot find module")||n.includes("Cannot find package"))}function M(e,t,n=`@blyp/core/${e}`){let o=`@blyp/core/${e}`,r=`${o}::${n}`,a=Ke.get(r);if(a)return a;try{let s=ln(n);return Ke.set(r,s),s}catch(s){if(!dn(s))throw s;let i=t.map(u=>`"${u}"`).join(", "),c=t.join(" ");throw new Error(`[Blyp] Optional connector dependencies missing for "${o}". Install ${i} to use this API. Example: bun add ${c}. You can also import directly from "${o}".`,{cause:s instanceof Error?s:void 0})}}var fn=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('anthropic.js', document.baseURI).href))),be=null;function gn(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,n="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof n=="string"&&(n.includes("Cannot find module")||n.includes("Cannot find package"))}function mn(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 We(){if(be)return be;let e;try{e=fn("pino-pretty");}catch(n){throw gn(n)?new Error('[Blyp] Failed to initialize the pretty logger transport because pretty: true requires "pino-pretty" to be installed.',{cause:n instanceof Error?n:void 0}):new Error('[Blyp] Failed to initialize the pretty logger transport with "pino-pretty".',{cause:n instanceof Error?n:void 0})}let t=mn(e);if(!t)throw new Error('[Blyp] Failed to initialize the pretty logger transport because "pino-pretty" did not expose a callable factory.');return be=t,t}var hn=new async_hooks.AsyncLocalStorage;function Ce(){return hn.getStore()}function Z(){return Ce()?.activeLogger}function we(){return Ce()?.traceId}function Re(){let e=Ce();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 ee(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let n=e;return n.cause!==void 0&&(t.cause=T(n.cause)),t}function T(e,t=new WeakSet){if(e instanceof Error)return ee(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(n=>T(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let n={};for(let[o,r]of Object.entries(e))n[o]=T(r,t);return t.delete(e),n}return e}function Te(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=T(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var bn="[REDACTED]",Cn=["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"];var wn=[{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}],Rn=/\b(?:\d[ -]*?){16}\b/g;function He(e){let t=new Set,n=[];for(let o of e)typeof o!="string"||o.length===0||t.has(o)||(t.add(o),n.push(o));return n}function Tn(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function Sn(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function kn(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function Ln(e){return e.split(".").filter(Boolean)}function Se(e,t,n=0,o=0){if(n===e.length)return o===t.length;let r=e[n];if(r==="**"){if(n===e.length-1)return true;for(let a=o;a<=t.length;a+=1)if(Se(e,t,n+1,a))return true;return false}return o>=t.length||r!=="*"&&r!==t[o]?false:Se(e,t,n+1,o+1)}function vn(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(n=>Se(Ln(n),e))}function Dn(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let n=0,o=false;for(let r=t.length-1;r>=0;r-=1){let a=Number(t[r]);o&&(a*=2,a>9&&(a-=9)),n+=a,o=!o;}return n%10===0}function Qe(e,t,n){if(n||t.disablePatternScanning)return e;let o=e;for(let{type:r,pattern:a}of wn)o=o.replace(a,`[REDACTED:${r}]`);o=o.replace(Rn,r=>Dn(r)?"[REDACTED:card]":r);for(let r of t.patterns)o=o.replace(Tn(r),"[REDACTED:pattern]");return o}function te(e,t,n,o){if(typeof e=="string")return Qe(e,t,!!o.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((a,s)=>te(a,t,n,{path:[...o.path,String(s)],skipPatternScanning:o.skipPatternScanning}));if(!Sn(e))return e;let r={};for(let[a,s]of Object.entries(e)){let i=[...o.path,a];if(n.has(a.toLowerCase())||vn(i,t)){if(s==null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[a]=bn;continue}r[a]=te(s,t,n,{path:i,skipPatternScanning:o.skipPatternScanning});continue}r[a]=te(s,t,n,{path:i,skipPatternScanning:o.skipPatternScanning});}return r}function k(e,t){return {keys:He([...Cn,...e?.keys??[],...t?.keys??[]]),paths:He([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(n=>n instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function h(e,t,n={path:[]}){let o=T(e);return te(o,t,kn(t),n)}function q(e,t){return typeof e=="string"?Qe(e,t,false):Te(h(e,t))}function Je(){return F__default.default.join(xn__default.default.homedir(),".blyp","queue.db")}var An=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"}),Ge=zod.z.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),Le=zod.z.string().trim().min(1);function ve(e){return An.safeParse(e).success}function De(e){return Ge.safeParse(e).success}function x(e){return Le.safeParse(e).success}var xe="/inngest";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:Le})]);function _n(e){try{return e()}catch{return}}function Pn(){return Math.random().toString(36).slice(2,10)}function Ve(){let e=_n(()=>globalThis.crypto),t=e&&typeof e.randomUUID=="function"?e.randomUUID.bind(e):void 0;return t?t():`${Date.now().toString(36)}-${Pn()}`}function Bn(e,t=new Set){return (n,o,r)=>{if(t.has(n)||typeof console>"u")return;let a=console[e];if(typeof a=="function"){if(t.add(n),r===void 0){a.call(console,o);return}a.call(console,o,r);}}}function v(e){return Bn("warn",e)}var Nn="@blyp/core",Fn=".gitignore",et=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],zn="blyp.config.json",jn="https://us.i.posthog.com",Un="blyp-app",qn=Un,$n=new Set,D=v($n),tt={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},nt={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:tt},Ee={enabled:true,path:xe},rt=k(),O={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},R={enabled:false,memoryBufferSize:500,durableQueuePath:Je(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:O},ot={maxRetries:1,backoffMs:100},Kn={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:ot},Xe={pretty:true,level:"info",destination:"file",file:nt,clientLogging:Ee,redact:rt,connectors:{delivery:R}},$=null;function Wn(e){let t=e;for(;;){let n=F.resolve(t,"package.json");if(w.existsSync(n))try{let r=JSON.parse(w.readFileSync(n,"utf-8"));if(x(r.name))return r.name}catch{}let o=F.dirname(t);if(o===t)return;t=o;}}function _e(e=process.cwd()){return Wn(e)??qn}function Hn(){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:xe},redact:rt,connectors:{delivery:R}}}function Qn(e){let t=F.resolve(e,"package.json");if(!w.existsSync(t))return true;try{return JSON.parse(w.readFileSync(t,"utf-8")).name!==Nn}catch{return true}}function Jn(e){if(et.some(n=>w.existsSync(F.resolve(e,n))))return;let t=F.resolve(e,zn);if(!w.existsSync(t))try{w.writeFileSync(t,`${JSON.stringify(Hn(),null,2)}
|
|
2
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to create blyp.config.json:",n);}}function Gn(e){let t=F.resolve(e,Fn);if(!w.existsSync(t)){try{w.writeFileSync(t,`logs
|
|
3
|
+
.blyp
|
|
4
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to create .gitignore:",n);}return}try{let n=w.readFileSync(t,"utf-8"),o=["logs",".blyp"].filter(a=>{let s=a.replace(".","\\.");return !new RegExp(`^(?:/?${s}/?)\\s*$`,"m").test(n)});if(o.length===0)return;let r=n.endsWith(`
|
|
5
|
+
`)?"":`
|
|
6
|
+
`;w.appendFileSync(t,`${r}${o.join(`
|
|
7
|
+
`)}
|
|
8
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to update .gitignore:",n);}}function Vn(){let e=process.cwd();Qn(e)&&(Jn(e),Gn(e));}function Xn(){let e=process.cwd(),t=et.map(o=>F.resolve(e,o)).filter(o=>w.existsSync(o));if(t.length===0)return null;if(t.length>1){let o=t[0];D(`config-multiple:${o}`,`[Blyp] Warning: Multiple config files found. Using ${o} and ignoring ${t.slice(1).join(", ")}.`);}let n=t[0];return {path:n,type:n.endsWith(".json")?"json":"jiti"}}function at(e,t){let n=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !n||typeof n!="object"||Array.isArray(n)?(D(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):n}function Yn(e){try{let t=w.readFileSync(e,"utf-8");return at(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function Zn(e){try{let t=jiti.createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return at(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function er(e){return e.type==="json"?Yn(e.path):Zn(e.path)}function Ye(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function tr(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function nr(e,t){return {...ot,...e,...t}}function rr(e,t){return {...Kn,...e,...t,retry:nr(e?.retry,t?.retry)}}function or(e){let t=e.model??"blypLog",o=e.client?.[t];return !!o&&typeof o.create=="function"}function ar(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function ir(e,t){if(!e)return;let n=e.adapter,o=false;t==="json"?D("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"?D(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):n?Ye(n)?(o=or({...n,model:n.model??"blypLog"}),o||D("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${n.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):tr(n)&&(o=ar(n),o||D("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):D("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let r=Ye(n)?{...n,model:n.model??"blypLog"}:n;return {dialect:e.dialect,adapter:r,delivery:rr(void 0,e.delivery),ready:o,status:o?"enabled":"missing"}}function sr(e,t){return {...tt,...e,...t}}function cr(e,t){return {...nt,...e,...t,rotation:sr(e?.rotation,t?.rotation)}}function ur(e,t){return {...Ee,...e,...t,path:t?.path??e?.path??Ee.path}}function lr(e,t){return k(e,t)}function dr(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??O.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??O.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??O.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??O.multiplier),jitter:t?.jitter??e?.jitter??O.jitter}}function pr(e,t){let n=t?.durableQueuePath??e?.durableQueuePath??R.durableQueuePath;return {enabled:t?.enabled??e?.enabled??R.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??R.memoryBufferSize)),durableQueuePath:x(n)?n:R.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??R.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??R.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??R.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??R.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??R.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??R.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??R.overflowStrategy,retry:dr(e?.retry,t?.retry),durableReady:false}}function fr(e,t,n){if(!(!e&&!t))return ir({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},n)}function gr(e,t){let n=t?.enabled??e?.enabled??false,o=t?.projectKey??e?.projectKey,r=e?.enabled===true?e?.errorTracking:void 0,a=t?.errorTracking?.mode??r?.mode??"auto",s=t?.errorTracking?.enabled??r?.enabled??n,i=n&&s&&typeof o=="string"&&o.trim().length>0;return {enabled:n,mode:t?.mode??e?.mode??"auto",projectKey:o,host:t?.host??e?.host??jn,serviceName:t?.serviceName??e?.serviceName??_e(),errorTracking:{enabled:s,mode:a,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??r?.enableExceptionAutocapture??a==="auto",ready:i,status:i?"enabled":"missing"}}}function mr(e,t){let n=t?.enabled??e?.enabled??false,o=t?.apiKey??e?.apiKey,r=t?.websiteId??e?.websiteId,a=n&&x(o)&&x(r);return {enabled:n,mode:t?.mode??e?.mode??"auto",apiKey:o,websiteId:r,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:a,status:a?"enabled":"missing"}}function yr(e,t){let n=t?.sourceToken??e?.sourceToken,o=t?.ingestingHost??e?.ingestingHost,r=t?.enabled??e?.enabled??false,a=e?.enabled===true?e?.errorTracking:void 0,s=hr(r,a,t?.errorTracking),i=r&&x(n)&&ve(o);return {enabled:r,mode:t?.mode??e?.mode??"auto",sourceToken:n,ingestingHost:o,serviceName:t?.serviceName??e?.serviceName??_e(),errorTracking:s,ready:i,status:i?"enabled":"missing"}}function hr(e,t,n){let o=n?.dsn??t?.dsn,r=n?.enabled??t?.enabled??e,a=r&&x(o);return {enabled:r,dsn:o,tracesSampleRate:n?.tracesSampleRate??t?.tracesSampleRate??1,environment:n?.environment??t?.environment,release:n?.release??t?.release,ready:a,status:a?"enabled":"missing"}}function br(e,t){let n=t?.dsn??e?.dsn,o=t?.enabled??e?.enabled??false,r=o&&typeof n=="string"&&n.trim().length>0;return {enabled:o,mode:t?.mode??e?.mode??"auto",dsn:n,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:r,status:r?"enabled":"missing"}}function Cr(e,t){let n=t?.endpoint??e?.endpoint,o=t?.enabled??e?.enabled??false,r={...{},...t?.headers??{}},a=o&&ve(n);return {name:t?.name??e?.name??"",enabled:o,mode:t?.mode??e?.mode??"auto",endpoint:n,headers:r,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??_e(),ready:a,status:a?"enabled":"missing"}}function wr(e,t){let n=t??e??[],o=new Map;for(let r of n)!r||typeof r.name!="string"||r.name.length===0||(o.has(r.name)&&D(`otlp-duplicate:${r.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${r.name}" found. Using the last definition.`),o.set(r.name,Cr(void 0,r)));return Array.from(o.values())}function Rr(e,t){return {betterstack:yr(e?.betterstack,t?.betterstack),databuddy:mr(e?.databuddy,t?.databuddy),posthog:gr(e?.posthog,t?.posthog),sentry:br(e?.sentry,t?.sentry),otlp:wr(e?.otlp,t?.otlp),delivery:pr(e?.delivery,t?.delivery)}}function Ae(e,t={},n={}){return {...e,...t,destination:t.destination??e.destination??"file",file:cr(e.file,t.file),database:fr(e.database,t.database,n.configFileType),clientLogging:ur(e.clientLogging,t.clientLogging),redact:lr(e.redact,t.redact),connectors:Rr(e.connectors,t.connectors)}}function Tr(){if($!==null)return $;Vn();let e=Xn();if(e){let t=er(e);$=Ae(Xe,t,{configFileType:e.type});}else $=Ae(Xe);return $}function it(e={}){return Ae(Tr(),e)}var st={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function re(e){return e.replace(/\\/g,"/")}function Sr(e){let t=re(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 kr(e){let t=re(e),n=re(process.cwd());return t.startsWith(`${n}/`)?t.slice(n.length+1):t}function ct(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
|
|
9
|
+
`),n=null;for(let o=2;o<t.length;o+=1){let r=t[o];if(!r)continue;let a=r.match(/\((.*):(\d+):\d+\)/)||r.match(/at\s+(.*):(\d+):(\d+)/);if(!a)continue;let s=a[1]||"",i=parseInt(a[2]||"0",10)||null;if(s&&!s.includes("node_modules")&&!Sr(s)){let c=kr(s);if(!re(c).startsWith("dist/"))return {file:c,line:i};n??(n={file:c,line:i});}}if(n)return n}catch{return {file:null,line:null}}return {file:null,line:null}}var ut=q;function lt(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function dt(e,t,n,o,r=k()){let{file:a,line:s}=ct(),i=ut(t,r),c={timestamp:new Date().toISOString(),level:st[e],message:lt(i)},u=we();return t instanceof Error&&(c.error=h(ee(t),r)),a&&(c.caller=s!==null?`${a}:${s}`:a),n.length===1?c.data=h(n[0],r):n.length>1&&(c.data=h(n,r)),Object.keys(o).length>0&&(c.bindings=h(o,r)),u&&(c.traceId=u),c}function pt(e,t,n,o,r=k()){let{file:a,line:s}=ct(),i=h(n,r),c=we(),u={message:lt(ut(t,r)),...i};return a&&(u.caller=s!==null?`${a}:${s}`:a),Object.keys(o).length>0&&(u.bindings=h(o,r)),c&&u.traceId===void 0&&(u.traceId=c),u.level=typeof i.level=="string"&&i.level.length>0?i.level:st[e],u.timestamp=typeof i.timestamp=="string"&&i.timestamp.length>0?i.timestamp:new Date().toISOString(),u}function ft(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 vr(e){return Buffer.from(fflate.gzipSync(e))}function Dr(e,t){console.warn(`[Blyp] Warning: ${e}`,t);}function oe(e){w__default.default.mkdirSync(e,{recursive:true});}function xr(e){try{return w__default.default.statSync(e).size}catch{return 0}}function Er(e){let t=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),o=String(e.getUTCDate()).padStart(2,"0"),r=String(e.getUTCHours()).padStart(2,"0"),a=String(e.getUTCMinutes()).padStart(2,"0"),s=String(e.getUTCSeconds()).padStart(2,"0");return `${t}${n}${o}T${r}${a}${s}Z`}function Ar(e,t){let n=`${e}${t}`,o=1;for(;w__default.default.existsSync(n);)n=`${e}-${o}${t}`,o+=1;return n}function _r(e,t,n,o){let r=`${t}.`;try{let a=w__default.default.readdirSync(e).filter(i=>i.startsWith(r)&&(i.endsWith(".ndjson")||i.endsWith(".ndjson.gz"))).map(i=>F__default.default.join(e,i)).sort((i,c)=>w__default.default.statSync(i).mtimeMs-w__default.default.statSync(c).mtimeMs),s=Math.max(a.length-n,0);for(let i=0;i<s;i+=1)w__default.default.rmSync(a[i]);}catch(a){o(`Failed to prune archives for ${t}`,a);}}function Pr(){let e=new WeakSet;return (t,n)=>{if(typeof n=="function")return `[Function: ${n.name||"anonymous"}]`;if(n===void 0)return "[undefined]";if(typeof n=="symbol")return n.toString();if(n!==null&&typeof n=="object"){if(e.has(n))return "[Circular]";e.add(n);}return n}}function Br(e){return JSON.stringify(e,Pr())}function Mr(e){let t=e.file,n=t?.dir||e.logDir||F__default.default.join(process.cwd(),"logs"),o=t?.archiveDir||F__default.default.join(n,"archive"),r=t?.rotation;return {enabled:t?.enabled??true,dir:n,archiveDir:o,rotationEnabled:r?.enabled??true,maxSizeBytes:r?.maxSizeBytes??10*1024*1024,maxArchives:r?.maxArchives??5,compress:r?.compress??true}}var Pe=class{constructor(t,n={}){l(this,"config");l(this,"gzip");l(this,"warn");l(this,"combined");l(this,"error");this.config=Mr(t),this.gzip=n.gzip??vr,this.warn=n.warn??Dr,this.combined={activePath:F__default.default.join(this.config.dir,"log.ndjson"),archivePrefix:"log",bytes:0,queue:[],processing:false},this.error={activePath:F__default.default.join(this.config.dir,"log.error.ndjson"),archivePrefix:"log.error",bytes:0,queue:[],processing:false},this.config.enabled&&(oe(this.config.dir),oe(this.config.archiveDir),this.seedStream(this.combined),this.seedStream(this.error));}write(t){if(!this.config.enabled)return;let n=`${Br(t)}
|
|
10
|
+
`;this.enqueue(this.combined,n),(t.level==="error"||t.level==="critical")&&this.enqueue(this.error,n);}enqueue(t,n){t.queue.push(n),this.processQueue(t);}processQueue(t){if(!t.processing){t.processing=true;try{for(;t.queue.length>0;){let n=t.queue.shift();if(n!==void 0)try{this.append(t,n);}catch(o){this.warn(`Failed writing log line for ${t.archivePrefix}`,o);}}}finally{t.processing=false;}}}seedStream(t){t.bytes=xr(t.activePath),this.config.rotationEnabled&&t.bytes>this.config.maxSizeBytes&&t.bytes>0&&(this.rotate(t),w__default.default.closeSync(w__default.default.openSync(t.activePath,"a")),t.bytes=0);}append(t,n){oe(this.config.dir);let o=Buffer.byteLength(n,"utf8");this.config.rotationEnabled&&t.bytes>0&&t.bytes+o>this.config.maxSizeBytes&&this.rotate(t),w__default.default.appendFileSync(t.activePath,n,"utf8"),t.bytes+=o;}rotate(t){if(oe(this.config.archiveDir),!w__default.default.existsSync(t.activePath)||t.bytes===0){t.bytes=0;return}let n=Er(new Date),o=F__default.default.join(this.config.archiveDir,`${t.archivePrefix}.${n}`),r=Ar(o,".ndjson");if(w__default.default.renameSync(t.activePath,r),this.config.compress)try{let a=`${r}.gz`,s=this.gzip(w__default.default.readFileSync(r));w__default.default.writeFileSync(a,s),w__default.default.rmSync(r);}catch(a){this.warn(`Failed to gzip archive ${r}`,a);}t.bytes=0,_r(this.config.archiveDir,t.archivePrefix,this.config.maxArchives,this.warn);}};function gt(e){return new Pe(e)}var Be=class{constructor(t){this.logger=t;l(this,"isAsync",false);l(this,"isReady",true);}write(t){this.logger.write(t);}async flush(){}async shutdown(){}};function mt(e){return new Be(gt(e))}function yt(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(n){n.length!==0&&await t.insert(e.table).values(n);}}}function Or(e){let t=String(e??"");return t.includes("createMany")||t.includes("Unknown argument")||t.includes("not supported")||t.includes("is not a function")}function ht(e){let t=e.client,n=e.model??"blypLog",o=t[n];if(!o||typeof o.create!="function")throw new Error(`[Blyp] Prisma database adapter is missing the "${n}" delegate or its create method.`);let r=o,a=typeof r.createMany=="function";async function s(i){if(typeof t.$transaction=="function"){await t.$transaction(i.map(c=>r.create({data:c})));return}for(let c of i)await r.create({data:c});}return {async insert(i){if(i.length!==0){if(i.length===1){await r.create({data:i[0]});return}if(!a||typeof r.createMany!="function"){await s(i);return}try{await r.createMany({data:i});}catch(c){if(!Or(c))throw c;a=false,await s(i);}}}}}function bt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function z(e){return typeof e=="string"&&e.length>0?e:null}function Nr(e){if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function Ct(e){let t=T(e);return {id:crypto$1.randomUUID(),timestamp:Nr(e.timestamp),level:e.level,message:e.message,caller:z(e.caller),type:z(e.type),traceId:z(e.traceId),groupId:z(e.groupId),method:z(e.method),path:z(e.path),status:bt(e.status),duration:bt(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 Fr(e){return !!e&&e.type==="prisma"}function zr(e){return !!e&&e.type==="drizzle"}function wt(e){if(Fr(e.adapter))return ht(e.adapter);if(zr(e.adapter))return yt(e.adapter);throw new Error("[Blyp] Unsupported database adapter configuration.")}function jr(e){return new Promise(t=>{setTimeout(t,e);})}var ae=class{constructor(t){this.config=t;l(this,"isAsync",true);l(this,"isReady",true);l(this,"warnOnce",v(new Set));l(this,"queue",[]);l(this,"writer");l(this,"timer",null);l(this,"processing",false);l(this,"closed",false);l(this,"terminalError",null);l(this,"activeDispatch",null);this.writer=wt(t);}write(t){this.closed||(this.enqueue(Ct(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})(),n=null;try{await Promise.race([t,new Promise((o,r)=>{n=setTimeout(()=>{this.warnOnce("database-flush-timeout",`[Blyp] Warning: Timed out flushing database logs after ${this.config.delivery.flushTimeoutMs}ms.`),r(new Error("[Blyp] Timed out flushing database logs."));},this.config.delivery.flushTimeoutMs);})]);}finally{n&&clearTimeout(n);}}async shutdown(){this.closed=true,await this.flush();}enqueue(t){this.queue.push(t);let n=this.queue.length-this.config.delivery.maxQueueSize;if(!(n<=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,n);}}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,n=this.queue.splice(0,t);try{await this.insertWithRetry(n);}catch(o){let r=o instanceof Error?o:new Error(String(o??"Unknown database logging failure"));throw this.terminalError=r,this.warnOnce("database-insert-failure",`[Blyp] Warning: Failed to persist logs to the ${this.config.dialect??"database"} database.`,r),r}}}async insertWithRetry(t){let n=Math.max(1,this.config.delivery.retry.maxRetries+1),o=0;for(;o<n;){o+=1;try{await this.writer.insert(t);return}catch(r){if(o>=n)throw r;await jr(this.config.delivery.retry.backoffMs);}}}};var Me=class{constructor(){l(this,"isAsync",false);l(this,"isReady",false);}write(t){}async flush(){}async shutdown(){}},Ur=v(new Set);function Rt(e){if(e.destination!=="database")return mt(e);let t=e.database;return t?.ready?new ae(t):(Ur("database-sink-disabled","[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."),new Me)}function qr(e){return De(e.data)?e.data:e}function $r(e,t){if(t in e){let r=e[t];if(typeof r=="string"||typeof r=="number")return r}let o=qr(e)[t];if(typeof o=="string"||typeof o=="number")return o}function Tt(e){return $r(e,"type")}function St(e,t){let n=Math.max(1,Math.floor(e)),o=Math.pow(t.multiplier,n-1),r=Math.min(Math.max(0,Math.floor(t.initialBackoffMs*o)),Math.max(0,t.maxBackoffMs));return t.jitter?Math.floor(Math.random()*(r+1)):r}var kt="bun:sqlite";var Lt="node:sqlite";function vt(){return `
|
|
11
|
+
const { parentPort } = require('node:worker_threads');
|
|
12
|
+
const fs = require('node:fs');
|
|
13
|
+
const path = require('node:path');
|
|
14
|
+
|
|
15
|
+
const NODE_SQLITE_MODULE = ${JSON.stringify(Lt)};
|
|
16
|
+
const BUN_SQLITE_MODULE = ${JSON.stringify(kt)};
|
|
17
|
+
const CLAIM_LEASE_MS = 30000;
|
|
18
|
+
|
|
19
|
+
let db;
|
|
20
|
+
let runtime = 'unsupported';
|
|
21
|
+
|
|
22
|
+
async function loadDatabase() {
|
|
23
|
+
try {
|
|
24
|
+
const mod = await import(BUN_SQLITE_MODULE);
|
|
25
|
+
const Database = mod.default;
|
|
26
|
+
runtime = 'bun';
|
|
27
|
+
return {
|
|
28
|
+
create(filePath) {
|
|
29
|
+
return new Database(filePath);
|
|
30
|
+
},
|
|
31
|
+
exec(instance, sql) {
|
|
32
|
+
instance.exec(sql);
|
|
33
|
+
},
|
|
34
|
+
prepare(instance, sql) {
|
|
35
|
+
return instance.prepare(sql);
|
|
36
|
+
},
|
|
37
|
+
close(instance) {
|
|
38
|
+
instance.close();
|
|
39
|
+
},
|
|
40
|
+
run(statement, params) {
|
|
41
|
+
statement.run(...params);
|
|
42
|
+
},
|
|
43
|
+
all(statement, params) {
|
|
44
|
+
return statement.all(...params);
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
} catch {}
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const mod = await import(NODE_SQLITE_MODULE);
|
|
51
|
+
runtime = 'node';
|
|
52
|
+
return {
|
|
53
|
+
create(filePath) {
|
|
54
|
+
return new mod.DatabaseSync(filePath);
|
|
55
|
+
},
|
|
56
|
+
exec(instance, sql) {
|
|
57
|
+
instance.exec(sql);
|
|
58
|
+
},
|
|
59
|
+
prepare(instance, sql) {
|
|
60
|
+
return instance.prepare(sql);
|
|
61
|
+
},
|
|
62
|
+
close(instance) {
|
|
63
|
+
instance.close();
|
|
64
|
+
},
|
|
65
|
+
run(statement, params) {
|
|
66
|
+
statement.run(...params);
|
|
67
|
+
},
|
|
68
|
+
all(statement, params) {
|
|
69
|
+
return statement.all(...params);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
} catch {}
|
|
73
|
+
|
|
74
|
+
throw new Error('No built-in SQLite runtime is available in this worker.');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
let adapter;
|
|
78
|
+
|
|
79
|
+
function ensureReady() {
|
|
80
|
+
if (!db || !adapter) {
|
|
81
|
+
throw new Error('SQLite durable queue is not initialized.');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function normalizeConnectorTarget(value) {
|
|
86
|
+
return typeof value === 'string' && value.length > 0 ? value : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function createConnectorCondition() {
|
|
90
|
+
return '(connector_type = ? AND ((connector_target IS NULL AND ? IS NULL) OR connector_target = ?))';
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function updateConnectorDeliveryStatus(item, success) {
|
|
94
|
+
const connectorTarget = normalizeConnectorTarget(item.connectorTarget);
|
|
95
|
+
const select = adapter.prepare(
|
|
96
|
+
db,
|
|
97
|
+
'SELECT rowid FROM connector_delivery_status WHERE ' + createConnectorCondition() + ' LIMIT 1'
|
|
98
|
+
);
|
|
99
|
+
const existing = adapter.all(select, [item.connectorType, connectorTarget, connectorTarget])[0];
|
|
100
|
+
|
|
101
|
+
if (existing) {
|
|
102
|
+
const update = adapter.prepare(
|
|
103
|
+
db,
|
|
104
|
+
success
|
|
105
|
+
? 'UPDATE connector_delivery_status SET last_success_at = ?, last_error = NULL, updated_at = ? WHERE rowid = ?'
|
|
106
|
+
: 'UPDATE connector_delivery_status SET last_failure_at = ?, last_error = ?, updated_at = ? WHERE rowid = ?'
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
adapter.run(
|
|
110
|
+
update,
|
|
111
|
+
success
|
|
112
|
+
? [item.timestamp, item.timestamp, existing.rowid]
|
|
113
|
+
: [item.timestamp, item.lastError ?? null, item.timestamp, existing.rowid]
|
|
114
|
+
);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const insert = adapter.prepare(
|
|
119
|
+
db,
|
|
120
|
+
'INSERT INTO connector_delivery_status (connector_type, connector_target, last_success_at, last_failure_at, last_error, updated_at) VALUES (?, ?, ?, ?, ?, ?)'
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
adapter.run(insert, [
|
|
124
|
+
item.connectorType,
|
|
125
|
+
connectorTarget,
|
|
126
|
+
success ? item.timestamp : null,
|
|
127
|
+
success ? null : item.timestamp,
|
|
128
|
+
success ? null : item.lastError ?? null,
|
|
129
|
+
item.timestamp,
|
|
130
|
+
]);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function initializeSchema() {
|
|
134
|
+
ensureReady();
|
|
135
|
+
adapter.exec(db, [
|
|
136
|
+
'PRAGMA journal_mode = WAL;',
|
|
137
|
+
'PRAGMA busy_timeout = 5000;',
|
|
138
|
+
'CREATE TABLE IF NOT EXISTS connector_queue_meta (schema_version INTEGER NOT NULL);',
|
|
139
|
+
'DELETE FROM connector_queue_meta;',
|
|
140
|
+
'INSERT INTO connector_queue_meta (schema_version) VALUES (2);',
|
|
141
|
+
'CREATE TABLE IF NOT EXISTS connector_jobs (',
|
|
142
|
+
' id TEXT PRIMARY KEY,',
|
|
143
|
+
' connector_type TEXT NOT NULL,',
|
|
144
|
+
' connector_target TEXT NULL,',
|
|
145
|
+
' operation TEXT NOT NULL,',
|
|
146
|
+
' payload_json TEXT NOT NULL,',
|
|
147
|
+
' attempt_count INTEGER NOT NULL,',
|
|
148
|
+
' max_attempts INTEGER NOT NULL,',
|
|
149
|
+
' next_attempt_at INTEGER NOT NULL,',
|
|
150
|
+
' state TEXT NOT NULL,',
|
|
151
|
+
' last_error TEXT NULL,',
|
|
152
|
+
' created_at INTEGER NOT NULL,',
|
|
153
|
+
' updated_at INTEGER NOT NULL,',
|
|
154
|
+
' claimed_at INTEGER NULL',
|
|
155
|
+
');',
|
|
156
|
+
'CREATE TABLE IF NOT EXISTS connector_dead_letters (',
|
|
157
|
+
' id TEXT PRIMARY KEY,',
|
|
158
|
+
' connector_type TEXT NOT NULL,',
|
|
159
|
+
' connector_target TEXT NULL,',
|
|
160
|
+
' operation TEXT NOT NULL,',
|
|
161
|
+
' payload_json TEXT NOT NULL,',
|
|
162
|
+
' attempt_count INTEGER NOT NULL,',
|
|
163
|
+
' max_attempts INTEGER NOT NULL,',
|
|
164
|
+
' last_error TEXT NULL,',
|
|
165
|
+
' first_enqueued_at INTEGER NOT NULL,',
|
|
166
|
+
' dead_lettered_at INTEGER NOT NULL,',
|
|
167
|
+
' last_attempt_at INTEGER NOT NULL',
|
|
168
|
+
');',
|
|
169
|
+
'CREATE TABLE IF NOT EXISTS connector_delivery_status (',
|
|
170
|
+
' connector_type TEXT NOT NULL,',
|
|
171
|
+
' connector_target TEXT NULL,',
|
|
172
|
+
' last_success_at INTEGER NULL,',
|
|
173
|
+
' last_failure_at INTEGER NULL,',
|
|
174
|
+
' last_error TEXT NULL,',
|
|
175
|
+
' updated_at INTEGER NOT NULL',
|
|
176
|
+
');',
|
|
177
|
+
'CREATE INDEX IF NOT EXISTS idx_connector_jobs_state_due ON connector_jobs(state, next_attempt_at);',
|
|
178
|
+
'CREATE INDEX IF NOT EXISTS idx_connector_jobs_connector_state_due ON connector_jobs(connector_type, connector_target, state, next_attempt_at);',
|
|
179
|
+
'CREATE INDEX IF NOT EXISTS idx_connector_dead_letters_connector_dead_lettered ON connector_dead_letters(connector_type, connector_target, dead_lettered_at);',
|
|
180
|
+
'CREATE INDEX IF NOT EXISTS idx_connector_delivery_status_connector ON connector_delivery_status(connector_type, connector_target);'
|
|
181
|
+
].join('\\n'));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function reclaimExpired(now) {
|
|
185
|
+
ensureReady();
|
|
186
|
+
const statement = adapter.prepare(
|
|
187
|
+
db,
|
|
188
|
+
'UPDATE connector_jobs SET state = ?, claimed_at = NULL, updated_at = ? WHERE state = ? AND claimed_at IS NOT NULL AND claimed_at <= ?'
|
|
189
|
+
);
|
|
190
|
+
adapter.run(statement, ['pending', now, 'claimed', now - CLAIM_LEASE_MS]);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function insertJobs(jobs) {
|
|
194
|
+
ensureReady();
|
|
195
|
+
if (!Array.isArray(jobs) || jobs.length === 0) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
adapter.exec(db, 'BEGIN');
|
|
200
|
+
try {
|
|
201
|
+
const statement = adapter.prepare(
|
|
202
|
+
db,
|
|
203
|
+
'INSERT OR REPLACE INTO connector_jobs (id, connector_type, connector_target, operation, payload_json, attempt_count, max_attempts, next_attempt_at, state, last_error, created_at, updated_at, claimed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
204
|
+
);
|
|
205
|
+
|
|
206
|
+
for (const job of jobs) {
|
|
207
|
+
adapter.run(statement, [
|
|
208
|
+
job.id,
|
|
209
|
+
job.connectorType,
|
|
210
|
+
normalizeConnectorTarget(job.connectorTarget),
|
|
211
|
+
job.operation,
|
|
212
|
+
job.payloadJson,
|
|
213
|
+
job.attemptCount,
|
|
214
|
+
job.maxAttempts,
|
|
215
|
+
job.nextAttemptAt,
|
|
216
|
+
job.state,
|
|
217
|
+
job.lastError ?? null,
|
|
218
|
+
job.createdAt,
|
|
219
|
+
job.updatedAt,
|
|
220
|
+
job.claimedAt ?? null,
|
|
221
|
+
]);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
adapter.exec(db, 'COMMIT');
|
|
225
|
+
} catch (error) {
|
|
226
|
+
adapter.exec(db, 'ROLLBACK');
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function claimDue(limit, now) {
|
|
232
|
+
ensureReady();
|
|
233
|
+
reclaimExpired(now);
|
|
234
|
+
|
|
235
|
+
const select = adapter.prepare(
|
|
236
|
+
db,
|
|
237
|
+
'SELECT * FROM connector_jobs WHERE state = ? AND next_attempt_at <= ? ORDER BY next_attempt_at ASC LIMIT ?'
|
|
238
|
+
);
|
|
239
|
+
const rows = adapter.all(select, ['pending', now, limit]);
|
|
240
|
+
|
|
241
|
+
if (!Array.isArray(rows) || rows.length === 0) {
|
|
242
|
+
return [];
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
adapter.exec(db, 'BEGIN');
|
|
246
|
+
try {
|
|
247
|
+
const update = adapter.prepare(
|
|
248
|
+
db,
|
|
249
|
+
'UPDATE connector_jobs SET state = ?, claimed_at = ?, updated_at = ? WHERE id = ?'
|
|
250
|
+
);
|
|
251
|
+
for (const row of rows) {
|
|
252
|
+
adapter.run(update, ['claimed', now, now, row.id]);
|
|
253
|
+
row.state = 'claimed';
|
|
254
|
+
row.claimed_at = now;
|
|
255
|
+
row.updated_at = now;
|
|
256
|
+
}
|
|
257
|
+
adapter.exec(db, 'COMMIT');
|
|
258
|
+
} catch (error) {
|
|
259
|
+
adapter.exec(db, 'ROLLBACK');
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
return rows.map((row) => ({
|
|
264
|
+
id: row.id,
|
|
265
|
+
connectorType: row.connector_type,
|
|
266
|
+
connectorTarget: row.connector_target ?? undefined,
|
|
267
|
+
operation: row.operation,
|
|
268
|
+
payloadJson: row.payload_json,
|
|
269
|
+
attemptCount: row.attempt_count,
|
|
270
|
+
maxAttempts: row.max_attempts,
|
|
271
|
+
nextAttemptAt: row.next_attempt_at,
|
|
272
|
+
state: row.state,
|
|
273
|
+
lastError: row.last_error ?? undefined,
|
|
274
|
+
createdAt: row.created_at,
|
|
275
|
+
updatedAt: row.updated_at,
|
|
276
|
+
claimedAt: row.claimed_at ?? undefined,
|
|
277
|
+
}));
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function ack(ids) {
|
|
281
|
+
ensureReady();
|
|
282
|
+
if (!Array.isArray(ids) || ids.length === 0) {
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
adapter.exec(db, 'BEGIN');
|
|
287
|
+
try {
|
|
288
|
+
const statement = adapter.prepare(db, 'DELETE FROM connector_jobs WHERE id = ?');
|
|
289
|
+
for (const id of ids) {
|
|
290
|
+
adapter.run(statement, [id]);
|
|
291
|
+
}
|
|
292
|
+
adapter.exec(db, 'COMMIT');
|
|
293
|
+
} catch (error) {
|
|
294
|
+
adapter.exec(db, 'ROLLBACK');
|
|
295
|
+
throw error;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function reschedule(items, now) {
|
|
300
|
+
ensureReady();
|
|
301
|
+
if (!Array.isArray(items) || items.length === 0) {
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
adapter.exec(db, 'BEGIN');
|
|
306
|
+
try {
|
|
307
|
+
const statement = adapter.prepare(
|
|
308
|
+
db,
|
|
309
|
+
'UPDATE connector_jobs SET state = ?, attempt_count = ?, next_attempt_at = ?, last_error = ?, claimed_at = NULL, updated_at = ? WHERE id = ?'
|
|
310
|
+
);
|
|
311
|
+
for (const item of items) {
|
|
312
|
+
adapter.run(statement, [
|
|
313
|
+
'pending',
|
|
314
|
+
item.attemptCount,
|
|
315
|
+
item.nextAttemptAt,
|
|
316
|
+
item.lastError ?? null,
|
|
317
|
+
now,
|
|
318
|
+
item.id,
|
|
319
|
+
]);
|
|
320
|
+
}
|
|
321
|
+
adapter.exec(db, 'COMMIT');
|
|
322
|
+
} catch (error) {
|
|
323
|
+
adapter.exec(db, 'ROLLBACK');
|
|
324
|
+
throw error;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function deadLetter(items) {
|
|
329
|
+
ensureReady();
|
|
330
|
+
if (!Array.isArray(items) || items.length === 0) {
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
adapter.exec(db, 'BEGIN');
|
|
335
|
+
try {
|
|
336
|
+
const insert = adapter.prepare(
|
|
337
|
+
db,
|
|
338
|
+
'INSERT OR REPLACE INTO connector_dead_letters (id, connector_type, connector_target, operation, payload_json, attempt_count, max_attempts, last_error, first_enqueued_at, dead_lettered_at, last_attempt_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
339
|
+
);
|
|
340
|
+
const remove = adapter.prepare(db, 'DELETE FROM connector_jobs WHERE id = ?');
|
|
341
|
+
|
|
342
|
+
for (const item of items) {
|
|
343
|
+
adapter.run(insert, [
|
|
344
|
+
item.id,
|
|
345
|
+
item.connectorType,
|
|
346
|
+
normalizeConnectorTarget(item.connectorTarget),
|
|
347
|
+
item.operation,
|
|
348
|
+
item.payloadJson,
|
|
349
|
+
item.attemptCount,
|
|
350
|
+
item.maxAttempts,
|
|
351
|
+
item.lastError ?? null,
|
|
352
|
+
item.firstEnqueuedAt,
|
|
353
|
+
item.deadLetteredAt,
|
|
354
|
+
item.lastAttemptAt,
|
|
355
|
+
]);
|
|
356
|
+
adapter.run(remove, [item.id]);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
adapter.exec(db, 'COMMIT');
|
|
360
|
+
} catch (error) {
|
|
361
|
+
adapter.exec(db, 'ROLLBACK');
|
|
362
|
+
throw error;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function markSuccess(items) {
|
|
367
|
+
ensureReady();
|
|
368
|
+
if (!Array.isArray(items) || items.length === 0) {
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
adapter.exec(db, 'BEGIN');
|
|
373
|
+
try {
|
|
374
|
+
for (const item of items) {
|
|
375
|
+
updateConnectorDeliveryStatus(item, true);
|
|
376
|
+
}
|
|
377
|
+
adapter.exec(db, 'COMMIT');
|
|
378
|
+
} catch (error) {
|
|
379
|
+
adapter.exec(db, 'ROLLBACK');
|
|
380
|
+
throw error;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function markFailure(items) {
|
|
385
|
+
ensureReady();
|
|
386
|
+
if (!Array.isArray(items) || items.length === 0) {
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
adapter.exec(db, 'BEGIN');
|
|
391
|
+
try {
|
|
392
|
+
for (const item of items) {
|
|
393
|
+
updateConnectorDeliveryStatus(item, false);
|
|
394
|
+
}
|
|
395
|
+
adapter.exec(db, 'COMMIT');
|
|
396
|
+
} catch (error) {
|
|
397
|
+
adapter.exec(db, 'ROLLBACK');
|
|
398
|
+
throw error;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function getStatusSummary() {
|
|
403
|
+
ensureReady();
|
|
404
|
+
const rows = [];
|
|
405
|
+
const byKey = new Map();
|
|
406
|
+
|
|
407
|
+
const statusRows = adapter.all(
|
|
408
|
+
adapter.prepare(
|
|
409
|
+
db,
|
|
410
|
+
'SELECT connector_type, connector_target, last_success_at, last_failure_at, last_error, updated_at FROM connector_delivery_status'
|
|
411
|
+
),
|
|
412
|
+
[]
|
|
413
|
+
);
|
|
414
|
+
|
|
415
|
+
for (const row of statusRows) {
|
|
416
|
+
const key = row.connector_type + ':' + (row.connector_target ?? '');
|
|
417
|
+
const item = {
|
|
418
|
+
connectorType: row.connector_type,
|
|
419
|
+
connectorTarget: row.connector_target ?? undefined,
|
|
420
|
+
pendingCount: 0,
|
|
421
|
+
deadLetterCount: 0,
|
|
422
|
+
lastSuccessAt: row.last_success_at ?? undefined,
|
|
423
|
+
lastFailureAt: row.last_failure_at ?? undefined,
|
|
424
|
+
lastError: row.last_error ?? undefined,
|
|
425
|
+
updatedAt: row.updated_at ?? undefined,
|
|
426
|
+
};
|
|
427
|
+
byKey.set(key, item);
|
|
428
|
+
rows.push(item);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const pendingRows = adapter.all(
|
|
432
|
+
adapter.prepare(
|
|
433
|
+
db,
|
|
434
|
+
'SELECT connector_type, connector_target, COUNT(*) AS count FROM connector_jobs WHERE state = ? GROUP BY connector_type, connector_target'
|
|
435
|
+
),
|
|
436
|
+
['pending']
|
|
437
|
+
);
|
|
438
|
+
|
|
439
|
+
for (const row of pendingRows) {
|
|
440
|
+
const key = row.connector_type + ':' + (row.connector_target ?? '');
|
|
441
|
+
const item = byKey.get(key) ?? {
|
|
442
|
+
connectorType: row.connector_type,
|
|
443
|
+
connectorTarget: row.connector_target ?? undefined,
|
|
444
|
+
pendingCount: 0,
|
|
445
|
+
deadLetterCount: 0,
|
|
446
|
+
};
|
|
447
|
+
item.pendingCount = Number(row.count ?? 0);
|
|
448
|
+
if (!byKey.has(key)) {
|
|
449
|
+
byKey.set(key, item);
|
|
450
|
+
rows.push(item);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const deadLetterRows = adapter.all(
|
|
455
|
+
adapter.prepare(
|
|
456
|
+
db,
|
|
457
|
+
'SELECT connector_type, connector_target, COUNT(*) AS count FROM connector_dead_letters GROUP BY connector_type, connector_target'
|
|
458
|
+
),
|
|
459
|
+
[]
|
|
460
|
+
);
|
|
461
|
+
|
|
462
|
+
for (const row of deadLetterRows) {
|
|
463
|
+
const key = row.connector_type + ':' + (row.connector_target ?? '');
|
|
464
|
+
const item = byKey.get(key) ?? {
|
|
465
|
+
connectorType: row.connector_type,
|
|
466
|
+
connectorTarget: row.connector_target ?? undefined,
|
|
467
|
+
pendingCount: 0,
|
|
468
|
+
deadLetterCount: 0,
|
|
469
|
+
};
|
|
470
|
+
item.deadLetterCount = Number(row.count ?? 0);
|
|
471
|
+
if (!byKey.has(key)) {
|
|
472
|
+
byKey.set(key, item);
|
|
473
|
+
rows.push(item);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
return rows.sort((left, right) => {
|
|
478
|
+
const leftKey = left.connectorType + ':' + (left.connectorTarget ?? '');
|
|
479
|
+
const rightKey = right.connectorType + ':' + (right.connectorTarget ?? '');
|
|
480
|
+
return leftKey.localeCompare(rightKey);
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function listDeadLetters(limit, offset, connectorType, connectorTarget) {
|
|
485
|
+
ensureReady();
|
|
486
|
+
const clauses = [];
|
|
487
|
+
const params = [];
|
|
488
|
+
|
|
489
|
+
if (typeof connectorType === 'string' && connectorType.length > 0) {
|
|
490
|
+
clauses.push('connector_type = ?');
|
|
491
|
+
params.push(connectorType);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
if (connectorTarget !== undefined) {
|
|
495
|
+
if (connectorTarget === null || connectorTarget === '') {
|
|
496
|
+
clauses.push('connector_target IS NULL');
|
|
497
|
+
} else {
|
|
498
|
+
clauses.push('connector_target = ?');
|
|
499
|
+
params.push(connectorTarget);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const whereSql = clauses.length > 0 ? ' WHERE ' + clauses.join(' AND ') : '';
|
|
504
|
+
const countRow = adapter.all(
|
|
505
|
+
adapter.prepare(db, 'SELECT COUNT(*) AS count FROM connector_dead_letters' + whereSql),
|
|
506
|
+
params
|
|
507
|
+
)[0];
|
|
508
|
+
const rows = adapter.all(
|
|
509
|
+
adapter.prepare(
|
|
510
|
+
db,
|
|
511
|
+
'SELECT * FROM connector_dead_letters' + whereSql + ' ORDER BY dead_lettered_at DESC LIMIT ? OFFSET ?'
|
|
512
|
+
),
|
|
513
|
+
[...params, limit, offset]
|
|
514
|
+
);
|
|
515
|
+
|
|
516
|
+
return {
|
|
517
|
+
items: rows.map((row) => ({
|
|
518
|
+
id: row.id,
|
|
519
|
+
connectorType: row.connector_type,
|
|
520
|
+
connectorTarget: row.connector_target ?? undefined,
|
|
521
|
+
operation: row.operation,
|
|
522
|
+
payloadJson: row.payload_json,
|
|
523
|
+
attemptCount: row.attempt_count,
|
|
524
|
+
maxAttempts: row.max_attempts,
|
|
525
|
+
lastError: row.last_error ?? undefined,
|
|
526
|
+
firstEnqueuedAt: row.first_enqueued_at,
|
|
527
|
+
deadLetteredAt: row.dead_lettered_at,
|
|
528
|
+
lastAttemptAt: row.last_attempt_at,
|
|
529
|
+
})),
|
|
530
|
+
total: Number(countRow?.count ?? 0),
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function retryDeadLetters(ids, now) {
|
|
535
|
+
ensureReady();
|
|
536
|
+
if (!Array.isArray(ids) || ids.length === 0) {
|
|
537
|
+
return 0;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
adapter.exec(db, 'BEGIN');
|
|
541
|
+
try {
|
|
542
|
+
const select = adapter.prepare(db, 'SELECT * FROM connector_dead_letters WHERE id = ?');
|
|
543
|
+
const insert = adapter.prepare(
|
|
544
|
+
db,
|
|
545
|
+
'INSERT OR REPLACE INTO connector_jobs (id, connector_type, connector_target, operation, payload_json, attempt_count, max_attempts, next_attempt_at, state, last_error, created_at, updated_at, claimed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
546
|
+
);
|
|
547
|
+
const remove = adapter.prepare(db, 'DELETE FROM connector_dead_letters WHERE id = ?');
|
|
548
|
+
let count = 0;
|
|
549
|
+
|
|
550
|
+
for (const id of ids) {
|
|
551
|
+
const row = adapter.all(select, [id])[0];
|
|
552
|
+
if (!row) {
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
adapter.run(insert, [
|
|
557
|
+
row.id,
|
|
558
|
+
row.connector_type,
|
|
559
|
+
row.connector_target ?? null,
|
|
560
|
+
row.operation,
|
|
561
|
+
row.payload_json,
|
|
562
|
+
0,
|
|
563
|
+
row.max_attempts,
|
|
564
|
+
now,
|
|
565
|
+
'pending',
|
|
566
|
+
null,
|
|
567
|
+
row.first_enqueued_at,
|
|
568
|
+
now,
|
|
569
|
+
null,
|
|
570
|
+
]);
|
|
571
|
+
adapter.run(remove, [id]);
|
|
572
|
+
count += 1;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
adapter.exec(db, 'COMMIT');
|
|
576
|
+
return count;
|
|
577
|
+
} catch (error) {
|
|
578
|
+
adapter.exec(db, 'ROLLBACK');
|
|
579
|
+
throw error;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function clearDeadLetters(ids) {
|
|
584
|
+
ensureReady();
|
|
585
|
+
if (!Array.isArray(ids) || ids.length === 0) {
|
|
586
|
+
return 0;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
adapter.exec(db, 'BEGIN');
|
|
590
|
+
try {
|
|
591
|
+
const select = adapter.prepare(db, 'SELECT id FROM connector_dead_letters WHERE id = ?');
|
|
592
|
+
const remove = adapter.prepare(db, 'DELETE FROM connector_dead_letters WHERE id = ?');
|
|
593
|
+
let count = 0;
|
|
594
|
+
for (const id of ids) {
|
|
595
|
+
const row = adapter.all(select, [id])[0];
|
|
596
|
+
if (!row) {
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
adapter.run(remove, [id]);
|
|
600
|
+
count += 1;
|
|
601
|
+
}
|
|
602
|
+
adapter.exec(db, 'COMMIT');
|
|
603
|
+
return count;
|
|
604
|
+
} catch (error) {
|
|
605
|
+
adapter.exec(db, 'ROLLBACK');
|
|
606
|
+
throw error;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function count() {
|
|
611
|
+
ensureReady();
|
|
612
|
+
const statement = adapter.prepare(db, 'SELECT COUNT(*) as count FROM connector_jobs');
|
|
613
|
+
const rows = adapter.all(statement, []);
|
|
614
|
+
return Number(rows[0]?.count ?? 0);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
parentPort.on('message', async (message) => {
|
|
618
|
+
const { id, type, payload } = message;
|
|
619
|
+
try {
|
|
620
|
+
switch (type) {
|
|
621
|
+
case 'init': {
|
|
622
|
+
adapter = await loadDatabase();
|
|
623
|
+
const filePath = payload.path;
|
|
624
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
625
|
+
db = adapter.create(filePath);
|
|
626
|
+
initializeSchema();
|
|
627
|
+
reclaimExpired(Date.now());
|
|
628
|
+
parentPort.postMessage({ id, ok: true, result: { runtime } });
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
case 'insert':
|
|
632
|
+
insertJobs(payload.jobs);
|
|
633
|
+
parentPort.postMessage({ id, ok: true, result: true });
|
|
634
|
+
return;
|
|
635
|
+
case 'claimDue':
|
|
636
|
+
parentPort.postMessage({ id, ok: true, result: claimDue(payload.limit, payload.now) });
|
|
637
|
+
return;
|
|
638
|
+
case 'ack':
|
|
639
|
+
ack(payload.ids);
|
|
640
|
+
parentPort.postMessage({ id, ok: true, result: true });
|
|
641
|
+
return;
|
|
642
|
+
case 'reschedule':
|
|
643
|
+
reschedule(payload.items, payload.now);
|
|
644
|
+
parentPort.postMessage({ id, ok: true, result: true });
|
|
645
|
+
return;
|
|
646
|
+
case 'deadLetter':
|
|
647
|
+
deadLetter(payload.items);
|
|
648
|
+
parentPort.postMessage({ id, ok: true, result: true });
|
|
649
|
+
return;
|
|
650
|
+
case 'markSuccess':
|
|
651
|
+
markSuccess(payload.items);
|
|
652
|
+
parentPort.postMessage({ id, ok: true, result: true });
|
|
653
|
+
return;
|
|
654
|
+
case 'markFailure':
|
|
655
|
+
markFailure(payload.items);
|
|
656
|
+
parentPort.postMessage({ id, ok: true, result: true });
|
|
657
|
+
return;
|
|
658
|
+
case 'getStatusSummary':
|
|
659
|
+
parentPort.postMessage({ id, ok: true, result: getStatusSummary() });
|
|
660
|
+
return;
|
|
661
|
+
case 'listDeadLetters':
|
|
662
|
+
parentPort.postMessage({
|
|
663
|
+
id,
|
|
664
|
+
ok: true,
|
|
665
|
+
result: listDeadLetters(
|
|
666
|
+
payload.limit,
|
|
667
|
+
payload.offset,
|
|
668
|
+
payload.connectorType,
|
|
669
|
+
payload.connectorTarget
|
|
670
|
+
),
|
|
671
|
+
});
|
|
672
|
+
return;
|
|
673
|
+
case 'retryDeadLetters':
|
|
674
|
+
parentPort.postMessage({ id, ok: true, result: retryDeadLetters(payload.ids, payload.now) });
|
|
675
|
+
return;
|
|
676
|
+
case 'clearDeadLetters':
|
|
677
|
+
parentPort.postMessage({ id, ok: true, result: clearDeadLetters(payload.ids) });
|
|
678
|
+
return;
|
|
679
|
+
case 'count':
|
|
680
|
+
parentPort.postMessage({ id, ok: true, result: count() });
|
|
681
|
+
return;
|
|
682
|
+
case 'shutdown':
|
|
683
|
+
if (db && adapter) {
|
|
684
|
+
adapter.close(db);
|
|
685
|
+
db = undefined;
|
|
686
|
+
}
|
|
687
|
+
parentPort.postMessage({ id, ok: true, result: true });
|
|
688
|
+
return;
|
|
689
|
+
default:
|
|
690
|
+
throw new Error('Unknown SQLite worker command: ' + type);
|
|
691
|
+
}
|
|
692
|
+
} catch (error) {
|
|
693
|
+
parentPort.postMessage({
|
|
694
|
+
id,
|
|
695
|
+
ok: false,
|
|
696
|
+
error: error instanceof Error ? error.message : String(error),
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
});
|
|
700
|
+
`}var ie=class{constructor(t){this.path=t;l(this,"worker");l(this,"pending",new Map);l(this,"nextId",1);this.worker=new worker_threads.Worker(vt(),{eval:true}),this.worker.on("message",n=>{let o=this.pending.get(n.id);if(o){if(this.pending.delete(n.id),n.ok){o.resolve(n.result);return}o.reject(new Error(n.error??"SQLite worker request failed."));}}),this.worker.on("error",n=>{for(let o of this.pending.values())o.reject(n instanceof Error?n:new Error(String(n)));this.pending.clear();});}request(t,n={}){let o=this.nextId++;return new Promise((r,a)=>{this.pending.set(o,{resolve:r,reject:a}),this.worker.postMessage({id:o,type:t,payload:n});})}async init(){await this.request("init",{path:this.path});}async insert(t){await this.request("insert",{jobs:t});}async claimDue(t,n){return this.request("claimDue",{limit:t,now:n})}async ack(t){await this.request("ack",{ids:t});}async reschedule(t,n){await this.request("reschedule",{items:t,now:n});}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,n){return this.request("retryDeadLetters",{ids:t,now:n})}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 Dt=Symbol("blyp.connector.batch-dispatch"),K=Symbol("blyp.connector.delivery-binder");function W(e){return new Promise(t=>{setTimeout(t,e);})}function Wr(e){return e.data===void 0||typeof e.data!="object"||e.data===null||e.data.type!=="client_log"}function xt(e){return JSON.stringify(e)}function Hr(e){try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.jobId!="string"?null:t}catch{return null}}function Et(e){let t=new Map;for(let n of e){let o=`${n.connectorType}:${n.connectorTarget??""}`;t.has(o)||t.set(o,{connectorType:n.connectorType,connectorTarget:n.connectorTarget});}return [...t.values()]}var se=class{constructor(t){this.config=t;l(this,"warnOnce",v(new Set));l(this,"memoryQueue",[]);l(this,"durableStaging",[]);l(this,"dispatchers",new Map);l(this,"activeDispatches",0);l(this,"flushPromise",null);l(this,"durableFlushPromise",null);l(this,"pollTimer",null);l(this,"durablePollRunning",false);l(this,"closed",false);l(this,"durableClient",null);l(this,"durableReady",false);l(this,"durableInitPromise",null);t.enabled&&(this.durableInitPromise=this.initializeDurableQueue());}bindTarget(t){typeof t[K]=="function"&&t[K](this);let n=t[Dt];n&&this.dispatchers.set(n.dispatchKey,n);}unbindTarget(t){typeof t[K]=="function"&&t[K](null);}enqueue(t,n,o,r){this.closed||!Wr(n)||(this.dispatchers.set(o.dispatchKey,o),this.memoryQueue.push({id:Ve(),connectorType:t,connectorTarget:r,source:"server",record:n,attemptCount:0,maxAttempts:this.config.retry.maxAttempts,nextAttemptAt:Date.now(),createdAt:Date.now(),dispatchKey:o.dispatchKey,dispatcher:o}),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 n of t)this.stageDurableJob(n,n.attemptCount,Math.max(n.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 ie(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 W(10);}}takeNextMemoryBatch(){let t=Date.now(),n=this.memoryQueue.findIndex(a=>a.nextAttemptAt<=t);if(n===-1)return [];let o=this.memoryQueue[n],r=[o];this.memoryQueue.splice(n,1);for(let a=this.memoryQueue.length-1;a>=0;a-=1){let s=this.memoryQueue[a];s.dispatchKey===o.dispatchKey&&s.connectorTarget===o.connectorTarget&&s.nextAttemptAt<=t&&r.length<this.config.memoryBatchSize&&(r.push(s),this.memoryQueue.splice(a,1));}return r}async dispatchMemoryBatch(t){let n=t[0].dispatcher,o=Date.now(),r=await n.dispatch(t.map(a=>a.record),{source:"server",target:t[0].connectorTarget}).catch(a=>({ok:false,retryable:true,error:a instanceof Error?a.message:String(a)}));if(r.ok){await this.recordSuccessfulDispatch(t,o);return}await this.handleRetryableFailure(t,r,false,o);}async handleRetryableFailure(t,n,o,r){o||await this.durableInitPromise?.catch(()=>{});let a=[],s=[];await this.recordFailedDispatch(t,n,r);for(let i of t){let c=i.attemptCount+1;if(!n.retryable||c>=i.maxAttempts){s.push({id:i.id,connectorType:i.connectorType,connectorTarget:i.connectorTarget,operation:"send",payloadJson:xt({jobId:i.id,connectorType:i.connectorType,connectorTarget:i.connectorTarget,source:i.source,record:i.record,createdAt:i.createdAt}),attemptCount:c,maxAttempts:i.maxAttempts,lastError:n.error,firstEnqueuedAt:i.createdAt,deadLetteredAt:r,lastAttemptAt:r}),this.warnOnce(`connector-drop:${i.connectorType}:${i.connectorTarget??"default"}:${i.id}`,o&&this.durableReady?`[Blyp] Warning: Dead-lettered ${i.connectorType} connector job after ${c} failed attempt(s). ${n.error??"Connector delivery failed."}`:`[Blyp] Warning: Dropped ${i.connectorType} connector job after ${c} failed attempt(s). ${n.error??"Connector delivery failed."}`);continue}let u=r+St(c,this.config.retry);if(o){a.push({id:i.id,attemptCount:c,nextAttemptAt:u,lastError:n.error});continue}if(this.durableReady&&this.config.durableSpillStrategy==="after-first-failure"){this.stageDurableJob(i,c,u,n.error);continue}this.memoryQueue.push({...i,attemptCount:c,nextAttemptAt:u});}s.length>0&&await this.durableClient?.deadLetter(s).catch(i=>{this.warnOnce("connector-dead-letter-failure","[Blyp] Warning: Failed to persist dead-lettered connector queue jobs.",i);}),a.length>0&&await this.durableClient?.reschedule(a,r).catch(i=>{this.warnOnce("connector-reschedule-failure","[Blyp] Warning: Failed to reschedule durable connector queue jobs.",i);});}async recordSuccessfulDispatch(t,n){if(!this.durableReady||!this.durableClient||t.length===0)return;let o=Et(t).map(r=>({connectorType:r.connectorType,connectorTarget:r.connectorTarget,timestamp:n}));await this.durableClient.markSuccess(o).catch(r=>{this.warnOnce("connector-status-success-failure","[Blyp] Warning: Failed to record connector delivery success state.",r);});}async recordFailedDispatch(t,n,o){if(!this.durableReady||!this.durableClient||t.length===0)return;let r=Et(t).map(a=>({connectorType:a.connectorType,connectorTarget:a.connectorTarget,timestamp:o,lastError:n.error}));await this.durableClient.markFailure(r).catch(a=>{this.warnOnce("connector-status-failure-failure","[Blyp] Warning: Failed to record connector delivery failure state.",a);});}stageDurableJob(t,n,o,r){let a=xt({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:a,attemptCount:n,maxAttempts:t.maxAttempts,nextAttemptAt:o,state:"pending",lastError:r,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(n){this.warnOnce("connector-durable-insert-failure","[Blyp] Warning: Failed to persist connector jobs into the durable SQLite queue.",n),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 n=new Map,o=[];for(let r of t){let a=Hr(r.payloadJson);if(!a){o.push(r.id);continue}let s=r.connectorType==="otlp"?`otlp:${r.connectorTarget??""}`:r.connectorType,i=this.dispatchers.get(s);if(!i){o.push(r.id);continue}let c={id:r.id,connectorType:r.connectorType,connectorTarget:r.connectorTarget,source:a.source,record:a.record,attemptCount:r.attemptCount,maxAttempts:r.maxAttempts,nextAttemptAt:r.nextAttemptAt,createdAt:r.createdAt,dispatchKey:s,dispatcher:i},u=n.get(s)??[];u.push(c),n.set(s,u);}o.length>0&&await this.durableClient.ack(o);for(let r of n.values()){let s=await r[0].dispatcher.dispatch(r.map(i=>i.record),{source:"server",target:r[0].connectorTarget}).catch(i=>({ok:!1,retryable:!0,error:i instanceof Error?i.message:String(i)}));if(s.ok){await this.recordSuccessfulDispatch(r,Date.now()),await this.durableClient.ack(r.map(i=>i.id));continue}await this.handleRetryableFailure(r,s,!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 W(10);if(await this.processDurableQueueOnce(),await this.flushDurableStaging(),await this.durableClient.count().catch(()=>0)===0&&!this.durablePollRunning&&this.durableStaging.length===0)break;await W(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,[n]=this.memoryQueue.splice(t,1);if(!n)break;if(this.durableReady){this.stageDurableJob(n,n.attemptCount,Math.max(Date.now(),n.nextAttemptAt),"spilled from in-memory buffer");continue}this.warnOnce(`connector-overflow:${n.connectorType}:${n.connectorTarget??"default"}:${t}`,`[Blyp] Warning: Connector queue overflow reached ${this.config.memoryBufferSize}. Dropping queued ${n.connectorType} job.`);}}hasReadyMemoryJobs(){let t=Date.now();return this.memoryQueue.some(n=>n.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(n=>n.nextAttemptAt));await W(Math.max(t-Date.now(),0));}else await W(10);if(this.activeDispatches===0&&this.memoryQueue.length===0&&this.durableStaging.length===0)break}}};var E=class E{constructor(){l(this,"_type",null);}static getInstance(){return E.instance||(E.instance=new E),E.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"}};l(E,"instance");var Oe=E,Ie=class{constructor(){l(this,"type","bun");l(this,"isBun",true);l(this,"isNode",false);l(this,"file",{existsSync:t=>{try{let n=Bun.file(t);return n.size>0||n.name!==""}catch{return false}},mkdirSync:(t,n)=>{try{w__default.default.mkdirSync(t,n);}catch{}},writeFileSync:(t,n)=>{Bun.write(t,n);}});l(this,"path",{join:(...t)=>F__default.default.join(...t)});l(this,"env",{get:t=>Bun.env[t]});l(this,"cwd",()=>process.cwd());}},Ne=class{constructor(){l(this,"type","node");l(this,"isBun",false);l(this,"isNode",true);l(this,"file",{existsSync:t=>w__default.default.existsSync(t),mkdirSync:(t,n)=>{w__default.default.mkdirSync(t,n);},writeFileSync:(t,n)=>{w__default.default.writeFileSync(t,n);}});l(this,"path",{join:(...t)=>F__default.default.join(...t)});l(this,"env",{get:t=>process.env[t]});l(this,"cwd",()=>process.cwd());}};function Qr(){return Oe.getInstance().isBun?new Ie:new Ne}var _t=Qr();function Pt(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let n=[e,...t];return n.length===1?n[0]:n}function Bt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Jr(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 n=e;return {message:e.message,code:n.code,type:n.type??e.name??e.constructor?.name,stack:e.stack,why:n.why,fix:n.fix,link:n.link,details:Bt(n.details),cause:n.cause}}if(typeof e=="object"){let n=e,o=typeof n.statusCode=="number"?n.statusCode:typeof n.status=="number"?n.status:t;return {message:typeof n.message=="string"?n.message:`HTTP ${o??500}`,code:typeof n.code=="string"||typeof n.code=="number"?n.code:o,type:typeof n.type=="string"?n.type:typeof n.name=="string"?n.name:"Error",stack:typeof n.stack=="string"?n.stack:void 0,why:typeof n.why=="string"?n.why:void 0,fix:typeof n.fix=="string"?n.fix:void 0,link:typeof n.link=="string"?n.link:void 0,details:Bt(n.details),cause:n.cause}}return {message:String(e),code:t,type:typeof e}}function Gr(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 Mt(e,t){let n=t.redact??k(),o=performance.now(),r=h(t.initialFields??{},n),a=[],s;t.onCreate?.();let i=(u,d,g)=>(a.push({level:u,message:q(d,n),timestamp:new Date().toISOString(),...Pt(d,g)===void 0?{}:{data:h(Pt(d,g),n)}}),c),c={set(u){return Object.assign(r,h(u,n)),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(s)return s;let d=h(t.resolveDefaultFields?.()??{},n),g=Gr(u),C=h(Jr(u.error,g),n),_=u.level??(C?"error":"info"),y=h({...d,...r,groupId:e,timestamp:new Date().toISOString(),level:_,duration:Math.round(performance.now()-o),...typeof g=="number"?{status:g}:{},...a.length>0?{events:[...a]}:{},...C?{error:C}:{}},n);return t.write(y,q(u.message??"structured_log",n)),s=y,t.onEmit?.(y),y}};return c}var $t=Symbol("blyp.logger.factory"),It={success:25,info:30,debug:35,table:37,warning:40,error:50,critical:60},Nt={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warn",table:"debug"},Vr="\x1B[35m",Xr="\x1B[0m";function H(e){return Tt(e)==="client_log"}function Yr(){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 Zr(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function eo(){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 to(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,send:()=>{},flush:async()=>{}}}function no(e){return {name:e,enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",endpoint:void 0,status:"missing",send:()=>{},flush:async()=>{}}}function ro(){return {get:e=>no(e),getAutoForwardTargets:()=>[],send:()=>{},flush:async()=>{}}}function oo(e){return e.connectors?.betterstack?.enabled?M("betterstack",["@logtail/node","@sentry/node"],"../connectors/betterstack/sender").createBetterStackSender(e):Yr()}function ao(e){return e.connectors?.databuddy?.enabled?M("databuddy",["@databuddy/sdk"],"../connectors/databuddy/sender").createDatabuddySender(e):Zr()}function io(e){return e.connectors?.posthog?.enabled?M("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/posthog/sender").createPostHogSender(e):eo()}function so(e){return e.connectors?.sentry?.enabled?M("sentry",["@sentry/node"],"../connectors/sentry/sender").createSentrySender(e):to()}function co(e){return e.connectors?.otlp?.some(t=>t.enabled)?M("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/otlp/sender").createOTLPRegistry(e):ro()}function uo(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n={};t.data!==void 0&&(n.data=t.data);let o=typeof t.page?.pathname=="string"?t.page.pathname:void 0,r=typeof t.page?.url=="string"?t.page.url:void 0;return (o||r)&&(n.page=o??r),t.metadata!==void 0&&(n.metadata=t.metadata),Object.keys(n).length>0?n:null}function lo(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 n=uo(e);return n?{hidden:false,value:n}:{hidden:true}}return {hidden:false,value:e}}function po(e){if(e.pretty){let n=We()({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:(o,r)=>{let a=String(o[r]??""),s=typeof o.caller=="string"?o.caller.trim():"";return s?`${a} ${Vr}${s}${Xr}`:a}});return Ot__default.default({level:e.level,customLevels:It},n)}return Ot__default.default({level:e.level,customLevels:It})}function fo(e){let t=e[$t];if(!t)throw new Error("Unsupported Blyp logger instance");return t}function go(e,t,n={}){let o=fo(e);return Mt(t,{initialFields:n.initialFields,resolveDefaultFields:()=>({...o.bindings,...n.resolveDefaultFields?.()??{}}),write:(r,a)=>{o.writeStructured(r,a,"structured-flush");},onCreate:n.onCreate,onEmit:n.onEmit,redact:n.redact??o.redact})}function Ft(e,t){if(!H(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function zt(e,t){if(!H(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function jt(e,t){if(!H(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Ut(e,t){if(!H(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function qt(e,t){if(!H(t))for(let n of e.getAutoForwardTargets())n.send(t,{source:"server",warnIfUnavailable:true});}function ze(e,t,n,o,r,a,s,i,c,u={},d="root"){let g=Object.keys(u).length>0?e.child(u):e,C=(f,p,P,B=d)=>{if(B==="root"&&Re())return;let m=dt(f,p,P,u,c),ye=m.message,U={caller:m.caller},Y=lo(m.data);!Y.hidden&&Y.value!==void 0&&(U.data=Y.value);let $e=Nt[f],he=g;(he[$e]??he.info??((vo,Do)=>{})).call(g,U,ye),t.write(m),zt(o,m),jt(r,m),Ft(a,m),Ut(s,m),qt(i,m);},_=(f,p,P="structured-flush")=>{let B=ft(f.level),m=pt(B,p,f,u,c),ye=Nt[B],U=g;(U[ye]??U.info??(($e,he)=>{})).call(g,{caller:m.caller,...m},m.message),(P!=="root"||!Re())&&t.write(m),zt(o,m),jt(r,m),Ft(a,m),Ut(s,m),qt(i,m);},y={success:(f,...p)=>{C("success",f,p);},critical:(f,...p)=>{C("critical",f,p);},warning:(f,...p)=>{C("warning",f,p);},info:(f,...p)=>{C("info",f,p);},debug:(f,...p)=>{C("debug",f,p);},error:(f,...p)=>{C("error",f,p);},warn:(f,...p)=>{C("warn",f,p);},table:(f,p)=>{p&&typeof p=="object"&&_t.env.get("NODE_ENV")!=="production"&&(console.log("TABLE:",f),console.table(h(p,c))),C("table",f,p===void 0?[]:[p]);},flush:async()=>{await t.flush(),n&&await n.flush(),await Promise.allSettled([o.flush(),r.flush(),a.flush(),s.flush(),i.flush()]);},shutdown:async()=>{await t.shutdown(),n&&await n.shutdown(),await Promise.allSettled([o.flush(),r.flush(),a.flush(),s.flush(),i.flush()]);},createStructuredLog:(f,p)=>go(y,f,{initialFields:p}),child:f=>{let p={...u,...f};return ze(e,t,n,o,r,a,s,i,c,p,d)},[$t]:{bindings:u,betterstack:o,databuddy:r,posthog:a,sentry:s,otlp:i,redact:c,sink:t,create:(f,p=u)=>ze(e,t,n,o,r,a,s,i,c,p,f),writeStructured:(f,p,P="structured-flush")=>{_(f,p,P);}}};return y}var Fe=null;function mo(e){if(Fe)return Fe;let t=it(e),n=po(t),o=Rt(t),r=oo(t),a=ao(t),s=io(t),i=so(t),c=co(t),u=t.connectors.delivery.enabled?new se(t.connectors.delivery):null;if(u){u.bindTarget(r),u.bindTarget(a),u.bindTarget(s),u.bindTarget(i);for(let g of c.getAutoForwardTargets())u.bindTarget(g);}let d=ze(n,o,u,r,a,s,i,c,t.redact);return (Fe=d),d}var ue=mo();var yo=new TextEncoder;function le(e){return yo.encode(e).length}function ho(e){if(!e||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function b(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(n=>b(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";if(t.add(e),!ho(e)){let n=e.constructor?.name;return n?`[${n}]`:"[Object]"}return Object.fromEntries(Object.entries(e).map(([n,o])=>[n,b(o,t)]))}return String(e)}function S(e,t){if(t.length===0)return e;let n=b(e);for(let o of t){let r=o.split(".").filter(Boolean);if(r.length===0)continue;let a=n;for(let s=0;s<r.length-1;s+=1){if(!a||typeof a!="object"){a=void 0;break}a=a[r[s]];}a&&typeof a=="object"&&delete a[r[r.length-1]];}return n}function de(e,t){let n=b(e);if(t<=0)return {value:"[Truncated]",truncated:true};if(typeof n=="string"){if(le(n)<=t)return {value:n,truncated:false};let a=n;for(;a.length>0&&le(`${a}\u2026[truncated]`)>t;)a=a.slice(0,Math.max(1,Math.floor(a.length*.8)));return {value:`${a}\u2026[truncated]`,truncated:true}}let o=JSON.stringify(n);if(o===void 0||le(o)<=t)return {value:n,truncated:false};let r=o;for(;r.length>0&&le(`${r}\u2026[truncated]`)>t;)r=r.slice(0,Math.max(1,Math.floor(r.length*.8)));return {value:{truncated:true,preview:`${r}\u2026[truncated]`},truncated:true}}function pe(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(n=>n===void 0))return t}function fe(e){if(typeof e=="string"&&e.length>0)return e;if(e&&typeof e=="object"){let t=e;for(let n of ["type","reason","stop_reason","finish_reason","raw","unified"]){let o=t[n];if(typeof o=="string"&&o.length>0)return o}}}function Kt(e){return {toolName:e.name,toolCallId:e.id,status:e.status}}function Wt(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 Ht(e){return b(e)}var je={input:false,output:false,toolInputs:false,toolOutputs:false,reasoning:false,streamEvents:false,streamChunks:false,rawProviderPayload:false},Q={providerOptions:false,requestPaths:[],responsePaths:[],metadataPaths:[],toolNames:[]},Ue={maxContentBytes:16384,maxEvents:200,maxToolCalls:50};function bo(){return `ai_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`}function Co(){return new Date().toISOString()}function Qt(e){return b(e)}function qe(){return new Date().toISOString()}function wo(e={}){return {logger:e.logger,provider:e.provider,operation:e.operation,metadata:{...e.metadata??{}},capture:{...je,...e.capture??{},streamEvents:e.capture?.streamEvents??e.capture?.streamChunks??je.streamEvents,streamChunks:e.capture?.streamChunks??e.capture?.streamEvents??je.streamChunks},exclude:{providerOptions:e.exclude?.providerOptions??Q.providerOptions,requestPaths:[...e.exclude?.requestPaths??Q.requestPaths],responsePaths:[...e.exclude?.responsePaths??Q.responsePaths],metadataPaths:[...e.exclude?.metadataPaths??Q.metadataPaths],toolNames:[...e.exclude?.toolNames??Q.toolNames]},limits:{maxContentBytes:e.limits?.maxContentBytes??Ue.maxContentBytes,maxEvents:e.limits?.maxEvents??Ue.maxEvents,maxToolCalls:e.limits?.maxToolCalls??Ue.maxToolCalls},hooks:e.hooks??{}}}function Jt(e={}){return wo(e)}function Gt(e){let t=e.config.logger??Z()??ue,n=bo(),o=qe(),r={traceId:n,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:o,startedAtMs:performance.now(),options:e.config,capture:{...e.config.capture},streamed:e.streamed,truncated:false},a={traceId:n,provider:r.provider,sdk:r.sdk,operation:r.operation,method:r.method,logger:t,metadata:r.metadata,request:r.request,get response(){return r.response},get usage(){return r.usage},get finishReason(){return r.finishReason},get input(){return r.input},get output(){return r.output},get reasoning(){return r.reasoning},get toolCalls(){return r.toolCalls.length>0?r.toolCalls:void 0},get startedAt(){return r.startedAt},get firstChunkAt(){return r.firstChunkAt},get endedAt(){return r.endedAt},get error(){return r.error},setMetadata(s){Object.assign(r.metadata,s);},disableCapture(s){r.capture[s]=false;}};return {state:r,context:a}}function G(e,t){e.usage=pe(t);}function ge(e,t){e.finishReason=fe(t);}function Vt(e,t){e.response=t;}function Xt(e,t){e.input=t;}function me(e,t){e.output=t;}function Yt(e,t){e.rawProviderPayload=Ht(t);}async function Zt(e,t){e.firstChunkAt||(e.firstChunkAt=qe(),e.firstChunkAtMs=performance.now(),await A(e,t,{type:"ai.first_chunk",timestamp:e.firstChunkAt}));}async function en(e,t,n){e.capture.streamEvents&&await A(e,t,{type:"ai.chunk",data:n});}function V(e,t){let n=t.id??`${t.name}:${e.toolCalls.length}`,o=e.toolCalls.findIndex((r,a)=>(r.id??`${r.name}:${a}`)===n);if(o===-1&&e.toolCalls.length>=e.options.limits.maxToolCalls){e.truncated=true;return}if(o===-1){e.toolCalls.push(t);return}e.toolCalls[o]={...e.toolCalls[o],...t};}async function tn(e,t,n){V(e,n),await A(e,t,{type:"ai.tool_call.start",data:Kt(n)});}function Ro(e){let t=e.toolCalls.filter(n=>!e.options.exclude.toolNames.includes(n.name)).map(n=>{let o={id:n.id,name:n.name,status:n.status};if(e.capture.toolInputs&&n.input!==void 0){let r=j(n.input,e.options.limits.maxContentBytes);o.input=r.value,e.truncated||(e.truncated=r.truncated);}if(e.capture.toolOutputs&&n.output!==void 0){let r=j(n.output,e.options.limits.maxContentBytes);o.output=r.value,e.truncated||(e.truncated=r.truncated);}return n.providerFormat!==void 0&&(o.providerFormat=b(n.providerFormat)),o});return t.length>0?t:void 0}async function X(e,t,n){if(e.emitted)return;e.emitted=true,n?.error!==void 0&&(e.error=n.error,await A(e,t,{type:"ai.error",data:{error:b(n.error)}}),await J(e.options.hooks.onError,[t])),e.endedAt=qe(),await A(e,t,{type:"ai.finish",timestamp:e.endedAt}),e.error||await J(e.options.hooks.onFinish,[t]);let o={startedAt:e.startedAt,endedAt:e.endedAt,durationMs:Math.max(0,Math.round(performance.now()-e.startedAtMs))};e.firstChunkAt&&e.firstChunkAtMs!==void 0&&(o.firstChunkAt=e.firstChunkAt,o.msToFirstChunk=Math.max(0,Math.round(e.firstChunkAtMs-e.startedAtMs)));let r={provider:e.provider,sdk:e.sdk,model:e.model,operation:e.operation,method:e.method,streamed:e.streamed,timing:o,metadata:S(e.metadata,e.options.exclude.metadataPaths)};if(e.usage&&(r.usage=e.usage),e.finishReason&&(r.finishReason=e.finishReason),e.capture.input&&e.input!==void 0){let i=j(S(b(e.input),e.options.exclude.requestPaths),e.options.limits.maxContentBytes);r.input=i.value,e.truncated||(e.truncated=i.truncated);}if(e.capture.output&&e.output!==void 0){let i=b(e.output),c=j(typeof i=="object"&&i!==null&&!Array.isArray(i)?S(i,e.options.exclude.responsePaths):i,e.options.limits.maxContentBytes);r.output=c.value,e.truncated||(e.truncated=c.truncated);}if(e.capture.reasoning&&e.reasoning!==void 0){let i=b(e.reasoning),c=j(i,e.options.limits.maxContentBytes);r.reasoning=c.value,e.truncated||(e.truncated=c.truncated);}let a=Ro(e);if(a&&(r.tools=a,r.toolCalls=a),e.capture.rawProviderPayload&&e.rawProviderPayload!==void 0){let i=j(e.rawProviderPayload,e.options.limits.maxContentBytes);r.rawProviderPayload=i.value,e.truncated||(e.truncated=i.truncated);}e.truncated&&r.metadata&&(r.metadata={...r.metadata,truncated:true});let s={...r};if(e.error!==void 0){let{errorType:i,errorCode:c}=Wt(e.error);i&&(s.errorType=i),c!==void 0&&(s.errorCode=c);}try{e.logger.createStructuredLog(e.traceId,{type:"ai_trace",ai:s,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.",Qt(i));}}async function J(e,t){if(e)try{await e(...t);}catch(n){console.warn("[Blyp] AI middleware hook failed.",Qt(n));}}async function A(e,t,n){e.events.length<e.options.limits.maxEvents?e.events.push({...n,timestamp:n.timestamp??Co()}):e.truncated=true,await J(e.options.hooks.onEvent,[e.events[e.events.length-1],t]);}function j(e,t){return de(e,t)}function nn(e){return !!e&&typeof e[Symbol.asyncIterator]=="function"}function rn(e,t){return {[Symbol.asyncIterator](){let n=e[Symbol.asyncIterator]();return {async next(){try{let o=await n.next();return o.done?(await t.onReturn?.(),o):(await t.onChunk?.(o.value),o)}catch(o){throw await t.onError?.(o),o}},async return(o){try{return typeof n.return=="function"?await n.return(o):{done:!0,value:o}}finally{await t.onReturn?.();}},async throw(o){try{if(typeof n.throw=="function")return await n.throw(o);throw o}catch(r){throw await t.onError?.(r),r}}}}}}function on(e){if(!e||typeof e!="object")return {toolCalls:[]};let t=e,n=t.usage&&typeof t.usage=="object"?pe({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,o=Array.isArray(t.content)?t.content:[],r=o.filter(s=>!!s&&typeof s=="object").filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join(""),a=o.filter(s=>!!s&&typeof s=="object").filter(s=>s.type==="tool_use").map(s=>({id:typeof s.id=="string"?s.id:void 0,name:typeof s.name=="string"?s.name:"unknown",input:s.input,status:"started"}));return {model:typeof t.model=="string"?t.model:void 0,usage:n,finishReason:fe(t.stop_reason),output:r||void 0,toolCalls:a}}async function an(e,t,n){if(!n||typeof n!="object")return;let o=n,r=o.type;if(typeof r=="string"){if(await Zt(e,t),await en(e,t,{type:r}),r==="content_block_delta"){let a=o.delta;if(a&&typeof a=="object"){let s=a;if(s.type==="text_delta"&&typeof s.text=="string"&&me(e,`${typeof e.output=="string"?e.output:""}${s.text}`),s.type==="input_json_delta"&&typeof s.partial_json=="string"){let i=typeof o.index=="number"?o.index:0,c=e.toolCalls[i];V(e,{id:c?.id,name:c?.name??"unknown",input:`${typeof c?.input=="string"?c.input:""}${s.partial_json}`,status:c?.status??"started"});}}}if(r==="content_block_start"){let a=o.content_block;if(a&&typeof a=="object"){let s=a;s.type==="tool_use"&&await tn(e,t,{id:typeof s.id=="string"?s.id:void 0,name:typeof s.name=="string"?s.name:"unknown",input:s.input,status:"started"});}}if(r==="message_delta"&&(ge(e,o.stop_reason),o.usage&&typeof o.usage=="object")){let a=o.usage;G(e,{outputTokens:typeof a.output_tokens=="number"?a.output_tokens:void 0});}if(r==="message_stop"&&o.usage&&typeof o.usage=="object"){let a=o.usage;G(e,{inputTokens:typeof a.input_tokens=="number"?a.input_tokens:void 0,outputTokens:typeof a.output_tokens=="number"?a.output_tokens:void 0});}}}function To(e,t,n){return Object.assign(Object.create(Object.getPrototypeOf(e)),e,{[t]:n})}function So(e,t={}){let n=Object.create(Object.getPrototypeOf(e));if(Object.assign(n,e),!e.messages?.create)return n;let o=async(r,...a)=>{let s=Jt({...t,provider:"anthropic"}),{state:i,context:c}=Gt({provider:"anthropic",sdk:"anthropic-sdk",operation:t.operation,method:"messages.create",model:typeof r?.model=="string"?r.model:"unknown",request:r,streamed:r?.stream===true,config:s});Xt(i,r?.messages??r),await A(i,c,{type:"ai.start"}),await J(s.hooks.onStart,[c]);try{let u=await e.messages.create(r,...a);if(r?.stream===!0&&nn(u))return rn(u,{onChunk:async g=>{await an(i,c,g);},onReturn:async()=>{await X(i,c);},onError:async g=>{await X(i,c,{error:g});}});let d=on(u);Vt(i,u),Yt(i,u),d.usage&&G(i,d.usage),d.finishReason&&ge(i,d.finishReason),d.output!==void 0&&me(i,d.output);for(let g of d.toolCalls)V(i,g);return await X(i,c),u}catch(u){throw await X(i,c,{error:u}),u}};return n.messages=To(e.messages,"create",o),n}function ko(e,t={}){let n=t.logger??Z()??ue,o={...t.metadata??{}},r=t.limits?.maxContentBytes??16384,a=t.exclude?.requestPaths??[],s=t.exclude?.responsePaths??[],i=(async(c,u)=>{let d=performance.now(),g=new Date().toISOString(),C=u?.method??(c instanceof Request?c.method:"GET"),_=typeof c=="string"?c:c instanceof URL?c.toString():c.url;try{let y=await e(c,u),f=new Date().toISOString(),p=n.createStructuredLog(`fetch_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`,{type:"fetch_trace",fetch:{url:_,method:C,status:y.status,startedAt:g,endedAt:f,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:S(o,t.exclude?.metadataPaths??[])}});if(t.inspectJsonBody===!0&&!y.bodyUsed&&y.headers.get("content-type")?.includes("application/json"))try{let B=await y.clone().json(),m=de({request:S(b(u??{}),a),response:S(b(B),s)},r);p.set({fetchBody:m.value});}catch{}return p.emit({message:"fetch_trace",level:y.ok?"info":"error"}),y}catch(y){throw n.createStructuredLog(`fetch_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`,{type:"fetch_trace",fetch:{url:_,method:C,startedAt:g,endedAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-d)),metadata:S(o,t.exclude?.metadataPaths??[])}}).emit({message:"fetch_trace",level:"error",error:b(y)}),y}});return "preconnect"in e&&(i.preconnect=e.preconnect),i}
|
|
701
|
+
exports.blypFetch=ko;exports.wrapAnthropic=So;
|