@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.
Files changed (230) hide show
  1. package/README.md +273 -14
  2. package/STABILITY.md +56 -0
  3. package/dist/ai/anthropic/index.d.ts +3 -0
  4. package/dist/ai/anthropic/normalize.d.ts +9 -0
  5. package/dist/ai/anthropic/stream.d.ts +3 -0
  6. package/dist/ai/anthropic/wrap.d.ts +13 -0
  7. package/dist/ai/anthropic.js +701 -0
  8. package/dist/ai/anthropic.mjs +701 -0
  9. package/dist/ai/fetch.js +701 -0
  10. package/dist/ai/fetch.mjs +701 -0
  11. package/dist/ai/openai/index.d.ts +3 -0
  12. package/dist/ai/openai/normalize.d.ts +10 -0
  13. package/dist/ai/openai/stream.d.ts +3 -0
  14. package/dist/ai/openai/wrap.d.ts +24 -0
  15. package/dist/ai/openai.js +701 -0
  16. package/dist/ai/openai.mjs +701 -0
  17. package/dist/ai/shared/fetch.d.ts +5 -0
  18. package/dist/ai/shared/index.d.ts +2 -0
  19. package/dist/ai/shared/normalize.d.ts +17 -0
  20. package/dist/ai/shared/redaction.d.ts +6 -0
  21. package/dist/ai/shared/stream.d.ts +7 -0
  22. package/dist/ai/shared/trace.d.ts +116 -0
  23. package/dist/ai/shared/types.d.ts +161 -0
  24. package/dist/ai/shared.js +701 -0
  25. package/dist/ai/shared.mjs +701 -0
  26. package/dist/ai/vercel/index.d.ts +3 -0
  27. package/dist/ai/vercel/middleware.d.ts +3 -0
  28. package/dist/ai/vercel/model.d.ts +3 -0
  29. package/dist/ai/vercel.js +701 -0
  30. package/dist/ai/vercel.mjs +701 -0
  31. package/dist/astro.js +701 -0
  32. package/dist/astro.mjs +701 -0
  33. package/dist/client.js +1 -1132
  34. package/dist/client.mjs +1 -1125
  35. package/dist/connectors/betterstack.js +9 -1508
  36. package/dist/connectors/betterstack.mjs +9 -1483
  37. package/dist/connectors/databuddy/index.d.ts +7 -0
  38. package/dist/connectors/databuddy/sender.d.ts +5 -0
  39. package/dist/connectors/databuddy.js +9 -0
  40. package/dist/connectors/databuddy.mjs +9 -0
  41. package/dist/connectors/delivery/backoff.d.ts +2 -0
  42. package/dist/connectors/delivery/manager.d.ts +44 -0
  43. package/dist/connectors/delivery/queue-path.d.ts +1 -0
  44. package/dist/connectors/delivery/sqlite-adapter-bun.d.ts +1 -0
  45. package/dist/connectors/delivery/sqlite-adapter-node.d.ts +1 -0
  46. package/dist/connectors/delivery/sqlite-client.d.ts +37 -0
  47. package/dist/connectors/delivery/sqlite-worker.d.ts +1 -0
  48. package/dist/connectors/delivery/studio-queue.d.ts +12 -0
  49. package/dist/connectors/delivery/types.d.ts +98 -0
  50. package/dist/connectors/otlp/index.d.ts +1 -0
  51. package/dist/connectors/otlp.js +9 -1347
  52. package/dist/connectors/otlp.mjs +9 -1344
  53. package/dist/connectors/posthog/properties.d.ts +4 -0
  54. package/dist/connectors/posthog/sender.d.ts +0 -1
  55. package/dist/connectors/posthog.js +10 -1503
  56. package/dist/connectors/posthog.mjs +10 -1498
  57. package/dist/connectors/sentry.js +9 -1356
  58. package/dist/connectors/sentry.mjs +9 -1333
  59. package/dist/core/config.d.ts +7 -2
  60. package/dist/core/log-record.d.ts +5 -4
  61. package/dist/core/logger.d.ts +5 -0
  62. package/dist/core/optional-module.d.ts +1 -0
  63. package/dist/core/pino-pretty-loader.d.ts +4 -0
  64. package/dist/database.js +1 -24
  65. package/dist/database.mjs +1 -21
  66. package/dist/elysia.js +621 -4100
  67. package/dist/elysia.mjs +622 -4073
  68. package/dist/expo.js +1 -719
  69. package/dist/expo.mjs +1 -717
  70. package/dist/express.js +616 -4085
  71. package/dist/express.mjs +616 -4056
  72. package/dist/fastify.js +618 -4104
  73. package/dist/fastify.mjs +618 -4075
  74. package/dist/frameworks/astro/index.d.ts +2 -0
  75. package/dist/frameworks/astro/logger.d.ts +3 -0
  76. package/dist/frameworks/elysia/index.d.ts +1 -1
  77. package/dist/frameworks/elysia/logger.d.ts +2 -35
  78. package/dist/frameworks/nestjs/helpers.d.ts +2 -0
  79. package/dist/frameworks/nitro/index.d.ts +2 -0
  80. package/dist/frameworks/nitro/logger.d.ts +6 -0
  81. package/dist/frameworks/nuxt/index.d.ts +2 -0
  82. package/dist/frameworks/nuxt/logger.d.ts +3 -0
  83. package/dist/frameworks/react-router/index.d.ts +2 -0
  84. package/dist/frameworks/react-router/logger.d.ts +3 -0
  85. package/dist/frameworks/shared/h3.d.ts +19 -0
  86. package/dist/frameworks/shared/http.d.ts +3 -2
  87. package/dist/frameworks/shared/index.d.ts +2 -1
  88. package/dist/frameworks/shared/logger.d.ts +2 -0
  89. package/dist/frameworks/shared/request-context.d.ts +2 -0
  90. package/dist/frameworks/shared/trace.d.ts +6 -0
  91. package/dist/hono.js +624 -4079
  92. package/dist/hono.mjs +626 -4053
  93. package/dist/index.d.ts +57 -17
  94. package/dist/index.js +616 -6494
  95. package/dist/index.mjs +619 -6410
  96. package/dist/nestjs.js +626 -4574
  97. package/dist/nestjs.mjs +622 -4542
  98. package/dist/nextjs.js +625 -4107
  99. package/dist/nextjs.mjs +627 -4081
  100. package/dist/nitro.js +701 -0
  101. package/dist/nitro.mjs +701 -0
  102. package/dist/nuxt.js +701 -0
  103. package/dist/nuxt.mjs +701 -0
  104. package/dist/react-router.js +701 -0
  105. package/dist/react-router.mjs +701 -0
  106. package/dist/shared/redaction.d.ts +17 -0
  107. package/dist/standalone.js +606 -3258
  108. package/dist/standalone.mjs +611 -3234
  109. package/dist/sveltekit.js +625 -4106
  110. package/dist/sveltekit.mjs +626 -4079
  111. package/dist/tanstack-start.js +624 -4105
  112. package/dist/tanstack-start.mjs +626 -4079
  113. package/dist/types/connectors/databuddy.d.ts +52 -0
  114. package/dist/types/core/config.d.ts +89 -0
  115. package/dist/types/core/logger.d.ts +5 -0
  116. package/dist/types/core/structured-log.d.ts +2 -0
  117. package/dist/types/database.d.ts +1 -0
  118. package/dist/types/frameworks/astro.d.ts +33 -0
  119. package/dist/types/frameworks/client.d.ts +2 -0
  120. package/dist/types/frameworks/elysia.d.ts +2 -0
  121. package/dist/types/frameworks/express.d.ts +1 -0
  122. package/dist/types/frameworks/fastify.d.ts +1 -0
  123. package/dist/types/frameworks/hono.d.ts +1 -0
  124. package/dist/types/frameworks/http.d.ts +1 -0
  125. package/dist/types/frameworks/nestjs.d.ts +2 -0
  126. package/dist/types/frameworks/nextjs.d.ts +1 -0
  127. package/dist/types/frameworks/nitro.d.ts +63 -0
  128. package/dist/types/frameworks/nuxt.d.ts +12 -0
  129. package/dist/types/frameworks/react-router.d.ts +35 -0
  130. package/dist/types/frameworks/request-context.d.ts +1 -0
  131. package/dist/types/frameworks/shared.d.ts +28 -1
  132. package/dist/types/frameworks/standalone.d.ts +3 -2
  133. package/dist/types/frameworks/sveltekit.d.ts +1 -0
  134. package/dist/types/frameworks/tanstack-start.d.ts +9 -3
  135. package/dist/types/frameworks/workers.d.ts +3 -0
  136. package/dist/types/shared/client-log.d.ts +2 -1
  137. package/dist/workers.js +2 -626
  138. package/dist/workers.mjs +2 -623
  139. package/package.json +273 -143
  140. package/dist/client.js.map +0 -1
  141. package/dist/client.mjs.map +0 -1
  142. package/dist/connectors/betterstack.js.map +0 -1
  143. package/dist/connectors/betterstack.mjs.map +0 -1
  144. package/dist/connectors/otlp.js.map +0 -1
  145. package/dist/connectors/otlp.mjs.map +0 -1
  146. package/dist/connectors/posthog.js.map +0 -1
  147. package/dist/connectors/posthog.mjs.map +0 -1
  148. package/dist/connectors/sentry.js.map +0 -1
  149. package/dist/connectors/sentry.mjs.map +0 -1
  150. package/dist/database.js.map +0 -1
  151. package/dist/database.mjs.map +0 -1
  152. package/dist/elysia.js.map +0 -1
  153. package/dist/elysia.mjs.map +0 -1
  154. package/dist/expo.js.map +0 -1
  155. package/dist/expo.mjs.map +0 -1
  156. package/dist/express.js.map +0 -1
  157. package/dist/express.mjs.map +0 -1
  158. package/dist/fastify.js.map +0 -1
  159. package/dist/fastify.mjs.map +0 -1
  160. package/dist/hono.js.map +0 -1
  161. package/dist/hono.mjs.map +0 -1
  162. package/dist/index.js.map +0 -1
  163. package/dist/index.mjs.map +0 -1
  164. package/dist/nestjs.js.map +0 -1
  165. package/dist/nestjs.mjs.map +0 -1
  166. package/dist/nextjs.js.map +0 -1
  167. package/dist/nextjs.mjs.map +0 -1
  168. package/dist/standalone.js.map +0 -1
  169. package/dist/standalone.mjs.map +0 -1
  170. package/dist/sveltekit.js.map +0 -1
  171. package/dist/sveltekit.mjs.map +0 -1
  172. package/dist/tanstack-start.js.map +0 -1
  173. package/dist/tanstack-start.mjs.map +0 -1
  174. package/dist/workers.js.map +0 -1
  175. package/dist/workers.mjs.map +0 -1
  176. package/exports/client.js +0 -3
  177. package/exports/client.mjs +0 -3
  178. package/exports/connectors/betterstack.js +0 -1
  179. package/exports/connectors/betterstack.mjs +0 -1
  180. package/exports/connectors/otlp.js +0 -1
  181. package/exports/connectors/otlp.mjs +0 -1
  182. package/exports/connectors/posthog.js +0 -1
  183. package/exports/connectors/posthog.mjs +0 -1
  184. package/exports/connectors/sentry.js +0 -1
  185. package/exports/connectors/sentry.mjs +0 -1
  186. package/exports/database.js +0 -1
  187. package/exports/database.mjs +0 -1
  188. package/exports/expo.js +0 -1
  189. package/exports/expo.mjs +0 -1
  190. package/exports/frameworks/elysia.js +0 -1
  191. package/exports/frameworks/elysia.mjs +0 -1
  192. package/exports/frameworks/express.js +0 -1
  193. package/exports/frameworks/express.mjs +0 -1
  194. package/exports/frameworks/fastify.js +0 -1
  195. package/exports/frameworks/fastify.mjs +0 -1
  196. package/exports/frameworks/hono.js +0 -1
  197. package/exports/frameworks/hono.mjs +0 -1
  198. package/exports/frameworks/nestjs.js +0 -1
  199. package/exports/frameworks/nestjs.mjs +0 -1
  200. package/exports/frameworks/nextjs.js +0 -1
  201. package/exports/frameworks/nextjs.mjs +0 -1
  202. package/exports/frameworks/standalone.js +0 -1
  203. package/exports/frameworks/standalone.mjs +0 -1
  204. package/exports/frameworks/sveltekit.js +0 -1
  205. package/exports/frameworks/sveltekit.mjs +0 -1
  206. package/exports/frameworks/tanstack-start.js +0 -1
  207. package/exports/frameworks/tanstack-start.mjs +0 -1
  208. package/exports/workers.js +0 -1
  209. package/exports/workers.mjs +0 -1
  210. package/types/client.d.ts +0 -34
  211. package/types/connectors/betterstack.d.ts +0 -1
  212. package/types/connectors/otlp.d.ts +0 -1
  213. package/types/connectors/posthog.d.ts +0 -1
  214. package/types/connectors/sentry.d.ts +0 -1
  215. package/types/database.d.ts +0 -1
  216. package/types/expo.d.ts +0 -17
  217. package/types/frameworks/client.d.ts +0 -160
  218. package/types/frameworks/elysia.d.ts +0 -1
  219. package/types/frameworks/expo.d.ts +0 -50
  220. package/types/frameworks/express.d.ts +0 -1
  221. package/types/frameworks/fastify.d.ts +0 -1
  222. package/types/frameworks/hono.d.ts +0 -1
  223. package/types/frameworks/nestjs.d.ts +0 -1
  224. package/types/frameworks/nextjs.d.ts +0 -1
  225. package/types/frameworks/standalone.d.ts +0 -1
  226. package/types/frameworks/sveltekit.d.ts +0 -1
  227. package/types/frameworks/tanstack-start.d.ts +0 -1
  228. package/types/frameworks/workers.d.ts +0 -115
  229. package/types/index.d.ts +0 -1
  230. package/types/workers.d.ts +0 -13
