@blyp/core 0.1.2 → 0.1.22
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 +273 -14
- 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/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 +116 -0
- package/dist/ai/shared/types.d.ts +161 -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 +701 -0
- package/dist/astro.mjs +701 -0
- package/dist/client.js +1 -1132
- package/dist/client.mjs +1 -1125
- package/dist/connectors/betterstack.js +9 -1508
- package/dist/connectors/betterstack.mjs +9 -1483
- package/dist/connectors/databuddy/index.d.ts +7 -0
- package/dist/connectors/databuddy/sender.d.ts +5 -0
- package/dist/connectors/databuddy.js +9 -0
- package/dist/connectors/databuddy.mjs +9 -0
- 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 -1347
- package/dist/connectors/otlp.mjs +9 -1344
- package/dist/connectors/posthog/properties.d.ts +4 -0
- package/dist/connectors/posthog/sender.d.ts +0 -1
- package/dist/connectors/posthog.js +10 -1503
- package/dist/connectors/posthog.mjs +10 -1498
- package/dist/connectors/sentry.js +9 -1356
- package/dist/connectors/sentry.mjs +9 -1333
- package/dist/core/config.d.ts +7 -2
- package/dist/core/log-record.d.ts +5 -4
- package/dist/core/logger.d.ts +5 -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 +621 -4100
- package/dist/elysia.mjs +622 -4073
- package/dist/expo.js +1 -719
- package/dist/expo.mjs +1 -717
- package/dist/express.js +616 -4085
- package/dist/express.mjs +616 -4056
- package/dist/fastify.js +618 -4104
- package/dist/fastify.mjs +618 -4075
- package/dist/frameworks/astro/index.d.ts +2 -0
- package/dist/frameworks/astro/logger.d.ts +3 -0
- 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/nitro/index.d.ts +2 -0
- package/dist/frameworks/nitro/logger.d.ts +6 -0
- package/dist/frameworks/nuxt/index.d.ts +2 -0
- package/dist/frameworks/nuxt/logger.d.ts +3 -0
- package/dist/frameworks/react-router/index.d.ts +2 -0
- package/dist/frameworks/react-router/logger.d.ts +3 -0
- package/dist/frameworks/shared/h3.d.ts +19 -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 +624 -4079
- package/dist/hono.mjs +626 -4053
- package/dist/index.d.ts +57 -17
- package/dist/index.js +616 -6494
- package/dist/index.mjs +619 -6410
- package/dist/nestjs.js +626 -4574
- package/dist/nestjs.mjs +622 -4542
- package/dist/nextjs.js +625 -4107
- package/dist/nextjs.mjs +627 -4081
- package/dist/nitro.js +701 -0
- package/dist/nitro.mjs +701 -0
- package/dist/nuxt.js +701 -0
- package/dist/nuxt.mjs +701 -0
- package/dist/react-router.js +701 -0
- package/dist/react-router.mjs +701 -0
- package/dist/shared/redaction.d.ts +17 -0
- package/dist/standalone.js +606 -3258
- package/dist/standalone.mjs +611 -3234
- package/dist/sveltekit.js +625 -4106
- package/dist/sveltekit.mjs +626 -4079
- package/dist/tanstack-start.js +624 -4105
- package/dist/tanstack-start.mjs +626 -4079
- package/dist/types/connectors/databuddy.d.ts +52 -0
- package/dist/types/core/config.d.ts +89 -0
- package/dist/types/core/logger.d.ts +5 -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 +33 -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 +63 -0
- package/dist/types/frameworks/nuxt.d.ts +12 -0
- package/dist/types/frameworks/react-router.d.ts +35 -0
- package/dist/types/frameworks/request-context.d.ts +1 -0
- package/dist/types/frameworks/shared.d.ts +28 -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 +2 -1
- package/dist/workers.js +2 -626
- package/dist/workers.mjs +2 -623
- package/package.json +273 -143
- 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/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/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/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/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/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/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/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/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
|
+
import Et from'pino';import {createJiti}from'jiti';import {createRequire}from'module';import {AsyncLocalStorage}from'async_hooks';import y,{existsSync,readFileSync,writeFileSync,appendFileSync}from'fs';import B,{resolve,dirname}from'path';import hn from'os';import {z}from'zod';import {gzipSync}from'fflate';import {randomUUID}from'crypto';import {Worker}from'worker_threads';import {wrapLanguageModel}from'ai';var Gt=Object.defineProperty;var Vt=(e,t,n)=>t in e?Gt(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var l=(e,t,n)=>Vt(e,typeof t!="symbol"?t+"":t,n);var Yt=createJiti(typeof __filename=="string"?__filename:import.meta.url,{interopDefault:false,moduleCache:true,fsCache:false}),Ne=new Map;function Zt(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 A(e,t,n=`@blyp/core/${e}`){let o=`@blyp/core/${e}`,r=`${o}::${n}`,a=Ne.get(r);if(a)return a;try{let s=Yt(n);return Ne.set(r,s),s}catch(s){if(!Zt(s))throw s;let i=t.map(c=>`"${c}"`).join(", "),u=t.join(" ");throw new Error(`[Blyp] Optional connector dependencies missing for "${o}". Install ${i} to use this API. Example: bun add ${u}. You can also import directly from "${o}".`,{cause:s instanceof Error?s:void 0})}}var tn=createRequire(typeof __filename=="string"?__filename:import.meta.url),ue=null;function nn(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 rn(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 Fe(){if(ue)return ue;let e;try{e=tn("pino-pretty");}catch(n){throw nn(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=rn(e);if(!t)throw new Error('[Blyp] Failed to initialize the pretty logger transport because "pino-pretty" did not expose a callable factory.');return ue=t,t}var an=new AsyncLocalStorage;function le(){return an.getStore()}function ze(){return le()?.activeLogger}function de(){return le()?.traceId}function pe(){let e=le();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 V(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=R(n.cause)),t}function R(e,t=new WeakSet){if(e instanceof Error)return V(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=>R(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]=R(r,t);return t.delete(e),n}return e}function ge(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=R(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var sn="[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 un=[{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}],ln=/\b(?:\d[ -]*?){16}\b/g;function je(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 dn(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function pn(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function gn(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function fn(e){return e.split(".").filter(Boolean)}function fe(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(fe(e,t,n+1,a))return true;return false}return o>=t.length||r!=="*"&&r!==t[o]?false:fe(e,t,n+1,o+1)}function mn(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(n=>fe(fn(n),e))}function yn(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 Ue(e,t,n){if(n||t.disablePatternScanning)return e;let o=e;for(let{type:r,pattern:a}of un)o=o.replace(a,`[REDACTED:${r}]`);o=o.replace(ln,r=>yn(r)?"[REDACTED:card]":r);for(let r of t.patterns)o=o.replace(dn(r),"[REDACTED:pattern]");return o}function X(e,t,n,o){if(typeof e=="string")return Ue(e,t,!!o.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((a,s)=>X(a,t,n,{path:[...o.path,String(s)],skipPatternScanning:o.skipPatternScanning}));if(!pn(e))return e;let r={};for(let[a,s]of Object.entries(e)){let i=[...o.path,a];if(n.has(a.toLowerCase())||mn(i,t)){if(s==null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[a]=sn;continue}r[a]=X(s,t,n,{path:i,skipPatternScanning:o.skipPatternScanning});continue}r[a]=X(s,t,n,{path:i,skipPatternScanning:o.skipPatternScanning});}return r}function T(e,t){return {keys:je([...cn,...e?.keys??[],...t?.keys??[]]),paths:je([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(n=>n instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function m(e,t,n={path:[]}){let o=R(e);return X(o,t,gn(t),n)}function j(e,t){return typeof e=="string"?Ue(e,t,false):ge(m(e,t))}function qe(){return B.join(hn.homedir(),".blyp","queue.db")}var Cn=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"}),$e=z.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),ye=z.string().trim().min(1);function he(e){return Cn.safeParse(e).success}function be(e){return $e.safeParse(e).success}function x(e){return ye.safeParse(e).success}var Ce="/inngest";z.union([z.literal("betterstack"),z.literal("databuddy"),z.literal("posthog"),z.literal("sentry"),z.undefined(),z.object({type:z.literal("otlp"),name:ye})]);function wn(e){try{return e()}catch{return}}function Sn(){return Math.random().toString(36).slice(2,10)}function We(){let e=wn(()=>globalThis.crypto),t=e&&typeof e.randomUUID=="function"?e.randomUUID.bind(e):void 0;return t?t():`${Date.now().toString(36)}-${Sn()}`}function Rn(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 k(e){return Rn("warn",e)}var vn="@blyp/core",Dn=".gitignore",Je=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],xn="blyp.config.json",En="https://us.i.posthog.com",An="blyp-app",Pn=An,_n=new Set,v=k(_n),Ge={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},Ve={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:Ge},we={enabled:true,path:Ce},Xe=T(),P={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},b={enabled:false,memoryBufferSize:500,durableQueuePath:qe(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:P},Ye={maxRetries:1,backoffMs:100},Mn={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:Ye},Ke={pretty:true,level:"info",destination:"file",file:Ve,clientLogging:we,redact:Xe,connectors:{delivery:b}},U=null;function Bn(e){let t=e;for(;;){let n=resolve(t,"package.json");if(existsSync(n))try{let r=JSON.parse(readFileSync(n,"utf-8"));if(x(r.name))return r.name}catch{}let o=dirname(t);if(o===t)return;t=o;}}function Re(e=process.cwd()){return Bn(e)??Pn}function On(){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:Ce},redact:Xe,connectors:{delivery:b}}}function In(e){let t=resolve(e,"package.json");if(!existsSync(t))return true;try{return JSON.parse(readFileSync(t,"utf-8")).name!==vn}catch{return true}}function Nn(e){if(Je.some(n=>existsSync(resolve(e,n))))return;let t=resolve(e,xn);if(!existsSync(t))try{writeFileSync(t,`${JSON.stringify(On(),null,2)}
|
|
2
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to create blyp.config.json:",n);}}function Fn(e){let t=resolve(e,Dn);if(!existsSync(t)){try{writeFileSync(t,`logs
|
|
3
|
+
.blyp
|
|
4
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to create .gitignore:",n);}return}try{let n=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
|
+
`;appendFileSync(t,`${r}${o.join(`
|
|
7
|
+
`)}
|
|
8
|
+
`);}catch(n){console.error("[Blyp] Warning: Failed to update .gitignore:",n);}}function zn(){let e=process.cwd();In(e)&&(Nn(e),Fn(e));}function jn(){let e=process.cwd(),t=Je.map(o=>resolve(e,o)).filter(o=>existsSync(o));if(t.length===0)return null;if(t.length>1){let o=t[0];v(`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 Ze(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)?(v(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):n}function Un(e){try{let t=readFileSync(e,"utf-8");return Ze(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function qn(e){try{let t=createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return Ze(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function $n(e){return e.type==="json"?Un(e.path):qn(e.path)}function He(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function Wn(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function Kn(e,t){return {...Ye,...e,...t}}function Hn(e,t){return {...Mn,...e,...t,retry:Kn(e?.retry,t?.retry)}}function Qn(e){let t=e.model??"blypLog",o=e.client?.[t];return !!o&&typeof o.create=="function"}function Jn(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function Gn(e,t){if(!e)return;let n=e.adapter,o=false;t==="json"?v("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"?v(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):n?He(n)?(o=Qn({...n,model:n.model??"blypLog"}),o||v("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${n.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):Wn(n)&&(o=Jn(n),o||v("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):v("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let r=He(n)?{...n,model:n.model??"blypLog"}:n;return {dialect:e.dialect,adapter:r,delivery:Hn(void 0,e.delivery),ready:o,status:o?"enabled":"missing"}}function Vn(e,t){return {...Ge,...e,...t}}function Xn(e,t){return {...Ve,...e,...t,rotation:Vn(e?.rotation,t?.rotation)}}function Yn(e,t){return {...we,...e,...t,path:t?.path??e?.path??we.path}}function Zn(e,t){return T(e,t)}function er(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??P.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??P.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??P.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??P.multiplier),jitter:t?.jitter??e?.jitter??P.jitter}}function tr(e,t){let n=t?.durableQueuePath??e?.durableQueuePath??b.durableQueuePath;return {enabled:t?.enabled??e?.enabled??b.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??b.memoryBufferSize)),durableQueuePath:x(n)?n:b.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??b.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??b.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??b.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??b.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??b.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??b.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??b.overflowStrategy,retry:er(e?.retry,t?.retry),durableReady:false}}function nr(e,t,n){if(!(!e&&!t))return Gn({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},n)}function rr(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??En,serviceName:t?.serviceName??e?.serviceName??Re(),errorTracking:{enabled:s,mode:a,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??r?.enableExceptionAutocapture??a==="auto",ready:i,status:i?"enabled":"missing"}}}function or(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 ar(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=ir(r,a,t?.errorTracking),i=r&&x(n)&&he(o);return {enabled:r,mode:t?.mode??e?.mode??"auto",sourceToken:n,ingestingHost:o,serviceName:t?.serviceName??e?.serviceName??Re(),errorTracking:s,ready:i,status:i?"enabled":"missing"}}function ir(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 sr(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&&he(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??Re(),ready:a,status:a?"enabled":"missing"}}function ur(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)&&v(`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 lr(e,t){return {betterstack:ar(e?.betterstack,t?.betterstack),databuddy:or(e?.databuddy,t?.databuddy),posthog:rr(e?.posthog,t?.posthog),sentry:sr(e?.sentry,t?.sentry),otlp:ur(e?.otlp,t?.otlp),delivery:tr(e?.delivery,t?.delivery)}}function Se(e,t={},n={}){return {...e,...t,destination:t.destination??e.destination??"file",file:Xn(e.file,t.file),database:nr(e.database,t.database,n.configFileType),clientLogging:Yn(e.clientLogging,t.clientLogging),redact:Zn(e.redact,t.redact),connectors:lr(e.connectors,t.connectors)}}function dr(){if(U!==null)return U;zn();let e=jn();if(e){let t=$n(e);U=Se(Ke,t,{configFileType:e.type});}else U=Se(Ke);return U}function et(e={}){return Se(dr(),e)}var tt={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function Z(e){return e.replace(/\\/g,"/")}function pr(e){let t=Z(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 gr(e){let t=Z(e),n=Z(process.cwd());return t.startsWith(`${n}/`)?t.slice(n.length+1):t}function nt(){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")&&!pr(s)){let u=gr(s);if(!Z(u).startsWith("dist/"))return {file:u,line:i};n??(n={file:u,line:i});}}if(n)return n}catch{return {file:null,line:null}}return {file:null,line:null}}var rt=j;function ot(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function at(e,t,n,o,r=T()){let{file:a,line:s}=nt(),i=rt(t,r),u={timestamp:new Date().toISOString(),level:tt[e],message:ot(i)},c=de();return t instanceof Error&&(u.error=m(V(t),r)),a&&(u.caller=s!==null?`${a}:${s}`:a),n.length===1?u.data=m(n[0],r):n.length>1&&(u.data=m(n,r)),Object.keys(o).length>0&&(u.bindings=m(o,r)),c&&(u.traceId=c),u}function it(e,t,n,o,r=T()){let{file:a,line:s}=nt(),i=m(n,r),u=de(),c={message:ot(rt(t,r)),...i};return a&&(c.caller=s!==null?`${a}:${s}`:a),Object.keys(o).length>0&&(c.bindings=m(o,r)),u&&c.traceId===void 0&&(c.traceId=u),c.level=typeof i.level=="string"&&i.level.length>0?i.level:tt[e],c.timestamp=typeof i.timestamp=="string"&&i.timestamp.length>0?i.timestamp:new Date().toISOString(),c}function st(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 mr(e){return Buffer.from(gzipSync(e))}function yr(e,t){console.warn(`[Blyp] Warning: ${e}`,t);}function ee(e){y.mkdirSync(e,{recursive:true});}function hr(e){try{return y.statSync(e).size}catch{return 0}}function br(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 Cr(e,t){let n=`${e}${t}`,o=1;for(;y.existsSync(n);)n=`${e}-${o}${t}`,o+=1;return n}function wr(e,t,n,o){let r=`${t}.`;try{let a=y.readdirSync(e).filter(i=>i.startsWith(r)&&(i.endsWith(".ndjson")||i.endsWith(".ndjson.gz"))).map(i=>B.join(e,i)).sort((i,u)=>y.statSync(i).mtimeMs-y.statSync(u).mtimeMs),s=Math.max(a.length-n,0);for(let i=0;i<s;i+=1)y.rmSync(a[i]);}catch(a){o(`Failed to prune archives for ${t}`,a);}}function Sr(){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 Rr(e){return JSON.stringify(e,Sr())}function Tr(e){let t=e.file,n=t?.dir||e.logDir||B.join(process.cwd(),"logs"),o=t?.archiveDir||B.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 Te=class{constructor(t,n={}){l(this,"config");l(this,"gzip");l(this,"warn");l(this,"combined");l(this,"error");this.config=Tr(t),this.gzip=n.gzip??mr,this.warn=n.warn??yr,this.combined={activePath:B.join(this.config.dir,"log.ndjson"),archivePrefix:"log",bytes:0,queue:[],processing:false},this.error={activePath:B.join(this.config.dir,"log.error.ndjson"),archivePrefix:"log.error",bytes:0,queue:[],processing:false},this.config.enabled&&(ee(this.config.dir),ee(this.config.archiveDir),this.seedStream(this.combined),this.seedStream(this.error));}write(t){if(!this.config.enabled)return;let n=`${Rr(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=hr(t.activePath),this.config.rotationEnabled&&t.bytes>this.config.maxSizeBytes&&t.bytes>0&&(this.rotate(t),y.closeSync(y.openSync(t.activePath,"a")),t.bytes=0);}append(t,n){ee(this.config.dir);let o=Buffer.byteLength(n,"utf8");this.config.rotationEnabled&&t.bytes>0&&t.bytes+o>this.config.maxSizeBytes&&this.rotate(t),y.appendFileSync(t.activePath,n,"utf8"),t.bytes+=o;}rotate(t){if(ee(this.config.archiveDir),!y.existsSync(t.activePath)||t.bytes===0){t.bytes=0;return}let n=br(new Date),o=B.join(this.config.archiveDir,`${t.archivePrefix}.${n}`),r=Cr(o,".ndjson");if(y.renameSync(t.activePath,r),this.config.compress)try{let a=`${r}.gz`,s=this.gzip(y.readFileSync(r));y.writeFileSync(a,s),y.rmSync(r);}catch(a){this.warn(`Failed to gzip archive ${r}`,a);}t.bytes=0,wr(this.config.archiveDir,t.archivePrefix,this.config.maxArchives,this.warn);}};function ct(e){return new Te(e)}var Le=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 ut(e){return new Le(ct(e))}function lt(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 Lr(e){let t=String(e??"");return t.includes("createMany")||t.includes("Unknown argument")||t.includes("not supported")||t.includes("is not a function")}function dt(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(u=>r.create({data:u})));return}for(let u of i)await r.create({data:u});}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(u){if(!Lr(u))throw u;a=false,await s(i);}}}}}function pt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function O(e){return typeof e=="string"&&e.length>0?e:null}function vr(e){if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function gt(e){let t=R(e);return {id:randomUUID(),timestamp:vr(e.timestamp),level:e.level,message:e.message,caller:O(e.caller),type:O(e.type),traceId:O(e.traceId),groupId:O(e.groupId),method:O(e.method),path:O(e.path),status:pt(e.status),duration:pt(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 Dr(e){return !!e&&e.type==="prisma"}function xr(e){return !!e&&e.type==="drizzle"}function ft(e){if(Dr(e.adapter))return dt(e.adapter);if(xr(e.adapter))return lt(e.adapter);throw new Error("[Blyp] Unsupported database adapter configuration.")}function Er(e){return new Promise(t=>{setTimeout(t,e);})}var te=class{constructor(t){this.config=t;l(this,"isAsync",true);l(this,"isReady",true);l(this,"warnOnce",k(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=ft(t);}write(t){this.closed||(this.enqueue(gt(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 Er(this.config.delivery.retry.backoffMs);}}}};var ke=class{constructor(){l(this,"isAsync",false);l(this,"isReady",false);}write(t){}async flush(){}async shutdown(){}},Ar=k(new Set);function mt(e){if(e.destination!=="database")return ut(e);let t=e.database;return t?.ready?new te(t):(Ar("database-sink-disabled","[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."),new ke)}function Pr(e){return be(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=Pr(e)[t];if(typeof o=="string"||typeof o=="number")return o}function yt(e){return _r(e,"type")}function ht(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 bt="bun:sqlite";var Ct="node:sqlite";function wt(){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(Ct)};
|
|
16
|
+
const BUN_SQLITE_MODULE = ${JSON.stringify(bt)};
|
|
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 ne=class{constructor(t){this.path=t;l(this,"worker");l(this,"pending",new Map);l(this,"nextId",1);this.worker=new Worker(wt(),{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 St=Symbol("blyp.connector.batch-dispatch"),q=Symbol("blyp.connector.delivery-binder");function $(e){return new Promise(t=>{setTimeout(t,e);})}function Br(e){return e.data===void 0||typeof e.data!="object"||e.data===null||e.data.type!=="client_log"}function Rt(e){return JSON.stringify(e)}function Or(e){try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.jobId!="string"?null:t}catch{return null}}function Tt(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 re=class{constructor(t){this.config=t;l(this,"warnOnce",k(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[q]=="function"&&t[q](this);let n=t[St];n&&this.dispatchers.set(n.dispatchKey,n);}unbindTarget(t){typeof t[q]=="function"&&t[q](null);}enqueue(t,n,o,r){this.closed||!Br(n)||(this.dispatchers.set(o.dispatchKey,o),this.memoryQueue.push({id:We(),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 ne(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 $(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 u=i.attemptCount+1;if(!n.retryable||u>=i.maxAttempts){s.push({id:i.id,connectorType:i.connectorType,connectorTarget:i.connectorTarget,operation:"send",payloadJson:Rt({jobId:i.id,connectorType:i.connectorType,connectorTarget:i.connectorTarget,source:i.source,record:i.record,createdAt:i.createdAt}),attemptCount:u,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 ${u} failed attempt(s). ${n.error??"Connector delivery failed."}`:`[Blyp] Warning: Dropped ${i.connectorType} connector job after ${u} failed attempt(s). ${n.error??"Connector delivery failed."}`);continue}let c=r+ht(u,this.config.retry);if(o){a.push({id:i.id,attemptCount:u,nextAttemptAt:c,lastError:n.error});continue}if(this.durableReady&&this.config.durableSpillStrategy==="after-first-failure"){this.stageDurableJob(i,u,c,n.error);continue}this.memoryQueue.push({...i,attemptCount:u,nextAttemptAt:c});}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=Tt(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=Tt(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=Rt({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=Or(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 u={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},c=n.get(s)??[];c.push(u),n.set(s,c);}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 $(10);if(await this.processDurableQueueOnce(),await this.flushDurableStaging(),await this.durableClient.count().catch(()=>0)===0&&!this.durablePollRunning&&this.durableStaging.length===0)break;await $(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 $(Math.max(t-Date.now(),0));}else await $(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 ve=E,De=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{y.mkdirSync(t,n);}catch{}},writeFileSync:(t,n)=>{Bun.write(t,n);}});l(this,"path",{join:(...t)=>B.join(...t)});l(this,"env",{get:t=>Bun.env[t]});l(this,"cwd",()=>process.cwd());}},xe=class{constructor(){l(this,"type","node");l(this,"isBun",false);l(this,"isNode",true);l(this,"file",{existsSync:t=>y.existsSync(t),mkdirSync:(t,n)=>{y.mkdirSync(t,n);},writeFileSync:(t,n)=>{y.writeFileSync(t,n);}});l(this,"path",{join:(...t)=>B.join(...t)});l(this,"env",{get:t=>process.env[t]});l(this,"cwd",()=>process.cwd());}};function Ir(){return ve.getInstance().isBun?new De:new xe}var kt=Ir();function vt(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 Dt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Nr(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:Dt(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:Dt(n.details),cause:n.cause}}return {message:String(e),code:t,type:typeof e}}function Fr(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 xt(e,t){let n=t.redact??T(),o=performance.now(),r=m(t.initialFields??{},n),a=[],s;t.onCreate?.();let i=(c,p,h)=>(a.push({level:c,message:j(p,n),timestamp:new Date().toISOString(),...vt(p,h)===void 0?{}:{data:m(vt(p,h),n)}}),u),u={set(c){return Object.assign(r,m(c,n)),u},debug(c,...p){return i("debug",c,p)},info(c,...p){return i("info",c,p)},warn(c,...p){return i("warn",c,p)},warning(c,...p){return i("warning",c,p)},error(c,...p){return i("error",c,p)},success(c,...p){return i("success",c,p)},critical(c,...p){return i("critical",c,p)},table(c,p){return i("table",c,p===void 0?[]:[p])},emit(c={}){if(s)return s;let p=m(t.resolveDefaultFields?.()??{},n),h=Fr(c),C=m(Nr(c.error,h),n),ie=c.level??(C?"error":"info"),D=m({...p,...r,groupId:e,timestamp:new Date().toISOString(),level:ie,duration:Math.round(performance.now()-o),...typeof h=="number"?{status:h}:{},...a.length>0?{events:[...a]}:{},...C?{error:C}:{}},n);return t.write(D,j(c.message??"structured_log",n)),s=D,t.onEmit?.(D),D}};return u}var Nt=Symbol("blyp.logger.factory"),At={success:25,info:30,debug:35,table:37,warning:40,error:50,critical:60},Pt={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warn",table:"debug"},zr="\x1B[35m",jr="\x1B[0m";function W(e){return yt(e)==="client_log"}function Ur(){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 qr(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function $r(){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 Wr(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,send:()=>{},flush:async()=>{}}}function Kr(e){return {name:e,enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",endpoint:void 0,status:"missing",send:()=>{},flush:async()=>{}}}function Hr(){return {get:e=>Kr(e),getAutoForwardTargets:()=>[],send:()=>{},flush:async()=>{}}}function Qr(e){return e.connectors?.betterstack?.enabled?A("betterstack",["@logtail/node","@sentry/node"],"../connectors/betterstack/sender").createBetterStackSender(e):Ur()}function Jr(e){return e.connectors?.databuddy?.enabled?A("databuddy",["@databuddy/sdk"],"../connectors/databuddy/sender").createDatabuddySender(e):qr()}function Gr(e){return e.connectors?.posthog?.enabled?A("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/posthog/sender").createPostHogSender(e):$r()}function Vr(e){return e.connectors?.sentry?.enabled?A("sentry",["@sentry/node"],"../connectors/sentry/sender").createSentrySender(e):Wr()}function Xr(e){return e.connectors?.otlp?.some(t=>t.enabled)?A("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/otlp/sender").createOTLPRegistry(e):Hr()}function Yr(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 Zr(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=Yr(e);return n?{hidden:false,value:n}:{hidden:true}}return {hidden:false,value:e}}function eo(e){if(e.pretty){let n=Fe()({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} ${zr}${s}${jr}`:a}});return Et({level:e.level,customLevels:At},n)}return Et({level:e.level,customLevels:At})}function to(e){let t=e[Nt];if(!t)throw new Error("Unsupported Blyp logger instance");return t}function no(e,t,n={}){let o=to(e);return xt(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 _t(e,t){if(!W(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Mt(e,t){if(!W(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Bt(e,t){if(!W(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function Ot(e,t){if(!W(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function It(e,t){if(!W(t))for(let n of e.getAutoForwardTargets())n.send(t,{source:"server",warnIfUnavailable:true});}function Ae(e,t,n,o,r,a,s,i,u,c={},p="root"){let h=Object.keys(c).length>0?e.child(c):e,C=(g,d,F,J=p)=>{if(J==="root"&&pe())return;let f=at(g,d,F,c,u),se=f.message,z={caller:f.caller},G=Zr(f.data);!G.hidden&&G.value!==void 0&&(z.data=G.value);let Ie=Pt[g],ce=h;(ce[Ie]??ce.info??((fo,mo)=>{})).call(h,z,se),t.write(f),Mt(o,f),Bt(r,f),_t(a,f),Ot(s,f),It(i,f);},ie=(g,d,F="structured-flush")=>{let J=st(g.level),f=it(J,d,g,c,u),se=Pt[J],z=h;(z[se]??z.info??((Ie,ce)=>{})).call(h,{caller:f.caller,...f},f.message),(F!=="root"||!pe())&&t.write(f),Mt(o,f),Bt(r,f),_t(a,f),Ot(s,f),It(i,f);},D={success:(g,...d)=>{C("success",g,d);},critical:(g,...d)=>{C("critical",g,d);},warning:(g,...d)=>{C("warning",g,d);},info:(g,...d)=>{C("info",g,d);},debug:(g,...d)=>{C("debug",g,d);},error:(g,...d)=>{C("error",g,d);},warn:(g,...d)=>{C("warn",g,d);},table:(g,d)=>{d&&typeof d=="object"&&kt.env.get("NODE_ENV")!=="production"&&(console.log("TABLE:",g),console.table(m(d,u))),C("table",g,d===void 0?[]:[d]);},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:(g,d)=>no(D,g,{initialFields:d}),child:g=>{let d={...c,...g};return Ae(e,t,n,o,r,a,s,i,u,d,p)},[Nt]:{bindings:c,betterstack:o,databuddy:r,posthog:a,sentry:s,otlp:i,redact:u,sink:t,create:(g,d=c)=>Ae(e,t,n,o,r,a,s,i,u,d,g),writeStructured:(g,d,F="structured-flush")=>{ie(g,d,F);}}};return D}var Ee=null;function ro(e){if(Ee)return Ee;let t=et(e),n=eo(t),o=mt(t),r=Qr(t),a=Jr(t),s=Gr(t),i=Vr(t),u=Xr(t),c=t.connectors.delivery.enabled?new re(t.connectors.delivery):null;if(c){c.bindTarget(r),c.bindTarget(a),c.bindTarget(s),c.bindTarget(i);for(let h of u.getAutoForwardTargets())c.bindTarget(h);}let p=Ae(n,o,c,r,a,s,i,u,t.redact);return (Ee=p),p}var Ft=ro();var oo=new TextEncoder;function ae(e){return oo.encode(e).length}function ao(e){if(!e||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function w(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=>w(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";if(t.add(e),!ao(e)){let n=e.constructor?.name;return n?`[${n}]`:"[Object]"}return Object.fromEntries(Object.entries(e).map(([n,o])=>[n,w(o,t)]))}return String(e)}function zt(e,t){if(t.length===0)return e;let n=w(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 jt(e,t){let n=w(e);if(t<=0)return {value:"[Truncated]",truncated:true};if(typeof n=="string"){if(ae(n)<=t)return {value:n,truncated:false};let a=n;for(;a.length>0&&ae(`${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||ae(o)<=t)return {value:n,truncated:false};let r=o;for(;r.length>0&&ae(`${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}}var Pe={input:false,output:false,toolInputs:false,toolOutputs:false,reasoning:false,streamEvents:false,streamChunks:false,rawProviderPayload:false},K={providerOptions:false,requestPaths:[],responsePaths:[],metadataPaths:[],toolNames:[]},_e={maxContentBytes:16384,maxEvents:200,maxToolCalls:50};function io(){return `ai_${crypto.randomUUID().replace(/-/g,"").slice(0,16)}`}function Me(){return new Date().toISOString()}function qt(e){return w(e)}function $t(e){try{return JSON.parse(e)}catch{return e}}function Wt(e){if(!e)return;let t=e.inputTokens.total,n=e.outputTokens.total,o=(t??0)+(n??0)||void 0;return {inputTokens:t,outputTokens:n,totalTokens:o,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function Kt(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e;if(typeof t.unified=="string")return t.unified;if(typeof t.raw=="string")return t.raw}}function Ut(e,t){return e.filter(n=>n.type===t).map(n=>n.text).join("")}function so(e){let t=new Map;for(let n of e){if(n.type==="tool-call"){t.set(n.toolCallId,{id:n.toolCallId,name:n.toolName,input:$t(n.input),status:"started"});continue}if(n.type==="tool-result"){let o=t.get(n.toolCallId);t.set(n.toolCallId,{id:n.toolCallId,name:n.toolName,input:o?.input,output:n.result,status:n.isError?"failed":"completed",error:n.isError?n.result:void 0});}}return [...t.values()]}function co(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 {logger:e.logger,provider:e.provider,operation:e.operation,metadata:{...e.metadata??{}},capture:{...Pe,...e.capture??{},streamEvents:e.capture?.streamEvents??e.capture?.streamChunks??Pe.streamEvents,streamChunks:e.capture?.streamChunks??e.capture?.streamEvents??Pe.streamChunks},exclude:{providerOptions:e.exclude?.providerOptions??K.providerOptions,requestPaths:[...e.exclude?.requestPaths??K.requestPaths],responsePaths:[...e.exclude?.responsePaths??K.responsePaths],metadataPaths:[...e.exclude?.metadataPaths??K.metadataPaths],toolNames:[...e.exclude?.toolNames??K.toolNames]},limits:{maxContentBytes:e.limits?.maxContentBytes??_e.maxContentBytes,maxEvents:e.limits?.maxEvents??_e.maxEvents,maxToolCalls:e.limits?.maxToolCalls??_e.maxToolCalls},hooks:e.hooks??{}}}function Be(e){let t=e.config.logger??ze()??Ft,n=io(),o=Me(),r={traceId:n,provider:e.model.provider,model:e.model.modelId,callType:e.callType,logger:t,params:e.params,options:e.config,operation:e.config.operation??(e.callType==="stream"?"ai.stream":"ai.generate"),metadata:{...e.config.metadata},startedAt:o,startedAtMs:performance.now(),toolCalls:[],toolCallMap:new Map,events:[],streamChunks:[],truncated:false,capture:{...e.config.capture}},a={traceId:n,operation:r.operation,provider:r.provider,model:r.model,callType:r.callType,logger:t,params:e.params,metadata:r.metadata,startedAt:o,get usage(){return r.usage},get finishReason(){return r.finishReason},get streamedText(){return r.streamedText},get outputText(){return r.outputText},get toolCalls(){return r.toolCalls.length>0?r.toolCalls:void 0},get error(){return r.error},setMetadata(s){Object.assign(r.metadata,s);},disableCapture(s){r.capture[s]=false;}};return {state:r,context:a}}async function N(e,t){if(e)try{await e(...t);}catch(n){console.warn("[Blyp] AI middleware hook failed.",qt(n));}}async function S(e,t,n){e.events.length<e.options.limits.maxEvents?e.events.push({...n,timestamp:n.timestamp??Me()}):e.truncated=true,await N(e.options.hooks.onEvent,[e.events[e.events.length-1],t]);}function I(e,t){return jt(e,t)}function uo(e,t){let n=w(e);return t.options.exclude.providerOptions&&delete n.providerOptions,n}function Qt(e,t){e.usage=Wt(t.usage),e.finishReason=Kt(t.finishReason),e.outputText=Ut(t.content,"text")||void 0;let n=Ut(t.content,"reasoning");n&&(e.reasoningText=n);for(let o of so(t.content))H(e,o);}function H(e,t){let n=t.id??`${t.name}:${e.toolCalls.length}`,o=e.toolCallMap.get(n),r={...o,...t};if(!o&&e.toolCalls.length>=e.options.limits.maxToolCalls){e.truncated=true;return}if(!o)e.toolCalls.push(r);else {let a=e.toolCalls.findIndex((s,i)=>(s.id??`${s.name}:${i}`)===n);a>=0&&(e.toolCalls[a]=r);}e.toolCallMap.set(n,r);}async function Jt(e,t,n){let o=Me();switch(e.firstChunkAtMs===void 0&&n.type!=="stream-start"&&(e.firstChunkAtMs=performance.now(),await S(e,t,{type:"ai.first_chunk",timestamp:o})),n.type){case "text-delta":e.streamedText=`${e.streamedText??""}${n.delta}`,e.capture.streamChunks&&(e.streamChunks.push(n.delta),await S(e,t,{type:"ai.chunk",timestamp:o,data:{kind:"text",delta:n.delta}}));break;case "reasoning-delta":e.reasoningText=`${e.reasoningText??""}${n.delta}`,e.capture.streamChunks&&(e.streamChunks.push({reasoning:n.delta}),await S(e,t,{type:"ai.chunk",timestamp:o,data:{kind:"reasoning",delta:n.delta}}));break;case "tool-input-start":{let r={id:n.id,name:n.toolName,startedAt:o,status:"started"};H(e,r),await S(e,t,{type:"ai.tool_call.start",timestamp:o,data:{toolName:n.toolName,toolCallId:n.id}});break}case "tool-input-delta":{let r=e.toolCallMap.get(n.id);if(r){let a=`${typeof r.input=="string"?r.input:""}${n.delta}`;H(e,{...r,input:a});}break}case "tool-call":{let r=e.toolCallMap.get(n.toolCallId);H(e,{id:n.toolCallId,name:n.toolName,startedAt:r?.startedAt??o,input:$t(n.input),status:r?.status??"started"});break}case "tool-result":{let r=e.toolCallMap.get(n.toolCallId);H(e,{id:n.toolCallId,name:n.toolName,input:r?.input,output:n.result,startedAt:r?.startedAt,finishedAt:o,durationMs:r?.startedAt?Math.max(0,Math.round(Date.parse(o)-Date.parse(r.startedAt))):void 0,status:n.isError?"failed":"completed",error:n.isError?n.result:void 0}),await S(e,t,{type:"ai.tool_call.result",timestamp:o,data:{toolName:n.toolName,toolCallId:n.toolCallId,status:n.isError?"failed":"completed"}});break}case "finish":e.usage=Wt(n.usage),e.finishReason=Kt(n.finishReason);break;case "error":e.error=n.error,await S(e,t,{type:"ai.error",timestamp:o,data:{error:w(n.error)}});break;case "raw":e.capture.streamChunks&&e.streamChunks.push({raw:w(n.rawValue)});break;}}async function Q(e,t,n){if(e.emitted)return;e.emitted=true,n?.error!==void 0&&(e.error=n.error,await S(e,t,{type:"ai.error",data:{error:w(n.error)}}),await N(e.options.hooks.onError,[t])),await S(e,t,{type:"ai.finish"}),e.error||await N(e.options.hooks.onFinish,[t]);let o=zt(e.metadata,e.options.exclude.metadataPaths),r={sdk:"ai-sdk",provider:e.provider,model:e.model,operation:e.operation,callType:e.callType,streamed:e.callType==="stream",finishReason:e.finishReason,toolCallCount:e.toolCalls.length,metadata:o,...e.usage??{}},a=Math.max(0,Math.round(performance.now()-e.startedAtMs));if(r.msToFinish=a,e.firstChunkAtMs!==void 0&&(r.msToFirstChunk=Math.max(0,Math.round(e.firstChunkAtMs-e.startedAtMs))),typeof e.usage?.outputTokens=="number"&&e.usage.outputTokens>0&&a>0&&(r.tokensPerSecond=Number((e.usage.outputTokens/a*1e3).toFixed(2))),e.capture.input){let i=I(uo(e.params,e),e.options.limits.maxContentBytes);r.input=i.value,e.truncated||(e.truncated=i.truncated);}if(e.capture.output){let i=e.callType==="stream"?e.streamedText??e.outputText:e.outputText??e.output;if(i!==void 0){let u=I(i,e.options.limits.maxContentBytes);r.output=u.value,e.truncated||(e.truncated=u.truncated);}}if(e.capture.reasoning&&e.reasoningText){let i=I(e.reasoningText,e.options.limits.maxContentBytes);r.reasoning=i.value,e.truncated||(e.truncated=i.truncated);}if(e.capture.streamChunks&&e.streamChunks.length>0){let i=I(e.streamChunks,e.options.limits.maxContentBytes);r.streamChunks=i.value,e.truncated||(e.truncated=i.truncated);}let s=e.toolCalls.filter(i=>!e.options.exclude.toolNames.includes(i.name)).map(i=>{let u={id:i.id,name:i.name,startedAt:i.startedAt,finishedAt:i.finishedAt,durationMs:i.durationMs,status:i.status};if(i.error!==void 0&&(u.error=w(i.error)),e.capture.toolInputs&&i.input!==void 0){let c=I(i.input,e.options.limits.maxContentBytes);u.input=c.value,e.truncated||(e.truncated=c.truncated);}if(e.capture.toolOutputs&&i.output!==void 0){let c=I(i.output,e.options.limits.maxContentBytes);u.output=c.value,e.truncated||(e.truncated=c.truncated);}return u});if(s.length>0&&(r.toolCalls=s),e.error!==void 0){let{errorType:i,errorCode:u}=co(e.error);i&&(r.errorType=i),u!==void 0&&(r.errorCode=u);}e.truncated&&(r.truncated=true);try{e.logger.createStructuredLog(e.traceId,{type:"ai_trace",ai:r,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));}}function Oe(e={}){let t=Ht(e);return {specificationVersion:"v3",async wrapGenerate({doGenerate:n,model:o,params:r}){let{state:a,context:s}=Be({model:o,params:r,callType:"generate",config:t});await S(a,s,{type:"ai.start"}),await N(t.hooks.onStart,[s]);try{let i=await n();return Qt(a,i),await Q(a,s),i}catch(i){throw await Q(a,s,{error:i}),i}},async wrapStream({doStream:n,model:o,params:r}){let{state:a,context:s}=Be({model:o,params:r,callType:"stream",config:t});await S(a,s,{type:"ai.start"}),await N(t.hooks.onStart,[s]);try{let i=await n(),u=i.stream.pipeThrough(new TransformStream({async transform(c,p){await Jt(a,s,c),p.enqueue(c);},async flush(){await Q(a,s);}}));return {...i,stream:u}}catch(i){throw await Q(a,s,{error:i}),i}}}}function po(e,t={}){return wrapLanguageModel({model:e,middleware:Oe(t)})}
|
|
701
|
+
export{Oe as blypMiddleware,po as blypModel};
|