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