package/dist/hono.js CHANGED
@@ -1,4156 +1,701 @@
1
- 'use strict';
1
+ 'use strict';var zod=require('zod'),S=require('fs'),jiti=require('jiti'),U=require('path'),tn=require('os'),fflate=require('fflate'),rr=require('pino'),module$1=require('module'),async_hooks=require('async_hooks'),crypto=require('crypto'),worker_threads=require('worker_threads');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var S__default=/*#__PURE__*/_interopDefault(S);var U__default=/*#__PURE__*/_interopDefault(U);var tn__default=/*#__PURE__*/_interopDefault(tn);var rr__default=/*#__PURE__*/_interopDefault(rr);var Er=Object.defineProperty;var kr=(e,t,r)=>t in e?Er(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var d=(e,t,r)=>kr(e,typeof t!="symbol"?t+"":t,r);function ne(e){return `${{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[33m",PATCH:"\x1B[34m",DELETE:"\x1B[31m"}[e.toUpperCase()]||""}${e}\x1B[0m`}function oe(e){let t="\x1B[0m";return e>=500?`\x1B[31m${e}${t}`:e>=400?`\x1B[33m${e}${t}`:e>=300?`\x1B[36m${e}${t}`:e>=200?`\x1B[32m${e}${t}`:`\x1B[37m${e}${t}`}function dt(e){return {GET:"\u2192",POST:"\u2191",PUT:"\u21D1",PATCH:"\u2197",DELETE:"\u2715"}[e.toUpperCase()]||"\u2022"}function ie(e){let t="\x1B[0m";return e<100?`\x1B[32m${e}ms${t}`:e<300?`\x1B[33m${e}ms${t}`:e<1e3?`\x1B[31m${e}ms${t}`:`\x1B[41m\x1B[37m${e}ms${t}`}function ae(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let r=e;return r.cause!==void 0&&(t.cause=x(r.cause)),t}function x(e,t=new WeakSet){if(e instanceof Error)return ae(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e==null)return e;if(Array.isArray(e))return e.map(r=>x(r,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let r={};for(let[o,n]of Object.entries(e))r[o]=x(n,t);return t.delete(e),r}return e}function ve(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=x(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var pt="[REDACTED]",_r=["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"],Pr=["authorization","cookie","set-cookie","x-api-key","x-auth-token"],Ar=[{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}],Br=/\b(?:\d[ -]*?){16}\b/g;function gt(e){let t=new Set,r=[];for(let o of e)typeof o!="string"||o.length===0||t.has(o)||(t.add(o),r.push(o));return r}function Ir(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function Or(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Nr(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function Mr(e){return new Set([...Pr,...e.keys.map(t=>t.toLowerCase())])}function Fr(e){return e.split(".").filter(Boolean)}function Te(e,t,r=0,o=0){if(r===e.length)return o===t.length;let n=e[r];if(n==="**"){if(r===e.length-1)return true;for(let i=o;i<=t.length;i+=1)if(Te(e,t,r+1,i))return true;return false}return o>=t.length||n!=="*"&&n!==t[o]?false:Te(e,t,r+1,o+1)}function zr(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(r=>Te(Fr(r),e))}function qr(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let r=0,o=false;for(let n=t.length-1;n>=0;n-=1){let i=Number(t[n]);o&&(i*=2,i>9&&(i-=9)),r+=i,o=!o;}return r%10===0}function ce(e,t,r){if(r||t.disablePatternScanning)return e;let o=e;for(let{type:n,pattern:i}of Ar)o=o.replace(i,`[REDACTED:${n}]`);o=o.replace(Br,n=>qr(n)?"[REDACTED:card]":n);for(let n of t.patterns)o=o.replace(Ir(n),"[REDACTED:pattern]");return o}function se(e,t,r,o){if(typeof e=="string")return ce(e,t,!!o.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((i,a)=>se(i,t,r,{path:[...o.path,String(a)],skipPatternScanning:o.skipPatternScanning}));if(!Or(e))return e;let n={};for(let[i,a]of Object.entries(e)){let s=[...o.path,i];if(r.has(i.toLowerCase())||zr(s,t)){if(a==null||typeof a=="string"||typeof a=="number"||typeof a=="boolean"){n[i]=pt;continue}n[i]=se(a,t,r,{path:s,skipPatternScanning:o.skipPatternScanning});continue}n[i]=se(a,t,r,{path:s,skipPatternScanning:o.skipPatternScanning});}return n}function T(e,t){return {keys:gt([..._r,...e?.keys??[],...t?.keys??[]]),paths:gt([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(r=>r instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function b(e,t,r={path:[]}){let o=x(e);return se(o,t,Nr(t),r)}function B(e,t){return typeof e=="string"?ce(e,t,false):ve(b(e,t))}function jr(e){if(!e)return {};if(e instanceof Headers){let t={};return e.forEach((r,o)=>{t[o]=r;}),t}if(typeof e.entries=="function"){let t={};for(let[r,o]of e.entries())t[r]=o;return t}return typeof e.get=="function"?{}:{...e}}function ft(e,t){let r=jr(e),o=Mr(t),n={};for(let[i,a]of Object.entries(r)){if(o.has(i.toLowerCase())){n[i]=pt;continue}if(Array.isArray(a)){n[i]=a.map(s=>ce(s,t,false));continue}n[i]=typeof a=="string"?ce(a,t,false):a;}return n}function C(e,t){if(!e)return;if(e instanceof Headers||typeof e.get=="function")return e.get(t)??e.get(t.toLowerCase())??void 0;let r=e,o=r[t]??r[t.toLowerCase()];return Array.isArray(o)?o[0]:o}function $r(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>t.match(/for="?(\[[^\]]+\]|[^;,\s"]+)/i)?.[1]?.replace(/^"|"$/g,"")??"").map(t=>t.replace(/^\[|\]$/g,"")).filter(Boolean):[]}function Ur(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Hr(e){if(e.startsWith("[")){let t=e.indexOf("]");return t>=0?e.slice(1,t):e}return e.replace(/:\d+$/,"")}function Wr(e){return /edg\//i.test(e)?"Edge":/opr\//i.test(e)||/opera/i.test(e)?"Opera":/chrome\//i.test(e)&&!/edg\//i.test(e)?"Chrome":/firefox\//i.test(e)?"Firefox":/safari\//i.test(e)&&!/chrome\//i.test(e)?"Safari":/curl\//i.test(e)?"curl":/postmanruntime/i.test(e)?"Postman":"Unknown"}function Qr(e){return /windows/i.test(e)?"Windows":/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/mac os x|macintosh/i.test(e)?"macOS":/linux/i.test(e)?"Linux":"Unknown"}function Jr(e){return e?/bot|crawler|spider|curl|wget|postmanruntime/i.test(e)?"bot":/ipad|tablet/i.test(e)?"tablet":/mobi|iphone|android/i.test(e)?"mobile":"desktop":"unknown"}function I(e,t="/"){if(!e)return t;if(e.startsWith("http://")||e.startsWith("https://"))try{return new URL(e).pathname||t}catch{return t}if(e.startsWith("/")){let r=e.indexOf("?");return r>=0?e.slice(0,r):e}try{return new URL(e,"http://localhost").pathname||t}catch{return t}}function xe(e,t,r){return {method:e,url:t,headers:r}}function De(e,t,r=T()){let o=t??I(e.url),n=(()=>{try{return new URL(e.url)}catch{try{return new URL(o,"http://localhost")}catch{return null}}})(),i=C(e.headers,"x-forwarded-host")??C(e.headers,"host")??n?.host??void 0,a=i?Hr(i):n?.hostname,s=i?.match(/:(\d+)$/)?.[1]??(n?.port||void 0),l=Ur(C(e.headers,"x-forwarded-for")),u=$r(C(e.headers,"forwarded")),c=[C(e.headers,"cf-connecting-ip"),C(e.headers,"true-client-ip"),C(e.headers,"fly-client-ip"),C(e.headers,"x-real-ip"),C(e.headers,"x-client-ip"),l[0],u[0]].filter(w=>!!w),p=C(e.headers,"user-agent"),m=C(e.headers,"sec-ch-ua-platform")?.replace(/^"|"$/g,"")??void 0,R=Jr(p??"");return {hostname:a,ip:c[0],forwardedFor:[...l,...u].filter((w,f,g)=>g.indexOf(w)===f),protocol:C(e.headers,"x-forwarded-proto")??(n?.protocol?n.protocol.replace(/:$/,""):void 0),port:s,userAgent:p,origin:C(e.headers,"origin"),referer:C(e.headers,"referer"),acceptLanguage:C(e.headers,"accept-language"),headers:ft(e.headers,r),client:{ip:c[0],hostname:a,browser:p?Wr(p):void 0,os:p?Qr(p):void 0,deviceType:R,platform:m,isMobile:R==="mobile"}}}function ue(e,t,r,o,n,i={},a=T()){return {type:t,method:e.method,url:r,statusCode:o,responseTime:n,...De(e,r,a),...i}}function le(e,t,r,o){let n=ne(e),i=oe(t),a=ie(o),s=dt(e);return `${n} ${s} ${i} ${r} ${a}`}function Ee(e,t){if(e==null)return t===void 0?void 0:{statusCode:t,message:`HTTP ${t}`};if(e instanceof Error){let r=e;return {status:r.status,statusCode:r.statusCode??t,code:r.code,message:e.message,stack:e.stack,why:r.why,fix:r.fix,link:r.link,details:r.details,cause:r.cause}}if(typeof e=="object"){let r=e;return {status:typeof r.status=="number"?r.status:void 0,statusCode:typeof r.statusCode=="number"?r.statusCode:t,code:typeof r.code=="string"||typeof r.code=="number"?r.code:void 0,message:typeof r.message=="string"?r.message:`HTTP ${t??500}`,stack:typeof r.stack=="string"?r.stack:void 0,why:typeof r.why=="string"?r.why:void 0,fix:typeof r.fix=="string"?r.fix:void 0,link:typeof r.link=="string"?r.link:void 0,details:r.details!==null&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:void 0,cause:r.cause}}return {statusCode:t,message:typeof e=="string"?e:`HTTP ${t??500}`}}function ke(e){return e>=400}var Gr=zod.z.string().url().refine(e=>{try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}},{message:"Expected an absolute http(s) URL"}),G=zod.z.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),Pe=zod.z.string().trim().min(1);function Ae(e){return Gr.safeParse(e).success}function z(e){return G.safeParse(e).success}function O(e){return Pe.safeParse(e).success}var N="/inngest";var Kr=["debug","info","warning","error","critical","success","table"],Vr=zod.z.union([zod.z.literal("betterstack"),zod.z.literal("databuddy"),zod.z.literal("posthog"),zod.z.literal("sentry"),zod.z.undefined(),zod.z.object({type:zod.z.literal("otlp"),name:Pe})]);function Xr(e){return typeof e=="string"&&Kr.includes(e)}function Yr(e){return Vr.safeParse(e).success}function Zr(e){try{return e()}catch{return}}function en(){return Math.random().toString(36).slice(2,10)}function de(){let e=Zr(()=>globalThis.crypto),t=e&&typeof e.randomUUID=="function"?e.randomUUID.bind(e):void 0;return t?t():`${Date.now().toString(36)}-${en()}`}function mt(e){if(!z(e)||e.type!=="client_log"||e.source!=="client"||!Xr(e.level)||typeof e.id!="string"||typeof e.message!="string"||typeof e.clientTimestamp!="string")return false;let t=G.safeParse(e.page),r=G.safeParse(e.browser),o=G.safeParse(e.session);return !t.success||!r.success||!o.success||!Yr(e.connector)?false:typeof o.data.pageId=="string"&&typeof o.data.sessionId=="string"}function Be(e){return e?e.startsWith("/")?e:`/${e}`:N}function yt(){return U__default.default.join(tn__default.default.homedir(),".blyp","queue.db")}function nn(e,t=new Set){return (r,o,n)=>{if(t.has(r)||typeof console>"u")return;let i=console[e];if(typeof i=="function"){if(t.add(r),n===void 0){i.call(console,o);return}i.call(console,o,n);}}}function k(e){return nn("warn",e)}var cn="@blyp/core",un=".gitignore",wt=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],ln="blyp.config.json",dn="https://us.i.posthog.com",gn="blyp-app",pn=gn,fn=new Set,_=k(fn),Rt={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},Lt={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:Rt},Ie={enabled:true,path:N},St=T(),q={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},v={enabled:false,memoryBufferSize:500,durableQueuePath:yt(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:q},vt={maxRetries:1,backoffMs:100},mn={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:vt},ht={pretty:true,level:"info",destination:"file",file:Lt,clientLogging:Ie,redact:St,connectors:{delivery:v}},K=null;function yn(e){let t=e;for(;;){let r=U.resolve(t,"package.json");if(S.existsSync(r))try{let n=JSON.parse(S.readFileSync(r,"utf-8"));if(O(n.name))return n.name}catch{}let o=U.dirname(t);if(o===t)return;t=o;}}function Ne(e=process.cwd()){return yn(e)??pn}function hn(){return {pretty:true,level:"info",destination:"file",file:{enabled:true,format:"ndjson",rotation:{enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true}},clientLogging:{enabled:true,path:N},redact:St,connectors:{delivery:v}}}function bn(e){let t=U.resolve(e,"package.json");if(!S.existsSync(t))return true;try{return JSON.parse(S.readFileSync(t,"utf-8")).name!==cn}catch{return true}}function Cn(e){if(wt.some(r=>S.existsSync(U.resolve(e,r))))return;let t=U.resolve(e,ln);if(!S.existsSync(t))try{S.writeFileSync(t,`${JSON.stringify(hn(),null,2)}
2
+ `);}catch(r){console.error("[Blyp] Warning: Failed to create blyp.config.json:",r);}}function wn(e){let t=U.resolve(e,un);if(!S.existsSync(t)){try{S.writeFileSync(t,`logs
3
+ .blyp
4
+ `);}catch(r){console.error("[Blyp] Warning: Failed to create .gitignore:",r);}return}try{let r=S.readFileSync(t,"utf-8"),o=["logs",".blyp"].filter(i=>{let a=i.replace(".","\\.");return !new RegExp(`^(?:/?${a}/?)\\s*$`,"m").test(r)});if(o.length===0)return;let n=r.endsWith(`
5
+ `)?"":`
6
+ `;S.appendFileSync(t,`${n}${o.join(`
7
+ `)}
8
+ `);}catch(r){console.error("[Blyp] Warning: Failed to update .gitignore:",r);}}function Rn(){let e=process.cwd();bn(e)&&(Cn(e),wn(e));}function Ln(){let e=process.cwd(),t=wt.map(o=>U.resolve(e,o)).filter(o=>S.existsSync(o));if(t.length===0)return null;if(t.length>1){let o=t[0];_(`config-multiple:${o}`,`[Blyp] Warning: Multiple config files found. Using ${o} and ignoring ${t.slice(1).join(", ")}.`);}let r=t[0];return {path:r,type:r.endsWith(".json")?"json":"jiti"}}function Tt(e,t){let r=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !r||typeof r!="object"||Array.isArray(r)?(_(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):r}function Sn(e){try{let t=S.readFileSync(e,"utf-8");return Tt(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function vn(e){try{let t=jiti.createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return Tt(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function Tn(e){return e.type==="json"?Sn(e.path):vn(e.path)}function bt(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function xn(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function Dn(e,t){return {...vt,...e,...t}}function En(e,t){return {...mn,...e,...t,retry:Dn(e?.retry,t?.retry)}}function kn(e){let t=e.model??"blypLog",o=e.client?.[t];return !!o&&typeof o.create=="function"}function _n(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function Pn(e,t){if(!e)return;let r=e.adapter,o=false;t==="json"?_("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"?_(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):r?bt(r)?(o=kn({...r,model:r.model??"blypLog"}),o||_("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${r.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):xn(r)&&(o=_n(r),o||_("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):_("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let n=bt(r)?{...r,model:r.model??"blypLog"}:r;return {dialect:e.dialect,adapter:n,delivery:En(void 0,e.delivery),ready:o,status:o?"enabled":"missing"}}function An(e,t){return {...Rt,...e,...t}}function Bn(e,t){return {...Lt,...e,...t,rotation:An(e?.rotation,t?.rotation)}}function In(e,t){return {...Ie,...e,...t,path:t?.path??e?.path??Ie.path}}function On(e,t){return T(e,t)}function Nn(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??q.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??q.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??q.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??q.multiplier),jitter:t?.jitter??e?.jitter??q.jitter}}function Mn(e,t){let r=t?.durableQueuePath??e?.durableQueuePath??v.durableQueuePath;return {enabled:t?.enabled??e?.enabled??v.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??v.memoryBufferSize)),durableQueuePath:O(r)?r:v.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??v.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??v.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??v.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??v.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??v.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??v.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??v.overflowStrategy,retry:Nn(e?.retry,t?.retry),durableReady:false}}function Fn(e,t,r){if(!(!e&&!t))return Pn({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},r)}function zn(e,t){let r=t?.enabled??e?.enabled??false,o=t?.projectKey??e?.projectKey,n=e?.enabled===true?e?.errorTracking:void 0,i=t?.errorTracking?.mode??n?.mode??"auto",a=t?.errorTracking?.enabled??n?.enabled??r,s=r&&a&&typeof o=="string"&&o.trim().length>0;return {enabled:r,mode:t?.mode??e?.mode??"auto",projectKey:o,host:t?.host??e?.host??dn,serviceName:t?.serviceName??e?.serviceName??Ne(),errorTracking:{enabled:a,mode:i,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??n?.enableExceptionAutocapture??i==="auto",ready:s,status:s?"enabled":"missing"}}}function qn(e,t){let r=t?.enabled??e?.enabled??false,o=t?.apiKey??e?.apiKey,n=t?.websiteId??e?.websiteId,i=r&&O(o)&&O(n);return {enabled:r,mode:t?.mode??e?.mode??"auto",apiKey:o,websiteId:n,namespace:t?.namespace??e?.namespace,source:t?.source??e?.source,apiUrl:t?.apiUrl??e?.apiUrl,debug:t?.debug??e?.debug??false,enableBatching:t?.enableBatching??e?.enableBatching??true,batchSize:t?.batchSize??e?.batchSize,batchTimeout:t?.batchTimeout??e?.batchTimeout,maxQueueSize:t?.maxQueueSize??e?.maxQueueSize,ready:i,status:i?"enabled":"missing"}}function jn(e,t){let r=t?.sourceToken??e?.sourceToken,o=t?.ingestingHost??e?.ingestingHost,n=t?.enabled??e?.enabled??false,i=e?.enabled===true?e?.errorTracking:void 0,a=$n(n,i,t?.errorTracking),s=n&&O(r)&&Ae(o);return {enabled:n,mode:t?.mode??e?.mode??"auto",sourceToken:r,ingestingHost:o,serviceName:t?.serviceName??e?.serviceName??Ne(),errorTracking:a,ready:s,status:s?"enabled":"missing"}}function $n(e,t,r){let o=r?.dsn??t?.dsn,n=r?.enabled??t?.enabled??e,i=n&&O(o);return {enabled:n,dsn:o,tracesSampleRate:r?.tracesSampleRate??t?.tracesSampleRate??1,environment:r?.environment??t?.environment,release:r?.release??t?.release,ready:i,status:i?"enabled":"missing"}}function Un(e,t){let r=t?.dsn??e?.dsn,o=t?.enabled??e?.enabled??false,n=o&&typeof r=="string"&&r.trim().length>0;return {enabled:o,mode:t?.mode??e?.mode??"auto",dsn:r,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:n,status:n?"enabled":"missing"}}function Hn(e,t){let r=t?.endpoint??e?.endpoint,o=t?.enabled??e?.enabled??false,n={...{},...t?.headers??{}},i=o&&Ae(r);return {name:t?.name??e?.name??"",enabled:o,mode:t?.mode??e?.mode??"auto",endpoint:r,headers:n,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??Ne(),ready:i,status:i?"enabled":"missing"}}function Wn(e,t){let r=t??e??[],o=new Map;for(let n of r)!n||typeof n.name!="string"||n.name.length===0||(o.has(n.name)&&_(`otlp-duplicate:${n.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${n.name}" found. Using the last definition.`),o.set(n.name,Hn(void 0,n)));return Array.from(o.values())}function Qn(e,t){return {betterstack:jn(e?.betterstack,t?.betterstack),databuddy:qn(e?.databuddy,t?.databuddy),posthog:zn(e?.posthog,t?.posthog),sentry:Un(e?.sentry,t?.sentry),otlp:Wn(e?.otlp,t?.otlp),delivery:Mn(e?.delivery,t?.delivery)}}function Oe(e,t={},r={}){return {...e,...t,destination:t.destination??e.destination??"file",file:Bn(e.file,t.file),database:Fn(e.database,t.database,r.configFileType),clientLogging:In(e.clientLogging,t.clientLogging),redact:On(e.redact,t.redact),connectors:Qn(e.connectors,t.connectors)}}function Jn(){if(K!==null)return K;Rn();let e=Ln();if(e){let t=Tn(e);K=Oe(ht,t,{configFileType:e.type});}else K=Oe(ht);return K}function V(e={}){return Oe(Jn(),e)}function Gn(e){let t=e.indexOf("?"),r=t>=0?e.substring(0,t):e;return r.endsWith("/")&&r.length>1&&(r=r.slice(0,-1)),r.startsWith("/")||(r="/"+r),r}function Kn(e){let t=e.indexOf("?"),r=t>=0?e.substring(0,t):e;return r.endsWith("/")&&r.length>1&&(r=r.slice(0,-1)),r.startsWith("/")||(r="/"+r),r}function Me(e,t){if(!t||t.length===0)return false;let r=Gn(e);return t.some(o=>{let n=Kn(o);if(n===r||n==="/**"||n==="**")return true;if(n==="/*")return r.split("/").filter(a=>a.length>0).length===1;if(n.endsWith("/*")&&!n.includes("**")){let i=n.slice(0,-1);return r.startsWith(i)?r.slice(i.length).split("/").filter(l=>l.length>0).length===1:false}if(n.includes("**")){if(n==="/**")return true;if(n.startsWith("/")&&n.endsWith("**")){let l=n.slice(0,-2);return l.endsWith("/")&&l.length>1&&(l=l.slice(0,-1)),l===r?true:r.startsWith(l+"/")}let i=n.indexOf("**"),a=n.substring(0,i),s=n.substring(i+2);return a.endsWith("/")&&a.length>1&&(a=a.slice(0,-1)),a===""&&s===""?true:a!==""&&s===""?r.startsWith(a+"/"):a===""&&s!==""?r.endsWith(s)||r.includes(s+"/"):a!==""&&s!==""?r.startsWith(a)&&(r.endsWith(s)||r.includes(s+"/")):false}if(n.includes("*")){let i=n.lastIndexOf("."),a=n.lastIndexOf("*");if(i>a&&a>0&&n[a-1]==="/"){let c=n.slice(a),p=r.slice(r.lastIndexOf("/")+1),m=p.lastIndexOf(".");if(m>0)return p.slice(m)===c}let s=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*");return new RegExp("^"+s+"$").test(r)}return false})}function Xn(e){return Buffer.from(fflate.gzipSync(e))}function Yn(e,t){console.warn(`[Blyp] Warning: ${e}`,t);}function pe(e){S__default.default.mkdirSync(e,{recursive:true});}function Zn(e){try{return S__default.default.statSync(e).size}catch{return 0}}function eo(e){let t=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),o=String(e.getUTCDate()).padStart(2,"0"),n=String(e.getUTCHours()).padStart(2,"0"),i=String(e.getUTCMinutes()).padStart(2,"0"),a=String(e.getUTCSeconds()).padStart(2,"0");return `${t}${r}${o}T${n}${i}${a}Z`}function to(e,t){let r=`${e}${t}`,o=1;for(;S__default.default.existsSync(r);)r=`${e}-${o}${t}`,o+=1;return r}function ro(e,t,r,o){let n=`${t}.`;try{let i=S__default.default.readdirSync(e).filter(s=>s.startsWith(n)&&(s.endsWith(".ndjson")||s.endsWith(".ndjson.gz"))).map(s=>U__default.default.join(e,s)).sort((s,l)=>S__default.default.statSync(s).mtimeMs-S__default.default.statSync(l).mtimeMs),a=Math.max(i.length-r,0);for(let s=0;s<a;s+=1)S__default.default.rmSync(i[s]);}catch(i){o(`Failed to prune archives for ${t}`,i);}}function no(){let e=new WeakSet;return (t,r)=>{if(typeof r=="function")return `[Function: ${r.name||"anonymous"}]`;if(r===void 0)return "[undefined]";if(typeof r=="symbol")return r.toString();if(r!==null&&typeof r=="object"){if(e.has(r))return "[Circular]";e.add(r);}return r}}function ze(e){return JSON.stringify(e,no())}function oo(e){let t=e.file,r=t?.dir||e.logDir||U__default.default.join(process.cwd(),"logs"),o=t?.archiveDir||U__default.default.join(r,"archive"),n=t?.rotation;return {enabled:t?.enabled??true,dir:r,archiveDir:o,rotationEnabled:n?.enabled??true,maxSizeBytes:n?.maxSizeBytes??10*1024*1024,maxArchives:n?.maxArchives??5,compress:n?.compress??true}}var Fe=class{constructor(t,r={}){d(this,"config");d(this,"gzip");d(this,"warn");d(this,"combined");d(this,"error");this.config=oo(t),this.gzip=r.gzip??Xn,this.warn=r.warn??Yn,this.combined={activePath:U__default.default.join(this.config.dir,"log.ndjson"),archivePrefix:"log",bytes:0,queue:[],processing:false},this.error={activePath:U__default.default.join(this.config.dir,"log.error.ndjson"),archivePrefix:"log.error",bytes:0,queue:[],processing:false},this.config.enabled&&(pe(this.config.dir),pe(this.config.archiveDir),this.seedStream(this.combined),this.seedStream(this.error));}write(t){if(!this.config.enabled)return;let r=`${ze(t)}
9
+ `;this.enqueue(this.combined,r),(t.level==="error"||t.level==="critical")&&this.enqueue(this.error,r);}enqueue(t,r){t.queue.push(r),this.processQueue(t);}processQueue(t){if(!t.processing){t.processing=true;try{for(;t.queue.length>0;){let r=t.queue.shift();if(r!==void 0)try{this.append(t,r);}catch(o){this.warn(`Failed writing log line for ${t.archivePrefix}`,o);}}}finally{t.processing=false;}}}seedStream(t){t.bytes=Zn(t.activePath),this.config.rotationEnabled&&t.bytes>this.config.maxSizeBytes&&t.bytes>0&&(this.rotate(t),S__default.default.closeSync(S__default.default.openSync(t.activePath,"a")),t.bytes=0);}append(t,r){pe(this.config.dir);let o=Buffer.byteLength(r,"utf8");this.config.rotationEnabled&&t.bytes>0&&t.bytes+o>this.config.maxSizeBytes&&this.rotate(t),S__default.default.appendFileSync(t.activePath,r,"utf8"),t.bytes+=o;}rotate(t){if(pe(this.config.archiveDir),!S__default.default.existsSync(t.activePath)||t.bytes===0){t.bytes=0;return}let r=eo(new Date),o=U__default.default.join(this.config.archiveDir,`${t.archivePrefix}.${r}`),n=to(o,".ndjson");if(S__default.default.renameSync(t.activePath,n),this.config.compress)try{let i=`${n}.gz`,a=this.gzip(S__default.default.readFileSync(n));S__default.default.writeFileSync(i,a),S__default.default.rmSync(n);}catch(i){this.warn(`Failed to gzip archive ${n}`,i);}t.bytes=0,ro(this.config.archiveDir,t.archivePrefix,this.config.maxArchives,this.warn);}};function xt(e){return new Fe(e)}function qe(e){return z(e.data)?e.data:e}function P(e,t){if(t in e){let n=e[t];if(typeof n=="string"||typeof n=="number")return n}let o=qe(e)[t];if(typeof o=="string"||typeof o=="number")return o}function je(e,t){let r=qe(e),n=(z(r.page)?r.page:void 0)?.[t];return typeof n=="string"?n:void 0}function $e(e,t){let r=qe(e),n=(z(r.session)?r.session:void 0)?.[t];return typeof n=="string"?n:void 0}function fe(e){return P(e,"type")}function io(e,t){let r=fe(e),o=typeof e.caller=="string"?e.caller:void 0,n=P(e,"groupId"),i=P(e,"traceId"),a=P(e,"method"),s=P(e,"path"),l=P(e,"status"),u=P(e,"duration"),c=je(e,"pathname"),p=je(e,"url"),m=$e(e,"sessionId"),R=$e(e,"pageId"),w={"blyp.level":e.level,"blyp.source":t,"blyp.payload":ze(e)},f=[["blyp.type",r],["blyp.caller",o],["blyp.group_id",n],["blyp.trace_id",i],["http.method",a],["url.path",s],["client.page_path",c],["client.page_url",p],["client.session_id",m],["client.page_id",R]],g=[["http.status_code",l],["blyp.duration_ms",u]];for(let[y,L]of f)L&&(w[y]=L);for(let[y,L]of g)L!==void 0&&(w[y]=L);return w}function Ue(e,t,r={}){return {...io(e,t),...r}}var so=jiti.createJiti(typeof __filename=="string"?__filename:(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('hono.js', document.baseURI).href)),{interopDefault:false,moduleCache:true,fsCache:false}),Dt=new Map;function co(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,r="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof r=="string"&&(r.includes("Cannot find module")||r.includes("Cannot find package"))}function H(e,t,r=`@blyp/core/${e}`){let o=`@blyp/core/${e}`,n=`${o}::${r}`,i=Dt.get(n);if(i)return i;try{let a=so(r);return Dt.set(n,a),a}catch(a){if(!co(a))throw a;let s=t.map(u=>`"${u}"`).join(", "),l=t.join(" ");throw new Error(`[Blyp] Optional connector dependencies missing for "${o}". Install ${s} to use this API. Example: bun add ${l}. You can also import directly from "${o}".`,{cause:a instanceof Error?a:void 0})}}var lo=module$1.createRequire(typeof __filename=="string"?__filename:(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('hono.js', document.baseURI).href))),He=null;function go(e){if(!e||typeof e!="object")return false;let t="code"in e?e.code:void 0,r="message"in e?e.message:void 0;return t==="MODULE_NOT_FOUND"||t==="ERR_MODULE_NOT_FOUND"||typeof r=="string"&&(r.includes("Cannot find module")||r.includes("Cannot find package"))}function po(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 Et(){if(He)return He;let e;try{e=lo("pino-pretty");}catch(r){throw go(r)?new Error('[Blyp] Failed to initialize the pretty logger transport because pretty: true requires "pino-pretty" to be installed.',{cause:r instanceof Error?r:void 0}):new Error('[Blyp] Failed to initialize the pretty logger transport with "pino-pretty".',{cause:r instanceof Error?r:void 0})}let t=po(e);if(!t)throw new Error('[Blyp] Failed to initialize the pretty logger transport because "pino-pretty" did not expose a callable factory.');return He=t,t}var kt=new async_hooks.AsyncLocalStorage;function mo(){return {requestScopedLoggerActive:true,structuredCollectorActive:false,structuredLogEmitted:false,mixedLoggerWarningShown:false}}function We(e){return kt.run(mo(),e)}function M(){return kt.getStore()}function Qe(e){let t=M();t&&(t.activeLogger=e);}function X(e){let t=M();t&&(t.traceId=e);}function A(){return M()?.traceId}function Je(){let e=M();e&&(e.structuredCollectorActive=true);}function Ge(){let e=M();e&&(e.structuredLogEmitted=true);}function me(){let e=M();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)}var _t={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function ye(e){return e.replace(/\\/g,"/")}function yo(e){let t=ye(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 ho(e){let t=ye(e),r=ye(process.cwd());return t.startsWith(`${r}/`)?t.slice(r.length+1):t}function Pt(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
10
+ `),r=null;for(let o=2;o<t.length;o+=1){let n=t[o];if(!n)continue;let i=n.match(/\((.*):(\d+):\d+\)/)||n.match(/at\s+(.*):(\d+):(\d+)/);if(!i)continue;let a=i[1]||"",s=parseInt(i[2]||"0",10)||null;if(a&&!a.includes("node_modules")&&!yo(a)){let l=ho(a);if(!ye(l).startsWith("dist/"))return {file:l,line:s};r??(r={file:l,line:s});}}if(r)return r}catch{return {file:null,line:null}}return {file:null,line:null}}var At=B;function Bt(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function It(e,t,r,o,n=T()){let{file:i,line:a}=Pt(),s=At(t,n),l={timestamp:new Date().toISOString(),level:_t[e],message:Bt(s)},u=A();return t instanceof Error&&(l.error=b(ae(t),n)),i&&(l.caller=a!==null?`${i}:${a}`:i),r.length===1?l.data=b(r[0],n):r.length>1&&(l.data=b(r,n)),Object.keys(o).length>0&&(l.bindings=b(o,n)),u&&(l.traceId=u),l}function Ot(e,t,r,o,n=T()){let{file:i,line:a}=Pt(),s=b(r,n),l=A(),u={message:Bt(At(t,n)),...s};return i&&(u.caller=a!==null?`${i}:${a}`:i),Object.keys(o).length>0&&(u.bindings=b(o,n)),l&&u.traceId===void 0&&(u.traceId=l),u.level=typeof s.level=="string"&&s.level.length>0?s.level:_t[e],u.timestamp=typeof s.timestamp=="string"&&s.timestamp.length>0?s.timestamp:new Date().toISOString(),u}function Nt(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"}}var Ke=class{constructor(t){this.logger=t;d(this,"isAsync",false);d(this,"isReady",true);}write(t){this.logger.write(t);}async flush(){}async shutdown(){}};function Mt(e){return new Ke(xt(e))}function Ft(e){let t=e.db;if(typeof t?.insert!="function"||e.table===void 0)throw new Error("[Blyp] Drizzle database adapter is missing a db.insert function or table reference.");return {async insert(r){r.length!==0&&await t.insert(e.table).values(r);}}}function bo(e){let t=String(e??"");return t.includes("createMany")||t.includes("Unknown argument")||t.includes("not supported")||t.includes("is not a function")}function zt(e){let t=e.client,r=e.model??"blypLog",o=t[r];if(!o||typeof o.create!="function")throw new Error(`[Blyp] Prisma database adapter is missing the "${r}" delegate or its create method.`);let n=o,i=typeof n.createMany=="function";async function a(s){if(typeof t.$transaction=="function"){await t.$transaction(s.map(l=>n.create({data:l})));return}for(let l of s)await n.create({data:l});}return {async insert(s){if(s.length!==0){if(s.length===1){await n.create({data:s[0]});return}if(!i||typeof n.createMany!="function"){await a(s);return}try{await n.createMany({data:s});}catch(l){if(!bo(l))throw l;i=false,await a(s);}}}}}function qt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function W(e){return typeof e=="string"&&e.length>0?e:null}function wo(e){if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function jt(e){let t=x(e);return {id:crypto.randomUUID(),timestamp:wo(e.timestamp),level:e.level,message:e.message,caller:W(e.caller),type:W(e.type),traceId:W(e.traceId),groupId:W(e.groupId),method:W(e.method),path:W(e.path),status:qt(e.status),duration:qt(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 Ro(e){return !!e&&e.type==="prisma"}function Lo(e){return !!e&&e.type==="drizzle"}function $t(e){if(Ro(e.adapter))return zt(e.adapter);if(Lo(e.adapter))return Ft(e.adapter);throw new Error("[Blyp] Unsupported database adapter configuration.")}function So(e){return new Promise(t=>{setTimeout(t,e);})}var he=class{constructor(t){this.config=t;d(this,"isAsync",true);d(this,"isReady",true);d(this,"warnOnce",k(new Set));d(this,"queue",[]);d(this,"writer");d(this,"timer",null);d(this,"processing",false);d(this,"closed",false);d(this,"terminalError",null);d(this,"activeDispatch",null);this.writer=$t(t);}write(t){this.closed||(this.enqueue(jt(t)),this.scheduleDispatch());}async flush(){this.timer&&(clearTimeout(this.timer),this.timer=null);let t=(async()=>{if(await this.drain(),this.terminalError)throw this.terminalError})(),r=null;try{await Promise.race([t,new Promise((o,n)=>{r=setTimeout(()=>{this.warnOnce("database-flush-timeout",`[Blyp] Warning: Timed out flushing database logs after ${this.config.delivery.flushTimeoutMs}ms.`),n(new Error("[Blyp] Timed out flushing database logs."));},this.config.delivery.flushTimeoutMs);})]);}finally{r&&clearTimeout(r);}}async shutdown(){this.closed=true,await this.flush();}enqueue(t){this.queue.push(t);let r=this.queue.length-this.config.delivery.maxQueueSize;if(!(r<=0)){if(this.warnOnce("database-overflow",`[Blyp] Warning: Database log queue exceeded ${this.config.delivery.maxQueueSize} entries. Applying ${this.config.delivery.overflowStrategy} overflow handling.`),this.config.delivery.overflowStrategy==="drop-new"){this.queue.splice(this.config.delivery.maxQueueSize);return}this.queue.splice(0,r);}}scheduleDispatch(){if(!this.processing){if(this.config.delivery.strategy==="immediate"){this.drain();return}if(this.queue.length>=this.config.delivery.batchSize){this.drain();return}this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.drain();},this.config.delivery.flushIntervalMs));}}async drain(){if(this.processing){this.activeDispatch&&await this.activeDispatch;return}this.processing=true,this.activeDispatch=this.processQueue();try{await this.activeDispatch;}finally{this.processing=false,this.activeDispatch=null;}}async processQueue(){for(;this.queue.length>0;){let t=this.config.delivery.strategy==="batch"?Math.max(1,this.config.delivery.batchSize):1,r=this.queue.splice(0,t);try{await this.insertWithRetry(r);}catch(o){let n=o instanceof Error?o:new Error(String(o??"Unknown database logging failure"));throw this.terminalError=n,this.warnOnce("database-insert-failure",`[Blyp] Warning: Failed to persist logs to the ${this.config.dialect??"database"} database.`,n),n}}}async insertWithRetry(t){let r=Math.max(1,this.config.delivery.retry.maxRetries+1),o=0;for(;o<r;){o+=1;try{await this.writer.insert(t);return}catch(n){if(o>=r)throw n;await So(this.config.delivery.retry.backoffMs);}}}};var Ve=class{constructor(){d(this,"isAsync",false);d(this,"isReady",false);}write(t){}async flush(){}async shutdown(){}},vo=k(new Set);function Ut(e){if(e.destination!=="database")return Mt(e);let t=e.database;return t?.ready?new he(t):(vo("database-sink-disabled","[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."),new Ve)}function Ht(e,t){let r=Math.max(1,Math.floor(e)),o=Math.pow(t.multiplier,r-1),n=Math.min(Math.max(0,Math.floor(t.initialBackoffMs*o)),Math.max(0,t.maxBackoffMs));return t.jitter?Math.floor(Math.random()*(n+1)):n}var Wt="bun:sqlite";var Qt="node:sqlite";function Jt(){return `
11
+ const { parentPort } = require('node:worker_threads');
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
2
14
 
3
- var zod = require('zod');
4
- var fs = require('fs');
5
- var jiti = require('jiti');
6
- var path = require('path');
7
- var apiLogs = require('@opentelemetry/api-logs');
8
- var exporterLogsOtlpHttp = require('@opentelemetry/exporter-logs-otlp-http');
9
- var resources = require('@opentelemetry/resources');
10
- var sdkLogs = require('@opentelemetry/sdk-logs');
11
- var posthogNode = require('posthog-node');
12
- var fflate = require('fflate');
13
- var pino = require('pino');
14
- var async_hooks = require('async_hooks');
15
- var crypto = require('crypto');
16
- var Sentry = require('@sentry/node');
17
- var node = require('@logtail/node');
15
+ const NODE_SQLITE_MODULE = ${JSON.stringify(Qt)};
16
+ const BUN_SQLITE_MODULE = ${JSON.stringify(Wt)};
17
+ const CLAIM_LEASE_MS = 30000;
18
18
 
19
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
19
+ let db;
20
+ let runtime = 'unsupported';
20
21
 
21
- function _interopNamespace(e) {
22
- if (e && e.__esModule) return e;
23
- var n = Object.create(null);
24
- if (e) {
25
- Object.keys(e).forEach(function (k) {
26
- if (k !== 'default') {
27
- var d = Object.getOwnPropertyDescriptor(e, k);
28
- Object.defineProperty(n, k, d.get ? d : {
29
- enumerable: true,
30
- get: function () { return e[k]; }
31
- });
32
- }
33
- });
34
- }
35
- n.default = e;
36
- return Object.freeze(n);
37
- }
38
-
39
- var fs__default = /*#__PURE__*/_interopDefault(fs);
40
- var path__default = /*#__PURE__*/_interopDefault(path);
41
- var pino__default = /*#__PURE__*/_interopDefault(pino);
42
- var Sentry__namespace = /*#__PURE__*/_interopNamespace(Sentry);
43
-
44
- var __defProp = Object.defineProperty;
45
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
46
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
47
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
48
- }) : x)(function(x) {
49
- if (typeof require !== "undefined") return require.apply(this, arguments);
50
- throw Error('Dynamic require of "' + x + '" is not supported');
51
- });
52
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
53
-
54
- // src/core/colors.ts
55
- function getMethodColor(method) {
56
- const colors = {
57
- GET: "\x1B[32m",
58
- POST: "\x1B[36m",
59
- PUT: "\x1B[33m",
60
- PATCH: "\x1B[34m",
61
- DELETE: "\x1B[31m"
62
- };
63
- const reset = "\x1B[0m";
64
- return `${colors[method.toUpperCase()] || ""}${method}${reset}`;
65
- }
66
- function getStatusColor(statusCode) {
67
- const reset = "\x1B[0m";
68
- if (statusCode >= 500) return `\x1B[31m${statusCode}${reset}`;
69
- if (statusCode >= 400) return `\x1B[33m${statusCode}${reset}`;
70
- if (statusCode >= 300) return `\x1B[36m${statusCode}${reset}`;
71
- if (statusCode >= 200) return `\x1B[32m${statusCode}${reset}`;
72
- return `\x1B[37m${statusCode}${reset}`;
73
- }
74
- function getArrowForMethod(method) {
75
- const arrows = {
76
- GET: "\u2192",
77
- POST: "\u2191",
78
- PUT: "\u21D1",
79
- PATCH: "\u2197",
80
- DELETE: "\u2715"
81
- };
82
- return arrows[method.toUpperCase()] || "\u2022";
83
- }
84
- function getResponseTimeColor(ms) {
85
- const reset = "\x1B[0m";
86
- if (ms < 100) return `\x1B[32m${ms}ms${reset}`;
87
- if (ms < 300) return `\x1B[33m${ms}ms${reset}`;
88
- if (ms < 1e3) return `\x1B[31m${ms}ms${reset}`;
89
- return `\x1B[41m\x1B[37m${ms}ms${reset}`;
90
- }
91
-
92
- // src/frameworks/shared/http.ts
93
- function getHeaderValue(headers, name) {
94
- if (!headers) {
95
- return void 0;
96
- }
97
- if (headers instanceof Headers) {
98
- return headers.get(name) ?? headers.get(name.toLowerCase()) ?? void 0;
99
- }
100
- if (typeof headers.get === "function") {
101
- const direct2 = headers.get(name);
102
- return direct2 ?? headers.get(name.toLowerCase()) ?? void 0;
103
- }
104
- const record = headers;
105
- const direct = record[name] ?? record[name.toLowerCase()];
106
- if (Array.isArray(direct)) {
107
- return direct[0];
108
- }
109
- return direct;
110
- }
111
- function parseForwardedHeader(value) {
112
- if (!value) {
113
- return [];
114
- }
115
- return value.split(",").map((entry) => entry.trim()).filter(Boolean).map((entry) => {
116
- const match = entry.match(/for="?(\[[^\]]+\]|[^;,\s"]+)/i);
117
- return match?.[1]?.replace(/^"|"$/g, "") ?? "";
118
- }).map((entry) => entry.replace(/^\[|\]$/g, "")).filter(Boolean);
119
- }
120
- function parseForwardedFor(value) {
121
- if (!value) {
122
- return [];
123
- }
124
- return value.split(",").map((entry) => entry.trim()).filter(Boolean);
125
- }
126
- function stripPort(host) {
127
- if (host.startsWith("[")) {
128
- const endIndex = host.indexOf("]");
129
- return endIndex >= 0 ? host.slice(1, endIndex) : host;
130
- }
131
- return host.replace(/:\d+$/, "");
132
- }
133
- function detectBrowser(userAgent) {
134
- if (/edg\//i.test(userAgent)) return "Edge";
135
- if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) return "Opera";
136
- if (/chrome\//i.test(userAgent) && !/edg\//i.test(userAgent)) return "Chrome";
137
- if (/firefox\//i.test(userAgent)) return "Firefox";
138
- if (/safari\//i.test(userAgent) && !/chrome\//i.test(userAgent)) return "Safari";
139
- if (/curl\//i.test(userAgent)) return "curl";
140
- if (/postmanruntime/i.test(userAgent)) return "Postman";
141
- return "Unknown";
142
- }
143
- function detectOperatingSystem(userAgent) {
144
- if (/windows/i.test(userAgent)) return "Windows";
145
- if (/android/i.test(userAgent)) return "Android";
146
- if (/iphone|ipad|ipod/i.test(userAgent)) return "iOS";
147
- if (/mac os x|macintosh/i.test(userAgent)) return "macOS";
148
- if (/linux/i.test(userAgent)) return "Linux";
149
- return "Unknown";
150
- }
151
- function detectDeviceType(userAgent) {
152
- if (!userAgent) return "unknown";
153
- if (/bot|crawler|spider|curl|wget|postmanruntime/i.test(userAgent)) return "bot";
154
- if (/ipad|tablet/i.test(userAgent)) return "tablet";
155
- if (/mobi|iphone|android/i.test(userAgent)) return "mobile";
156
- return "desktop";
157
- }
158
- function extractPathname(requestUrl, fallbackPath = "/") {
159
- if (!requestUrl) {
160
- return fallbackPath;
161
- }
162
- if (requestUrl.startsWith("http://") || requestUrl.startsWith("https://")) {
163
- try {
164
- return new URL(requestUrl).pathname || fallbackPath;
165
- } catch {
166
- return fallbackPath;
167
- }
168
- }
169
- if (requestUrl.startsWith("/")) {
170
- const queryIndex = requestUrl.indexOf("?");
171
- return queryIndex >= 0 ? requestUrl.slice(0, queryIndex) : requestUrl;
172
- }
173
- try {
174
- return new URL(requestUrl, "http://localhost").pathname || fallbackPath;
175
- } catch {
176
- return fallbackPath;
177
- }
178
- }
179
- function createRequestLike(method, url, headers) {
180
- return { method, url, headers };
181
- }
182
- function buildClientDetails(request, fallbackPath) {
183
- const pathname = fallbackPath ?? extractPathname(request.url);
184
- const urlObject = (() => {
185
- try {
186
- return new URL(request.url);
187
- } catch {
188
- try {
189
- return new URL(pathname, "http://localhost");
190
- } catch {
191
- return null;
192
- }
193
- }
194
- })();
195
- const hostHeader = getHeaderValue(request.headers, "x-forwarded-host") ?? getHeaderValue(request.headers, "host") ?? urlObject?.host ?? void 0;
196
- const hostname = hostHeader ? stripPort(hostHeader) : urlObject?.hostname;
197
- const port = hostHeader?.match(/:(\d+)$/)?.[1] ?? (urlObject?.port || void 0);
198
- const xForwardedFor = parseForwardedFor(getHeaderValue(request.headers, "x-forwarded-for"));
199
- const forwardedFor = parseForwardedHeader(getHeaderValue(request.headers, "forwarded"));
200
- const ipCandidates = [
201
- getHeaderValue(request.headers, "cf-connecting-ip"),
202
- getHeaderValue(request.headers, "true-client-ip"),
203
- getHeaderValue(request.headers, "fly-client-ip"),
204
- getHeaderValue(request.headers, "x-real-ip"),
205
- getHeaderValue(request.headers, "x-client-ip"),
206
- xForwardedFor[0],
207
- forwardedFor[0]
208
- ].filter((value) => Boolean(value));
209
- const userAgent = getHeaderValue(request.headers, "user-agent");
210
- const platform = getHeaderValue(request.headers, "sec-ch-ua-platform")?.replace(/^"|"$/g, "") ?? void 0;
211
- const deviceType = detectDeviceType(userAgent ?? "");
212
- return {
213
- hostname,
214
- ip: ipCandidates[0],
215
- forwardedFor: [...xForwardedFor, ...forwardedFor].filter((value, index, values) => {
216
- return values.indexOf(value) === index;
217
- }),
218
- protocol: getHeaderValue(request.headers, "x-forwarded-proto") ?? (urlObject?.protocol ? urlObject.protocol.replace(/:$/, "") : void 0),
219
- port,
220
- userAgent,
221
- origin: getHeaderValue(request.headers, "origin"),
222
- referer: getHeaderValue(request.headers, "referer"),
223
- acceptLanguage: getHeaderValue(request.headers, "accept-language"),
224
- client: {
225
- ip: ipCandidates[0],
226
- hostname,
227
- browser: userAgent ? detectBrowser(userAgent) : void 0,
228
- os: userAgent ? detectOperatingSystem(userAgent) : void 0,
229
- deviceType,
230
- platform,
231
- isMobile: deviceType === "mobile"
232
- }
233
- };
234
- }
235
- function buildRequestLogData(request, type, path3, statusCode, responseTime, extra = {}) {
236
- return {
237
- type,
238
- method: request.method,
239
- url: path3,
240
- statusCode,
241
- responseTime,
242
- ...buildClientDetails(request, path3),
243
- ...extra
244
- };
245
- }
246
- function buildInfoLogMessage(method, statusCode, url, responseTime) {
247
- const methodColor = getMethodColor(method);
248
- const statusColor = getStatusColor(statusCode);
249
- const timeColor = getResponseTimeColor(responseTime);
250
- const arrow = getArrowForMethod(method);
251
- return `${methodColor} ${arrow} ${statusColor} ${url} ${timeColor}`;
252
- }
253
- function toErrorLike(error, fallbackStatusCode) {
254
- if (error === void 0 || error === null) {
255
- return fallbackStatusCode === void 0 ? void 0 : { statusCode: fallbackStatusCode, message: `HTTP ${fallbackStatusCode}` };
256
- }
257
- if (error instanceof Error) {
258
- const errorWithStatus = error;
259
- return {
260
- status: errorWithStatus.status,
261
- statusCode: errorWithStatus.statusCode ?? fallbackStatusCode,
262
- code: errorWithStatus.code,
263
- message: error.message,
264
- stack: error.stack,
265
- why: errorWithStatus.why,
266
- fix: errorWithStatus.fix,
267
- link: errorWithStatus.link,
268
- details: errorWithStatus.details,
269
- cause: errorWithStatus.cause
270
- };
271
- }
272
- if (typeof error === "object") {
273
- const record = error;
274
- return {
275
- status: typeof record.status === "number" ? record.status : void 0,
276
- statusCode: typeof record.statusCode === "number" ? record.statusCode : fallbackStatusCode,
277
- code: typeof record.code === "string" || typeof record.code === "number" ? record.code : void 0,
278
- message: typeof record.message === "string" ? record.message : `HTTP ${fallbackStatusCode ?? 500}`,
279
- stack: typeof record.stack === "string" ? record.stack : void 0,
280
- why: typeof record.why === "string" ? record.why : void 0,
281
- fix: typeof record.fix === "string" ? record.fix : void 0,
282
- link: typeof record.link === "string" ? record.link : void 0,
283
- details: record.details !== null && typeof record.details === "object" && !Array.isArray(record.details) ? record.details : void 0,
284
- cause: record.cause
285
- };
286
- }
287
- return {
288
- statusCode: fallbackStatusCode,
289
- message: typeof error === "string" ? error : `HTTP ${fallbackStatusCode ?? 500}`
290
- };
291
- }
292
- function isErrorStatus(statusCode) {
293
- return statusCode >= 400;
294
- }
295
-
296
- // src/shared/log-value.ts
297
- function normalizeError(error) {
298
- const normalized = {
299
- name: error.name,
300
- message: error.message
301
- };
302
- if (error.stack) {
303
- normalized.stack = error.stack;
304
- }
305
- const errorWithCause = error;
306
- if (errorWithCause.cause !== void 0) {
307
- normalized.cause = normalizeLogValue(errorWithCause.cause);
308
- }
309
- return normalized;
310
- }
311
- function normalizeLogValue(value, seen = /* @__PURE__ */ new WeakSet()) {
312
- if (value instanceof Error) {
313
- return normalizeError(value);
314
- }
315
- if (typeof value === "function") {
316
- return `[Function: ${value.name || "anonymous"}]`;
317
- }
318
- if (typeof value === "symbol") {
319
- return value.toString();
320
- }
321
- if (value === void 0 || value === null) {
322
- return value;
323
- }
324
- if (Array.isArray(value)) {
325
- return value.map((entry) => normalizeLogValue(entry, seen));
326
- }
327
- if (typeof value === "object") {
328
- if (seen.has(value)) {
329
- return "[Circular]";
330
- }
331
- seen.add(value);
332
- const normalized = {};
333
- for (const [key, entry] of Object.entries(value)) {
334
- normalized[key] = normalizeLogValue(entry, seen);
335
- }
336
- seen.delete(value);
337
- return normalized;
338
- }
339
- return value;
340
- }
341
- function serializeLogMessage(message) {
342
- if (typeof message === "string") {
343
- return message;
344
- }
345
- if (message instanceof Error) {
346
- return message.message || message.name;
347
- }
348
- const normalized = normalizeLogValue(message);
349
- if (typeof normalized === "string") {
350
- return normalized;
351
- }
352
- try {
353
- const serialized = JSON.stringify(normalized, null, 2);
354
- return serialized ?? String(normalized);
355
- } catch {
356
- return String(normalized);
357
- }
358
- }
359
- var absoluteHttpUrlSchema = zod.z.string().url().refine((value) => {
360
- try {
361
- const url = new URL(value);
362
- return url.protocol === "http:" || url.protocol === "https:";
363
- } catch {
364
- return false;
365
- }
366
- }, {
367
- message: "Expected an absolute http(s) URL"
368
- });
369
- var plainObjectSchema = zod.z.custom(
370
- (value) => {
371
- return value !== null && typeof value === "object" && !Array.isArray(value);
372
- },
373
- {
374
- message: "Expected a plain object"
375
- }
376
- );
377
- var nonEmptyStringSchema = zod.z.string().trim().min(1);
378
- function isAbsoluteHttpUrl(value) {
379
- return absoluteHttpUrlSchema.safeParse(value).success;
380
- }
381
- function isPlainObject(value) {
382
- return plainObjectSchema.safeParse(value).success;
383
- }
384
- function hasNonEmptyString(value) {
385
- return nonEmptyStringSchema.safeParse(value).success;
386
- }
387
-
388
- // src/shared/client-log.ts
389
- var DEFAULT_CLIENT_LOG_ENDPOINT = "/inngest";
390
- var CLIENT_LOG_LEVELS = [
391
- "debug",
392
- "info",
393
- "warning",
394
- "error",
395
- "critical",
396
- "success",
397
- "table"
398
- ];
399
- var clientConnectorRequestSchema = zod.z.union([
400
- zod.z.literal("betterstack"),
401
- zod.z.literal("posthog"),
402
- zod.z.literal("sentry"),
403
- zod.z.undefined(),
404
- zod.z.object({
405
- type: zod.z.literal("otlp"),
406
- name: nonEmptyStringSchema
407
- })
408
- ]);
409
- function isClientLogLevel(value) {
410
- return typeof value === "string" && CLIENT_LOG_LEVELS.includes(value);
411
- }
412
- function isClientConnectorRequest(value) {
413
- return clientConnectorRequestSchema.safeParse(value).success;
414
- }
415
- function isClientLogEvent(payload) {
416
- if (!isPlainObject(payload)) {
417
- return false;
418
- }
419
- if (payload.type !== "client_log" || payload.source !== "client" || !isClientLogLevel(payload.level) || typeof payload.id !== "string" || typeof payload.message !== "string" || typeof payload.clientTimestamp !== "string") {
420
- return false;
421
- }
422
- const pageResult = plainObjectSchema.safeParse(payload.page);
423
- const browserResult = plainObjectSchema.safeParse(payload.browser);
424
- const sessionResult = plainObjectSchema.safeParse(payload.session);
425
- if (!pageResult.success || !browserResult.success || !sessionResult.success) {
426
- return false;
427
- }
428
- if (!isClientConnectorRequest(payload.connector)) {
429
- return false;
430
- }
431
- return typeof sessionResult.data.pageId === "string" && typeof sessionResult.data.sessionId === "string";
432
- }
433
- function normalizeEndpointPath(path3) {
434
- if (!path3) {
435
- return DEFAULT_CLIENT_LOG_ENDPOINT;
436
- }
437
- return path3.startsWith("/") ? path3 : `/${path3}`;
438
- }
439
-
440
- // src/shared/once.ts
441
- function createConsoleOnceLogger(method, warnedKeys6 = /* @__PURE__ */ new Set()) {
442
- return (key, message, error) => {
443
- if (warnedKeys6.has(key) || typeof console === "undefined") {
444
- return;
445
- }
446
- const writer = console[method];
447
- if (typeof writer !== "function") {
448
- return;
449
- }
450
- warnedKeys6.add(key);
451
- if (error === void 0) {
452
- writer.call(console, message);
453
- return;
454
- }
455
- writer.call(console, message, error);
456
- };
457
- }
458
- function createWarnOnceLogger(warnedKeys6) {
459
- return createConsoleOnceLogger("warn", warnedKeys6);
460
- }
461
- function createErrorOnceLogger(warnedKeys6) {
462
- return createConsoleOnceLogger("error", warnedKeys6);
463
- }
464
-
465
- // src/core/config.ts
466
- var PACKAGE_NAME = "@blyp/core";
467
- var GITIGNORE_FILE_NAME = ".gitignore";
468
- var CONFIG_FILE_NAMES = [
469
- "blyp.config.ts",
470
- "blyp.config.mts",
471
- "blyp.config.cts",
472
- "blyp.config.js",
473
- "blyp.config.mjs",
474
- "blyp.config.cjs",
475
- "blyp.config.json"
476
- ];
477
- var CONFIG_FILE_NAME = "blyp.config.json";
478
- var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
479
- var DEFAULT_CONNECTOR_SERVICE_NAME = "blyp-app";
480
- var DEFAULT_POSTHOG_SERVICE_NAME = DEFAULT_CONNECTOR_SERVICE_NAME;
481
- var warnedKeys = /* @__PURE__ */ new Set();
482
- var warnOnce = createWarnOnceLogger(warnedKeys);
483
- var DEFAULT_ROTATION_CONFIG = {
484
- enabled: true,
485
- maxSizeBytes: 10 * 1024 * 1024,
486
- maxArchives: 5,
487
- compress: true
488
- };
489
- var DEFAULT_FILE_CONFIG = {
490
- enabled: true,
491
- dir: "",
492
- archiveDir: "",
493
- format: "ndjson",
494
- rotation: DEFAULT_ROTATION_CONFIG
495
- };
496
- var DEFAULT_CLIENT_LOGGING_CONFIG = {
497
- enabled: true,
498
- path: DEFAULT_CLIENT_LOG_ENDPOINT
499
- };
500
- var DEFAULT_DATABASE_RETRY_CONFIG = {
501
- maxRetries: 1,
502
- backoffMs: 100
503
- };
504
- var DEFAULT_DATABASE_DELIVERY_CONFIG = {
505
- strategy: "immediate",
506
- batchSize: 1,
507
- flushIntervalMs: 250,
508
- maxQueueSize: 1e3,
509
- overflowStrategy: "drop-oldest",
510
- flushTimeoutMs: 5e3,
511
- retry: DEFAULT_DATABASE_RETRY_CONFIG
512
- };
513
- var DEFAULT_CONFIG = {
514
- pretty: true,
515
- level: "info",
516
- destination: "file",
517
- file: DEFAULT_FILE_CONFIG,
518
- clientLogging: DEFAULT_CLIENT_LOGGING_CONFIG,
519
- connectors: {}
520
- };
521
- var cachedConfig = null;
522
- function findNearestPackageName(startDir) {
523
- let currentDir = startDir;
524
- while (true) {
525
- const packageJsonPath = path.resolve(currentDir, "package.json");
526
- if (fs.existsSync(packageJsonPath)) {
527
- try {
528
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
529
- if (hasNonEmptyString(packageJson.name)) {
530
- return packageJson.name;
531
- }
532
- } catch {
533
- }
534
- }
535
- const parentDir = path.dirname(currentDir);
536
- if (parentDir === currentDir) {
537
- return void 0;
538
- }
539
- currentDir = parentDir;
540
- }
541
- }
542
- function resolveDefaultConnectorServiceName(cwd = process.cwd()) {
543
- return findNearestPackageName(cwd) ?? DEFAULT_POSTHOG_SERVICE_NAME;
544
- }
545
- function getBootstrapConfig() {
546
- return {
547
- pretty: true,
548
- level: "info",
549
- destination: "file",
550
- file: {
551
- enabled: true,
552
- format: "ndjson",
553
- rotation: {
554
- enabled: true,
555
- maxSizeBytes: 10 * 1024 * 1024,
556
- maxArchives: 5,
557
- compress: true
558
- }
559
- },
560
- clientLogging: {
561
- enabled: true,
562
- path: DEFAULT_CLIENT_LOG_ENDPOINT
563
- },
564
- connectors: {}
565
- };
566
- }
567
- function shouldBootstrapProjectFiles(cwd) {
568
- const packageJsonPath = path.resolve(cwd, "package.json");
569
- if (!fs.existsSync(packageJsonPath)) {
570
- return true;
571
- }
572
- try {
573
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
574
- return packageJson.name !== PACKAGE_NAME;
575
- } catch {
576
- return true;
577
- }
578
- }
579
- function ensureConfigFile(cwd) {
580
- if (CONFIG_FILE_NAMES.some((fileName) => fs.existsSync(path.resolve(cwd, fileName)))) {
581
- return;
582
- }
583
- const configPath = path.resolve(cwd, CONFIG_FILE_NAME);
584
- if (fs.existsSync(configPath)) {
585
- return;
586
- }
587
- try {
588
- fs.writeFileSync(configPath, `${JSON.stringify(getBootstrapConfig(), null, 2)}
589
- `);
590
- } catch (error) {
591
- console.error("[Blyp] Warning: Failed to create blyp.config.json:", error);
592
- }
593
- }
594
- function ensureLogsIgnored(cwd) {
595
- const gitignorePath = path.resolve(cwd, GITIGNORE_FILE_NAME);
596
- if (!fs.existsSync(gitignorePath)) {
597
- try {
598
- fs.writeFileSync(gitignorePath, "logs\n");
599
- } catch (error) {
600
- console.error("[Blyp] Warning: Failed to create .gitignore:", error);
601
- }
602
- return;
603
- }
604
- try {
605
- const currentContent = fs.readFileSync(gitignorePath, "utf-8");
606
- if (/^(?:\/?logs\/?)\s*$/m.test(currentContent)) {
607
- return;
608
- }
609
- const separator = currentContent.endsWith("\n") ? "" : "\n";
610
- fs.appendFileSync(gitignorePath, `${separator}logs
611
- `);
612
- } catch (error) {
613
- console.error("[Blyp] Warning: Failed to update .gitignore:", error);
614
- }
615
- }
616
- function bootstrapProjectFiles() {
617
- const cwd = process.cwd();
618
- if (!shouldBootstrapProjectFiles(cwd)) {
619
- return;
620
- }
621
- ensureConfigFile(cwd);
622
- ensureLogsIgnored(cwd);
623
- }
624
- function findConfigFile() {
625
- const cwd = process.cwd();
626
- const matches = CONFIG_FILE_NAMES.map((fileName) => path.resolve(cwd, fileName)).filter((filePath) => fs.existsSync(filePath));
627
- if (matches.length === 0) {
628
- return null;
629
- }
630
- if (matches.length > 1) {
631
- const preferred = matches[0];
632
- warnOnce(
633
- `config-multiple:${preferred}`,
634
- `[Blyp] Warning: Multiple config files found. Using ${preferred} and ignoring ${matches.slice(1).join(", ")}.`
635
- );
636
- }
637
- const selectedPath = matches[0];
638
- return {
639
- path: selectedPath,
640
- type: selectedPath.endsWith(".json") ? "json" : "jiti"
641
- };
642
- }
643
- function normalizeLoadedConfig(value, configPath) {
644
- const normalized = value && typeof value === "object" && "default" in value && value.default !== void 0 ? value.default : value;
645
- if (!normalized || typeof normalized !== "object" || Array.isArray(normalized)) {
646
- warnOnce(
647
- `config-invalid:${configPath}`,
648
- `[Blyp] Warning: Config file ${configPath} did not export an object. Falling back to defaults.`
649
- );
650
- return {};
651
- }
652
- return normalized;
653
- }
654
- function parseJsonConfigFile(configPath) {
655
- try {
656
- const content = fs.readFileSync(configPath, "utf-8");
657
- return normalizeLoadedConfig(JSON.parse(content), configPath);
658
- } catch (error) {
659
- console.error("[Blyp] Warning: Failed to parse blyp.config.json:", error);
660
- return {};
661
- }
662
- }
663
- function parseExecutableConfigFile(configPath) {
664
- try {
665
- const jiti$1 = jiti.createJiti(process.cwd(), {
666
- interopDefault: true,
667
- moduleCache: false,
668
- fsCache: false
669
- });
670
- return normalizeLoadedConfig(jiti$1(configPath), configPath);
671
- } catch (error) {
672
- console.error(`[Blyp] Warning: Failed to load ${configPath}:`, error);
673
- return {};
674
- }
675
- }
676
- function parseConfigFile(config) {
677
- return config.type === "json" ? parseJsonConfigFile(config.path) : parseExecutableConfigFile(config.path);
678
- }
679
- function isPrismaAdapter(value) {
680
- return !!value && typeof value === "object" && value.type === "prisma";
681
- }
682
- function isDrizzleAdapter(value) {
683
- return !!value && typeof value === "object" && value.type === "drizzle";
684
- }
685
- function mergeDatabaseRetryConfig(base, override) {
686
- return {
687
- ...DEFAULT_DATABASE_RETRY_CONFIG,
688
- ...base,
689
- ...override
690
- };
691
- }
692
- function mergeDatabaseDeliveryConfig(base, override) {
693
- return {
694
- ...DEFAULT_DATABASE_DELIVERY_CONFIG,
695
- ...base,
696
- ...override,
697
- retry: mergeDatabaseRetryConfig(base?.retry, override?.retry)
698
- };
699
- }
700
- function hasPrismaDelegate(adapter) {
701
- const model = adapter.model ?? "blypLog";
702
- const client = adapter.client;
703
- const delegate = client?.[model];
704
- return !!delegate && typeof delegate.create === "function";
705
- }
706
- function hasDrizzleAdapterShape(adapter) {
707
- const db = adapter.db;
708
- return !!db && typeof db.insert === "function" && adapter.table !== void 0;
709
- }
710
- function resolveDatabaseLoggerConfig(config, sourceType) {
711
- if (!config) {
712
- return void 0;
713
- }
714
- const adapter = config.adapter;
715
- let ready = false;
716
- if (sourceType === "json") {
717
- warnOnce(
718
- "database-json-config",
719
- "[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."
720
- );
721
- } else if (config.dialect !== "postgres" && config.dialect !== "mysql") {
722
- warnOnce(
723
- `database-dialect:${String(config.dialect)}`,
724
- `[Blyp] Warning: Unsupported database dialect "${String(config.dialect)}". Database logging is disabled.`
725
- );
726
- } else if (!adapter) {
727
- warnOnce(
728
- "database-adapter-missing",
729
- "[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled."
730
- );
731
- } else if (isPrismaAdapter(adapter)) {
732
- ready = hasPrismaDelegate({
733
- ...adapter,
734
- model: adapter.model ?? "blypLog"
735
- });
736
- if (!ready) {
737
- warnOnce(
738
- "database-prisma-missing",
739
- `[Blyp] Warning: Prisma database adapter is missing the "${adapter.model ?? "blypLog"}" delegate or its create method. Database logging is disabled.`
740
- );
741
- }
742
- } else if (isDrizzleAdapter(adapter)) {
743
- ready = hasDrizzleAdapterShape(adapter);
744
- if (!ready) {
745
- warnOnce(
746
- "database-drizzle-missing",
747
- "[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled."
748
- );
749
- }
750
- }
751
- const normalizedAdapter = isPrismaAdapter(adapter) ? {
752
- ...adapter,
753
- model: adapter.model ?? "blypLog"
754
- } : adapter;
755
- return {
756
- dialect: config.dialect,
757
- adapter: normalizedAdapter,
758
- delivery: mergeDatabaseDeliveryConfig(void 0, config.delivery),
759
- ready,
760
- status: ready ? "enabled" : "missing"
761
- };
762
- }
763
- function mergeRotationConfig(base, override) {
764
- return {
765
- ...DEFAULT_ROTATION_CONFIG,
766
- ...base,
767
- ...override
768
- };
769
- }
770
- function mergeFileConfig(base, override) {
771
- return {
772
- ...DEFAULT_FILE_CONFIG,
773
- ...base,
774
- ...override,
775
- rotation: mergeRotationConfig(base?.rotation, override?.rotation)
776
- };
777
- }
778
- function mergeClientLoggingConfig(base, override) {
779
- return {
780
- ...DEFAULT_CLIENT_LOGGING_CONFIG,
781
- ...base,
782
- ...override,
783
- path: override?.path ?? base?.path ?? DEFAULT_CLIENT_LOGGING_CONFIG.path
784
- };
785
- }
786
- function mergeDatabaseLoggerConfig(base, override, sourceType) {
787
- if (!base && !override) {
788
- return void 0;
789
- }
790
- return resolveDatabaseLoggerConfig(
791
- {
792
- dialect: override?.dialect ?? base?.dialect,
793
- adapter: override?.adapter ?? base?.adapter,
794
- delivery: {
795
- ...base?.delivery ?? {},
796
- ...override?.delivery ?? {},
797
- retry: {
798
- ...base?.delivery?.retry ?? {},
799
- ...override?.delivery?.retry ?? {}
800
- }
801
- }
802
- },
803
- sourceType
804
- );
805
- }
806
- function mergePostHogConnectorConfig(base, override) {
807
- const enabled = override?.enabled ?? base?.enabled ?? false;
808
- const projectKey = override?.projectKey ?? base?.projectKey;
809
- const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
810
- const errorTrackingMode = override?.errorTracking?.mode ?? baseErrorTracking?.mode ?? "auto";
811
- const errorTrackingEnabled = override?.errorTracking?.enabled ?? baseErrorTracking?.enabled ?? enabled;
812
- const errorTrackingReady = enabled && errorTrackingEnabled && typeof projectKey === "string" && projectKey.trim().length > 0;
813
- return {
814
- enabled,
815
- mode: override?.mode ?? base?.mode ?? "auto",
816
- projectKey,
817
- host: override?.host ?? base?.host ?? DEFAULT_POSTHOG_HOST,
818
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
819
- errorTracking: {
820
- enabled: errorTrackingEnabled,
821
- mode: errorTrackingMode,
822
- enableExceptionAutocapture: override?.errorTracking?.enableExceptionAutocapture ?? baseErrorTracking?.enableExceptionAutocapture ?? errorTrackingMode === "auto",
823
- ready: errorTrackingReady,
824
- status: errorTrackingReady ? "enabled" : "missing"
825
- }
826
- };
827
- }
828
- function mergeBetterStackConnectorConfig(base, override) {
829
- const sourceToken = override?.sourceToken ?? base?.sourceToken;
830
- const ingestingHost = override?.ingestingHost ?? base?.ingestingHost;
831
- const enabled = override?.enabled ?? base?.enabled ?? false;
832
- const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
833
- const errorTracking = mergeBetterStackErrorTrackingConfig(
834
- enabled,
835
- baseErrorTracking,
836
- override?.errorTracking
837
- );
838
- const ready = enabled && hasNonEmptyString(sourceToken) && isAbsoluteHttpUrl(ingestingHost);
839
- return {
840
- enabled,
841
- mode: override?.mode ?? base?.mode ?? "auto",
842
- sourceToken,
843
- ingestingHost,
844
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
845
- errorTracking,
846
- ready,
847
- status: ready ? "enabled" : "missing"
848
- };
849
- }
850
- function mergeBetterStackErrorTrackingConfig(connectorEnabled, base, override) {
851
- const dsn = override?.dsn ?? base?.dsn;
852
- const enabled = override?.enabled ?? base?.enabled ?? connectorEnabled;
853
- const ready = enabled && hasNonEmptyString(dsn);
854
- return {
855
- enabled,
856
- dsn,
857
- tracesSampleRate: override?.tracesSampleRate ?? base?.tracesSampleRate ?? 1,
858
- environment: override?.environment ?? base?.environment,
859
- release: override?.release ?? base?.release,
860
- ready,
861
- status: ready ? "enabled" : "missing"
862
- };
863
- }
864
- function mergeSentryConnectorConfig(base, override) {
865
- const dsn = override?.dsn ?? base?.dsn;
866
- const enabled = override?.enabled ?? base?.enabled ?? false;
867
- const ready = enabled && typeof dsn === "string" && dsn.trim().length > 0;
868
- return {
869
- enabled,
870
- mode: override?.mode ?? base?.mode ?? "auto",
871
- dsn,
872
- environment: override?.environment ?? base?.environment,
873
- release: override?.release ?? base?.release,
874
- ready,
875
- status: ready ? "enabled" : "missing"
876
- };
877
- }
878
- function mergeOTLPConnectorConfig(base, override) {
879
- const endpoint = override?.endpoint ?? base?.endpoint;
880
- const enabled = override?.enabled ?? base?.enabled ?? false;
881
- const resolvedHeaders = {
882
- ...{},
883
- ...override?.headers ?? {}
884
- };
885
- const ready = enabled && isAbsoluteHttpUrl(endpoint);
886
- return {
887
- name: override?.name ?? base?.name ?? "",
888
- enabled,
889
- mode: override?.mode ?? base?.mode ?? "auto",
890
- endpoint,
891
- headers: resolvedHeaders,
892
- auth: override?.auth ?? base?.auth,
893
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
894
- ready,
895
- status: ready ? "enabled" : "missing"
896
- };
897
- }
898
- function mergeOTLPConnectorsConfig(base, override) {
899
- const source = override ?? base ?? [];
900
- const deduped = /* @__PURE__ */ new Map();
901
- for (const connector of source) {
902
- if (!connector || typeof connector.name !== "string" || connector.name.length === 0) {
903
- continue;
904
- }
905
- if (deduped.has(connector.name)) {
906
- warnOnce(
907
- `otlp-duplicate:${connector.name}`,
908
- `[Blyp] Warning: Duplicate OTLP connector name "${connector.name}" found. Using the last definition.`
909
- );
910
- }
911
- deduped.set(connector.name, mergeOTLPConnectorConfig(void 0, connector));
912
- }
913
- return Array.from(deduped.values());
914
- }
915
- function mergeConnectorsConfig(base, override) {
916
- return {
917
- betterstack: mergeBetterStackConnectorConfig(base?.betterstack, override?.betterstack),
918
- posthog: mergePostHogConnectorConfig(base?.posthog, override?.posthog),
919
- sentry: mergeSentryConnectorConfig(base?.sentry, override?.sentry),
920
- otlp: mergeOTLPConnectorsConfig(base?.otlp, override?.otlp)
921
- };
922
- }
923
- function mergeBlypConfig(base, override = {}, options = {}) {
924
- return {
925
- ...base,
926
- ...override,
927
- destination: override.destination ?? base.destination ?? "file",
928
- file: mergeFileConfig(base.file, override.file),
929
- database: mergeDatabaseLoggerConfig(base.database, override.database, options.configFileType),
930
- clientLogging: mergeClientLoggingConfig(base.clientLogging, override.clientLogging),
931
- connectors: mergeConnectorsConfig(base.connectors, override.connectors)
932
- };
933
- }
934
- function loadConfig() {
935
- if (cachedConfig !== null) {
936
- return cachedConfig;
937
- }
938
- bootstrapProjectFiles();
939
- const configFile = findConfigFile();
940
- if (configFile) {
941
- const userConfig = parseConfigFile(configFile);
942
- cachedConfig = mergeBlypConfig(DEFAULT_CONFIG, userConfig, {
943
- configFileType: configFile.type
944
- });
945
- } else {
946
- cachedConfig = mergeBlypConfig(DEFAULT_CONFIG);
947
- }
948
- return cachedConfig;
949
- }
950
- function resolveConfig(overrides = {}) {
951
- return mergeBlypConfig(loadConfig(), overrides);
952
- }
953
-
954
- // src/core/helpers.ts
955
- function normalizePath(path3) {
956
- const queryIndex = path3.indexOf("?");
957
- let withoutQuery = queryIndex >= 0 ? path3.substring(0, queryIndex) : path3;
958
- if (withoutQuery.endsWith("/") && withoutQuery.length > 1) {
959
- withoutQuery = withoutQuery.slice(0, -1);
960
- }
961
- if (!withoutQuery.startsWith("/")) {
962
- withoutQuery = "/" + withoutQuery;
963
- }
964
- return withoutQuery;
965
- }
966
- function normalizePattern(pattern) {
967
- const queryIndex = pattern.indexOf("?");
968
- let withoutQuery = queryIndex >= 0 ? pattern.substring(0, queryIndex) : pattern;
969
- if (withoutQuery.endsWith("/") && withoutQuery.length > 1) {
970
- withoutQuery = withoutQuery.slice(0, -1);
971
- }
972
- if (!withoutQuery.startsWith("/")) {
973
- withoutQuery = "/" + withoutQuery;
974
- }
975
- return withoutQuery;
976
- }
977
- function shouldIgnorePath(path3, ignorePaths) {
978
- if (!ignorePaths || ignorePaths.length === 0) {
979
- return false;
980
- }
981
- const normalizedPath = normalizePath(path3);
982
- return ignorePaths.some((ignoredPattern) => {
983
- const normalizedPattern = normalizePattern(ignoredPattern);
984
- if (normalizedPattern === normalizedPath) {
985
- return true;
986
- }
987
- if (normalizedPattern === "/**" || normalizedPattern === "**") {
988
- return true;
989
- }
990
- if (normalizedPattern === "/*") {
991
- const segments = normalizedPath.split("/").filter((s) => s.length > 0);
992
- return segments.length === 1;
993
- }
994
- if (normalizedPattern.endsWith("/*") && !normalizedPattern.includes("**")) {
995
- const prefix = normalizedPattern.slice(0, -1);
996
- if (normalizedPath.startsWith(prefix)) {
997
- const rest = normalizedPath.slice(prefix.length);
998
- const restSegments = rest.split("/").filter((s) => s.length > 0);
999
- return restSegments.length === 1;
1000
- }
1001
- return false;
1002
- }
1003
- if (normalizedPattern.includes("**")) {
1004
- if (normalizedPattern === "/**") {
1005
- return true;
1006
- }
1007
- if (normalizedPattern.startsWith("/") && normalizedPattern.endsWith("**")) {
1008
- let prefix2 = normalizedPattern.slice(0, -2);
1009
- if (prefix2.endsWith("/") && prefix2.length > 1) {
1010
- prefix2 = prefix2.slice(0, -1);
1011
- }
1012
- if (prefix2 === normalizedPath) {
1013
- return true;
1014
- }
1015
- return normalizedPath.startsWith(prefix2 + "/");
1016
- }
1017
- const starIndex = normalizedPattern.indexOf("**");
1018
- let prefix = normalizedPattern.substring(0, starIndex);
1019
- const suffix = normalizedPattern.substring(starIndex + 2);
1020
- if (prefix.endsWith("/") && prefix.length > 1) {
1021
- prefix = prefix.slice(0, -1);
1022
- }
1023
- if (prefix === "" && suffix === "") {
1024
- return true;
1025
- }
1026
- if (prefix !== "" && suffix === "") {
1027
- return normalizedPath.startsWith(prefix + "/");
1028
- }
1029
- if (prefix === "" && suffix !== "") {
1030
- return normalizedPath.endsWith(suffix) || normalizedPath.includes(suffix + "/");
1031
- }
1032
- if (prefix !== "" && suffix !== "") {
1033
- return normalizedPath.startsWith(prefix) && (normalizedPath.endsWith(suffix) || normalizedPath.includes(suffix + "/"));
1034
- }
1035
- return false;
1036
- }
1037
- if (normalizedPattern.includes("*")) {
1038
- const lastDotIndex = normalizedPattern.lastIndexOf(".");
1039
- const lastStarIndex = normalizedPattern.lastIndexOf("*");
1040
- if (lastDotIndex > lastStarIndex && lastStarIndex > 0) {
1041
- const charBeforeStar = normalizedPattern[lastStarIndex - 1];
1042
- if (charBeforeStar === "/") {
1043
- const extPattern = normalizedPattern.slice(lastStarIndex);
1044
- const filePart = normalizedPath.slice(normalizedPath.lastIndexOf("/") + 1);
1045
- const extIndex = filePart.lastIndexOf(".");
1046
- if (extIndex > 0) {
1047
- const actualExt = filePart.slice(extIndex);
1048
- return actualExt === extPattern;
1049
- }
1050
- }
1051
- }
1052
- const regexPattern = normalizedPattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*");
1053
- const regex = new RegExp("^" + regexPattern + "$");
1054
- return regex.test(normalizedPath);
1055
- }
1056
- return false;
1057
- });
1058
- }
1059
- function gzipBuffer(buf) {
1060
- return Buffer.from(fflate.gzipSync(buf));
1061
- }
1062
- function warnWithConsole(message, error) {
1063
- console.warn(`[Blyp] Warning: ${message}`, error);
1064
- }
1065
- function ensureDirectory(dirPath) {
1066
- fs__default.default.mkdirSync(dirPath, { recursive: true });
1067
- }
1068
- function getFileSize(filePath) {
1069
- try {
1070
- return fs__default.default.statSync(filePath).size;
1071
- } catch {
1072
- return 0;
1073
- }
1074
- }
1075
- function formatArchiveTimestamp(timestamp) {
1076
- const year = timestamp.getUTCFullYear();
1077
- const month = String(timestamp.getUTCMonth() + 1).padStart(2, "0");
1078
- const day = String(timestamp.getUTCDate()).padStart(2, "0");
1079
- const hours = String(timestamp.getUTCHours()).padStart(2, "0");
1080
- const minutes = String(timestamp.getUTCMinutes()).padStart(2, "0");
1081
- const seconds = String(timestamp.getUTCSeconds()).padStart(2, "0");
1082
- return `${year}${month}${day}T${hours}${minutes}${seconds}Z`;
1083
- }
1084
- function getUniqueArchivePath(basePath, extension) {
1085
- let candidate = `${basePath}${extension}`;
1086
- let suffix = 1;
1087
- while (fs__default.default.existsSync(candidate)) {
1088
- candidate = `${basePath}-${suffix}${extension}`;
1089
- suffix += 1;
1090
- }
1091
- return candidate;
1092
- }
1093
- function pruneArchives(archiveDir, archivePrefix, maxArchives, warn) {
1094
- const prefix = `${archivePrefix}.`;
1095
- try {
1096
- const archivePaths = fs__default.default.readdirSync(archiveDir).filter(
1097
- (name) => name.startsWith(prefix) && (name.endsWith(".ndjson") || name.endsWith(".ndjson.gz"))
1098
- ).map((name) => path__default.default.join(archiveDir, name)).sort((left, right) => {
1099
- return fs__default.default.statSync(left).mtimeMs - fs__default.default.statSync(right).mtimeMs;
1100
- });
1101
- const deleteCount = Math.max(archivePaths.length - maxArchives, 0);
1102
- for (let index = 0; index < deleteCount; index += 1) {
1103
- fs__default.default.rmSync(archivePaths[index]);
1104
- }
1105
- } catch (error) {
1106
- warn(`Failed to prune archives for ${archivePrefix}`, error);
1107
- }
1108
- }
1109
- function createSafeReplacer() {
1110
- const seen = /* @__PURE__ */ new WeakSet();
1111
- return (_key, value) => {
1112
- if (typeof value === "function") {
1113
- return `[Function: ${value.name || "anonymous"}]`;
1114
- }
1115
- if (value === void 0) {
1116
- return "[undefined]";
1117
- }
1118
- if (typeof value === "symbol") {
1119
- return value.toString();
1120
- }
1121
- if (value !== null && typeof value === "object") {
1122
- if (seen.has(value)) {
1123
- return "[Circular]";
1124
- }
1125
- seen.add(value);
1126
- }
1127
- return value;
1128
- };
1129
- }
1130
- function serializeLogRecord(record) {
1131
- return JSON.stringify(record, createSafeReplacer());
1132
- }
1133
- function resolveFileLoggerConfig(config) {
1134
- const fileConfig = config.file;
1135
- const dir = fileConfig?.dir || config.logDir || path__default.default.join(process.cwd(), "logs");
1136
- const archiveDir = fileConfig?.archiveDir || path__default.default.join(dir, "archive");
1137
- const rotation = fileConfig?.rotation;
1138
- return {
1139
- enabled: fileConfig?.enabled ?? true,
1140
- dir,
1141
- archiveDir,
1142
- rotationEnabled: rotation?.enabled ?? true,
1143
- maxSizeBytes: rotation?.maxSizeBytes ?? 10 * 1024 * 1024,
1144
- maxArchives: rotation?.maxArchives ?? 5,
1145
- compress: rotation?.compress ?? true
1146
- };
1147
- }
1148
- var RotatingFileLogger = class {
1149
- constructor(config, dependencies = {}) {
1150
- __publicField(this, "config");
1151
- __publicField(this, "gzip");
1152
- __publicField(this, "warn");
1153
- __publicField(this, "combined");
1154
- __publicField(this, "error");
1155
- this.config = resolveFileLoggerConfig(config);
1156
- this.gzip = dependencies.gzip ?? gzipBuffer;
1157
- this.warn = dependencies.warn ?? warnWithConsole;
1158
- this.combined = {
1159
- activePath: path__default.default.join(this.config.dir, "log.ndjson"),
1160
- archivePrefix: "log",
1161
- bytes: 0,
1162
- queue: [],
1163
- processing: false
1164
- };
1165
- this.error = {
1166
- activePath: path__default.default.join(this.config.dir, "log.error.ndjson"),
1167
- archivePrefix: "log.error",
1168
- bytes: 0,
1169
- queue: [],
1170
- processing: false
1171
- };
1172
- if (!this.config.enabled) {
1173
- return;
1174
- }
1175
- ensureDirectory(this.config.dir);
1176
- ensureDirectory(this.config.archiveDir);
1177
- this.seedStream(this.combined);
1178
- this.seedStream(this.error);
1179
- }
1180
- write(record) {
1181
- if (!this.config.enabled) {
1182
- return;
1183
- }
1184
- const line = `${serializeLogRecord(record)}
1185
- `;
1186
- this.enqueue(this.combined, line);
1187
- if (record.level === "error" || record.level === "critical") {
1188
- this.enqueue(this.error, line);
1189
- }
1190
- }
1191
- enqueue(stream, line) {
1192
- stream.queue.push(line);
1193
- this.processQueue(stream);
1194
- }
1195
- processQueue(stream) {
1196
- if (stream.processing) {
1197
- return;
1198
- }
1199
- stream.processing = true;
1200
- try {
1201
- while (stream.queue.length > 0) {
1202
- const queuedLine = stream.queue.shift();
1203
- if (queuedLine === void 0) {
1204
- continue;
1205
- }
1206
- try {
1207
- this.append(stream, queuedLine);
1208
- } catch (error) {
1209
- this.warn(`Failed writing log line for ${stream.archivePrefix}`, error);
1210
- }
1211
- }
1212
- } finally {
1213
- stream.processing = false;
1214
- }
1215
- }
1216
- seedStream(stream) {
1217
- stream.bytes = getFileSize(stream.activePath);
1218
- if (this.config.rotationEnabled && stream.bytes > this.config.maxSizeBytes && stream.bytes > 0) {
1219
- this.rotate(stream);
1220
- fs__default.default.closeSync(fs__default.default.openSync(stream.activePath, "a"));
1221
- stream.bytes = 0;
1222
- }
1223
- }
1224
- append(stream, line) {
1225
- ensureDirectory(this.config.dir);
1226
- const lineBytes = Buffer.byteLength(line, "utf8");
1227
- if (this.config.rotationEnabled && stream.bytes > 0 && stream.bytes + lineBytes > this.config.maxSizeBytes) {
1228
- this.rotate(stream);
1229
- }
1230
- fs__default.default.appendFileSync(stream.activePath, line, "utf8");
1231
- stream.bytes += lineBytes;
1232
- }
1233
- rotate(stream) {
1234
- ensureDirectory(this.config.archiveDir);
1235
- if (!fs__default.default.existsSync(stream.activePath) || stream.bytes === 0) {
1236
- stream.bytes = 0;
1237
- return;
1238
- }
1239
- const archiveTimestamp = formatArchiveTimestamp(/* @__PURE__ */ new Date());
1240
- const archiveBasePath = path__default.default.join(
1241
- this.config.archiveDir,
1242
- `${stream.archivePrefix}.${archiveTimestamp}`
1243
- );
1244
- const archivePath = getUniqueArchivePath(archiveBasePath, ".ndjson");
1245
- fs__default.default.renameSync(stream.activePath, archivePath);
1246
- if (this.config.compress) {
1247
- try {
1248
- const compressedPath = `${archivePath}.gz`;
1249
- const gzipped = this.gzip(fs__default.default.readFileSync(archivePath));
1250
- fs__default.default.writeFileSync(compressedPath, gzipped);
1251
- fs__default.default.rmSync(archivePath);
1252
- } catch (error) {
1253
- this.warn(`Failed to gzip archive ${archivePath}`, error);
1254
- }
1255
- }
1256
- stream.bytes = 0;
1257
- pruneArchives(this.config.archiveDir, stream.archivePrefix, this.config.maxArchives, this.warn);
1258
- }
1259
- };
1260
- function createFileLogger(config) {
1261
- return new RotatingFileLogger(config);
1262
- }
1263
-
1264
- // src/connectors/shared.ts
1265
- function isBlypConfig(config) {
1266
- return isPlainObject(config) && ("connectors" in config || "pretty" in config || "level" in config);
1267
- }
1268
- function getPrimaryPayload(record) {
1269
- return isPlainObject(record.data) ? record.data : record;
1270
- }
1271
- function getField(record, key) {
1272
- if (key in record) {
1273
- const direct = record[key];
1274
- if (typeof direct === "string" || typeof direct === "number") {
1275
- return direct;
1276
- }
1277
- }
1278
- const payload = getPrimaryPayload(record);
1279
- const nested = payload[key];
1280
- if (typeof nested === "string" || typeof nested === "number") {
1281
- return nested;
1282
- }
1283
- return void 0;
1284
- }
1285
- function getClientPageField(record, key) {
1286
- const payload = getPrimaryPayload(record);
1287
- const page = isPlainObject(payload.page) ? payload.page : void 0;
1288
- const value = page?.[key];
1289
- return typeof value === "string" ? value : void 0;
1290
- }
1291
- function getClientSessionField(record, key) {
1292
- const payload = getPrimaryPayload(record);
1293
- const session = isPlainObject(payload.session) ? payload.session : void 0;
1294
- const value = session?.[key];
1295
- return typeof value === "string" ? value : void 0;
1296
- }
1297
- function getRecordType(record) {
1298
- return getField(record, "type");
1299
- }
1300
-
1301
- // src/connectors/posthog/sender.ts
1302
- var PREVIOUSLY_CAPTURED_ERROR_KEY = "__posthog_previously_captured_error";
1303
- var warnedKeys2 = /* @__PURE__ */ new Set();
1304
- var testHooks = {};
1305
- var warnOnce2 = createErrorOnceLogger(warnedKeys2);
1306
- function normalizeHost(host) {
1307
- const trimmed = (host || "https://us.i.posthog.com").trim();
1308
- return trimmed.replace(/\/+$/, "");
1309
- }
1310
- function buildRecordAttributes(record, source) {
1311
- const recordType = getRecordType(record);
1312
- const caller = typeof record.caller === "string" ? record.caller : void 0;
1313
- const groupId = getField(record, "groupId");
1314
- const method = getField(record, "method");
1315
- const path3 = getField(record, "path");
1316
- const status = getField(record, "status");
1317
- const duration = getField(record, "duration");
1318
- const pagePath = getClientPageField(record, "pathname");
1319
- const pageUrl = getClientPageField(record, "url");
1320
- const sessionId = getClientSessionField(record, "sessionId");
1321
- const pageId = getClientSessionField(record, "pageId");
1322
- const attributes = {
1323
- "blyp.level": record.level,
1324
- "blyp.source": source,
1325
- "blyp.payload": serializeLogRecord(record)
1326
- };
1327
- const ifTruthy = [
1328
- ["blyp.type", recordType],
1329
- ["blyp.caller", caller],
1330
- ["blyp.group_id", groupId],
1331
- ["http.method", method],
1332
- ["url.path", path3],
1333
- ["client.page_path", pagePath],
1334
- ["client.page_url", pageUrl],
1335
- ["client.session_id", sessionId],
1336
- ["client.page_id", pageId]
1337
- ];
1338
- const ifDefined = [
1339
- ["http.status_code", status],
1340
- ["blyp.duration_ms", duration]
1341
- ];
1342
- for (const [k, v] of ifTruthy) if (v) attributes[k] = v;
1343
- for (const [k, v] of ifDefined) if (v !== void 0) attributes[k] = v;
1344
- return attributes;
1345
- }
1346
- function normalizeExceptionProperties(value) {
1347
- if (!isPlainObject(value)) {
1348
- return {};
1349
- }
1350
- return normalizeLogValue(value);
1351
- }
1352
- function assignExceptionField(target, key, value) {
1353
- if (value === void 0) {
1354
- return;
1355
- }
1356
- try {
1357
- target[key] = value;
1358
- } catch {
1359
- }
1360
- }
1361
- function createSyntheticError(message, source) {
1362
- const error = new Error(message);
1363
- const name = hasNonEmptyString(source.name) ? source.name : "Error";
1364
- error.name = name;
1365
- if (hasNonEmptyString(source.stack)) {
1366
- error.stack = source.stack;
1367
- }
1368
- assignExceptionField(error, "cause", source.cause);
1369
- assignExceptionField(error, "status", source.status);
1370
- assignExceptionField(error, "statusCode", source.statusCode);
1371
- assignExceptionField(error, "code", source.code);
1372
- assignExceptionField(error, "why", source.why);
1373
- assignExceptionField(error, "fix", source.fix);
1374
- assignExceptionField(error, "link", source.link);
1375
- assignExceptionField(error, "details", source.details);
1376
- return error;
1377
- }
1378
- function normalizeExceptionInput(input, fallbackMessage = "Unknown error") {
1379
- if (input instanceof Error) {
1380
- return {
1381
- error: input,
1382
- properties: normalizeExceptionProperties(input)
1383
- };
1384
- }
1385
- if (isPlainObject(input)) {
1386
- const message = hasNonEmptyString(input.message) ? input.message : hasNonEmptyString(input.error) ? input.error : fallbackMessage;
1387
- return {
1388
- error: createSyntheticError(message, input),
1389
- properties: normalizeExceptionProperties(input)
1390
- };
1391
- }
1392
- if (typeof input === "string") {
1393
- return {
1394
- error: new Error(input),
1395
- properties: {
1396
- message: input
1397
- }
1398
- };
1399
- }
1400
- return {
1401
- error: new Error(fallbackMessage),
1402
- properties: {
1403
- value: normalizeLogValue(input)
1404
- }
1405
- };
1406
- }
1407
- function createExceptionPropertiesFromRecord(record, source) {
1408
- return buildRecordAttributes(record, source);
1409
- }
1410
- function isPreviouslyCapturedPostHogError(value) {
1411
- return isPlainObject(value) && value[PREVIOUSLY_CAPTURED_ERROR_KEY] === true;
1412
- }
1413
- function markPostHogCapturedError(value) {
1414
- if (!isPlainObject(value) || isPreviouslyCapturedPostHogError(value)) {
1415
- return;
1416
- }
1417
- try {
1418
- Object.defineProperty(value, PREVIOUSLY_CAPTURED_ERROR_KEY, {
1419
- value: true,
1420
- enumerable: false,
1421
- configurable: true,
1422
- writable: true
1423
- });
1424
- } catch {
1425
- try {
1426
- value[PREVIOUSLY_CAPTURED_ERROR_KEY] = true;
1427
- } catch {
1428
- }
1429
- }
1430
- }
1431
- function isClientLogRecord(record) {
1432
- return getRecordType(record) === "client_log";
1433
- }
1434
- function normalizePostHogRecord(record, connector, source = "server") {
1435
- const severity = resolveSeverity(record.level);
1436
- const body = typeof record.message === "string" ? record.message : String(record.message);
1437
- return {
1438
- body,
1439
- severityText: severity.text,
1440
- severityNumber: severity.number,
1441
- attributes: buildRecordAttributes(record, source),
1442
- resourceAttributes: {
1443
- "service.name": connector.serviceName
1444
- }
1445
- };
1446
- }
1447
- function resolveSeverity(level) {
1448
- switch (level) {
1449
- case "debug":
1450
- return { text: "debug", number: apiLogs.SeverityNumber.DEBUG };
1451
- case "warning":
1452
- case "warn":
1453
- return { text: "warn", number: apiLogs.SeverityNumber.WARN };
1454
- case "error":
1455
- return { text: "error", number: apiLogs.SeverityNumber.ERROR };
1456
- case "critical":
1457
- return { text: "fatal", number: apiLogs.SeverityNumber.FATAL };
1458
- case "success":
1459
- case "table":
1460
- case "info":
1461
- default:
1462
- return { text: "info", number: apiLogs.SeverityNumber.INFO };
1463
- }
1464
- }
1465
- function registerShutdownHooks(key, shutdown) {
1466
- const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
1467
- for (const event of handlers) {
1468
- process.once(event, () => {
1469
- void shutdown().catch((error) => {
1470
- warnOnce2(
1471
- `${key}:shutdown`,
1472
- "[Blyp] Failed to flush PostHog telemetry during shutdown.",
1473
- error
1474
- );
1475
- });
1476
- });
1477
- }
1478
- }
1479
- function createDefaultTransport(connector) {
1480
- const exporter = new exporterLogsOtlpHttp.OTLPLogExporter({
1481
- url: `${normalizeHost(connector.host)}/i/v1/logs`,
1482
- headers: {
1483
- Authorization: `Bearer ${connector.projectKey}`
1484
- }
1485
- });
1486
- const provider = new sdkLogs.LoggerProvider({
1487
- resource: resources.resourceFromAttributes({
1488
- "service.name": connector.serviceName
1489
- }),
1490
- processors: [new sdkLogs.BatchLogRecordProcessor(exporter)]
1491
- });
1492
- const logger2 = provider.getLogger("blyp-posthog");
1493
- return {
1494
- emit(payload) {
1495
- logger2.emit({
1496
- body: payload.body,
1497
- severityText: payload.severityText,
1498
- severityNumber: payload.severityNumber,
1499
- attributes: payload.attributes
1500
- });
1501
- },
1502
- flush() {
1503
- return provider.forceFlush();
1504
- },
1505
- shutdown() {
1506
- return provider.shutdown();
1507
- }
1508
- };
1509
- }
1510
- function createDefaultExceptionClient(connector) {
1511
- const client = new posthogNode.PostHog(connector.projectKey ?? "", {
1512
- host: connector.host,
1513
- enableExceptionAutocapture: connector.errorTracking.enableExceptionAutocapture
1514
- });
1515
- return {
1516
- captureException(error, distinctId, additionalProperties) {
1517
- return client.captureExceptionImmediate(error, distinctId, additionalProperties);
1518
- },
1519
- shutdown() {
1520
- return client._shutdown();
1521
- }
1522
- };
1523
- }
1524
- function resolveConnectorConfig(config) {
1525
- const connector = isBlypConfig(config) ? config.connectors?.posthog : config;
1526
- const enabled = connector?.enabled ?? false;
1527
- const projectKey = connector?.projectKey;
1528
- const errorTrackingEnabled = connector?.errorTracking?.enabled ?? enabled;
1529
- const errorTrackingMode = connector?.errorTracking?.mode ?? "auto";
1530
- const errorTrackingReady = enabled && errorTrackingEnabled && hasNonEmptyString(projectKey);
1531
- return {
1532
- enabled,
1533
- mode: connector?.mode ?? "auto",
1534
- projectKey,
1535
- host: normalizeHost(connector?.host),
1536
- serviceName: connector?.serviceName ?? "blyp-app",
1537
- errorTracking: {
1538
- enabled: errorTrackingEnabled,
1539
- mode: errorTrackingMode,
1540
- enableExceptionAutocapture: connector?.errorTracking?.enableExceptionAutocapture ?? errorTrackingMode === "auto",
1541
- ready: errorTrackingReady,
1542
- status: errorTrackingReady ? "enabled" : "missing"
1543
- }
1544
- };
1545
- }
1546
- function createPostHogSender(config) {
1547
- const connector = resolveConnectorConfig(config);
1548
- const key = `${connector.serviceName}:${connector.host}:${connector.mode}`;
1549
- const ready = connector.enabled === true && hasNonEmptyString(connector.projectKey);
1550
- const transport = ready ? testHooks.createTransport?.(connector) ?? createDefaultTransport(connector) : void 0;
1551
- const exceptionClient = connector.errorTracking.ready ? testHooks.createExceptionClient?.(connector) ?? createDefaultExceptionClient(connector) : void 0;
1552
- const shutdown = async () => {
1553
- if (transport?.shutdown) {
1554
- await transport.shutdown();
1555
- } else if (transport?.flush) {
1556
- await transport.flush();
1557
- }
1558
- if (exceptionClient?.shutdown) {
1559
- await exceptionClient.shutdown();
1560
- }
1561
- };
1562
- if (transport || exceptionClient) {
1563
- registerShutdownHooks(key, shutdown);
1564
- }
1565
- const emitUnavailableWarning = () => {
1566
- warnOnce2(
1567
- `posthog-unavailable:${key}`,
1568
- "[Blyp] PostHog connector is not configured. Skipping PostHog delivery."
1569
- );
1570
- };
1571
- const emitExceptionUnavailableWarning = () => {
1572
- warnOnce2(
1573
- `posthog-exception-unavailable:${key}`,
1574
- "[Blyp] PostHog error tracking is not configured. Skipping PostHog exception capture."
1575
- );
1576
- };
1577
- return {
1578
- enabled: connector.enabled,
1579
- ready,
1580
- mode: connector.mode,
1581
- serviceName: connector.serviceName,
1582
- host: connector.host,
1583
- status: ready ? "enabled" : "missing",
1584
- errorTracking: {
1585
- enabled: connector.errorTracking.enabled,
1586
- ready: connector.errorTracking.ready,
1587
- mode: connector.errorTracking.mode,
1588
- status: connector.errorTracking.status,
1589
- enableExceptionAutocapture: connector.errorTracking.enableExceptionAutocapture
1590
- },
1591
- shouldAutoForwardServerLogs() {
1592
- return ready && connector.mode === "auto";
1593
- },
1594
- shouldAutoCaptureExceptions() {
1595
- return connector.errorTracking.ready && connector.errorTracking.mode === "auto";
1596
- },
1597
- send(record, options = {}) {
1598
- const source = options.source ?? "server";
1599
- if (!ready || !transport) {
1600
- if (options.warnIfUnavailable) {
1601
- emitUnavailableWarning();
1602
- }
1603
- return;
1604
- }
1605
- const normalized = normalizePostHogRecord(record, connector, source);
1606
- try {
1607
- const result = transport.emit(normalized);
1608
- if (result && typeof result.catch === "function") {
1609
- void result.catch((error) => {
1610
- warnOnce2(
1611
- `posthog-emit:${key}`,
1612
- "[Blyp] Failed to deliver log to PostHog.",
1613
- error
1614
- );
1615
- });
1616
- }
1617
- } catch (error) {
1618
- warnOnce2(
1619
- `posthog-emit:${key}`,
1620
- "[Blyp] Failed to deliver log to PostHog.",
1621
- error
1622
- );
1623
- }
1624
- },
1625
- captureException(error, options = {}) {
1626
- if (!connector.errorTracking.ready || !exceptionClient) {
1627
- if (options.warnIfUnavailable) {
1628
- emitExceptionUnavailableWarning();
1629
- }
1630
- return;
1631
- }
1632
- if (isPreviouslyCapturedPostHogError(error)) {
1633
- return;
1634
- }
1635
- const normalized = normalizeExceptionInput(
1636
- error,
1637
- options.source === "client" ? "Client error" : "Server error"
1638
- );
1639
- const properties = {
1640
- ...normalized.properties,
1641
- ...options.properties ?? {},
1642
- "blyp.source": options.source ?? "server"
1643
- };
1644
- try {
1645
- const result = exceptionClient.captureException(
1646
- normalized.error,
1647
- options.distinctId,
1648
- properties
1649
- );
1650
- markPostHogCapturedError(error);
1651
- markPostHogCapturedError(normalized.error);
1652
- if (result && typeof result.catch === "function") {
1653
- void result.catch((captureError) => {
1654
- warnOnce2(
1655
- `posthog-capture:${key}`,
1656
- "[Blyp] Failed to capture exception in PostHog.",
1657
- captureError
1658
- );
1659
- });
1660
- }
1661
- } catch (captureError) {
1662
- warnOnce2(
1663
- `posthog-capture:${key}`,
1664
- "[Blyp] Failed to capture exception in PostHog.",
1665
- captureError
1666
- );
1667
- }
1668
- },
1669
- async flush() {
1670
- try {
1671
- if (transport?.flush) {
1672
- await transport.flush();
1673
- }
1674
- } catch (error) {
1675
- warnOnce2(
1676
- `posthog-flush:${key}`,
1677
- "[Blyp] Failed to flush PostHog telemetry.",
1678
- error
1679
- );
1680
- }
1681
- }
1682
- };
1683
- }
1684
- function buildPostHogExceptionProperties(record, source, properties = {}) {
1685
- return {
1686
- ...createExceptionPropertiesFromRecord(record, source),
1687
- ...properties
1688
- };
1689
- }
1690
- var requestContextStorage = new async_hooks.AsyncLocalStorage();
1691
- function createStore() {
1692
- return {
1693
- requestScopedLoggerActive: true,
1694
- structuredCollectorActive: false,
1695
- structuredLogEmitted: false,
1696
- mixedLoggerWarningShown: false
1697
- };
1698
- }
1699
- function runWithRequestContext(callback) {
1700
- return requestContextStorage.run(createStore(), callback);
1701
- }
1702
- function getRequestContextStore() {
1703
- return requestContextStorage.getStore();
1704
- }
1705
- function setActiveRequestLogger(logger2) {
1706
- const store = getRequestContextStore();
1707
- if (store) {
1708
- store.activeLogger = logger2;
1709
- }
1710
- }
1711
- function markStructuredCollectorActive() {
1712
- const store = getRequestContextStore();
1713
- if (store) {
1714
- store.structuredCollectorActive = true;
1715
- }
1716
- }
1717
- function markStructuredLogEmitted() {
1718
- const store = getRequestContextStore();
1719
- if (store) {
1720
- store.structuredLogEmitted = true;
1721
- }
1722
- }
1723
- function shouldDropRootLogWrite() {
1724
- const store = getRequestContextStore();
1725
- if (!store || !store.requestScopedLoggerActive || !store.structuredCollectorActive) {
1726
- return false;
1727
- }
1728
- if (!store.mixedLoggerWarningShown) {
1729
- store.mixedLoggerWarningShown = true;
1730
- console.warn(
1731
- "[Blyp] Warning: Mixed logger usage detected for this request. The root logger call was ignored because a request-scoped structured logger is active."
1732
- );
1733
- }
1734
- return true;
1735
- }
1736
-
1737
- // src/core/log-record.ts
1738
- var RECORD_LEVELS = {
1739
- success: "success",
1740
- critical: "critical",
1741
- warning: "warning",
1742
- info: "info",
1743
- debug: "debug",
1744
- error: "error",
1745
- warn: "warning",
1746
- table: "table"
1747
- };
1748
- function normalizePath2(filePath) {
1749
- return filePath.replace(/\\/g, "/");
1750
- }
1751
- function isInternalLoggerFrame(filePath) {
1752
- const normalizedPath = normalizePath2(filePath);
1753
- return normalizedPath.startsWith("node:") || normalizedPath.includes("/node_modules/pino") || normalizedPath.includes("/node_modules/pino-pretty") || normalizedPath.includes("/node_modules/@blyp/core/") || normalizedPath.includes("/blyp/src/core/") || normalizedPath.includes("/blyp/src/frameworks/") || normalizedPath.includes("/blyp/src/posthog/") || normalizedPath.includes("/blyp/dist/");
1754
- }
1755
- function formatCallerPath(filePath) {
1756
- const normalizedPath = normalizePath2(filePath);
1757
- const normalizedCwd = normalizePath2(process.cwd());
1758
- return normalizedPath.startsWith(`${normalizedCwd}/`) ? normalizedPath.slice(normalizedCwd.length + 1) : normalizedPath;
1759
- }
1760
- function getCallerLocation() {
1761
- try {
1762
- const stack = new Error().stack;
1763
- if (!stack) {
1764
- return { file: null, line: null };
1765
- }
1766
- const lines = stack.split("\n");
1767
- let fallback = null;
1768
- for (let index = 2; index < lines.length; index += 1) {
1769
- const line = lines[index];
1770
- if (!line) {
1771
- continue;
1772
- }
1773
- const match = line.match(/\((.*):(\d+):\d+\)/) || line.match(/at\s+(.*):(\d+):(\d+)/);
1774
- if (!match) {
1775
- continue;
1776
- }
1777
- const fileName = match[1] || "";
1778
- const lineNumber = parseInt(match[2] || "0", 10) || null;
1779
- if (fileName && !fileName.includes("node_modules") && !isInternalLoggerFrame(fileName)) {
1780
- const formattedPath = formatCallerPath(fileName);
1781
- const normalizedFormattedPath = normalizePath2(formattedPath);
1782
- if (!normalizedFormattedPath.startsWith("dist/")) {
1783
- return { file: formattedPath, line: lineNumber };
1784
- }
1785
- fallback ?? (fallback = { file: formattedPath, line: lineNumber });
1786
- }
1787
- }
1788
- if (fallback) {
1789
- return fallback;
1790
- }
1791
- } catch {
1792
- return { file: null, line: null };
1793
- }
1794
- return { file: null, line: null };
1795
- }
1796
- var serializeMessage = serializeLogMessage;
1797
- function stripAnsi(value) {
1798
- return value.replace(/\u001b\[[0-9;]*m/g, "");
1799
- }
1800
- function buildRecord(level, message, args, bindings) {
1801
- const { file, line } = getCallerLocation();
1802
- const serializedMessage = serializeMessage(message);
1803
- const record = {
1804
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1805
- level: RECORD_LEVELS[level],
1806
- message: stripAnsi(serializedMessage)
1807
- };
1808
- if (message instanceof Error) {
1809
- record.error = normalizeError(message);
1810
- }
1811
- if (file) {
1812
- record.caller = line !== null ? `${file}:${line}` : file;
1813
- }
1814
- if (args.length === 1) {
1815
- record.data = normalizeLogValue(args[0]);
1816
- } else if (args.length > 1) {
1817
- record.data = normalizeLogValue(args);
1818
- }
1819
- if (Object.keys(bindings).length > 0) {
1820
- record.bindings = normalizeLogValue(bindings);
1821
- }
1822
- return record;
1823
- }
1824
- function buildStructuredRecord(level, message, payload, bindings) {
1825
- const { file, line } = getCallerLocation();
1826
- const normalizedPayload = normalizeLogValue(payload);
1827
- const record = {
1828
- message: stripAnsi(message),
1829
- ...normalizedPayload
1830
- };
1831
- if (file) {
1832
- record.caller = line !== null ? `${file}:${line}` : file;
1833
- }
1834
- if (Object.keys(bindings).length > 0) {
1835
- record.bindings = normalizeLogValue(bindings);
1836
- }
1837
- record.level = typeof normalizedPayload.level === "string" && normalizedPayload.level.length > 0 ? normalizedPayload.level : RECORD_LEVELS[level];
1838
- record.timestamp = typeof normalizedPayload.timestamp === "string" && normalizedPayload.timestamp.length > 0 ? normalizedPayload.timestamp : (/* @__PURE__ */ new Date()).toISOString();
1839
- return record;
1840
- }
1841
- function resolveStructuredWriteLevel(level) {
1842
- switch (level) {
1843
- case "debug":
1844
- return "debug";
1845
- case "warning":
1846
- return "warning";
1847
- case "warn":
1848
- return "warn";
1849
- case "error":
1850
- return "error";
1851
- case "success":
1852
- return "success";
1853
- case "critical":
1854
- return "critical";
1855
- case "table":
1856
- return "table";
1857
- case "info":
1858
- default:
1859
- return "info";
1860
- }
1861
- }
1862
-
1863
- // src/core/sinks/file-primary-sink.ts
1864
- var FilePrimarySink = class {
1865
- constructor(logger2) {
1866
- this.logger = logger2;
1867
- __publicField(this, "isAsync", false);
1868
- __publicField(this, "isReady", true);
1869
- }
1870
- write(record) {
1871
- this.logger.write(record);
1872
- }
1873
- async flush() {
1874
- }
1875
- async shutdown() {
1876
- }
1877
- };
1878
- function createFilePrimarySink(config) {
1879
- return new FilePrimarySink(createFileLogger(config));
1880
- }
1881
-
1882
- // src/database/adapters/drizzle.ts
1883
- function createDrizzleRowWriter(adapter) {
1884
- const db = adapter.db;
1885
- if (typeof db?.insert !== "function" || adapter.table === void 0) {
1886
- throw new Error(
1887
- "[Blyp] Drizzle database adapter is missing a db.insert function or table reference."
1888
- );
1889
- }
1890
- return {
1891
- async insert(rows) {
1892
- if (rows.length === 0) {
1893
- return;
1894
- }
1895
- await db.insert(adapter.table).values(rows);
1896
- }
1897
- };
1898
- }
1899
-
1900
- // src/database/adapters/prisma.ts
1901
- function shouldFallbackFromCreateMany(error) {
1902
- const message = String(error ?? "");
1903
- return message.includes("createMany") || message.includes("Unknown argument") || message.includes("not supported") || message.includes("is not a function");
1904
- }
1905
- function createPrismaRowWriter(adapter) {
1906
- const client = adapter.client;
1907
- const model = adapter.model ?? "blypLog";
1908
- const delegateCandidate = client[model];
1909
- if (!delegateCandidate || typeof delegateCandidate.create !== "function") {
1910
- throw new Error(
1911
- `[Blyp] Prisma database adapter is missing the "${model}" delegate or its create method.`
1912
- );
1913
- }
1914
- const delegate = delegateCandidate;
1915
- let useCreateMany = typeof delegate.createMany === "function";
1916
- async function fallbackInsert(rows) {
1917
- if (typeof client.$transaction === "function") {
1918
- await client.$transaction(
1919
- rows.map((row) => delegate.create({ data: row }))
1920
- );
1921
- return;
1922
- }
1923
- for (const row of rows) {
1924
- await delegate.create({ data: row });
1925
- }
1926
- }
1927
- return {
1928
- async insert(rows) {
1929
- if (rows.length === 0) {
1930
- return;
1931
- }
1932
- if (rows.length === 1) {
1933
- await delegate.create({ data: rows[0] });
1934
- return;
1935
- }
1936
- if (!useCreateMany || typeof delegate.createMany !== "function") {
1937
- await fallbackInsert(rows);
1938
- return;
1939
- }
1940
- try {
1941
- await delegate.createMany({ data: rows });
1942
- } catch (error) {
1943
- if (!shouldFallbackFromCreateMany(error)) {
1944
- throw error;
1945
- }
1946
- useCreateMany = false;
1947
- await fallbackInsert(rows);
1948
- }
1949
- }
1950
- };
1951
- }
1952
-
1953
- // src/database/helpers.ts
1954
- function normalizeNullableNumber(value) {
1955
- return typeof value === "number" && Number.isFinite(value) ? value : null;
1956
- }
1957
- function normalizeNullableString(value) {
1958
- return typeof value === "string" && value.length > 0 ? value : null;
1959
- }
1960
- function parseTimestamp(value) {
1961
- if (typeof value === "string") {
1962
- const timestamp = new Date(value);
1963
- if (!Number.isNaN(timestamp.getTime())) {
1964
- return timestamp;
1965
- }
1966
- }
1967
- return /* @__PURE__ */ new Date();
1968
- }
1969
- function toDatabaseLogRow(record) {
1970
- const normalizedRecord = normalizeLogValue(record);
1971
- return {
1972
- id: crypto.randomUUID(),
1973
- timestamp: parseTimestamp(record.timestamp),
1974
- level: record.level,
1975
- message: record.message,
1976
- caller: normalizeNullableString(record.caller),
1977
- type: normalizeNullableString(record.type),
1978
- groupId: normalizeNullableString(record.groupId),
1979
- method: normalizeNullableString(record.method),
1980
- path: normalizeNullableString(record.path),
1981
- status: normalizeNullableNumber(record.status),
1982
- duration: normalizeNullableNumber(record.duration),
1983
- hasError: normalizedRecord.error != null,
1984
- data: normalizedRecord.data ?? null,
1985
- bindings: normalizedRecord.bindings ?? null,
1986
- error: normalizedRecord.error ?? null,
1987
- events: normalizedRecord.events ?? null,
1988
- record: normalizedRecord,
1989
- createdAt: /* @__PURE__ */ new Date()
1990
- };
1991
- }
1992
- function isPrismaAdapter2(adapter) {
1993
- return !!adapter && adapter.type === "prisma";
1994
- }
1995
- function isDrizzleAdapter2(adapter) {
1996
- return !!adapter && adapter.type === "drizzle";
1997
- }
1998
- function createDatabaseRowWriter(config) {
1999
- if (isPrismaAdapter2(config.adapter)) {
2000
- return createPrismaRowWriter(config.adapter);
2001
- }
2002
- if (isDrizzleAdapter2(config.adapter)) {
2003
- return createDrizzleRowWriter(config.adapter);
2004
- }
2005
- throw new Error("[Blyp] Unsupported database adapter configuration.");
2006
- }
2007
-
2008
- // src/core/sinks/database-primary-sink.ts
2009
- function delay(ms) {
2010
- return new Promise((resolve2) => {
2011
- setTimeout(resolve2, ms);
2012
- });
2013
- }
2014
- var DatabasePrimarySink = class {
2015
- constructor(config) {
2016
- this.config = config;
2017
- __publicField(this, "isAsync", true);
2018
- __publicField(this, "isReady", true);
2019
- __publicField(this, "warnOnce", createWarnOnceLogger(/* @__PURE__ */ new Set()));
2020
- __publicField(this, "queue", []);
2021
- __publicField(this, "writer");
2022
- __publicField(this, "timer", null);
2023
- __publicField(this, "processing", false);
2024
- __publicField(this, "closed", false);
2025
- __publicField(this, "terminalError", null);
2026
- __publicField(this, "activeDispatch", null);
2027
- this.writer = createDatabaseRowWriter(config);
2028
- }
2029
- write(record) {
2030
- if (this.closed) {
2031
- return;
2032
- }
2033
- this.enqueue(toDatabaseLogRow(record));
2034
- this.scheduleDispatch();
2035
- }
2036
- async flush() {
2037
- if (this.timer) {
2038
- clearTimeout(this.timer);
2039
- this.timer = null;
2040
- }
2041
- const flushPromise = (async () => {
2042
- await this.drain();
2043
- if (this.terminalError) {
2044
- throw this.terminalError;
2045
- }
2046
- })();
2047
- let timeoutHandle = null;
2048
- try {
2049
- await Promise.race([
2050
- flushPromise,
2051
- new Promise((_, reject) => {
2052
- timeoutHandle = setTimeout(() => {
2053
- this.warnOnce(
2054
- "database-flush-timeout",
2055
- `[Blyp] Warning: Timed out flushing database logs after ${this.config.delivery.flushTimeoutMs}ms.`
2056
- );
2057
- reject(new Error("[Blyp] Timed out flushing database logs."));
2058
- }, this.config.delivery.flushTimeoutMs);
2059
- })
2060
- ]);
2061
- } finally {
2062
- if (timeoutHandle) {
2063
- clearTimeout(timeoutHandle);
2064
- }
2065
- }
2066
- }
2067
- async shutdown() {
2068
- this.closed = true;
2069
- await this.flush();
2070
- }
2071
- enqueue(row) {
2072
- this.queue.push(row);
2073
- const overflow = this.queue.length - this.config.delivery.maxQueueSize;
2074
- if (overflow <= 0) {
2075
- return;
2076
- }
2077
- this.warnOnce(
2078
- "database-overflow",
2079
- `[Blyp] Warning: Database log queue exceeded ${this.config.delivery.maxQueueSize} entries. Applying ${this.config.delivery.overflowStrategy} overflow handling.`
2080
- );
2081
- if (this.config.delivery.overflowStrategy === "drop-new") {
2082
- this.queue.splice(this.config.delivery.maxQueueSize);
2083
- return;
2084
- }
2085
- this.queue.splice(0, overflow);
2086
- }
2087
- scheduleDispatch() {
2088
- if (this.processing) {
2089
- return;
2090
- }
2091
- if (this.config.delivery.strategy === "immediate") {
2092
- void this.drain();
2093
- return;
2094
- }
2095
- if (this.queue.length >= this.config.delivery.batchSize) {
2096
- void this.drain();
2097
- return;
2098
- }
2099
- if (this.timer) {
2100
- return;
2101
- }
2102
- this.timer = setTimeout(() => {
2103
- this.timer = null;
2104
- void this.drain();
2105
- }, this.config.delivery.flushIntervalMs);
2106
- }
2107
- async drain() {
2108
- if (this.processing) {
2109
- if (this.activeDispatch) {
2110
- await this.activeDispatch;
2111
- }
2112
- return;
2113
- }
2114
- this.processing = true;
2115
- this.activeDispatch = this.processQueue();
2116
- try {
2117
- await this.activeDispatch;
2118
- } finally {
2119
- this.processing = false;
2120
- this.activeDispatch = null;
2121
- }
2122
- }
2123
- async processQueue() {
2124
- while (this.queue.length > 0) {
2125
- const batchSize = this.config.delivery.strategy === "batch" ? Math.max(1, this.config.delivery.batchSize) : 1;
2126
- const batch = this.queue.splice(0, batchSize);
2127
- try {
2128
- await this.insertWithRetry(batch);
2129
- } catch (error) {
2130
- const failure = error instanceof Error ? error : new Error(String(error ?? "Unknown database logging failure"));
2131
- this.terminalError = failure;
2132
- this.warnOnce(
2133
- "database-insert-failure",
2134
- `[Blyp] Warning: Failed to persist logs to the ${this.config.dialect ?? "database"} database.`,
2135
- failure
2136
- );
2137
- throw failure;
2138
- }
2139
- }
2140
- }
2141
- async insertWithRetry(batch) {
2142
- const maxAttempts = Math.max(1, this.config.delivery.retry.maxRetries + 1);
2143
- let attempt = 0;
2144
- while (attempt < maxAttempts) {
2145
- attempt += 1;
2146
- try {
2147
- await this.writer.insert(batch);
2148
- return;
2149
- } catch (error) {
2150
- if (attempt >= maxAttempts) {
2151
- throw error;
2152
- }
2153
- await delay(this.config.delivery.retry.backoffMs);
2154
- }
2155
- }
2156
- }
2157
- };
2158
-
2159
- // src/core/primary-sink.ts
2160
- var NoopPrimarySink = class {
2161
- constructor() {
2162
- __publicField(this, "isAsync", false);
2163
- __publicField(this, "isReady", false);
2164
- }
2165
- write(_record) {
2166
- }
2167
- async flush() {
2168
- }
2169
- async shutdown() {
2170
- }
2171
- };
2172
- var warnOnce3 = createWarnOnceLogger(/* @__PURE__ */ new Set());
2173
- function createPrimarySink(config) {
2174
- if (config.destination !== "database") {
2175
- return createFilePrimarySink(config);
2176
- }
2177
- const databaseConfig = config.database;
2178
- if (!databaseConfig?.ready) {
2179
- warnOnce3(
2180
- "database-sink-disabled",
2181
- "[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."
2182
- );
2183
- return new NoopPrimarySink();
2184
- }
2185
- return new DatabasePrimarySink(databaseConfig);
2186
- }
2187
- var PREVIOUSLY_CAPTURED_ERROR_KEY2 = "__betterstack_previously_captured_error";
2188
- var warnedKeys3 = /* @__PURE__ */ new Set();
2189
- var testHooks2 = {};
2190
- var warnOnce4 = createErrorOnceLogger(warnedKeys3);
2191
- function getSentryModule() {
2192
- return testHooks2.module ?? Sentry__namespace;
2193
- }
2194
- function resolveConnectorConfig2(config) {
2195
- const connector = isBlypConfig(config) ? config.connectors?.betterstack : config;
2196
- const enabled = connector?.enabled ?? false;
2197
- const sourceToken = connector?.sourceToken;
2198
- const ingestingHost = connector?.ingestingHost;
2199
- const errorTrackingEnabled = connector?.errorTracking?.enabled ?? enabled;
2200
- const errorTrackingDsn = connector?.errorTracking?.dsn;
2201
- const errorTrackingReady = enabled && errorTrackingEnabled && hasNonEmptyString(errorTrackingDsn);
2202
- const ready = enabled && hasNonEmptyString(sourceToken) && isAbsoluteHttpUrl(ingestingHost);
2203
- return {
2204
- enabled,
2205
- mode: connector?.mode ?? "auto",
2206
- sourceToken,
2207
- ingestingHost,
2208
- serviceName: connector?.serviceName ?? "blyp-app",
2209
- errorTracking: {
2210
- enabled: errorTrackingEnabled,
2211
- dsn: errorTrackingDsn,
2212
- tracesSampleRate: connector?.errorTracking?.tracesSampleRate ?? 1,
2213
- environment: connector?.errorTracking?.environment,
2214
- release: connector?.errorTracking?.release,
2215
- ready: errorTrackingReady,
2216
- status: errorTrackingReady ? "enabled" : "missing"
2217
- },
2218
- ready,
2219
- status: ready ? "enabled" : "missing"
2220
- };
2221
- }
2222
- function resolveBetterStackLevel(level) {
2223
- switch (level) {
2224
- case "debug":
2225
- return "debug";
2226
- case "warning":
2227
- case "warn":
2228
- return "warn";
2229
- case "error":
2230
- return "error";
2231
- case "critical":
2232
- return "fatal";
2233
- case "success":
2234
- case "table":
2235
- case "info":
2236
- default:
2237
- return "info";
2238
- }
2239
- }
2240
- function parseCaller(caller) {
2241
- if (typeof caller !== "string" || caller.trim().length === 0) {
2242
- return {};
2243
- }
2244
- const match = caller.match(/^(.*):(\d+)$/);
2245
- if (!match) {
2246
- return {};
2247
- }
2248
- const file = match[1]?.trim();
2249
- const line = Number.parseInt(match[2] ?? "", 10);
2250
- return {
2251
- ...file ? { file } : {},
2252
- ...Number.isFinite(line) ? { line } : {}
2253
- };
2254
- }
2255
- function buildContext(record, connector, source) {
2256
- const recordType = getRecordType(record);
2257
- const groupId = getField(record, "groupId");
2258
- const method = getField(record, "method");
2259
- const path3 = getField(record, "path");
2260
- const status = getField(record, "status");
2261
- const duration = getField(record, "duration");
2262
- const pagePath = getClientPageField(record, "pathname");
2263
- const pageUrl = getClientPageField(record, "url");
2264
- const sessionId = getClientSessionField(record, "sessionId");
2265
- const pageId = getClientSessionField(record, "pageId");
2266
- const runtime2 = parseCaller(record.caller);
2267
- return {
2268
- service: connector.serviceName,
2269
- context: {
2270
- blyp: {
2271
- level: record.level,
2272
- source,
2273
- ...recordType ? { type: recordType } : {},
2274
- ...groupId ? { group_id: groupId } : {},
2275
- ...record.caller ? { caller: record.caller } : {},
2276
- ...duration !== void 0 ? { duration_ms: duration } : {},
2277
- ...record.bindings ? { bindings: record.bindings } : {},
2278
- payload: serializeLogRecord(record)
2279
- },
2280
- ...method || path3 || status !== void 0 ? {
2281
- http: {
2282
- ...method ? { method } : {},
2283
- ...path3 ? { path: path3 } : {},
2284
- ...status !== void 0 ? { status_code: status } : {}
2285
- }
2286
- } : {},
2287
- ...pagePath || pageUrl || sessionId || pageId ? {
2288
- client: {
2289
- ...pagePath ? { page_path: pagePath } : {},
2290
- ...pageUrl ? { page_url: pageUrl } : {},
2291
- ...sessionId ? { session_id: sessionId } : {},
2292
- ...pageId ? { page_id: pageId } : {}
2293
- }
2294
- } : {},
2295
- ...Object.keys(runtime2).length > 0 ? { runtime: runtime2 } : {},
2296
- ...record.data !== void 0 ? { data: record.data } : {},
2297
- ...record.error !== void 0 ? { error: record.error } : {}
2298
- }
2299
- };
2300
- }
2301
- function toExceptionCandidate(value) {
2302
- if (!isPlainObject(value)) {
2303
- return void 0;
2304
- }
2305
- const message = typeof value.message === "string" ? value.message : void 0;
2306
- const name = typeof value.name === "string" ? value.name : void 0;
2307
- const stack = typeof value.stack === "string" ? value.stack : void 0;
2308
- if (!message && !name && !stack) {
2309
- return void 0;
2310
- }
2311
- const error = new Error(message ?? name ?? "Unknown error");
2312
- error.name = name ?? "Error";
2313
- if (stack) {
2314
- error.stack = stack;
2315
- }
2316
- for (const [key, entry] of Object.entries(value)) {
2317
- if (key === "message" || key === "name" || key === "stack") {
2318
- continue;
2319
- }
2320
- error[key] = entry;
2321
- }
2322
- return error;
2323
- }
2324
- function normalizeScopeLevel(level) {
2325
- switch (level) {
2326
- case "debug":
2327
- return "debug";
2328
- case "warning":
2329
- case "warn":
2330
- return "warning";
2331
- case "critical":
2332
- return "fatal";
2333
- case "error":
2334
- return "error";
2335
- case "success":
2336
- case "table":
2337
- case "info":
2338
- default:
2339
- return "info";
2340
- }
2341
- }
2342
- function normalizeExceptionInput2(input) {
2343
- if (input instanceof Error) {
2344
- return input;
2345
- }
2346
- const direct = toExceptionCandidate(input);
2347
- if (direct) {
2348
- return direct;
2349
- }
2350
- if (typeof input === "string") {
2351
- return new Error(input);
2352
- }
2353
- return new Error("Unknown Better Stack exception");
2354
- }
2355
- function isPreviouslyCapturedError(value) {
2356
- return isPlainObject(value) && value[PREVIOUSLY_CAPTURED_ERROR_KEY2] === true;
2357
- }
2358
- function markCapturedError(value) {
2359
- if (!isPlainObject(value) || isPreviouslyCapturedError(value)) {
2360
- return;
2361
- }
2362
- try {
2363
- Object.defineProperty(value, PREVIOUSLY_CAPTURED_ERROR_KEY2, {
2364
- value: true,
2365
- enumerable: false,
2366
- configurable: true,
2367
- writable: true
2368
- });
2369
- } catch {
2370
- try {
2371
- value[PREVIOUSLY_CAPTURED_ERROR_KEY2] = true;
2372
- } catch {
2373
- }
2374
- }
2375
- }
2376
- function createDefaultClient(connector) {
2377
- return new node.Logtail(connector.sourceToken ?? "", {
2378
- endpoint: connector.ingestingHost,
2379
- captureStackContext: false
2380
- });
2381
- }
2382
- function getClientOptions(client) {
2383
- return client?.getOptions?.() ?? {};
2384
- }
2385
- function registerShutdownHooks2(key, flush) {
2386
- const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
2387
- for (const event of handlers) {
2388
- process.once(event, () => {
2389
- void flush().catch((error) => {
2390
- warnOnce4(
2391
- `${key}:shutdown`,
2392
- "[Blyp] Failed to flush Better Stack logs during shutdown.",
2393
- error
2394
- );
2395
- });
2396
- });
2397
- }
2398
- }
2399
- function createBetterStackSender(config) {
2400
- const connector = resolveConnectorConfig2(config);
2401
- const key = `${connector.serviceName}:${connector.ingestingHost ?? "missing"}:${connector.mode}`;
2402
- const sentryModule = getSentryModule();
2403
- const client = connector.ready ? testHooks2.createClient?.(connector) ?? createDefaultClient(connector) : void 0;
2404
- let sentryClient = connector.errorTracking.enabled ? sentryModule?.getClient?.() : void 0;
2405
- if (sentryClient) {
2406
- const options = getClientOptions(sentryClient);
2407
- if (hasNonEmptyString(connector.errorTracking.dsn) && connector.errorTracking.dsn !== options.dsn || hasNonEmptyString(connector.errorTracking.environment) && connector.errorTracking.environment !== options.environment || hasNonEmptyString(connector.errorTracking.release) && connector.errorTracking.release !== options.release) {
2408
- warnOnce4(
2409
- `betterstack-error-mismatch:${key}`,
2410
- "[Blyp] Sentry is already initialized with different options. Reusing the existing Sentry client for Better Stack error tracking."
2411
- );
2412
- }
2413
- }
2414
- if (!sentryClient && connector.errorTracking.enabled && hasNonEmptyString(connector.errorTracking.dsn) && sentryModule) {
2415
- try {
2416
- sentryModule.init({
2417
- dsn: connector.errorTracking.dsn,
2418
- tracesSampleRate: connector.errorTracking.tracesSampleRate,
2419
- environment: connector.errorTracking.environment,
2420
- release: connector.errorTracking.release
2421
- });
2422
- sentryClient = sentryModule.getClient();
2423
- } catch (error) {
2424
- warnOnce4(
2425
- `betterstack-error-init:${key}`,
2426
- "[Blyp] Failed to initialize Better Stack error tracking.",
2427
- error
2428
- );
2429
- }
2430
- }
2431
- const errorTrackingReady = connector.errorTracking.enabled && sentryClient !== void 0;
2432
- if (client || errorTrackingReady) {
2433
- registerShutdownHooks2(key, async () => {
2434
- if (client) {
2435
- await client.flush();
2436
- }
2437
- if (errorTrackingReady) {
2438
- await sentryModule.flush(2e3);
2439
- }
2440
- });
2441
- }
2442
- const emitUnavailableWarning = () => {
2443
- warnOnce4(
2444
- `betterstack-unavailable:${key}`,
2445
- "[Blyp] Better Stack connector is not configured or not ready. Skipping Better Stack delivery."
2446
- );
2447
- };
2448
- const emitExceptionUnavailableWarning = () => {
2449
- warnOnce4(
2450
- `betterstack-exception-unavailable:${key}`,
2451
- "[Blyp] Better Stack error tracking is not configured. Skipping Better Stack exception capture."
2452
- );
2453
- };
2454
- return {
2455
- enabled: connector.enabled,
2456
- ready: connector.ready,
2457
- mode: connector.mode,
2458
- serviceName: connector.serviceName,
2459
- ingestingHost: connector.ingestingHost,
2460
- status: connector.status,
2461
- errorTracking: {
2462
- enabled: connector.errorTracking.enabled,
2463
- ready: errorTrackingReady,
2464
- status: errorTrackingReady ? "enabled" : "missing",
2465
- dsn: connector.errorTracking.dsn,
2466
- tracesSampleRate: connector.errorTracking.tracesSampleRate,
2467
- environment: connector.errorTracking.environment,
2468
- release: connector.errorTracking.release
2469
- },
2470
- shouldAutoForwardServerLogs() {
2471
- return connector.ready && connector.mode === "auto";
2472
- },
2473
- shouldAutoCaptureExceptions() {
2474
- return errorTrackingReady;
2475
- },
2476
- send(record, options = {}) {
2477
- if (!connector.ready || !client) {
2478
- if (options.warnIfUnavailable) {
2479
- emitUnavailableWarning();
2480
- }
2481
- return;
2482
- }
2483
- const source = options.source ?? "server";
2484
- void client.log(
2485
- record.message,
2486
- resolveBetterStackLevel(record.level),
2487
- buildContext(record, connector, source)
2488
- ).catch((error) => {
2489
- warnOnce4(
2490
- `betterstack-send:${key}`,
2491
- "[Blyp] Failed to deliver log to Better Stack.",
2492
- error
2493
- );
2494
- });
2495
- },
2496
- captureException(error, options = {}) {
2497
- if (!errorTrackingReady || !sentryModule) {
2498
- if (options.warnIfUnavailable) {
2499
- emitExceptionUnavailableWarning();
2500
- }
2501
- return;
2502
- }
2503
- if (isPreviouslyCapturedError(error)) {
2504
- return;
2505
- }
2506
- try {
2507
- const exception = normalizeExceptionInput2(error);
2508
- sentryModule.withScope((scope) => {
2509
- scope.setLevel(
2510
- normalizeScopeLevel(
2511
- options.source === "client" ? "error" : "error"
2512
- )
2513
- );
2514
- scope.setContext("blyp", {
2515
- source: options.source ?? "server",
2516
- ...options.context ? { context: options.context } : {}
2517
- });
2518
- sentryModule.captureException(exception);
2519
- });
2520
- markCapturedError(error);
2521
- markCapturedError(exception);
2522
- } catch (captureError) {
2523
- warnOnce4(
2524
- `betterstack-manual-capture:${key}`,
2525
- "[Blyp] Failed to capture exception in Better Stack error tracking.",
2526
- captureError
2527
- );
2528
- }
2529
- },
2530
- async flush() {
2531
- if (!client) {
2532
- if (!errorTrackingReady || !sentryModule) {
2533
- return;
2534
- }
2535
- }
2536
- try {
2537
- if (client) {
2538
- await client.flush();
2539
- }
2540
- if (errorTrackingReady && sentryModule) {
2541
- await sentryModule.flush(2e3);
2542
- }
2543
- } catch (error) {
2544
- warnOnce4(
2545
- `betterstack-flush:${key}`,
2546
- "[Blyp] Failed to flush Better Stack logs.",
2547
- error
2548
- );
2549
- }
2550
- }
2551
- };
2552
- }
2553
- var warnedKeys4 = /* @__PURE__ */ new Set();
2554
- var testHooks3 = {};
2555
- var warnOnce5 = createErrorOnceLogger(warnedKeys4);
2556
- function getSentryModule2() {
2557
- return testHooks3.module ?? Sentry__namespace;
2558
- }
2559
- function resolveConnectorConfig3(config) {
2560
- const connector = isBlypConfig(config) ? config.connectors?.sentry : config;
2561
- const enabled = connector?.enabled ?? false;
2562
- const dsn = connector?.dsn;
2563
- const ready = enabled && hasNonEmptyString(dsn);
2564
- return {
2565
- enabled,
2566
- mode: connector?.mode ?? "auto",
2567
- dsn,
2568
- environment: connector?.environment,
2569
- release: connector?.release,
2570
- ready,
2571
- status: ready ? "enabled" : "missing"
2572
- };
2573
- }
2574
- function normalizeAttributes(record, source) {
2575
- const attributes = {
2576
- "blyp.level": record.level,
2577
- "blyp.source": source,
2578
- "blyp.payload": serializeLogRecord(record)
2579
- };
2580
- const recordType = getRecordType(record);
2581
- const caller = typeof record.caller === "string" ? record.caller : void 0;
2582
- const groupId = getField(record, "groupId");
2583
- const method = getField(record, "method");
2584
- const path3 = getField(record, "path");
2585
- const status = getField(record, "status");
2586
- const duration = getField(record, "duration");
2587
- const pagePath = getClientPageField(record, "pathname");
2588
- const pageUrl = getClientPageField(record, "url");
2589
- const sessionId = getClientSessionField(record, "sessionId");
2590
- const pageId = getClientSessionField(record, "pageId");
2591
- const ifTruthy = [
2592
- ["blyp.type", recordType],
2593
- ["blyp.caller", caller],
2594
- ["blyp.group_id", groupId],
2595
- ["http.method", method],
2596
- ["url.path", path3],
2597
- ["client.page_path", pagePath],
2598
- ["client.page_url", pageUrl],
2599
- ["client.session_id", sessionId],
2600
- ["client.page_id", pageId]
2601
- ];
2602
- const ifDefined = [
2603
- ["http.status_code", status],
2604
- ["blyp.duration_ms", duration]
2605
- ];
2606
- for (const [k, v] of ifTruthy) if (v) attributes[k] = v;
2607
- for (const [k, v] of ifDefined) if (v !== void 0) attributes[k] = v;
2608
- return attributes;
2609
- }
2610
- function resolveLogMethod(module, level) {
2611
- switch (level) {
2612
- case "debug":
2613
- return module.logger.debug;
2614
- case "warning":
2615
- case "warn":
2616
- return module.logger.warn;
2617
- case "error":
2618
- return module.logger.error;
2619
- case "critical":
2620
- return module.logger.fatal;
2621
- case "success":
2622
- case "table":
2623
- case "info":
2624
- default:
2625
- return module.logger.info;
2626
- }
2627
- }
2628
- function normalizeScopeLevel2(level) {
2629
- switch (level) {
2630
- case "debug":
2631
- return "debug";
2632
- case "warning":
2633
- case "warn":
2634
- return "warning";
2635
- case "critical":
2636
- return "fatal";
2637
- case "error":
2638
- return "error";
2639
- case "success":
2640
- case "table":
2641
- case "info":
2642
- default:
2643
- return "info";
2644
- }
2645
- }
2646
- function toExceptionCandidate2(value) {
2647
- if (!isPlainObject(value)) {
2648
- return void 0;
2649
- }
2650
- const message = typeof value.message === "string" ? value.message : void 0;
2651
- const name = typeof value.name === "string" ? value.name : void 0;
2652
- const stack = typeof value.stack === "string" ? value.stack : void 0;
2653
- if (!message && !name && !stack) {
2654
- return void 0;
2655
- }
2656
- const error = new Error(message ?? name ?? "Unknown error");
2657
- error.name = name ?? "Error";
2658
- if (stack) {
2659
- error.stack = stack;
2660
- }
2661
- for (const [key, entry] of Object.entries(value)) {
2662
- if (key === "message" || key === "name" || key === "stack") {
2663
- continue;
2664
- }
2665
- error[key] = entry;
2666
- }
2667
- return error;
2668
- }
2669
- function extractExceptionCandidate(record) {
2670
- if (record.level !== "error" && record.level !== "critical") {
2671
- return void 0;
2672
- }
2673
- const direct = toExceptionCandidate2(record.error);
2674
- if (direct) {
2675
- return direct;
2676
- }
2677
- if (isPlainObject(record.data)) {
2678
- const directData = toExceptionCandidate2(record.data);
2679
- if (directData) {
2680
- return directData;
2681
- }
2682
- const nested = toExceptionCandidate2(record.data.error);
2683
- if (nested) {
2684
- return nested;
2685
- }
2686
- }
2687
- const payload = getPrimaryPayload(record);
2688
- if (isPlainObject(payload)) {
2689
- const nested = toExceptionCandidate2(payload.error);
2690
- if (nested) {
2691
- return nested;
2692
- }
2693
- }
2694
- return void 0;
2695
- }
2696
- function getClientOptions2(client) {
2697
- return client?.getOptions?.() ?? {};
2698
- }
2699
- function hasConfigMismatch(connector, client) {
2700
- const options = getClientOptions2(client);
2701
- return hasNonEmptyString(connector.dsn) && connector.dsn !== options.dsn || hasNonEmptyString(connector.environment) && connector.environment !== options.environment || hasNonEmptyString(connector.release) && connector.release !== options.release;
2702
- }
2703
- function createSentrySender(config) {
2704
- const connector = resolveConnectorConfig3(config);
2705
- const key = `${connector.mode}:${connector.dsn ?? "missing"}`;
2706
- const module = getSentryModule2();
2707
- let client = connector.enabled ? module.getClient() : void 0;
2708
- if (!client && connector.enabled && hasNonEmptyString(connector.dsn)) {
2709
- try {
2710
- module.init({
2711
- dsn: connector.dsn,
2712
- environment: connector.environment,
2713
- release: connector.release,
2714
- enableLogs: true
2715
- });
2716
- client = module.getClient();
2717
- } catch (error) {
2718
- warnOnce5(
2719
- `sentry-init:${key}`,
2720
- "[Blyp] Failed to initialize Sentry. Skipping Sentry delivery.",
2721
- error
2722
- );
2723
- }
2724
- }
2725
- if (client && hasConfigMismatch(connector, client)) {
2726
- warnOnce5(
2727
- `sentry-mismatch:${key}`,
2728
- "[Blyp] Sentry is already initialized with different options. Reusing the existing Sentry client."
2729
- );
2730
- }
2731
- const ready = connector.enabled && client !== void 0;
2732
- const emitUnavailableWarning = () => {
2733
- warnOnce5(
2734
- `sentry-unavailable:${key}`,
2735
- "[Blyp] Sentry connector is not configured. Skipping Sentry delivery."
2736
- );
2737
- };
2738
- return {
2739
- enabled: connector.enabled,
2740
- ready,
2741
- mode: connector.mode,
2742
- status: ready ? "enabled" : "missing",
2743
- shouldAutoForwardServerLogs() {
2744
- return ready && connector.mode === "auto";
2745
- },
2746
- send(record, options = {}) {
2747
- if (!ready) {
2748
- if (options.warnIfUnavailable) {
2749
- emitUnavailableWarning();
2750
- }
2751
- return;
2752
- }
2753
- const source = options.source ?? "server";
2754
- const attributes = normalizeAttributes(record, source);
2755
- const logMethod = resolveLogMethod(module, record.level);
2756
- try {
2757
- logMethod(record.message, attributes);
2758
- } catch (error) {
2759
- warnOnce5(
2760
- `sentry-log:${key}`,
2761
- "[Blyp] Failed to deliver log to Sentry.",
2762
- error
2763
- );
2764
- }
2765
- const exception = extractExceptionCandidate(record);
2766
- if (!exception) {
2767
- return;
2768
- }
2769
- try {
2770
- module.withScope((scope) => {
2771
- scope.setLevel(normalizeScopeLevel2(record.level));
2772
- scope.setContext("blyp", attributes);
2773
- scope.setExtra("blyp.payload", serializeLogRecord(record));
2774
- module.captureException(exception);
2775
- });
2776
- } catch (error) {
2777
- warnOnce5(
2778
- `sentry-exception:${key}`,
2779
- "[Blyp] Failed to capture exception in Sentry.",
2780
- error
2781
- );
2782
- }
2783
- },
2784
- async flush() {
2785
- try {
2786
- await module.flush(2e3);
2787
- } catch (error) {
2788
- warnOnce5(
2789
- `sentry-flush:${key}`,
2790
- "[Blyp] Failed to flush Sentry logs.",
2791
- error
2792
- );
2793
- }
2794
- }
2795
- };
2796
- }
2797
- var warnedKeys5 = /* @__PURE__ */ new Set();
2798
- var testHooks4 = {};
2799
- var warnOnce6 = createErrorOnceLogger(warnedKeys5);
2800
- function normalizeOTLPRecord(record, connector, source = "server") {
2801
- const severity = resolveSeverity2(record.level);
2802
- const body = typeof record.message === "string" ? record.message : String(record.message);
2803
- const recordType = getRecordType(record);
2804
- const caller = typeof record.caller === "string" ? record.caller : void 0;
2805
- const groupId = getField(record, "groupId");
2806
- const method = getField(record, "method");
2807
- const path3 = getField(record, "path");
2808
- const status = getField(record, "status");
2809
- const duration = getField(record, "duration");
2810
- const pagePath = getClientPageField(record, "pathname");
2811
- const pageUrl = getClientPageField(record, "url");
2812
- const sessionId = getClientSessionField(record, "sessionId");
2813
- const pageId = getClientSessionField(record, "pageId");
2814
- const attributes = {
2815
- "blyp.level": record.level,
2816
- "blyp.source": source,
2817
- "blyp.payload": serializeLogRecord(record)
2818
- };
2819
- const ifTruthy = [
2820
- ["blyp.type", recordType],
2821
- ["blyp.caller", caller],
2822
- ["blyp.group_id", groupId],
2823
- ["http.method", method],
2824
- ["url.path", path3],
2825
- ["client.page_path", pagePath],
2826
- ["client.page_url", pageUrl],
2827
- ["client.session_id", sessionId],
2828
- ["client.page_id", pageId]
2829
- ];
2830
- const ifDefined = [
2831
- ["http.status_code", status],
2832
- ["blyp.duration_ms", duration]
2833
- ];
2834
- for (const [k, v] of ifTruthy) if (v) attributes[k] = v;
2835
- for (const [k, v] of ifDefined) if (v !== void 0) attributes[k] = v;
2836
- return {
2837
- body,
2838
- severityText: severity.text,
2839
- severityNumber: severity.number,
2840
- attributes,
2841
- resourceAttributes: {
2842
- "service.name": connector.serviceName
2843
- }
2844
- };
2845
- }
2846
- function resolveSeverity2(level) {
2847
- switch (level) {
2848
- case "debug":
2849
- return { text: "debug", number: apiLogs.SeverityNumber.DEBUG };
2850
- case "warning":
2851
- case "warn":
2852
- return { text: "warn", number: apiLogs.SeverityNumber.WARN };
2853
- case "error":
2854
- return { text: "error", number: apiLogs.SeverityNumber.ERROR };
2855
- case "critical":
2856
- return { text: "fatal", number: apiLogs.SeverityNumber.FATAL };
2857
- case "success":
2858
- case "table":
2859
- case "info":
2860
- default:
2861
- return { text: "info", number: apiLogs.SeverityNumber.INFO };
2862
- }
2863
- }
2864
- function registerShutdownHooks3(key, shutdown) {
2865
- const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
2866
- for (const event of handlers) {
2867
- process.once(event, async () => {
2868
- try {
2869
- await shutdown();
2870
- } catch (error) {
2871
- warnOnce6(
2872
- `${key}:shutdown`,
2873
- "[Blyp] Failed to flush OTLP logs during shutdown.",
2874
- error
2875
- );
2876
- }
2877
- if (event !== "beforeExit") {
2878
- process.exit(0);
2879
- }
2880
- });
2881
- }
2882
- }
2883
- function resolveTransportHeaders(connector) {
2884
- const headers = {
2885
- ...connector.headers ?? {}
2886
- };
2887
- if (headers.Authorization === void 0 && connector.auth) {
2888
- headers.Authorization = connector.auth;
2889
- }
2890
- return headers;
2891
- }
2892
- function createDefaultTransport2(connector) {
2893
- const exporter = new exporterLogsOtlpHttp.OTLPLogExporter({
2894
- url: connector.endpoint,
2895
- headers: resolveTransportHeaders(connector)
2896
- });
2897
- const provider = new sdkLogs.LoggerProvider({
2898
- resource: resources.resourceFromAttributes({
2899
- "service.name": connector.serviceName
2900
- }),
2901
- processors: [new sdkLogs.BatchLogRecordProcessor(exporter)]
2902
- });
2903
- const logger2 = provider.getLogger(`blyp-otlp:${connector.name}`);
2904
- return {
2905
- emit(payload) {
2906
- logger2.emit({
2907
- body: payload.body,
2908
- severityText: payload.severityText,
2909
- severityNumber: payload.severityNumber,
2910
- attributes: payload.attributes
2911
- });
2912
- },
2913
- flush() {
2914
- return provider.forceFlush();
2915
- },
2916
- shutdown() {
2917
- return provider.shutdown();
2918
- }
2919
- };
2920
- }
2921
- function resolveConnectors(config) {
2922
- const connectors = isBlypConfig(config) ? config.connectors?.otlp ?? [] : config;
2923
- return connectors.map((connector) => {
2924
- const headers = {
2925
- ...connector.headers ?? {}
2926
- };
2927
- const enabled = connector.enabled ?? false;
2928
- const endpoint = connector.endpoint;
2929
- const explicitReady = "ready" in connector && typeof connector.ready === "boolean" ? connector.ready : void 0;
2930
- const ready = (explicitReady ?? (enabled && isAbsoluteHttpUrl(endpoint))) && isAbsoluteHttpUrl(endpoint);
2931
- return {
2932
- name: connector.name,
2933
- enabled,
2934
- mode: connector.mode ?? "auto",
2935
- endpoint,
2936
- headers,
2937
- auth: connector.auth,
2938
- serviceName: connector.serviceName ?? "blyp-app",
2939
- ready,
2940
- status: ready ? "enabled" : "missing"
2941
- };
2942
- });
2943
- }
2944
- function createUnavailableSender(name, connector) {
2945
- const senderName = name || connector?.name || "otlp";
2946
- const key = `${senderName}:${connector?.serviceName ?? "blyp-app"}:${connector?.endpoint ?? "missing"}`;
2947
- const emitUnavailableWarning = () => {
2948
- warnOnce6(
2949
- `otlp-unavailable:${key}`,
2950
- `[Blyp] OTLP target "${senderName}" is not configured or not ready. Skipping OTLP delivery.`
2951
- );
2952
- };
2953
- return {
2954
- name: senderName,
2955
- enabled: connector?.enabled ?? false,
2956
- ready: false,
2957
- mode: connector?.mode ?? "auto",
2958
- serviceName: connector?.serviceName ?? "blyp-app",
2959
- endpoint: connector?.endpoint,
2960
- status: "missing",
2961
- send(_record, options = {}) {
2962
- if (options.warnIfUnavailable) {
2963
- emitUnavailableWarning();
2964
- }
2965
- },
2966
- async flush() {
2967
- }
2968
- };
2969
- }
2970
- function createSender(connector) {
2971
- if (!connector.ready || !connector.endpoint) {
2972
- return createUnavailableSender(connector.name, connector);
2973
- }
2974
- const key = `${connector.name}:${connector.serviceName}:${connector.endpoint}:${connector.mode}`;
2975
- const transportConnector = {
2976
- ...connector,
2977
- headers: resolveTransportHeaders(connector)
2978
- };
2979
- const transport = testHooks4.createTransport?.(transportConnector) ?? createDefaultTransport2(transportConnector);
2980
- return {
2981
- name: connector.name,
2982
- enabled: connector.enabled,
2983
- ready: connector.ready,
2984
- mode: connector.mode,
2985
- serviceName: connector.serviceName,
2986
- endpoint: connector.endpoint,
2987
- status: connector.status,
2988
- send(record, options = {}) {
2989
- const source = options.source ?? "server";
2990
- const normalized = normalizeOTLPRecord(record, connector, source);
2991
- try {
2992
- const result = transport.emit(normalized);
2993
- if (result && typeof result.catch === "function") {
2994
- void result.catch((error) => {
2995
- warnOnce6(
2996
- `otlp-emit:${key}`,
2997
- `[Blyp] Failed to deliver log to OTLP target "${connector.name}".`,
2998
- error
2999
- );
3000
- });
3001
- }
3002
- } catch (error) {
3003
- warnOnce6(
3004
- `otlp-emit:${key}`,
3005
- `[Blyp] Failed to deliver log to OTLP target "${connector.name}".`,
3006
- error
3007
- );
3008
- }
3009
- },
3010
- async flush() {
3011
- try {
3012
- if (transport.flush) {
3013
- await transport.flush();
3014
- }
3015
- } catch (error) {
3016
- warnOnce6(
3017
- `otlp-flush:${key}`,
3018
- `[Blyp] Failed to flush OTLP logs for target "${connector.name}".`,
3019
- error
3020
- );
3021
- }
3022
- }
3023
- };
3024
- }
3025
- function createOTLPRegistry(config) {
3026
- const senders = /* @__PURE__ */ new Map();
3027
- for (const connector of resolveConnectors(config)) {
3028
- senders.set(connector.name, createSender(connector));
3029
- }
3030
- const registry = {
3031
- get(name) {
3032
- return senders.get(name) ?? createUnavailableSender(name);
3033
- },
3034
- getAutoForwardTargets() {
3035
- return Array.from(senders.values()).filter((sender) => sender.ready && sender.mode === "auto");
3036
- },
3037
- send(name, record, options = {}) {
3038
- const sender = senders.get(name) ?? createUnavailableSender(name);
3039
- sender.send(record, options);
3040
- },
3041
- async flush() {
3042
- await Promise.all(Array.from(senders.values()).map((sender) => sender.flush()));
3043
- }
3044
- };
3045
- registerShutdownHooks3("otlp-registry", () => registry.flush());
3046
- return registry;
3047
- }
3048
- var _RuntimeDetector = class _RuntimeDetector {
3049
- constructor() {
3050
- __publicField(this, "_type", null);
3051
- }
3052
- static getInstance() {
3053
- if (!_RuntimeDetector.instance) {
3054
- _RuntimeDetector.instance = new _RuntimeDetector();
3055
- }
3056
- return _RuntimeDetector.instance;
3057
- }
3058
- get type() {
3059
- if (this._type === null) {
3060
- this._type = this.detectRuntime();
3061
- }
3062
- return this._type;
3063
- }
3064
- get isBun() {
3065
- return this.type === "bun";
3066
- }
3067
- get isNode() {
3068
- return this.type === "node";
3069
- }
3070
- detectRuntime() {
3071
- if (typeof Bun !== "undefined" && typeof Bun.file === "function") {
3072
- return "bun";
3073
- }
3074
- return "node";
3075
- }
3076
- };
3077
- __publicField(_RuntimeDetector, "instance");
3078
- var RuntimeDetector = _RuntimeDetector;
3079
- var BunAdapter = class {
3080
- constructor() {
3081
- __publicField(this, "type", "bun");
3082
- __publicField(this, "isBun", true);
3083
- __publicField(this, "isNode", false);
3084
- __publicField(this, "file", {
3085
- existsSync: (filePath) => {
3086
- try {
3087
- const file = Bun.file(filePath);
3088
- return file.size > 0 || file.name !== "";
3089
- } catch {
3090
- return false;
3091
- }
3092
- },
3093
- mkdirSync: (filePath, options) => {
3094
- try {
3095
- fs__default.default.mkdirSync(filePath, options);
3096
- } catch {
3097
- }
3098
- },
3099
- writeFileSync: (filePath, data) => {
3100
- Bun.write(filePath, data);
3101
- }
3102
- });
3103
- __publicField(this, "path", {
3104
- join: (...paths) => {
3105
- return path__default.default.join(...paths);
3106
- }
3107
- });
3108
- __publicField(this, "env", {
3109
- get: (key) => Bun.env[key]
3110
- });
3111
- __publicField(this, "cwd", () => {
3112
- return process.cwd();
3113
- });
3114
- }
3115
- };
3116
- var NodeAdapter = class {
3117
- constructor() {
3118
- __publicField(this, "type", "node");
3119
- __publicField(this, "isBun", false);
3120
- __publicField(this, "isNode", true);
3121
- __publicField(this, "file", {
3122
- existsSync: (filePath) => fs__default.default.existsSync(filePath),
3123
- mkdirSync: (filePath, options) => {
3124
- fs__default.default.mkdirSync(filePath, options);
3125
- },
3126
- writeFileSync: (filePath, data) => {
3127
- fs__default.default.writeFileSync(filePath, data);
3128
- }
3129
- });
3130
- __publicField(this, "path", {
3131
- join: (...paths) => path__default.default.join(...paths)
3132
- });
3133
- __publicField(this, "env", {
3134
- get: (key) => process.env[key]
3135
- });
3136
- __publicField(this, "cwd", () => process.cwd());
3137
- }
3138
- };
3139
- function createRuntimeAdapter() {
3140
- const detector = RuntimeDetector.getInstance();
3141
- if (detector.isBun) {
3142
- return new BunAdapter();
3143
- }
3144
- return new NodeAdapter();
3145
- }
3146
- var runtime = createRuntimeAdapter();
3147
-
3148
- // src/core/structured-log.ts
3149
- function serializeMessage2(message) {
3150
- if (typeof message === "string") {
3151
- return message;
3152
- }
3153
- if (message !== null && typeof message === "object") {
3154
- try {
3155
- return JSON.stringify(
3156
- message,
3157
- (_key, value) => {
3158
- if (typeof value === "function") {
3159
- return `[Function: ${value.name || "anonymous"}]`;
3160
- }
3161
- if (value === void 0) {
3162
- return "[undefined]";
3163
- }
3164
- if (typeof value === "symbol") {
3165
- return value.toString();
3166
- }
3167
- return value;
3168
- },
3169
- 2
3170
- );
3171
- } catch {
3172
- return "[Object]";
3173
- }
3174
- }
3175
- return String(message);
3176
- }
3177
- function normalizeEventData(message, args) {
3178
- if (typeof message === "string") {
3179
- if (args.length === 0) {
3180
- return void 0;
3181
- }
3182
- return args.length === 1 ? args[0] : args;
3183
- }
3184
- const values = [message, ...args];
3185
- return values.length === 1 ? values[0] : values;
3186
- }
3187
- function normalizeDetails(value) {
3188
- if (!value || typeof value !== "object" || Array.isArray(value)) {
3189
- return void 0;
3190
- }
3191
- return value;
3192
- }
3193
- function normalizeError2(error, fallbackStatus) {
3194
- if (error === void 0 || error === null) {
3195
- return fallbackStatus === void 0 || fallbackStatus < 400 ? void 0 : {
3196
- message: `HTTP ${fallbackStatus}`,
3197
- code: fallbackStatus,
3198
- type: "HttpError"
3199
- };
3200
- }
3201
- if (error instanceof Error) {
3202
- const errorLike = error;
22
+ async function loadDatabase() {
23
+ try {
24
+ const mod = await import(BUN_SQLITE_MODULE);
25
+ const Database = mod.default;
26
+ runtime = 'bun';
3203
27
  return {
3204
- message: error.message,
3205
- code: errorLike.code,
3206
- type: errorLike.type ?? error.name ?? error.constructor?.name,
3207
- stack: error.stack,
3208
- why: errorLike.why,
3209
- fix: errorLike.fix,
3210
- link: errorLike.link,
3211
- details: normalizeDetails(errorLike.details),
3212
- cause: errorLike.cause
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
+ },
3213
46
  };
3214
- }
3215
- if (typeof error === "object") {
3216
- const record = error;
3217
- const statusCode = typeof record.statusCode === "number" ? record.statusCode : typeof record.status === "number" ? record.status : fallbackStatus;
47
+ } catch {}
48
+
49
+ try {
50
+ const mod = await import(NODE_SQLITE_MODULE);
51
+ runtime = 'node';
3218
52
  return {
3219
- message: typeof record.message === "string" ? record.message : `HTTP ${statusCode ?? 500}`,
3220
- code: typeof record.code === "string" || typeof record.code === "number" ? record.code : statusCode,
3221
- type: typeof record.type === "string" ? record.type : typeof record.name === "string" ? record.name : "Error",
3222
- stack: typeof record.stack === "string" ? record.stack : void 0,
3223
- why: typeof record.why === "string" ? record.why : void 0,
3224
- fix: typeof record.fix === "string" ? record.fix : void 0,
3225
- link: typeof record.link === "string" ? record.link : void 0,
3226
- details: normalizeDetails(record.details),
3227
- cause: record.cause
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
+ },
3228
71
  };
3229
- }
3230
- return {
3231
- message: String(error),
3232
- code: fallbackStatus,
3233
- type: typeof error
3234
- };
72
+ } catch {}
73
+
74
+ throw new Error('No built-in SQLite runtime is available in this worker.');
3235
75
  }
3236
- function resolveEmitStatus(options) {
3237
- if (options.response && typeof options.response.status === "number") {
3238
- return options.response.status;
3239
- }
3240
- if (typeof options.status === "number") {
3241
- return options.status;
3242
- }
3243
- if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.statusCode === "number") {
3244
- return options.error.statusCode;
3245
- }
3246
- if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.status === "number") {
3247
- return options.error.status;
76
+
77
+ let adapter;
78
+
79
+ function ensureReady() {
80
+ if (!db || !adapter) {
81
+ throw new Error('SQLite durable queue is not initialized.');
3248
82
  }
3249
- return options.error ? 500 : void 0;
3250
- }
3251
- function createStructuredLog(groupId, options) {
3252
- const startedAt = performance.now();
3253
- const fields = { ...options.initialFields ?? {} };
3254
- const events = [];
3255
- let emittedPayload;
3256
- options.onCreate?.();
3257
- const appendEvent = (level, message, args) => {
3258
- events.push({
3259
- level,
3260
- message: serializeMessage2(message),
3261
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3262
- ...normalizeEventData(message, args) === void 0 ? {} : { data: normalizeEventData(message, args) }
3263
- });
3264
- return structuredLog;
3265
- };
3266
- const structuredLog = {
3267
- set(extraFields) {
3268
- Object.assign(fields, extraFields);
3269
- return structuredLog;
3270
- },
3271
- debug(message, ...args) {
3272
- return appendEvent("debug", message, args);
3273
- },
3274
- info(message, ...args) {
3275
- return appendEvent("info", message, args);
3276
- },
3277
- warn(message, ...args) {
3278
- return appendEvent("warn", message, args);
3279
- },
3280
- warning(message, ...args) {
3281
- return appendEvent("warning", message, args);
3282
- },
3283
- error(message, ...args) {
3284
- return appendEvent("error", message, args);
3285
- },
3286
- success(message, ...args) {
3287
- return appendEvent("success", message, args);
3288
- },
3289
- critical(message, ...args) {
3290
- return appendEvent("critical", message, args);
3291
- },
3292
- table(message, data) {
3293
- return appendEvent("table", message, data === void 0 ? [] : [data]);
3294
- },
3295
- emit(emitOptions = {}) {
3296
- if (emittedPayload) {
3297
- return emittedPayload;
3298
- }
3299
- const defaultFields = options.resolveDefaultFields?.() ?? {};
3300
- const status = resolveEmitStatus(emitOptions);
3301
- const error = normalizeError2(emitOptions.error, status);
3302
- const level = emitOptions.level ?? (error ? "error" : "info");
3303
- const payload = {
3304
- ...defaultFields,
3305
- ...fields,
3306
- groupId,
3307
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3308
- level,
3309
- duration: Math.round(performance.now() - startedAt),
3310
- ...typeof status === "number" ? { status } : {},
3311
- ...events.length > 0 ? { events: [...events] } : {},
3312
- ...error ? { error } : {}
3313
- };
3314
- options.write(payload, emitOptions.message ?? "structured_log");
3315
- emittedPayload = payload;
3316
- options.onEmit?.(payload);
3317
- return payload;
3318
- }
3319
- };
3320
- return structuredLog;
3321
83
  }
3322
84
 
3323
- // src/core/logger.ts
3324
- var LOGGER_FACTORY = /* @__PURE__ */ Symbol("blyp.logger.factory");
3325
- var CUSTOM_LEVELS = {
3326
- success: 25,
3327
- info: 30,
3328
- debug: 35,
3329
- table: 37,
3330
- warning: 40,
3331
- error: 50,
3332
- critical: 60
3333
- };
3334
- var CONSOLE_LEVELS = {
3335
- success: "success",
3336
- critical: "critical",
3337
- warning: "warning",
3338
- info: "info",
3339
- debug: "debug",
3340
- error: "error",
3341
- warn: "warn",
3342
- table: "debug"
3343
- };
3344
- var MAGENTA = "\x1B[35m";
3345
- var RESET = "\x1B[0m";
3346
- function summarizeClientConsoleData(data) {
3347
- if (!data || typeof data !== "object" || Array.isArray(data)) {
3348
- return null;
3349
- }
3350
- const record = data;
3351
- const summary = {};
3352
- if (record.data !== void 0) {
3353
- summary.data = record.data;
3354
- }
3355
- const pathname = typeof record.page?.pathname === "string" ? record.page.pathname : void 0;
3356
- const url = typeof record.page?.url === "string" ? record.page.url : void 0;
3357
- if (pathname || url) {
3358
- summary.page = pathname ?? url;
3359
- }
3360
- if (record.metadata !== void 0) {
3361
- summary.metadata = record.metadata;
3362
- }
3363
- return Object.keys(summary).length > 0 ? summary : null;
85
+ function normalizeConnectorTarget(value) {
86
+ return typeof value === 'string' && value.length > 0 ? value : null;
3364
87
  }
3365
- function getConsoleDataPayload(data) {
3366
- if (!data || typeof data !== "object" || Array.isArray(data)) {
3367
- return { hidden: false, value: data };
3368
- }
3369
- const record = data;
3370
- if (record.type === "http_request" || record.type === "http_error") {
3371
- return { hidden: true };
3372
- }
3373
- if (record.type === "client_log") {
3374
- const summary = summarizeClientConsoleData(data);
3375
- if (!summary) {
3376
- return { hidden: true };
3377
- }
3378
- return {
3379
- hidden: false,
3380
- value: summary
3381
- };
3382
- }
3383
- return { hidden: false, value: data };
88
+
89
+ function createConnectorCondition() {
90
+ return '(connector_type = ? AND ((connector_target IS NULL AND ? IS NULL) OR connector_target = ?))';
3384
91
  }
3385
- function createPinoLogger(config) {
3386
- if (config.pretty) {
3387
- const pinoPretty = __require("pino-pretty");
3388
- const pretty = pinoPretty.default({
3389
- colorize: true,
3390
- translateTime: "SYS:HH:MM:ss",
3391
- ignore: "pid,hostname,caller",
3392
- customColors: {
3393
- success: "green",
3394
- critical: "red bold",
3395
- info: "blue",
3396
- warning: "yellow",
3397
- error: "red",
3398
- debug: "cyan",
3399
- table: "cyan"
3400
- },
3401
- messageFormat: (log, messageKey) => {
3402
- const message = String(log[messageKey] ?? "");
3403
- const caller = typeof log.caller === "string" ? log.caller.trim() : "";
3404
- if (!caller) {
3405
- return message;
3406
- }
3407
- return `${message} ${MAGENTA}${caller}${RESET}`;
3408
- }
3409
- });
3410
- return pino__default.default(
3411
- {
3412
- level: config.level,
3413
- customLevels: CUSTOM_LEVELS
3414
- },
3415
- pretty
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 = ?'
3416
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;
3417
116
  }
3418
- return pino__default.default({
3419
- level: config.level,
3420
- customLevels: CUSTOM_LEVELS
3421
- });
3422
- }
3423
- function getLoggerFactory(logger2) {
3424
- const factory = logger2[LOGGER_FACTORY];
3425
- if (!factory) {
3426
- throw new Error("Unsupported Blyp logger instance");
3427
- }
3428
- return factory;
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
+ ]);
3429
131
  }
3430
- function getPostHogSender(logger2) {
3431
- return getLoggerFactory(logger2).posthog;
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'));
3432
182
  }
3433
- function getBetterStackSender(logger2) {
3434
- return getLoggerFactory(logger2).betterstack;
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]);
3435
191
  }
3436
- function tryGetPostHogSender(logger2) {
192
+
193
+ function insertJobs(jobs) {
194
+ ensureReady();
195
+ if (!Array.isArray(jobs) || jobs.length === 0) {
196
+ return;
197
+ }
198
+
199
+ adapter.exec(db, 'BEGIN');
3437
200
  try {
3438
- return getPostHogSender(logger2);
3439
- } catch {
3440
- return null;
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;
3441
228
  }
3442
229
  }
3443
- function tryGetBetterStackSender(logger2) {
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');
3444
246
  try {
3445
- return getBetterStackSender(logger2);
3446
- } catch {
3447
- return null;
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;
3448
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
+ }));
3449
278
  }
3450
- function getSentrySender(logger2) {
3451
- return getLoggerFactory(logger2).sentry;
3452
- }
3453
- function getOtlpRegistry(logger2) {
3454
- return getLoggerFactory(logger2).otlp;
3455
- }
3456
- function attachLoggerInternals(target, source) {
3457
- const factory = getLoggerFactory(source);
3458
- Object.defineProperty(target, LOGGER_FACTORY, {
3459
- value: factory,
3460
- enumerable: false,
3461
- configurable: false,
3462
- writable: false
3463
- });
3464
- return target;
3465
- }
3466
- function createLoggerWithSource(logger2, source) {
3467
- const factory = getLoggerFactory(logger2);
3468
- return factory.create(source, factory.bindings);
3469
- }
3470
- function createStructuredLogForLogger(logger2, groupId, options = {}) {
3471
- const factory = getLoggerFactory(logger2);
3472
- return createStructuredLog(groupId, {
3473
- initialFields: options.initialFields,
3474
- resolveDefaultFields: () => ({
3475
- ...factory.bindings,
3476
- ...options.resolveDefaultFields?.() ?? {}
3477
- }),
3478
- write: (payload, message) => {
3479
- factory.writeStructured(payload, message, "structured-flush");
3480
- },
3481
- onCreate: options.onCreate,
3482
- onEmit: options.onEmit
3483
- });
3484
- }
3485
- function maybeSendToPostHog(posthog, record) {
3486
- if (isClientLogRecord(record)) {
279
+
280
+ function ack(ids) {
281
+ ensureReady();
282
+ if (!Array.isArray(ids) || ids.length === 0) {
3487
283
  return;
3488
284
  }
3489
- if (!posthog.shouldAutoForwardServerLogs()) {
3490
- if (posthog.enabled && !posthog.ready) {
3491
- posthog.send(record, { source: "server", warnIfUnavailable: true });
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]);
3492
291
  }
3493
- return;
292
+ adapter.exec(db, 'COMMIT');
293
+ } catch (error) {
294
+ adapter.exec(db, 'ROLLBACK');
295
+ throw error;
3494
296
  }
3495
- posthog.send(record, { source: "server", warnIfUnavailable: true });
3496
297
  }
3497
- function maybeSendToBetterStack(betterstack, record) {
3498
- if (isClientLogRecord(record)) {
298
+
299
+ function reschedule(items, now) {
300
+ ensureReady();
301
+ if (!Array.isArray(items) || items.length === 0) {
3499
302
  return;
3500
303
  }
3501
- if (!betterstack.shouldAutoForwardServerLogs()) {
3502
- if (betterstack.enabled && !betterstack.ready) {
3503
- betterstack.send(record, { source: "server", warnIfUnavailable: true });
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
+ ]);
3504
320
  }
3505
- return;
321
+ adapter.exec(db, 'COMMIT');
322
+ } catch (error) {
323
+ adapter.exec(db, 'ROLLBACK');
324
+ throw error;
3506
325
  }
3507
- betterstack.send(record, { source: "server", warnIfUnavailable: true });
3508
326
  }
3509
- function maybeSendToSentry(sentry, record) {
3510
- if (isClientLogRecord(record)) {
327
+
328
+ function deadLetter(items) {
329
+ ensureReady();
330
+ if (!Array.isArray(items) || items.length === 0) {
3511
331
  return;
3512
332
  }
3513
- if (!sentry.shouldAutoForwardServerLogs()) {
3514
- if (sentry.enabled && !sentry.ready) {
3515
- sentry.send(record, { source: "server", warnIfUnavailable: true });
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]);
3516
357
  }
3517
- return;
358
+
359
+ adapter.exec(db, 'COMMIT');
360
+ } catch (error) {
361
+ adapter.exec(db, 'ROLLBACK');
362
+ throw error;
3518
363
  }
3519
- sentry.send(record, { source: "server", warnIfUnavailable: true });
3520
364
  }
3521
- function maybeSendToOTLP(otlp, record) {
3522
- if (isClientLogRecord(record)) {
365
+
366
+ function markSuccess(items) {
367
+ ensureReady();
368
+ if (!Array.isArray(items) || items.length === 0) {
3523
369
  return;
3524
370
  }
3525
- for (const sender of otlp.getAutoForwardTargets()) {
3526
- sender.send(record, { source: "server", warnIfUnavailable: true });
3527
- }
3528
- }
3529
- function createLoggerInstance(rootRawLogger, sink, betterstack, posthog, sentry, otlp, bindings = {}, source = "root") {
3530
- const rawLogger = Object.keys(bindings).length > 0 ? rootRawLogger.child(bindings) : rootRawLogger;
3531
- const writeRecord = (level, message, args, writeSource = source) => {
3532
- if (writeSource === "root" && shouldDropRootLogWrite()) {
3533
- return;
3534
- }
3535
- const record = buildRecord(level, message, args, bindings);
3536
- const consoleMessage = serializeMessage(message);
3537
- const payload = {
3538
- caller: record.caller
3539
- };
3540
- const consoleData = getConsoleDataPayload(record.data);
3541
- if (!consoleData.hidden && consoleData.value !== void 0) {
3542
- payload.data = consoleData.value;
3543
- }
3544
- const consoleMethod = CONSOLE_LEVELS[level];
3545
- const boundLogger = rawLogger;
3546
- const logMethod = boundLogger[consoleMethod] ?? boundLogger.info ?? ((_payload, _message) => {
3547
- });
3548
- logMethod.call(
3549
- rawLogger,
3550
- payload,
3551
- consoleMessage
3552
- );
3553
- sink.write(record);
3554
- maybeSendToBetterStack(betterstack, record);
3555
- maybeSendToPostHog(posthog, record);
3556
- maybeSendToSentry(sentry, record);
3557
- maybeSendToOTLP(otlp, record);
3558
- };
3559
- const writeStructuredRecord = (payload, message, writeSource = "structured-flush") => {
3560
- const level = resolveStructuredWriteLevel(payload.level);
3561
- const record = buildStructuredRecord(level, message, payload, bindings);
3562
- const consoleMethod = CONSOLE_LEVELS[level];
3563
- const boundLogger = rawLogger;
3564
- const logMethod = boundLogger[consoleMethod] ?? boundLogger.info ?? ((_payload, _message) => {
3565
- });
3566
- logMethod.call(
3567
- rawLogger,
3568
- {
3569
- caller: record.caller,
3570
- ...payload
3571
- },
3572
- message
3573
- );
3574
- if (writeSource !== "root" || !shouldDropRootLogWrite()) {
3575
- sink.write(record);
3576
- }
3577
- maybeSendToBetterStack(betterstack, record);
3578
- maybeSendToPostHog(posthog, record);
3579
- maybeSendToSentry(sentry, record);
3580
- maybeSendToOTLP(otlp, record);
3581
- };
3582
- const logger2 = {
3583
- success: (message, ...args) => {
3584
- writeRecord("success", message, args);
3585
- },
3586
- critical: (message, ...args) => {
3587
- writeRecord("critical", message, args);
3588
- },
3589
- warning: (message, ...args) => {
3590
- writeRecord("warning", message, args);
3591
- },
3592
- info: (message, ...args) => {
3593
- writeRecord("info", message, args);
3594
- },
3595
- debug: (message, ...args) => {
3596
- writeRecord("debug", message, args);
3597
- },
3598
- error: (message, ...args) => {
3599
- writeRecord("error", message, args);
3600
- },
3601
- warn: (message, ...args) => {
3602
- writeRecord("warn", message, args);
3603
- },
3604
- table: (message, data) => {
3605
- if (data && typeof data === "object" && runtime.env.get("NODE_ENV") !== "production") {
3606
- console.log("TABLE:", message);
3607
- console.table(data);
3608
- }
3609
- writeRecord("table", message, data === void 0 ? [] : [data]);
3610
- },
3611
- flush: () => sink.flush(),
3612
- shutdown: () => sink.shutdown(),
3613
- createStructuredLog: (groupId, initial) => {
3614
- return createStructuredLogForLogger(logger2, groupId, {
3615
- initialFields: initial
3616
- });
3617
- },
3618
- child: (childBindings) => {
3619
- const mergedBindings = { ...bindings, ...childBindings };
3620
- return createLoggerInstance(
3621
- rootRawLogger,
3622
- sink,
3623
- betterstack,
3624
- posthog,
3625
- sentry,
3626
- otlp,
3627
- mergedBindings,
3628
- source
3629
- );
3630
- },
3631
- [LOGGER_FACTORY]: {
3632
- bindings,
3633
- betterstack,
3634
- posthog,
3635
- sentry,
3636
- otlp,
3637
- sink,
3638
- create: (nextSource, nextBindings = bindings) => {
3639
- return createLoggerInstance(
3640
- rootRawLogger,
3641
- sink,
3642
- betterstack,
3643
- posthog,
3644
- sentry,
3645
- otlp,
3646
- nextBindings,
3647
- nextSource
3648
- );
3649
- },
3650
- writeStructured: (payload, message, nextSource = "structured-flush") => {
3651
- writeStructuredRecord(payload, message, nextSource);
3652
- }
371
+
372
+ adapter.exec(db, 'BEGIN');
373
+ try {
374
+ for (const item of items) {
375
+ updateConnectorDeliveryStatus(item, true);
3653
376
  }
3654
- };
3655
- return logger2;
377
+ adapter.exec(db, 'COMMIT');
378
+ } catch (error) {
379
+ adapter.exec(db, 'ROLLBACK');
380
+ throw error;
381
+ }
3656
382
  }
3657
- var loggerInstance = null;
3658
- function createBaseLogger(config) {
3659
- if (config === void 0 && loggerInstance) {
3660
- return loggerInstance;
383
+
384
+ function markFailure(items) {
385
+ ensureReady();
386
+ if (!Array.isArray(items) || items.length === 0) {
387
+ return;
3661
388
  }
3662
- const resolvedConfig = resolveConfig(config);
3663
- const rawLogger = createPinoLogger(resolvedConfig);
3664
- const sink = createPrimarySink(resolvedConfig);
3665
- const betterstack = createBetterStackSender(resolvedConfig);
3666
- const posthog = createPostHogSender(resolvedConfig);
3667
- const sentry = createSentrySender(resolvedConfig);
3668
- const otlp = createOTLPRegistry(resolvedConfig);
3669
- const instance = createLoggerInstance(
3670
- rawLogger,
3671
- sink,
3672
- betterstack,
3673
- posthog,
3674
- sentry,
3675
- otlp
3676
- );
3677
- if (config === void 0) {
3678
- loggerInstance = instance;
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;
3679
399
  }
3680
- return instance;
3681
400
  }
3682
- createBaseLogger();
3683
401
 
3684
- // src/frameworks/shared/logger.ts
3685
- function buildVerboseLogMessage(method, statusCode, url, responseTime) {
3686
- const methodColor = getMethodColor(method);
3687
- const statusColor = getStatusColor(statusCode);
3688
- const timeColor = getResponseTimeColor(responseTime);
3689
- return `${methodColor} ${url} ${statusColor} ${timeColor}`;
3690
- }
3691
- function resolveClientLoggingConfig(clientLogging, defaultClientLogging) {
3692
- const defaultPath = normalizeEndpointPath(
3693
- defaultClientLogging?.path ?? DEFAULT_CLIENT_LOG_ENDPOINT
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
+ []
3694
413
  );
3695
- const defaultConfig = defaultClientLogging?.enabled === false ? null : { path: defaultPath };
3696
- if (clientLogging === false) {
3697
- return null;
3698
- }
3699
- if (clientLogging === void 0) {
3700
- return defaultConfig;
3701
- }
3702
- if (clientLogging === true) {
3703
- return {
3704
- path: defaultPath
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,
3705
426
  };
427
+ byKey.set(key, item);
428
+ rows.push(item);
3706
429
  }
3707
- return {
3708
- ...defaultConfig,
3709
- ...clientLogging,
3710
- path: normalizeEndpointPath(clientLogging.path ?? defaultPath)
3711
- };
3712
- }
3713
- function resolveServerLogger(config = {}, loggerOverride) {
3714
- const resolvedConfig = resolveConfig({
3715
- ...config.level !== void 0 ? { level: config.level } : {},
3716
- ...config.pretty !== void 0 ? { pretty: config.pretty } : {},
3717
- ...config.destination !== void 0 ? { destination: config.destination } : {},
3718
- ...config.logDir !== void 0 ? { logDir: config.logDir } : {},
3719
- ...config.file !== void 0 ? { file: config.file } : {},
3720
- ...config.database !== void 0 ? { database: config.database } : {},
3721
- ...config.connectors !== void 0 ? { connectors: config.connectors } : {}
3722
- });
3723
- const {
3724
- level = resolvedConfig.level,
3725
- pretty = resolvedConfig.pretty,
3726
- destination = resolvedConfig.destination,
3727
- logDir = resolvedConfig.logDir,
3728
- file = resolvedConfig.file,
3729
- database = resolvedConfig.database,
3730
- autoLogging = true,
3731
- customProps,
3732
- logErrors = true,
3733
- ignorePaths,
3734
- clientLogging,
3735
- connectors
3736
- } = config;
3737
- const logger2 = createBaseLogger({
3738
- level,
3739
- pretty,
3740
- destination,
3741
- logDir,
3742
- file,
3743
- database,
3744
- connectors
3745
- });
3746
- const resolvedClientLogging = resolveClientLoggingConfig(
3747
- clientLogging,
3748
- resolvedConfig.clientLogging
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']
3749
437
  );
3750
- const ingestionPath = resolvedClientLogging?.path ?? DEFAULT_CLIENT_LOG_ENDPOINT;
3751
- const resolvedIgnorePaths = resolvedClientLogging ? Array.from(/* @__PURE__ */ new Set([...ignorePaths ?? [], ingestionPath])) : ignorePaths;
3752
- return {
3753
- logger: logger2,
3754
- betterstack: getBetterStackSender(logger2),
3755
- posthog: getPostHogSender(logger2),
3756
- sentry: getSentrySender(logger2),
3757
- otlp: getOtlpRegistry(logger2),
3758
- resolvedConfig,
3759
- level,
3760
- pretty,
3761
- logDir,
3762
- file,
3763
- autoLogging,
3764
- customProps,
3765
- logErrors,
3766
- resolvedIgnorePaths,
3767
- resolvedClientLogging,
3768
- ingestionPath
3769
- };
3770
- }
3771
- function shouldSkipAutoLogging(config, ctx, path3) {
3772
- if (config.autoLogging === false) {
3773
- return true;
3774
- }
3775
- if (typeof config.autoLogging === "object" && config.autoLogging.ignore?.(ctx)) {
3776
- return true;
3777
- }
3778
- return shouldIgnorePath(path3, config.resolvedIgnorePaths);
3779
- }
3780
- function shouldSkipErrorLogging(config, path3) {
3781
- if (!config.logErrors) {
3782
- return true;
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
+ }
3783
452
  }
3784
- return shouldIgnorePath(path3, config.resolvedIgnorePaths);
3785
- }
3786
- function resolveAdditionalProps(config, ctx) {
3787
- return config.customProps ? config.customProps(ctx) : {};
3788
- }
3789
- function emitHttpRequestLog(logger2, level, request, path3, statusCode, responseTime, additionalProps = {}) {
3790
- const requestLogData = buildRequestLogData(
3791
- request,
3792
- "http_request",
3793
- path3,
3794
- statusCode,
3795
- responseTime,
3796
- additionalProps
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
+ []
3797
460
  );
3798
- if (level === "info") {
3799
- logger2.info(
3800
- buildInfoLogMessage(request.method, statusCode, path3, responseTime),
3801
- requestLogData
3802
- );
3803
- } else {
3804
- logger2.info(
3805
- buildVerboseLogMessage(request.method, statusCode, path3, responseTime),
3806
- requestLogData
3807
- );
3808
- if (Object.keys(additionalProps).length > 0) {
3809
- logger2.debug("Request context", additionalProps);
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);
3810
474
  }
3811
475
  }
3812
- return requestLogData;
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
+ });
3813
482
  }
3814
- function emitHttpErrorLog(logger2, level, request, path3, statusCode, responseTime, error, additionalProps = {}, captureContext = {}) {
3815
- const errorLogData = buildRequestLogData(
3816
- request,
3817
- "http_error",
3818
- path3,
3819
- statusCode,
3820
- responseTime,
3821
- {
3822
- error: error?.message ?? `HTTP ${statusCode}`,
3823
- stack: error?.stack,
3824
- code: error?.code,
3825
- why: error?.why,
3826
- fix: error?.fix,
3827
- link: error?.link,
3828
- details: error?.details,
3829
- ...additionalProps
3830
- }
3831
- );
3832
- const message = level === "info" ? buildInfoLogMessage(request.method, statusCode, path3, responseTime) : buildVerboseLogMessage(request.method, statusCode, path3, responseTime);
3833
- logger2.error(message, errorLogData);
3834
- const posthog = tryGetPostHogSender(logger2);
3835
- if (posthog?.shouldAutoCaptureExceptions()) {
3836
- posthog.captureException(captureContext.error ?? error ?? message, {
3837
- source: "server",
3838
- warnIfUnavailable: true,
3839
- distinctId: captureContext.distinctId ?? getHeaderValue(request.headers, "x-posthog-distinct-id"),
3840
- properties: buildPostHogExceptionProperties(
3841
- {
3842
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3843
- level: "error",
3844
- message,
3845
- data: errorLogData
3846
- },
3847
- "server",
3848
- {
3849
- $request_method: request.method,
3850
- $request_path: path3,
3851
- $current_url: request.url,
3852
- $response_status_code: statusCode,
3853
- ...getHeaderValue(request.headers, "user-agent") ? { $user_agent: getHeaderValue(request.headers, "user-agent") } : {},
3854
- ...errorLogData.ip ? { $ip: errorLogData.ip } : {}
3855
- }
3856
- )
3857
- });
3858
- }
3859
- const betterstack = tryGetBetterStackSender(logger2);
3860
- if (betterstack?.shouldAutoCaptureExceptions()) {
3861
- betterstack.captureException(captureContext.error ?? error ?? message, {
3862
- source: "server",
3863
- warnIfUnavailable: true,
3864
- context: {
3865
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3866
- level: "error",
3867
- message,
3868
- status: statusCode,
3869
- path: path3,
3870
- data: errorLogData
3871
- }
3872
- });
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);
3873
492
  }
3874
- return errorLogData;
3875
- }
3876
- async function parseClientLogPayload(request, body) {
3877
- if (body !== void 0) {
3878
- if (typeof body === "string") {
3879
- return JSON.parse(body);
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);
3880
500
  }
3881
- return body;
3882
- }
3883
- if (typeof request.json === "function") {
3884
- return await request.json();
3885
- }
3886
- throw new Error("Unable to parse client log payload");
3887
- }
3888
- function getClientLogMethod(logger2, level) {
3889
- switch (level) {
3890
- case "debug":
3891
- return logger2.debug;
3892
- case "info":
3893
- return logger2.info;
3894
- case "warning":
3895
- return logger2.warning;
3896
- case "error":
3897
- return logger2.error;
3898
- case "critical":
3899
- return logger2.critical;
3900
- case "success":
3901
- return logger2.success;
3902
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
+ };
3903
532
  }
3904
- async function handleClientLogIngestion(options) {
3905
- const { config, ctx, request, body, deliveryPath } = options;
3906
- if (!config.resolvedClientLogging) {
3907
- return { status: 404 };
533
+
534
+ function retryDeadLetters(ids, now) {
535
+ ensureReady();
536
+ if (!Array.isArray(ids) || ids.length === 0) {
537
+ return 0;
3908
538
  }
3909
- let payload;
539
+
540
+ adapter.exec(db, 'BEGIN');
3910
541
  try {
3911
- payload = await parseClientLogPayload(request, body);
3912
- } catch {
3913
- return { status: 400 };
3914
- }
3915
- if (!isClientLogEvent(payload)) {
3916
- return { status: 400 };
3917
- }
3918
- const isAllowed = config.resolvedClientLogging.validate ? await config.resolvedClientLogging.validate(ctx, payload) : true;
3919
- if (!isAllowed) {
3920
- return { status: 403 };
3921
- }
3922
- const serverContext = config.resolvedClientLogging.enrich ? await config.resolvedClientLogging.enrich(ctx, payload) : void 0;
3923
- const structuredPayload = {
3924
- ...payload,
3925
- receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
3926
- delivery: buildClientDetails(request, deliveryPath ?? extractPathname(request.url))
3927
- };
3928
- if (serverContext !== void 0) {
3929
- structuredPayload.serverContext = serverContext;
3930
- }
3931
- if (payload.level === "table") {
3932
- config.logger.table(`[client] ${payload.message}`, structuredPayload);
3933
- } else {
3934
- const logMethod = getClientLogMethod(config.logger, payload.level);
3935
- logMethod(`[client] ${payload.message}`, structuredPayload);
3936
- }
3937
- const headers = {};
3938
- if (payload.connector === "betterstack") {
3939
- headers["x-blyp-betterstack-status"] = config.betterstack.ready ? "enabled" : "missing";
3940
- if (config.betterstack.ready) {
3941
- const forwardedRecord = {
3942
- timestamp: structuredPayload.receivedAt,
3943
- level: payload.level,
3944
- message: `[client] ${payload.message}`,
3945
- data: structuredPayload
3946
- };
3947
- config.betterstack.send(forwardedRecord, {
3948
- source: "client"
3949
- });
3950
- if ((payload.level === "error" || payload.level === "critical") && config.betterstack.shouldAutoCaptureExceptions()) {
3951
- const clientErrorCandidate = payload.data && typeof payload.data === "object" && !Array.isArray(payload.data) && typeof payload.data.message === "string" ? payload.data : payload.message;
3952
- config.betterstack.captureException(clientErrorCandidate, {
3953
- source: "client",
3954
- warnIfUnavailable: true,
3955
- context: {
3956
- sessionId: payload.session.sessionId,
3957
- pageUrl: payload.page.url,
3958
- pagePath: payload.page.pathname,
3959
- metadata: payload.metadata,
3960
- payload: structuredPayload
3961
- }
3962
- });
3963
- }
3964
- }
3965
- } else if (payload.connector === "posthog") {
3966
- headers["x-blyp-posthog-status"] = config.posthog.ready ? "enabled" : "missing";
3967
- if (config.posthog.ready) {
3968
- const forwardedRecord = {
3969
- timestamp: structuredPayload.receivedAt,
3970
- level: payload.level,
3971
- message: `[client] ${payload.message}`,
3972
- data: structuredPayload
3973
- };
3974
- config.posthog.send(forwardedRecord, {
3975
- source: "client"
3976
- });
3977
- if ((payload.level === "error" || payload.level === "critical") && config.posthog.shouldAutoCaptureExceptions()) {
3978
- const metadata = structuredPayload.metadata;
3979
- const posthogDistinctId = metadata && typeof metadata === "object" && !Array.isArray(metadata) && typeof metadata.posthogDistinctId === "string" && metadata.posthogDistinctId ? String(metadata.posthogDistinctId) : void 0;
3980
- const clientErrorCandidate = payload.data && typeof payload.data === "object" && !Array.isArray(payload.data) && typeof payload.data.message === "string" ? payload.data : payload.message;
3981
- config.posthog.captureException(clientErrorCandidate, {
3982
- source: "client",
3983
- warnIfUnavailable: true,
3984
- distinctId: posthogDistinctId,
3985
- properties: buildPostHogExceptionProperties(forwardedRecord, "client", {
3986
- $session_id: payload.session.sessionId,
3987
- $current_url: payload.page.url,
3988
- $request_path: payload.page.pathname,
3989
- "client.runtime": payload.device?.runtime,
3990
- "client.metadata": payload.metadata
3991
- })
3992
- });
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;
3993
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;
3994
573
  }
3995
- } else if (payload.connector === "sentry") {
3996
- headers["x-blyp-sentry-status"] = config.sentry.ready ? "enabled" : "missing";
3997
- if (config.sentry.ready) {
3998
- config.sentry.send({
3999
- timestamp: structuredPayload.receivedAt,
4000
- level: payload.level,
4001
- message: `[client] ${payload.message}`,
4002
- data: structuredPayload
4003
- }, {
4004
- source: "client"
4005
- });
4006
- }
4007
- } else if (payload.connector?.type === "otlp") {
4008
- const sender = config.otlp.get(payload.connector.name);
4009
- headers["x-blyp-otlp-status"] = sender.ready ? "enabled" : "missing";
4010
- if (sender.ready) {
4011
- sender.send({
4012
- timestamp: structuredPayload.receivedAt,
4013
- level: payload.level,
4014
- message: `[client] ${payload.message}`,
4015
- data: structuredPayload
4016
- }, {
4017
- source: "client"
4018
- });
4019
- }
574
+
575
+ adapter.exec(db, 'COMMIT');
576
+ return count;
577
+ } catch (error) {
578
+ adapter.exec(db, 'ROLLBACK');
579
+ throw error;
4020
580
  }
4021
- return Object.keys(headers).length > 0 ? { status: 204, headers } : { status: 204 };
4022
581
  }
4023
- function shouldAutoFlushServerLogger(config) {
4024
- return config.resolvedConfig.destination === "database";
4025
- }
4026
- async function flushServerLoggerSafely(config) {
4027
- if (!shouldAutoFlushServerLogger(config)) {
4028
- return;
582
+
583
+ function clearDeadLetters(ids) {
584
+ ensureReady();
585
+ if (!Array.isArray(ids) || ids.length === 0) {
586
+ return 0;
4029
587
  }
588
+
589
+ adapter.exec(db, 'BEGIN');
4030
590
  try {
4031
- await config.logger.flush();
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;
4032
604
  } catch (error) {
4033
- console.warn("[Blyp] Warning: Failed to flush database logs.", error);
605
+ adapter.exec(db, 'ROLLBACK');
606
+ throw error;
4034
607
  }
4035
608
  }
4036
609
 
4037
- // src/frameworks/shared/request-logger.ts
4038
- function createRequestScopedLogger(logger2, options = {}) {
4039
- const scopedLogger = createLoggerWithSource(logger2, "request-scoped");
4040
- const requestScopedLogger = attachLoggerInternals({
4041
- ...scopedLogger,
4042
- createStructuredLog: (groupId, initial) => {
4043
- return createStructuredLogForLogger(requestScopedLogger, groupId, {
4044
- initialFields: initial,
4045
- resolveDefaultFields: options.resolveStructuredFields,
4046
- onCreate: () => {
4047
- markStructuredCollectorActive();
4048
- },
4049
- onEmit: () => {
4050
- markStructuredLogEmitted();
4051
- options.onStructuredEmit?.();
4052
- }
4053
- });
4054
- },
4055
- child(bindings) {
4056
- return createRequestScopedLogger(scopedLogger.child(bindings), options);
4057
- }
4058
- }, scopedLogger);
4059
- setActiveRequestLogger(requestScopedLogger);
4060
- return requestScopedLogger;
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);
4061
615
  }
4062
616
 
4063
- // src/frameworks/hono/logger.ts
4064
- function createHonoLogger(config = {}) {
4065
- const shared = resolveServerLogger(config);
4066
- return async (context, next) => {
4067
- return runWithRequestContext(async () => {
4068
- const startTime = performance.now();
4069
- let structuredLogEmitted = false;
4070
- context.set(
4071
- "blypLog",
4072
- createRequestScopedLogger(shared.logger, {
4073
- resolveStructuredFields: () => ({
4074
- method: context.req.method,
4075
- path: context.req.path || extractPathname(context.req.url),
4076
- ...resolveAdditionalProps(shared, context)
4077
- }),
4078
- onStructuredEmit: () => {
4079
- structuredLogEmitted = true;
4080
- }
4081
- })
4082
- );
4083
- context.set("blypStartTime", startTime);
4084
- const path3 = context.req.path || extractPathname(context.req.url);
4085
- if (shared.resolvedClientLogging && context.req.method === "POST" && path3 === shared.ingestionPath) {
4086
- const result = await handleClientLogIngestion({
4087
- config: shared,
4088
- ctx: context,
4089
- request: context.req.raw,
4090
- deliveryPath: shared.ingestionPath
4091
- });
4092
- await flushServerLoggerSafely(shared);
4093
- return new Response(null, {
4094
- status: result.status,
4095
- headers: result.headers
4096
- });
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;
4097
630
  }
4098
- let thrownError;
4099
- try {
4100
- await next();
4101
- } catch (error) {
4102
- thrownError = error;
4103
- throw error;
4104
- } finally {
4105
- if (structuredLogEmitted) {
4106
- await flushServerLoggerSafely(shared);
4107
- return;
4108
- }
4109
- const responseTime = Math.round(performance.now() - startTime);
4110
- const request = createRequestLike(
4111
- context.req.method,
4112
- context.req.url,
4113
- context.req.raw.headers
4114
- );
4115
- const statusCode = context.res?.status ?? (thrownError ? 500 : 200);
4116
- if (thrownError || isErrorStatus(statusCode)) {
4117
- if (!shouldSkipErrorLogging(shared, path3)) {
4118
- emitHttpErrorLog(
4119
- shared.logger,
4120
- shared.level,
4121
- request,
4122
- path3,
4123
- statusCode,
4124
- responseTime,
4125
- toErrorLike(thrownError, statusCode),
4126
- resolveAdditionalProps(shared, context),
4127
- {
4128
- error: thrownError
4129
- }
4130
- );
4131
- }
4132
- await flushServerLoggerSafely(shared);
4133
- return;
4134
- }
4135
- if (!shouldSkipAutoLogging(shared, context, path3)) {
4136
- emitHttpRequestLog(
4137
- shared.logger,
4138
- shared.level,
4139
- request,
4140
- path3,
4141
- statusCode,
4142
- responseTime,
4143
- resolveAdditionalProps(shared, context)
4144
- );
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;
4145
686
  }
4146
- await flushServerLoggerSafely(shared);
4147
- }
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),
4148
697
  });
4149
- };
4150
- }
4151
- var createLogger = createHonoLogger;
4152
-
4153
- exports.createHonoLogger = createHonoLogger;
4154
- exports.createLogger = createLogger;
4155
- //# sourceMappingURL=hono.js.map
4156
- //# sourceMappingURL=hono.js.map
698
+ }
699
+ });
700
+ `}var be=class{constructor(t){this.path=t;d(this,"worker");d(this,"pending",new Map);d(this,"nextId",1);this.worker=new worker_threads.Worker(Jt(),{eval:true}),this.worker.on("message",r=>{let o=this.pending.get(r.id);if(o){if(this.pending.delete(r.id),r.ok){o.resolve(r.result);return}o.reject(new Error(r.error??"SQLite worker request failed."));}}),this.worker.on("error",r=>{for(let o of this.pending.values())o.reject(r instanceof Error?r:new Error(String(r)));this.pending.clear();});}request(t,r={}){let o=this.nextId++;return new Promise((n,i)=>{this.pending.set(o,{resolve:n,reject:i}),this.worker.postMessage({id:o,type:t,payload:r});})}async init(){await this.request("init",{path:this.path});}async insert(t){await this.request("insert",{jobs:t});}async claimDue(t,r){return this.request("claimDue",{limit:t,now:r})}async ack(t){await this.request("ack",{ids:t});}async reschedule(t,r){await this.request("reschedule",{items:t,now:r});}async deadLetter(t){await this.request("deadLetter",{items:t});}async markSuccess(t){await this.request("markSuccess",{items:t});}async markFailure(t){await this.request("markFailure",{items:t});}async getStatusSummary(){return this.request("getStatusSummary")}async listDeadLetters(t){return this.request("listDeadLetters",t)}async retryDeadLetters(t,r){return this.request("retryDeadLetters",{ids:t,now:r})}async clearDeadLetters(t){return this.request("clearDeadLetters",{ids:t})}async count(){return this.request("count")}async shutdown(){try{await this.request("shutdown");}finally{await this.worker.terminate();}}};var Gt=Symbol("blyp.connector.batch-dispatch"),Y=Symbol("blyp.connector.delivery-binder");function Z(e){return new Promise(t=>{setTimeout(t,e);})}function xo(e){return e.data===void 0||typeof e.data!="object"||e.data===null||e.data.type!=="client_log"}function Kt(e){return JSON.stringify(e)}function Do(e){try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.jobId!="string"?null:t}catch{return null}}function Vt(e){let t=new Map;for(let r of e){let o=`${r.connectorType}:${r.connectorTarget??""}`;t.has(o)||t.set(o,{connectorType:r.connectorType,connectorTarget:r.connectorTarget});}return [...t.values()]}var Ce=class{constructor(t){this.config=t;d(this,"warnOnce",k(new Set));d(this,"memoryQueue",[]);d(this,"durableStaging",[]);d(this,"dispatchers",new Map);d(this,"activeDispatches",0);d(this,"flushPromise",null);d(this,"durableFlushPromise",null);d(this,"pollTimer",null);d(this,"durablePollRunning",false);d(this,"closed",false);d(this,"durableClient",null);d(this,"durableReady",false);d(this,"durableInitPromise",null);t.enabled&&(this.durableInitPromise=this.initializeDurableQueue());}bindTarget(t){typeof t[Y]=="function"&&t[Y](this);let r=t[Gt];r&&this.dispatchers.set(r.dispatchKey,r);}unbindTarget(t){typeof t[Y]=="function"&&t[Y](null);}enqueue(t,r,o,n){this.closed||!xo(r)||(this.dispatchers.set(o.dispatchKey,o),this.memoryQueue.push({id:de(),connectorType:t,connectorTarget:n,source:"server",record:r,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 r of t)this.stageDurableJob(r,r.attemptCount,Math.max(r.nextAttemptAt,Date.now()));await this.flushDurableStaging();}await this.processUntilIdle(),this.durableClient&&(await this.durableClient.shutdown().catch(()=>{}),this.durableClient=null);}async getDurableCountForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?0:this.durableClient.count()}async getStatusSummaryForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:this.durableClient.getStatusSummary()}async listDeadLettersForTests(){return await this.durableInitPromise?.catch(()=>{}),!this.durableReady||!this.durableClient?[]:(await this.durableClient.listDeadLetters({limit:1e3,offset:0})).items}async initializeDurableQueue(){try{let t=new be(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 Z(10);}}takeNextMemoryBatch(){let t=Date.now(),r=this.memoryQueue.findIndex(i=>i.nextAttemptAt<=t);if(r===-1)return [];let o=this.memoryQueue[r],n=[o];this.memoryQueue.splice(r,1);for(let i=this.memoryQueue.length-1;i>=0;i-=1){let a=this.memoryQueue[i];a.dispatchKey===o.dispatchKey&&a.connectorTarget===o.connectorTarget&&a.nextAttemptAt<=t&&n.length<this.config.memoryBatchSize&&(n.push(a),this.memoryQueue.splice(i,1));}return n}async dispatchMemoryBatch(t){let r=t[0].dispatcher,o=Date.now(),n=await r.dispatch(t.map(i=>i.record),{source:"server",target:t[0].connectorTarget}).catch(i=>({ok:false,retryable:true,error:i instanceof Error?i.message:String(i)}));if(n.ok){await this.recordSuccessfulDispatch(t,o);return}await this.handleRetryableFailure(t,n,false,o);}async handleRetryableFailure(t,r,o,n){o||await this.durableInitPromise?.catch(()=>{});let i=[],a=[];await this.recordFailedDispatch(t,r,n);for(let s of t){let l=s.attemptCount+1;if(!r.retryable||l>=s.maxAttempts){a.push({id:s.id,connectorType:s.connectorType,connectorTarget:s.connectorTarget,operation:"send",payloadJson:Kt({jobId:s.id,connectorType:s.connectorType,connectorTarget:s.connectorTarget,source:s.source,record:s.record,createdAt:s.createdAt}),attemptCount:l,maxAttempts:s.maxAttempts,lastError:r.error,firstEnqueuedAt:s.createdAt,deadLetteredAt:n,lastAttemptAt:n}),this.warnOnce(`connector-drop:${s.connectorType}:${s.connectorTarget??"default"}:${s.id}`,o&&this.durableReady?`[Blyp] Warning: Dead-lettered ${s.connectorType} connector job after ${l} failed attempt(s). ${r.error??"Connector delivery failed."}`:`[Blyp] Warning: Dropped ${s.connectorType} connector job after ${l} failed attempt(s). ${r.error??"Connector delivery failed."}`);continue}let u=n+Ht(l,this.config.retry);if(o){i.push({id:s.id,attemptCount:l,nextAttemptAt:u,lastError:r.error});continue}if(this.durableReady&&this.config.durableSpillStrategy==="after-first-failure"){this.stageDurableJob(s,l,u,r.error);continue}this.memoryQueue.push({...s,attemptCount:l,nextAttemptAt:u});}a.length>0&&await this.durableClient?.deadLetter(a).catch(s=>{this.warnOnce("connector-dead-letter-failure","[Blyp] Warning: Failed to persist dead-lettered connector queue jobs.",s);}),i.length>0&&await this.durableClient?.reschedule(i,n).catch(s=>{this.warnOnce("connector-reschedule-failure","[Blyp] Warning: Failed to reschedule durable connector queue jobs.",s);});}async recordSuccessfulDispatch(t,r){if(!this.durableReady||!this.durableClient||t.length===0)return;let o=Vt(t).map(n=>({connectorType:n.connectorType,connectorTarget:n.connectorTarget,timestamp:r}));await this.durableClient.markSuccess(o).catch(n=>{this.warnOnce("connector-status-success-failure","[Blyp] Warning: Failed to record connector delivery success state.",n);});}async recordFailedDispatch(t,r,o){if(!this.durableReady||!this.durableClient||t.length===0)return;let n=Vt(t).map(i=>({connectorType:i.connectorType,connectorTarget:i.connectorTarget,timestamp:o,lastError:r.error}));await this.durableClient.markFailure(n).catch(i=>{this.warnOnce("connector-status-failure-failure","[Blyp] Warning: Failed to record connector delivery failure state.",i);});}stageDurableJob(t,r,o,n){let i=Kt({jobId:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,source:t.source,record:t.record,createdAt:t.createdAt});this.durableStaging.push({id:t.id,connectorType:t.connectorType,connectorTarget:t.connectorTarget,operation:"send",payloadJson:i,attemptCount:r,maxAttempts:t.maxAttempts,nextAttemptAt:o,state:"pending",lastError:n,createdAt:t.createdAt,updatedAt:Date.now()}),this.flushDurableStaging();}async flushDurableStaging(){if(!(!this.durableReady||!this.durableClient||this.durableStaging.length===0)){if(this.durableFlushPromise){await this.durableFlushPromise;return}this.durableFlushPromise=(async()=>{for(;this.durableStaging.length>0;){let t=this.durableStaging.splice(0,this.config.sqliteWriteBatchSize);try{await this.durableClient.insert(t);}catch(r){this.warnOnce("connector-durable-insert-failure","[Blyp] Warning: Failed to persist connector jobs into the durable SQLite queue.",r),this.durableStaging.unshift(...t);break}}})();try{await this.durableFlushPromise;}finally{this.durableFlushPromise=null;}}}async processDurableQueueOnce(){if(!(!this.durableReady||!this.durableClient||this.durablePollRunning)){this.durablePollRunning=true;try{for(;!this.closed;){let t=await this.durableClient.claimDue(this.config.sqliteReadBatchSize,Date.now());if(t.length===0)break;let r=new Map,o=[];for(let n of t){let i=Do(n.payloadJson);if(!i){o.push(n.id);continue}let a=n.connectorType==="otlp"?`otlp:${n.connectorTarget??""}`:n.connectorType,s=this.dispatchers.get(a);if(!s){o.push(n.id);continue}let l={id:n.id,connectorType:n.connectorType,connectorTarget:n.connectorTarget,source:i.source,record:i.record,attemptCount:n.attemptCount,maxAttempts:n.maxAttempts,nextAttemptAt:n.nextAttemptAt,createdAt:n.createdAt,dispatchKey:a,dispatcher:s},u=r.get(a)??[];u.push(l),r.set(a,u);}o.length>0&&await this.durableClient.ack(o);for(let n of r.values()){let a=await n[0].dispatcher.dispatch(n.map(s=>s.record),{source:"server",target:n[0].connectorTarget}).catch(s=>({ok:!1,retryable:!0,error:s instanceof Error?s.message:String(s)}));if(a.ok){await this.recordSuccessfulDispatch(n,Date.now()),await this.durableClient.ack(n.map(s=>s.id));continue}await this.handleRetryableFailure(n,a,!0,Date.now());}}}finally{this.durablePollRunning=false;}}}async drainDurableQueueForFlush(){if(!(!this.durableReady||!this.durableClient)){this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null);try{for(;!this.closed;){for(;this.durablePollRunning;)await Z(10);if(await this.processDurableQueueOnce(),await this.flushDurableStaging(),await this.durableClient.count().catch(()=>0)===0&&!this.durablePollRunning&&this.durableStaging.length===0)break;await Z(10);}}finally{this.closed||this.scheduleDurablePoll();}}}scheduleDurablePoll(){this.closed||!this.durableReady||this.pollTimer||(this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.flushDurableStaging(),await this.processDurableQueueOnce(),this.scheduleDurablePoll();},this.config.pollIntervalMs));}enforceMemoryCapacity(){for(;this.memoryQueue.length>this.config.memoryBufferSize;){let t=this.config.overflowStrategy==="drop-new"?this.memoryQueue.length-1:0,[r]=this.memoryQueue.splice(t,1);if(!r)break;if(this.durableReady){this.stageDurableJob(r,r.attemptCount,Math.max(Date.now(),r.nextAttemptAt),"spilled from in-memory buffer");continue}this.warnOnce(`connector-overflow:${r.connectorType}:${r.connectorTarget??"default"}:${t}`,`[Blyp] Warning: Connector queue overflow reached ${this.config.memoryBufferSize}. Dropping queued ${r.connectorType} job.`);}}hasReadyMemoryJobs(){let t=Date.now();return this.memoryQueue.some(r=>r.nextAttemptAt<=t)}async processUntilIdle(){for(;this.activeDispatches>0||this.memoryQueue.length>0||this.durableStaging.length>0||this.flushPromise!==null||this.durableFlushPromise!==null;){if(this.scheduleDispatch(),await this.flushPromise?.catch(()=>{}),await this.flushDurableStaging(),this.memoryQueue.some(t=>t.nextAttemptAt>Date.now())||await this.processDurableQueueOnce(),this.activeDispatches===0&&this.memoryQueue.length>0&&!this.hasReadyMemoryJobs()){let t=Math.min(...this.memoryQueue.map(r=>r.nextAttemptAt));await Z(Math.max(t-Date.now(),0));}else await Z(10);if(this.activeDispatches===0&&this.memoryQueue.length===0&&this.durableStaging.length===0)break}}};var F=class F{constructor(){d(this,"_type",null);}static getInstance(){return F.instance||(F.instance=new F),F.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"}};d(F,"instance");var Xe=F,Ye=class{constructor(){d(this,"type","bun");d(this,"isBun",true);d(this,"isNode",false);d(this,"file",{existsSync:t=>{try{let r=Bun.file(t);return r.size>0||r.name!==""}catch{return false}},mkdirSync:(t,r)=>{try{S__default.default.mkdirSync(t,r);}catch{}},writeFileSync:(t,r)=>{Bun.write(t,r);}});d(this,"path",{join:(...t)=>U__default.default.join(...t)});d(this,"env",{get:t=>Bun.env[t]});d(this,"cwd",()=>process.cwd());}},Ze=class{constructor(){d(this,"type","node");d(this,"isBun",false);d(this,"isNode",true);d(this,"file",{existsSync:t=>S__default.default.existsSync(t),mkdirSync:(t,r)=>{S__default.default.mkdirSync(t,r);},writeFileSync:(t,r)=>{S__default.default.writeFileSync(t,r);}});d(this,"path",{join:(...t)=>U__default.default.join(...t)});d(this,"env",{get:t=>process.env[t]});d(this,"cwd",()=>process.cwd());}};function Eo(){return Xe.getInstance().isBun?new Ye:new Ze}var Yt=Eo();function Zt(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let r=[e,...t];return r.length===1?r[0]:r}function er(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function ko(e,t){if(e==null)return t===void 0||t<400?void 0:{message:`HTTP ${t}`,code:t,type:"HttpError"};if(e instanceof Error){let r=e;return {message:e.message,code:r.code,type:r.type??e.name??e.constructor?.name,stack:e.stack,why:r.why,fix:r.fix,link:r.link,details:er(r.details),cause:r.cause}}if(typeof e=="object"){let r=e,o=typeof r.statusCode=="number"?r.statusCode:typeof r.status=="number"?r.status:t;return {message:typeof r.message=="string"?r.message:`HTTP ${o??500}`,code:typeof r.code=="string"||typeof r.code=="number"?r.code:o,type:typeof r.type=="string"?r.type:typeof r.name=="string"?r.name:"Error",stack:typeof r.stack=="string"?r.stack:void 0,why:typeof r.why=="string"?r.why:void 0,fix:typeof r.fix=="string"?r.fix:void 0,link:typeof r.link=="string"?r.link:void 0,details:er(r.details),cause:r.cause}}return {message:String(e),code:t,type:typeof e}}function _o(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 tr(e,t){let r=t.redact??T(),o=performance.now(),n=b(t.initialFields??{},r),i=[],a;t.onCreate?.();let s=(u,c,p)=>(i.push({level:u,message:B(c,r),timestamp:new Date().toISOString(),...Zt(c,p)===void 0?{}:{data:b(Zt(c,p),r)}}),l),l={set(u){return Object.assign(n,b(u,r)),l},debug(u,...c){return s("debug",u,c)},info(u,...c){return s("info",u,c)},warn(u,...c){return s("warn",u,c)},warning(u,...c){return s("warning",u,c)},error(u,...c){return s("error",u,c)},success(u,...c){return s("success",u,c)},critical(u,...c){return s("critical",u,c)},table(u,c){return s("table",u,c===void 0?[]:[c])},emit(u={}){if(a)return a;let c=b(t.resolveDefaultFields?.()??{},r),p=_o(u),m=b(ko(u.error,p),r),R=u.level??(m?"error":"info"),w=b({...c,...n,groupId:e,timestamp:new Date().toISOString(),level:R,duration:Math.round(performance.now()-o),...typeof p=="number"?{status:p}:{},...i.length>0?{events:[...i]}:{},...m?{error:m}:{}},r);return t.write(w,B(u.message??"structured_log",r)),a=w,t.onEmit?.(w),w}};return l}var rt=Symbol("blyp.logger.factory"),nr={success:25,info:30,debug:35,table:37,warning:40,error:50,critical:60},or={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warn",table:"debug"},Po="\x1B[35m",Ao="\x1B[0m";function ee(e){return fe(e)==="client_log"}function Bo(){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 Io(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,shouldAutoCaptureExceptions:()=>false,send:()=>{},captureException:()=>{},flush:async()=>{}}}function Oo(){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 No(){return {enabled:false,ready:false,mode:"auto",status:"missing",shouldAutoForwardServerLogs:()=>false,send:()=>{},flush:async()=>{}}}function Mo(e){return {name:e,enabled:false,ready:false,mode:"auto",serviceName:"blyp-app",endpoint:void 0,status:"missing",send:()=>{},flush:async()=>{}}}function Fo(){return {get:e=>Mo(e),getAutoForwardTargets:()=>[],send:()=>{},flush:async()=>{}}}function zo(e){return e.connectors?.betterstack?.enabled?H("betterstack",["@logtail/node","@sentry/node"],"../connectors/betterstack/sender").createBetterStackSender(e):Bo()}function qo(e){return e.connectors?.databuddy?.enabled?H("databuddy",["@databuddy/sdk"],"../connectors/databuddy/sender").createDatabuddySender(e):Io()}function jo(e){return e.connectors?.posthog?.enabled?H("posthog",["posthog-node","@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/posthog/sender").createPostHogSender(e):Oo()}function $o(e){return e.connectors?.sentry?.enabled?H("sentry",["@sentry/node"],"../connectors/sentry/sender").createSentrySender(e):No()}function Uo(e){return e.connectors?.otlp?.some(t=>t.enabled)?H("otlp",["@opentelemetry/api-logs","@opentelemetry/exporter-logs-otlp-http","@opentelemetry/resources","@opentelemetry/sdk-logs"],"../connectors/otlp/sender").createOTLPRegistry(e):Fo()}function Ho(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};t.data!==void 0&&(r.data=t.data);let o=typeof t.page?.pathname=="string"?t.page.pathname:void 0,n=typeof t.page?.url=="string"?t.page.url:void 0;return (o||n)&&(r.page=o??n),t.metadata!==void 0&&(r.metadata=t.metadata),Object.keys(r).length>0?r:null}function Wo(e){if(!e||typeof e!="object"||Array.isArray(e))return {hidden:false,value:e};let t=e;if(t.type==="http_request"||t.type==="http_error")return {hidden:true};if(t.type==="client_log"){let r=Ho(e);return r?{hidden:false,value:r}:{hidden:true}}return {hidden:false,value:e}}function Qo(e){if(e.pretty){let r=Et()({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,n)=>{let i=String(o[n]??""),a=typeof o.caller=="string"?o.caller.trim():"";return a?`${i} ${Po}${a}${Ao}`:i}});return rr__default.default({level:e.level,customLevels:nr},r)}return rr__default.default({level:e.level,customLevels:nr})}function D(e){let t=e[rt];if(!t)throw new Error("Unsupported Blyp logger instance");return t}function nt(e){return D(e).posthog}function ot(e){return D(e).betterstack}function it(e){return D(e).databuddy}function lr(e){try{return nt(e)}catch{return null}}function dr(e){try{return ot(e)}catch{return null}}function gr(e){try{return it(e)}catch{return null}}function pr(e){return D(e).sentry}function fr(e){return D(e).otlp}function Re(e){try{return D(e).redact}catch{return V().redact}}function mr(e,t){let r=D(t);return Object.defineProperty(e,rt,{value:r,enumerable:false,configurable:false,writable:false}),e}function yr(e,t){let r=D(e);return r.create(t,r.bindings)}function at(e,t,r={}){let o=D(e);return tr(t,{initialFields:r.initialFields,resolveDefaultFields:()=>({...o.bindings,...r.resolveDefaultFields?.()??{}}),write:(n,i)=>{o.writeStructured(n,i,"structured-flush");},onCreate:r.onCreate,onEmit:r.onEmit,redact:r.redact??o.redact})}function ir(e,t){if(!ee(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function ar(e,t){if(!ee(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function sr(e,t){if(!ee(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function cr(e,t){if(!ee(t)){if(!e.shouldAutoForwardServerLogs()){e.enabled&&!e.ready&&e.send(t,{source:"server",warnIfUnavailable:true});return}e.send(t,{source:"server",warnIfUnavailable:true});}}function ur(e,t){if(!ee(t))for(let r of e.getAutoForwardTargets())r.send(t,{source:"server",warnIfUnavailable:true});}function tt(e,t,r,o,n,i,a,s,l,u={},c="root"){let p=Object.keys(u).length>0?e.child(u):e,m=(f,g,y,L=c)=>{if(L==="root"&&me())return;let h=It(f,g,y,u,l),Q=h.message,J={caller:h.caller},re=Wo(h.data);!re.hidden&&re.value!==void 0&&(J.data=re.value);let lt=or[f],Se=p;(Se[lt]??Se.info??((ri,ni)=>{})).call(p,J,Q),t.write(h),ar(o,h),sr(n,h),ir(i,h),cr(a,h),ur(s,h);},R=(f,g,y="structured-flush")=>{let L=Nt(f.level),h=Ot(L,g,f,u,l),Q=or[L],J=p;(J[Q]??J.info??((lt,Se)=>{})).call(p,{caller:h.caller,...h},h.message),(y!=="root"||!me())&&t.write(h),ar(o,h),sr(n,h),ir(i,h),cr(a,h),ur(s,h);},w={success:(f,...g)=>{m("success",f,g);},critical:(f,...g)=>{m("critical",f,g);},warning:(f,...g)=>{m("warning",f,g);},info:(f,...g)=>{m("info",f,g);},debug:(f,...g)=>{m("debug",f,g);},error:(f,...g)=>{m("error",f,g);},warn:(f,...g)=>{m("warn",f,g);},table:(f,g)=>{g&&typeof g=="object"&&Yt.env.get("NODE_ENV")!=="production"&&(console.log("TABLE:",f),console.table(b(g,l))),m("table",f,g===void 0?[]:[g]);},flush:async()=>{await t.flush(),r&&await r.flush(),await Promise.allSettled([o.flush(),n.flush(),i.flush(),a.flush(),s.flush()]);},shutdown:async()=>{await t.shutdown(),r&&await r.shutdown(),await Promise.allSettled([o.flush(),n.flush(),i.flush(),a.flush(),s.flush()]);},createStructuredLog:(f,g)=>at(w,f,{initialFields:g}),child:f=>{let g={...u,...f};return tt(e,t,r,o,n,i,a,s,l,g,c)},[rt]:{bindings:u,betterstack:o,databuddy:n,posthog:i,sentry:a,otlp:s,redact:l,sink:t,create:(f,g=u)=>tt(e,t,r,o,n,i,a,s,l,g,f),writeStructured:(f,g,y="structured-flush")=>{R(f,g,y);}}};return w}var et=null;function st(e){if(e===void 0&&et)return et;let t=V(e),r=Qo(t),o=Ut(t),n=zo(t),i=qo(t),a=jo(t),s=$o(t),l=Uo(t),u=t.connectors.delivery.enabled?new Ce(t.connectors.delivery):null;if(u){u.bindTarget(n),u.bindTarget(i),u.bindTarget(a),u.bindTarget(s);for(let p of l.getAutoForwardTargets())u.bindTarget(p);}let c=tt(r,o,u,n,i,a,s,l,t.redact);return e===void 0&&(et=c),c}st();function hr(e,t,r,o){let n=ne(e),i=oe(t),a=ie(o);return `${n} ${r} ${i} ${a}`}function Jo(e,t){let r=Be(t?.path??N),o=t?.enabled===false?null:{path:r};return e===false?null:e===void 0?o:e===true?{path:r}:{...o,...e,path:Be(e.path??r)}}function br(e={},t){let r=V({...e.level!==void 0?{level:e.level}:{},...e.pretty!==void 0?{pretty:e.pretty}:{},...e.destination!==void 0?{destination:e.destination}:{},...e.logDir!==void 0?{logDir:e.logDir}:{},...e.file!==void 0?{file:e.file}:{},...e.database!==void 0?{database:e.database}:{},...e.redact!==void 0?{redact:e.redact}:{},...e.connectors!==void 0?{connectors:e.connectors}:{}}),{level:o=r.level,pretty:n=r.pretty,destination:i=r.destination,logDir:a=r.logDir,file:s=r.file,database:l=r.database,autoLogging:u=true,customProps:c,logErrors:p=true,includePaths:m,ignorePaths:R,clientLogging:w,connectors:f}=e,g=st({level:o,pretty:n,destination:i,logDir:a,file:s,database:l,connectors:f}),y=Jo(w,r.clientLogging),L=y?.path??N,h=m,Q=y?Array.from(new Set([...R??[],L])):R;return {logger:g,betterstack:ot(g),databuddy:it(g),posthog:nt(g),sentry:pr(g),otlp:fr(g),resolvedConfig:r,level:o,pretty:n,logDir:a,file:s,autoLogging:u,customProps:c,logErrors:p,resolvedIncludePaths:h,resolvedIgnorePaths:Q,resolvedClientLogging:y,ingestionPath:L}}function Go(e,t){return !t||t.length===0?true:Me(e,t)}function Cr(e,t,r){return Go(e,t)?Me(e,r):true}function wr(e,t,r){return e.autoLogging===false||typeof e.autoLogging=="object"&&e.autoLogging.ignore?.(t)?true:Cr(r,e.resolvedIncludePaths,e.resolvedIgnorePaths)}function Rr(e,t){return e.logErrors?Cr(t,e.resolvedIncludePaths,e.resolvedIgnorePaths):true}function Le(e,t){return e.customProps?e.customProps(t):{}}function Lr(e,t,r,o,n,i,a={}){let s=ue(r,"http_request",o,n,i,a,Re(e));return t==="info"?e.info(le(r.method,n,o,i),s):(e.info(hr(r.method,n,o,i),s),Object.keys(a).length>0&&e.debug("Request context",a)),s}function Sr(e,t,r,o,n,i,a,s={},l={}){let u=ue(r,"http_error",o,n,i,{error:a?.message??`HTTP ${n}`,stack:a?.stack,code:a?.code,why:a?.why,fix:a?.fix,link:a?.link,details:a?.details,...s},Re(e)),c=t==="info"?le(r.method,n,o,i):hr(r.method,n,o,i);e.error(c,u);let p=lr(e);p?.shouldAutoCaptureExceptions()&&p.captureException(l.error??a??c,{source:"server",warnIfUnavailable:true,distinctId:l.distinctId??C(r.headers,"x-posthog-distinct-id"),properties:Ue({timestamp:new Date().toISOString(),level:"error",message:c,data:u},"server",{$request_method:r.method,$request_path:o,$current_url:r.url,$response_status_code:n,...C(r.headers,"user-agent")?{$user_agent:C(r.headers,"user-agent")}:{},...u.ip?{$ip:u.ip}:{}})});let m=dr(e);m?.shouldAutoCaptureExceptions()&&m.captureException(l.error??a??c,{source:"server",warnIfUnavailable:true,context:{timestamp:new Date().toISOString(),level:"error",message:c,status:n,path:o,data:u}});let R=gr(e);return R?.shouldAutoCaptureExceptions()&&R.captureException(l.error??a??c,{source:"server",warnIfUnavailable:true,properties:{method:r.method,path:o,status_code:n,...r.url?{current_url:r.url}:{},...C(r.headers,"user-agent")?{user_agent:C(r.headers,"user-agent")}:{},...u.ip?{ip:u.ip}:{},payload:u}}),u}async function Ko(e,t){if(t!==void 0)return typeof t=="string"?JSON.parse(t):t;if(typeof e.json=="function")return await e.json();throw new Error("Unable to parse client log payload")}function Vo(e,t){switch(t){case "debug":return e.debug;case "info":return e.info;case "warning":return e.warning;case "error":return e.error;case "critical":return e.critical;case "success":return e.success}}async function vr(e){let{config:t,ctx:r,request:o,body:n,deliveryPath:i}=e;if(!t.resolvedClientLogging)return {status:404};let a;try{a=await Ko(o,n);}catch{return {status:400}}if(!mt(a))return {status:400};if(!(t.resolvedClientLogging.validate?await t.resolvedClientLogging.validate(r,a):true))return {status:403};let l=t.resolvedClientLogging.enrich?await t.resolvedClientLogging.enrich(r,a):void 0,u=Re(t.logger),c=b(a,u),p=b({...c,receivedAt:new Date().toISOString(),delivery:De(o,i??I(o.url),u)},u);l!==void 0&&(p.serverContext=b(l,u));let m=B(`[client] ${c.message}`,u),R=A(),w=typeof c.traceId=="string"&&c.traceId.length>0?c.traceId:R;try{w&&X(w),c.level==="table"?t.logger.table(m,p):Vo(t.logger,c.level)(m,p);}finally{X(R);}let f={};if(c.connector==="betterstack"){if(f["x-blyp-betterstack-status"]=t.betterstack.ready?"enabled":"missing",t.betterstack.ready){let g={timestamp:p.receivedAt,level:c.level,message:m,data:p};if(t.betterstack.send(g,{source:"client"}),(c.level==="error"||c.level==="critical")&&t.betterstack.shouldAutoCaptureExceptions()){let y=c.data&&typeof c.data=="object"&&!Array.isArray(c.data)&&typeof c.data.message=="string"?c.data:c.message;t.betterstack.captureException(y,{source:"client",warnIfUnavailable:true,context:{sessionId:c.session.sessionId,pageUrl:c.page.url,pagePath:c.page.pathname,metadata:c.metadata,payload:p}});}}}else if(c.connector==="databuddy"){if(f["x-blyp-databuddy-status"]=t.databuddy.ready?"enabled":"missing",t.databuddy.ready){let g={timestamp:p.receivedAt,level:c.level,message:m,data:p};if(t.databuddy.send(g,{source:"client"}),(c.level==="error"||c.level==="critical")&&t.databuddy.shouldAutoCaptureExceptions()){let y=c.data&&typeof c.data=="object"&&!Array.isArray(c.data)&&typeof c.data.message=="string"?c.data:c.message;t.databuddy.captureException(y,{source:"client",warnIfUnavailable:true,sessionId:c.session.sessionId,properties:{page_url:c.page.url,page_path:c.page.pathname,client_runtime:c.device?.runtime,metadata:c.metadata,payload:p}});}}}else if(c.connector==="posthog"){if(f["x-blyp-posthog-status"]=t.posthog.ready?"enabled":"missing",t.posthog.ready){let g={timestamp:p.receivedAt,level:c.level,message:m,data:p};if(t.posthog.send(g,{source:"client"}),(c.level==="error"||c.level==="critical")&&t.posthog.shouldAutoCaptureExceptions()){let y=p.metadata,L=y&&typeof y=="object"&&!Array.isArray(y)&&typeof y.posthogDistinctId=="string"&&y.posthogDistinctId?String(y.posthogDistinctId):void 0,h=c.data&&typeof c.data=="object"&&!Array.isArray(c.data)&&typeof c.data.message=="string"?c.data:c.message;t.posthog.captureException(h,{source:"client",warnIfUnavailable:true,distinctId:L,properties:Ue(g,"client",{$session_id:c.session.sessionId,$current_url:c.page.url,$request_path:c.page.pathname,"client.runtime":c.device?.runtime,"client.metadata":c.metadata})});}}}else if(c.connector==="sentry")f["x-blyp-sentry-status"]=t.sentry.ready?"enabled":"missing",t.sentry.ready&&t.sentry.send({timestamp:p.receivedAt,level:c.level,message:m,data:p},{source:"client"});else if(c.connector?.type==="otlp"){let g=t.otlp.get(c.connector.name);f["x-blyp-otlp-status"]=g.ready?"enabled":"missing",g.ready&&g.send({timestamp:p.receivedAt,level:c.level,message:m,data:p},{source:"client"});}return Object.keys(f).length>0?{status:204,headers:f}:{status:204}}function Xo(e){return e.resolvedConfig.destination==="database"}async function te(e){if(Xo(e))try{await e.logger.flush();}catch(t){console.warn("[Blyp] Warning: Failed to flush database logs.",t);}}function ct(e,t={}){let r=yr(e,"request-scoped"),o=mr({...r,createStructuredLog:(n,i)=>at(o,n,{initialFields:i,resolveDefaultFields:()=>{let a=A();return {...t.resolveStructuredFields?.()??{},...a?{traceId:a}:{}}},onCreate:()=>{Je();},onEmit:()=>{Ge(),t.onStructuredEmit?.();}}),child(n){return ct(r.child(n),t)}},r);return Qe(o),o}var Yo="x-blyp-trace-id",Zo="trace_";function Tr(){return `${Zo}${de().replace(/[^a-z0-9]/gi,"").toLowerCase().slice(0,12)}`}function xr(e){X(e);}function ut(e,t){let r=new Headers(e.headers);return r.set(Yo,t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}function Dr(e={}){let t=br(e);return async(r,o)=>We(async()=>{let n=performance.now(),i=Tr(),a=false;xr(i),r.set("blypLog",ct(t.logger,{resolveStructuredFields:()=>({method:r.req.method,path:r.req.path||I(r.req.url),...Le(t,r)}),onStructuredEmit:()=>{a=true;}})),r.set("blypTraceId",i),r.set("blypStartTime",n);let s=r.req.path||I(r.req.url);if(t.resolvedClientLogging&&r.req.method==="POST"&&s===t.ingestionPath){let u=await vr({config:t,ctx:r,request:r.req.raw,deliveryPath:t.ingestionPath});return await te(t),new Response(null,{status:u.status,headers:{...u.headers,"x-blyp-trace-id":i}})}let l;try{await o();}catch(u){throw l=u,u}finally{if(a){await te(t),r.res=ut(r.res,i);return}let u=Math.round(performance.now()-n),c=xe(r.req.method,r.req.url,r.req.raw.headers),p=r.res?.status??(l?500:200);if(l||ke(p)){Rr(t,s)||Sr(t.logger,t.level,c,s,p,u,Ee(l,p),Le(t,r),{error:l}),await te(t);return}wr(t,r,s)||Lr(t.logger,t.level,c,s,p,u,Le(t,r)),await te(t),r.res=ut(r.res,i);}})}var ei=Dr;
701
+ exports.createHonoLogger=Dr;exports.createLogger=ei;