evlog 2.15.0 → 2.17.0

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 (169) hide show
  1. package/README.md +7 -7
  2. package/dist/adapters/axiom.d.mts +1 -1
  3. package/dist/adapters/axiom.mjs +4 -2
  4. package/dist/adapters/axiom.mjs.map +1 -1
  5. package/dist/adapters/better-stack.d.mts +1 -1
  6. package/dist/adapters/better-stack.mjs +4 -2
  7. package/dist/adapters/better-stack.mjs.map +1 -1
  8. package/dist/adapters/datadog.d.mts +1 -1
  9. package/dist/adapters/datadog.mjs +4 -2
  10. package/dist/adapters/datadog.mjs.map +1 -1
  11. package/dist/adapters/fs.d.mts +64 -2
  12. package/dist/adapters/fs.d.mts.map +1 -1
  13. package/dist/adapters/fs.mjs +222 -3
  14. package/dist/adapters/fs.mjs.map +1 -1
  15. package/dist/adapters/hyperdx.d.mts +1 -1
  16. package/dist/adapters/hyperdx.mjs +1 -1
  17. package/dist/adapters/otlp.d.mts +1 -1
  18. package/dist/adapters/otlp.mjs +6 -4
  19. package/dist/adapters/otlp.mjs.map +1 -1
  20. package/dist/adapters/posthog.d.mts +1 -1
  21. package/dist/adapters/posthog.mjs +4 -2
  22. package/dist/adapters/posthog.mjs.map +1 -1
  23. package/dist/adapters/sentry.d.mts +1 -1
  24. package/dist/adapters/sentry.mjs +5 -3
  25. package/dist/adapters/sentry.mjs.map +1 -1
  26. package/dist/ai/index.d.mts +15 -1
  27. package/dist/ai/index.d.mts.map +1 -1
  28. package/dist/ai/index.mjs +48 -16
  29. package/dist/ai/index.mjs.map +1 -1
  30. package/dist/{audit-CJl-wZ10.d.mts → audit-CC8nfazi.d.mts} +65 -3
  31. package/dist/{audit-CJl-wZ10.d.mts.map → audit-CC8nfazi.d.mts.map} +1 -1
  32. package/dist/{audit--n0QRR2Y.mjs → audit-pV5aLGP0.mjs} +2 -1
  33. package/dist/audit-pV5aLGP0.mjs.map +1 -0
  34. package/dist/better-auth/index.d.mts +14 -7
  35. package/dist/better-auth/index.d.mts.map +1 -1
  36. package/dist/better-auth/index.mjs +11 -1
  37. package/dist/better-auth/index.mjs.map +1 -1
  38. package/dist/browser.d.mts +1 -1
  39. package/dist/{define-Fp8TrdEB.d.mts → define-MSdhzmXn.d.mts} +3 -3
  40. package/dist/{define-Fp8TrdEB.d.mts.map → define-MSdhzmXn.d.mts.map} +1 -1
  41. package/dist/{dist-BIlS38vi.mjs → dist-H3GIh-KK.mjs} +1 -1
  42. package/dist/{dist-BIlS38vi.mjs.map → dist-H3GIh-KK.mjs.map} +1 -1
  43. package/dist/{drain-ByWUeOQC.mjs → drain-X7_5szSI.mjs} +6 -49
  44. package/dist/drain-X7_5szSI.mjs.map +1 -0
  45. package/dist/elysia/index.d.mts +2 -2
  46. package/dist/elysia/index.mjs +2 -2
  47. package/dist/{enricher-CLSnrzrr.d.mts → enricher-DxgML6IC.d.mts} +4 -4
  48. package/dist/{enricher-CLSnrzrr.d.mts.map → enricher-DxgML6IC.d.mts.map} +1 -1
  49. package/dist/{enricher-BA6viylF.mjs → enricher-N0erZS87.mjs} +2 -2
  50. package/dist/{enricher-BA6viylF.mjs.map → enricher-N0erZS87.mjs.map} +1 -1
  51. package/dist/enrichers.d.mts +2 -2
  52. package/dist/enrichers.mjs +1 -1
  53. package/dist/{error-C-66_G2M.d.mts → error-CpbbtyXL.d.mts} +7 -2
  54. package/dist/error-CpbbtyXL.d.mts.map +1 -0
  55. package/dist/error.d.mts +1 -1
  56. package/dist/error.mjs +8 -1
  57. package/dist/error.mjs.map +1 -1
  58. package/dist/{errors-DQoYsDW1.d.mts → errors-DySW1F9_.d.mts} +2 -2
  59. package/dist/{errors-DQoYsDW1.d.mts.map → errors-DySW1F9_.d.mts.map} +1 -1
  60. package/dist/{event-ef-5Dbxg.mjs → event-1BMl7o0k.mjs} +4 -2
  61. package/dist/event-1BMl7o0k.mjs.map +1 -0
  62. package/dist/express/index.d.mts +2 -2
  63. package/dist/express/index.d.mts.map +1 -1
  64. package/dist/express/index.mjs +5 -6
  65. package/dist/express/index.mjs.map +1 -1
  66. package/dist/fastify/index.d.mts +2 -2
  67. package/dist/fastify/index.mjs +2 -2
  68. package/dist/{fork-D44V93-K.mjs → fork-8u_zFOJq.mjs} +3 -3
  69. package/dist/{fork-D44V93-K.mjs.map → fork-8u_zFOJq.mjs.map} +1 -1
  70. package/dist/hono/index.d.mts +2 -2
  71. package/dist/hono/index.mjs +1 -1
  72. package/dist/http-6umVAKDW.mjs +82 -0
  73. package/dist/http-6umVAKDW.mjs.map +1 -0
  74. package/dist/http.d.mts +1 -1
  75. package/dist/http.mjs +1 -0
  76. package/dist/http.mjs.map +1 -1
  77. package/dist/index-o1_z4phv.d.mts +213 -0
  78. package/dist/index-o1_z4phv.d.mts.map +1 -0
  79. package/dist/index.d.mts +9 -8
  80. package/dist/index.mjs +210 -2
  81. package/dist/index.mjs.map +1 -0
  82. package/dist/{integration-Bz8X6_Lb.mjs → integration-DTZtjSqh.mjs} +2 -2
  83. package/dist/{integration-Bz8X6_Lb.mjs.map → integration-DTZtjSqh.mjs.map} +1 -1
  84. package/dist/{logger-Brt5-WMK.d.mts → logger-DntcxxHg.d.mts} +2 -2
  85. package/dist/{logger-Brt5-WMK.d.mts.map → logger-DntcxxHg.d.mts.map} +1 -1
  86. package/dist/logger.d.mts +1 -1
  87. package/dist/logger.mjs +1 -1
  88. package/dist/{middleware-CGM-bOvE.d.mts → middleware-U-lIAzHg.d.mts} +2 -2
  89. package/dist/{middleware-CGM-bOvE.d.mts.map → middleware-U-lIAzHg.d.mts.map} +1 -1
  90. package/dist/nestjs/index.d.mts +2 -2
  91. package/dist/nestjs/index.d.mts.map +1 -1
  92. package/dist/nestjs/index.mjs +4 -5
  93. package/dist/nestjs/index.mjs.map +1 -1
  94. package/dist/next/client.d.mts +1 -1
  95. package/dist/next/index.d.mts +4 -4
  96. package/dist/next/index.mjs +3 -3
  97. package/dist/next/instrumentation.d.mts +1 -1
  98. package/dist/next/instrumentation.mjs +1 -1
  99. package/dist/next/stream.d.mts +29 -0
  100. package/dist/next/stream.d.mts.map +1 -0
  101. package/dist/next/stream.mjs +78 -0
  102. package/dist/next/stream.mjs.map +1 -0
  103. package/dist/nitro/errorHandler.mjs +1 -1
  104. package/dist/nitro/module.d.mts +2 -2
  105. package/dist/nitro/plugin.mjs +12 -3
  106. package/dist/nitro/plugin.mjs.map +1 -1
  107. package/dist/nitro/v3/errorHandler.mjs +2 -2
  108. package/dist/nitro/v3/index.d.mts +2 -2
  109. package/dist/nitro/v3/module.d.mts +1 -1
  110. package/dist/nitro/v3/plugin.mjs +4 -4
  111. package/dist/nitro/v3/useLogger.d.mts +1 -1
  112. package/dist/{nitro-DavLelNz.mjs → nitro-DErMq_Zj.mjs} +1 -1
  113. package/dist/{nitro-DavLelNz.mjs.map → nitro-DErMq_Zj.mjs.map} +1 -1
  114. package/dist/{nitro-DHPb9dXG.d.mts → nitro-oZre8ab3.d.mts} +2 -2
  115. package/dist/{nitro-DHPb9dXG.d.mts.map → nitro-oZre8ab3.d.mts.map} +1 -1
  116. package/dist/{nitroConfigBridge-aZ1e5upQ.mjs → nitroConfigBridge-DKk7eOn-.mjs} +1 -1
  117. package/dist/{nitroConfigBridge-aZ1e5upQ.mjs.map → nitroConfigBridge-DKk7eOn-.mjs.map} +1 -1
  118. package/dist/nodeResponse-BkkionWl.mjs +42 -0
  119. package/dist/nodeResponse-BkkionWl.mjs.map +1 -0
  120. package/dist/nuxt/module.d.mts +28 -1
  121. package/dist/nuxt/module.d.mts.map +1 -1
  122. package/dist/nuxt/module.mjs +11 -4
  123. package/dist/nuxt/module.mjs.map +1 -1
  124. package/dist/package-v_MmOZeA.mjs +7 -0
  125. package/dist/package-v_MmOZeA.mjs.map +1 -0
  126. package/dist/{parseError-B1zJZvQ5.d.mts → parseError-yVZ58wIK.d.mts} +2 -2
  127. package/dist/parseError-yVZ58wIK.d.mts.map +1 -0
  128. package/dist/react-router/index.d.mts +2 -2
  129. package/dist/react-router/index.mjs +2 -2
  130. package/dist/{routes-B48wm7Pb.mjs → routes-CnIgYWf8.mjs} +1 -1
  131. package/dist/{routes-B48wm7Pb.mjs.map → routes-CnIgYWf8.mjs.map} +1 -1
  132. package/dist/runtime/client/log.d.mts +1 -1
  133. package/dist/runtime/server/routes/_evlog/ingest.post.mjs +1 -1
  134. package/dist/runtime/server/routes/_evlog/stream-info.get.d.mts +18 -0
  135. package/dist/runtime/server/routes/_evlog/stream-info.get.d.mts.map +1 -0
  136. package/dist/runtime/server/routes/_evlog/stream-info.get.mjs +28 -0
  137. package/dist/runtime/server/routes/_evlog/stream-info.get.mjs.map +1 -0
  138. package/dist/runtime/server/useLogger.d.mts +1 -1
  139. package/dist/runtime/utils/parseError.d.mts +2 -2
  140. package/dist/runtime/utils/parseError.mjs +8 -0
  141. package/dist/runtime/utils/parseError.mjs.map +1 -1
  142. package/dist/{severity-BYWZ96Sb.mjs → severity-R5Egq3qz.mjs} +1 -1
  143. package/dist/{severity-BYWZ96Sb.mjs.map → severity-R5Egq3qz.mjs.map} +1 -1
  144. package/dist/{storage-BT-3fT1-.mjs → storage-Dwinmg8P.mjs} +1 -1
  145. package/dist/{storage-BT-3fT1-.mjs.map → storage-Dwinmg8P.mjs.map} +1 -1
  146. package/dist/stream.d.mts +185 -0
  147. package/dist/stream.d.mts.map +1 -0
  148. package/dist/stream.mjs +374 -0
  149. package/dist/stream.mjs.map +1 -0
  150. package/dist/sveltekit/index.d.mts +2 -2
  151. package/dist/sveltekit/index.mjs +3 -3
  152. package/dist/toolkit.d.mts +43 -8
  153. package/dist/toolkit.d.mts.map +1 -1
  154. package/dist/toolkit.mjs +11 -10
  155. package/dist/types.d.mts +2 -2
  156. package/dist/{useLogger-Cb1R6bQE.d.mts → useLogger-BsPL4AQm.d.mts} +2 -2
  157. package/dist/{useLogger-Cb1R6bQE.d.mts.map → useLogger-BsPL4AQm.d.mts.map} +1 -1
  158. package/dist/{utils-gQCeZMbg.d.mts → utils-DLCeShxL.d.mts} +2 -2
  159. package/dist/{utils-gQCeZMbg.d.mts.map → utils-DLCeShxL.d.mts.map} +1 -1
  160. package/dist/utils.d.mts +1 -1
  161. package/dist/vite/index.d.mts +1 -1
  162. package/dist/workers.d.mts +1 -1
  163. package/dist/workers.mjs +1 -1
  164. package/package.json +17 -1
  165. package/dist/audit--n0QRR2Y.mjs.map +0 -1
  166. package/dist/drain-ByWUeOQC.mjs.map +0 -1
  167. package/dist/error-C-66_G2M.d.mts.map +0 -1
  168. package/dist/event-ef-5Dbxg.mjs.map +0 -1
  169. package/dist/parseError-B1zJZvQ5.d.mts.map +0 -1
@@ -0,0 +1,82 @@
1
+ import { n as version } from "./package-v_MmOZeA.mjs";
2
+ //#region src/shared/http.ts
3
+ /**
4
+ * Minimal HTTP transport for drain adapters: abort-based timeouts, exponential
5
+ * backoff on `5xx` / network errors, response bodies truncated in error messages.
6
+ *
7
+ * Identifies every outgoing request as coming from evlog via:
8
+ * - `User-Agent: evlog/<version>` (Node / server runtimes only — browsers strip this)
9
+ * - `X-Evlog-Source: <source>` when {@link HttpPostOptions.source} is set
10
+ */
11
+ /** Build-time evlog package version, e.g. `2.16.0`. */
12
+ const EVLOG_VERSION = version;
13
+ /** Default `User-Agent` value injected into outgoing drain requests. */
14
+ const EVLOG_USER_AGENT = `evlog/${EVLOG_VERSION}`;
15
+ function hasHeader(headers, target) {
16
+ const lower = target.toLowerCase();
17
+ for (const key of Object.keys(headers)) if (key.toLowerCase() === lower) return true;
18
+ return false;
19
+ }
20
+ /**
21
+ * Returns a copy of `headers` with evlog identity headers injected when
22
+ * absent. Caller-provided values always win.
23
+ *
24
+ * @internal Exposed for tests. Use {@link httpPost} from drains.
25
+ */
26
+ function withEvlogIdentityHeaders(headers, { userAgent, source } = {}) {
27
+ const out = { ...headers };
28
+ if (userAgent !== false && !hasHeader(out, "user-agent")) out["User-Agent"] = typeof userAgent === "string" && userAgent.length > 0 ? userAgent : EVLOG_USER_AGENT;
29
+ if (source && !hasHeader(out, "x-evlog-source")) out["X-Evlog-Source"] = source;
30
+ return out;
31
+ }
32
+ function isRetryable(error) {
33
+ if (error instanceof DOMException && error.name === "AbortError") return true;
34
+ if (error instanceof TypeError) return true;
35
+ if (error instanceof Error) {
36
+ const match = error.message.match(/API error: (\d+)/);
37
+ if (match) return Number.parseInt(match[1]) >= 500;
38
+ }
39
+ return false;
40
+ }
41
+ /**
42
+ * POST a body with timeout + retry. Throws label-prefixed errors with a
43
+ * truncated response body. Safe to call from any drain `send()`.
44
+ */
45
+ async function httpPost({ url, headers, body, timeout, label, retries = 2, userAgent, source }) {
46
+ const normalizedRetries = Number.isFinite(retries) && retries >= 0 ? Math.floor(retries) : 2;
47
+ const finalHeaders = withEvlogIdentityHeaders(headers, {
48
+ userAgent,
49
+ source
50
+ });
51
+ let lastError;
52
+ for (let attempt = 0; attempt <= normalizedRetries; attempt++) {
53
+ const controller = new AbortController();
54
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
55
+ try {
56
+ const response = await fetch(url, {
57
+ method: "POST",
58
+ headers: finalHeaders,
59
+ body,
60
+ signal: controller.signal
61
+ });
62
+ if (!response.ok) {
63
+ const text = await response.text().catch(() => "Unknown error");
64
+ const safeText = text.length > 200 ? `${text.slice(0, 200)}...[truncated]` : text;
65
+ throw new Error(`${label} API error: ${response.status} ${response.statusText} - ${safeText}`);
66
+ }
67
+ clearTimeout(timeoutId);
68
+ return;
69
+ } catch (error) {
70
+ clearTimeout(timeoutId);
71
+ if (error instanceof DOMException && error.name === "AbortError") lastError = /* @__PURE__ */ new Error(`${label} request timed out after ${timeout}ms`);
72
+ else lastError = error;
73
+ if (!isRetryable(error) || attempt === normalizedRetries) throw lastError;
74
+ await new Promise((r) => setTimeout(r, 200 * 2 ** attempt));
75
+ }
76
+ }
77
+ throw lastError;
78
+ }
79
+ //#endregion
80
+ export { withEvlogIdentityHeaders as i, EVLOG_VERSION as n, httpPost as r, EVLOG_USER_AGENT as t };
81
+
82
+ //# sourceMappingURL=http-6umVAKDW.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-6umVAKDW.mjs","names":["PKG_VERSION"],"sources":["../src/shared/http.ts"],"sourcesContent":["/**\n * Minimal HTTP transport for drain adapters: abort-based timeouts, exponential\n * backoff on `5xx` / network errors, response bodies truncated in error messages.\n *\n * Identifies every outgoing request as coming from evlog via:\n * - `User-Agent: evlog/<version>` (Node / server runtimes only — browsers strip this)\n * - `X-Evlog-Source: <source>` when {@link HttpPostOptions.source} is set\n */\n\nimport { version as PKG_VERSION } from '../../package.json'\n\n/** Build-time evlog package version, e.g. `2.16.0`. */\nexport const EVLOG_VERSION: string = PKG_VERSION\n\n/** Default `User-Agent` value injected into outgoing drain requests. */\nexport const EVLOG_USER_AGENT = `evlog/${EVLOG_VERSION}`\n\nexport interface HttpPostOptions {\n url: string\n /** Caller is responsible for `Content-Type`. */\n headers: Record<string, string>\n /** Pre-serialized request body. */\n body: string\n /** Abort the request after this many milliseconds. */\n timeout: number\n /** Prefix used in error messages. */\n label: string\n /**\n * Retries network errors, aborts, and `5xx` responses with exponential backoff.\n * @default 2\n */\n retries?: number\n /**\n * Override the default `User-Agent: evlog/<version>` header. Pass `false` or\n * an empty string to suppress it entirely (e.g. when the underlying transport\n * forbids overriding `User-Agent`).\n */\n userAgent?: string | false\n /**\n * When set, sends `X-Evlog-Source: <source>` so the receiving system can\n * distinguish evlog traffic from other clients. Typically the adapter name\n * (`axiom`, `datadog`, ...) or `client` for browser-originated drains.\n */\n source?: string\n}\n\nfunction hasHeader(headers: Record<string, string>, target: string): boolean {\n const lower = target.toLowerCase()\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === lower) return true\n }\n return false\n}\n\n/**\n * Returns a copy of `headers` with evlog identity headers injected when\n * absent. Caller-provided values always win.\n *\n * @internal Exposed for tests. Use {@link httpPost} from drains.\n */\nexport function withEvlogIdentityHeaders(\n headers: Record<string, string>,\n { userAgent, source }: { userAgent?: string | false; source?: string } = {},\n): Record<string, string> {\n const out = { ...headers }\n if (userAgent !== false && !hasHeader(out, 'user-agent')) {\n const ua = typeof userAgent === 'string' && userAgent.length > 0 ? userAgent : EVLOG_USER_AGENT\n out['User-Agent'] = ua\n }\n if (source && !hasHeader(out, 'x-evlog-source')) {\n out['X-Evlog-Source'] = source\n }\n return out\n}\n\nfunction isRetryable(error: unknown): boolean {\n if (error instanceof DOMException && error.name === 'AbortError') return true\n if (error instanceof TypeError) return true\n if (error instanceof Error) {\n const match = error.message.match(/API error: (\\d+)/)\n if (match) return Number.parseInt(match[1]) >= 500\n }\n return false\n}\n\n/**\n * POST a body with timeout + retry. Throws label-prefixed errors with a\n * truncated response body. Safe to call from any drain `send()`.\n */\nexport async function httpPost({ url, headers, body, timeout, label, retries = 2, userAgent, source }: HttpPostOptions): Promise<void> {\n const normalizedRetries = Number.isFinite(retries) && retries >= 0 ? Math.floor(retries) : 2\n const finalHeaders = withEvlogIdentityHeaders(headers, { userAgent, source })\n\n let lastError: Error | undefined\n\n for (let attempt = 0; attempt <= normalizedRetries; attempt++) {\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: finalHeaders,\n body,\n signal: controller.signal,\n })\n\n if (!response.ok) {\n const text = await response.text().catch(() => 'Unknown error')\n const safeText = text.length > 200 ? `${text.slice(0, 200)}...[truncated]` : text\n throw new Error(`${label} API error: ${response.status} ${response.statusText} - ${safeText}`)\n }\n\n clearTimeout(timeoutId)\n return\n } catch (error) {\n clearTimeout(timeoutId)\n\n if (error instanceof DOMException && error.name === 'AbortError') {\n lastError = new Error(`${label} request timed out after ${timeout}ms`)\n } else {\n lastError = error as Error\n }\n\n if (!isRetryable(error) || attempt === normalizedRetries) {\n throw lastError\n }\n\n await new Promise<void>(r => setTimeout(r, 200 * 2 ** attempt))\n }\n }\n\n throw lastError!\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAa,gBAAwBA;;AAGrC,MAAa,mBAAmB,SAAS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ChB,MAAM,OAAO,MAAM,SAAS,MAAM,CAAC,YAAY,gBAAgB;IAC/D,MAAM,WAAW,KAAK,SAAS,MAAM,GAAG,KAAK,MAAM,GAAG,IAAI,CAAC,kBAAkB;AAC7E,UAAM,IAAI,MAAM,GAAG,MAAM,cAAc,SAAS,OAAO,GAAG,SAAS,WAAW,KAAK,WAAW;;AAGhG,gBAAa,UAAU;AACvB;WACO,OAAO;AACd,gBAAa,UAAU;AAEvB,OAAI,iBAAiB,gBAAgB,MAAM,SAAS,aAClD,6BAAY,IAAI,MAAM,GAAG,MAAM,2BAA2B,QAAQ,IAAI;OAEtE,aAAY;AAGd,OAAI,CAAC,YAAY,MAAM,IAAI,YAAY,kBACrC,OAAM;AAGR,SAAM,IAAI,SAAc,MAAK,WAAW,GAAG,MAAM,KAAK,QAAQ,CAAC;;;AAInE,OAAM"}
package/dist/http.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { F as DrainContext } from "./audit-CJl-wZ10.mjs";
1
+ import { I as DrainContext } from "./audit-CC8nfazi.mjs";
2
2
  import { DrainPipelineOptions, PipelineDrainFn } from "./pipeline.mjs";
3
3
 
4
4
  //#region src/http.d.ts
package/dist/http.mjs CHANGED
@@ -33,6 +33,7 @@ function createHttpDrain(config) {
33
33
  method: "POST",
34
34
  headers: {
35
35
  "Content-Type": "application/json",
36
+ "X-Evlog-Source": "client",
36
37
  ...customHeaders
37
38
  },
38
39
  body,
package/dist/http.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"http.mjs","names":[],"sources":["../src/http.ts"],"sourcesContent":["import type { DrainContext } from './types'\nimport type { DrainPipelineOptions, PipelineDrainFn } from './pipeline'\nimport { createDrainPipeline } from './pipeline'\nimport { isBrowser } from './utils'\n\nexport interface HttpDrainConfig {\n /** URL of the server ingest endpoint */\n endpoint: string\n /** Custom headers sent with each fetch request (e.g. Authorization, X-API-Key). Not applied to sendBeacon — see `useBeacon`. */\n headers?: Record<string, string>\n /** Request timeout in milliseconds. @default 5000 */\n timeout?: number\n /** Use sendBeacon when the page is hidden. @default true */\n useBeacon?: boolean\n /** Fetch credentials mode. @default 'same-origin' */\n credentials?: RequestCredentials\n}\n\nexport interface HttpLogDrainOptions {\n /** HTTP drain configuration (endpoint is required) */\n drain: HttpDrainConfig\n /** Pipeline configuration overrides */\n pipeline?: DrainPipelineOptions<DrainContext>\n /** Auto-register visibilitychange flush listener. @default true */\n autoFlush?: boolean\n}\n\n/**\n * Create a low-level HTTP drain transport function (fetch / sendBeacon).\n *\n * Returns a function compatible with `createDrainPipeline` that sends batches\n * to the configured endpoint via `fetch` (with `keepalive: true`) or\n * `navigator.sendBeacon` when the page is hidden.\n *\n * @example\n * ```ts\n * import { createHttpDrain } from 'evlog/http'\n * import { createDrainPipeline } from 'evlog/pipeline'\n *\n * const pipeline = createDrainPipeline({ batch: { size: 50 } })\n * const drain = pipeline(createHttpDrain({ endpoint: '/api/logs' }))\n * ```\n */\nexport function createHttpDrain(config: HttpDrainConfig): (batch: DrainContext[]) => Promise<void> {\n const { endpoint, headers: customHeaders, timeout = 5000, useBeacon = true, credentials = 'same-origin' } = config\n\n return async (batch: DrainContext[]): Promise<void> => {\n if (batch.length === 0) return\n\n const body = JSON.stringify(batch)\n\n if (\n useBeacon\n && isBrowser()\n && document.visibilityState === 'hidden'\n && typeof navigator.sendBeacon === 'function'\n ) {\n const queued = navigator.sendBeacon(endpoint, new Blob([body], { type: 'application/json' }))\n if (!queued) {\n throw new Error('[evlog/http] sendBeacon failed — payload may exceed browser limit')\n }\n return\n }\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n try {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...customHeaders },\n body,\n signal: controller.signal,\n keepalive: true,\n credentials,\n })\n\n if (!response.ok) {\n throw new Error(`[evlog/http] Server responded with ${response.status}`)\n }\n } finally {\n clearTimeout(timeoutId)\n }\n }\n}\n\n/**\n * Create a pre-composed HTTP log drain with pipeline, batching, and auto-flush.\n *\n * Returns a `PipelineDrainFn<DrainContext>` directly usable with `initLogger({ drain })`.\n *\n * @example\n * ```ts\n * import { initLogger, log } from 'evlog'\n * import { createHttpLogDrain } from 'evlog/http'\n *\n * const drain = createHttpLogDrain({\n * drain: { endpoint: '/api/logs' },\n * })\n * initLogger({ drain })\n *\n * log.info({ action: 'page_view', path: location.pathname })\n * ```\n */\nexport function createHttpLogDrain(options: HttpLogDrainOptions): PipelineDrainFn<DrainContext> & { dispose: () => void } {\n const { autoFlush = true } = options\n\n const pipeline = createDrainPipeline<DrainContext>({\n batch: { size: 25, intervalMs: 2000 },\n retry: { maxAttempts: 2 },\n ...options.pipeline,\n })\n\n const drain = pipeline(createHttpDrain(options.drain)) as PipelineDrainFn<DrainContext> & { dispose: () => void }\n\n let onVisibilityChange: (() => void) | undefined\n\n if (autoFlush && isBrowser()) {\n onVisibilityChange = () => {\n if (document.visibilityState === 'hidden') {\n drain.flush()\n }\n }\n document.addEventListener('visibilitychange', onVisibilityChange)\n }\n\n drain.dispose = () => {\n if (onVisibilityChange) {\n document.removeEventListener('visibilitychange', onVisibilityChange)\n onVisibilityChange = undefined\n }\n }\n\n return drain\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,gBAAgB,QAAmE;CACjG,MAAM,EAAE,UAAU,SAAS,eAAe,UAAU,KAAM,YAAY,MAAM,cAAc,kBAAkB;AAE5G,QAAO,OAAO,UAAyC;AACrD,MAAI,MAAM,WAAW,EAAG;EAExB,MAAM,OAAO,KAAK,UAAU,MAAM;AAElC,MACE,aACG,WAAW,IACX,SAAS,oBAAoB,YAC7B,OAAO,UAAU,eAAe,YACnC;AAEA,OAAI,CADW,UAAU,WAAW,UAAU,IAAI,KAAK,CAAC,KAAK,EAAE,EAAE,MAAM,oBAAoB,CAAC,CACjF,CACT,OAAM,IAAI,MAAM,oEAAoE;AAEtF;;EAGF,MAAM,aAAa,IAAI,iBAAiB;EACxC,MAAM,YAAY,iBAAiB,WAAW,OAAO,EAAE,QAAQ;AAE/D,MAAI;GACF,MAAM,WAAW,MAAM,MAAM,UAAU;IACrC,QAAQ;IACR,SAAS;KAAE,gBAAgB;KAAoB,GAAG;KAAe;IACjE;IACA,QAAQ,WAAW;IACnB,WAAW;IACX;IACD,CAAC;AAEF,OAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MAAM,sCAAsC,SAAS,SAAS;YAElE;AACR,gBAAa,UAAU;;;;;;;;;;;;;;;;;;;;;;AAuB7B,SAAgB,mBAAmB,SAAuF;CACxH,MAAM,EAAE,YAAY,SAAS;CAQ7B,MAAM,QANW,oBAAkC;EACjD,OAAO;GAAE,MAAM;GAAI,YAAY;GAAM;EACrC,OAAO,EAAE,aAAa,GAAG;EACzB,GAAG,QAAQ;EACZ,CAEqB,CAAC,gBAAgB,QAAQ,MAAM,CAAC;CAEtD,IAAI;AAEJ,KAAI,aAAa,WAAW,EAAE;AAC5B,6BAA2B;AACzB,OAAI,SAAS,oBAAoB,SAC/B,OAAM,OAAO;;AAGjB,WAAS,iBAAiB,oBAAoB,mBAAmB;;AAGnE,OAAM,gBAAgB;AACpB,MAAI,oBAAoB;AACtB,YAAS,oBAAoB,oBAAoB,mBAAmB;AACpE,wBAAqB,KAAA;;;AAIzB,QAAO"}
1
+ {"version":3,"file":"http.mjs","names":[],"sources":["../src/http.ts"],"sourcesContent":["import type { DrainContext } from './types'\nimport type { DrainPipelineOptions, PipelineDrainFn } from './pipeline'\nimport { createDrainPipeline } from './pipeline'\nimport { isBrowser } from './utils'\n\nexport interface HttpDrainConfig {\n /** URL of the server ingest endpoint */\n endpoint: string\n /** Custom headers sent with each fetch request (e.g. Authorization, X-API-Key). Not applied to sendBeacon — see `useBeacon`. */\n headers?: Record<string, string>\n /** Request timeout in milliseconds. @default 5000 */\n timeout?: number\n /** Use sendBeacon when the page is hidden. @default true */\n useBeacon?: boolean\n /** Fetch credentials mode. @default 'same-origin' */\n credentials?: RequestCredentials\n}\n\nexport interface HttpLogDrainOptions {\n /** HTTP drain configuration (endpoint is required) */\n drain: HttpDrainConfig\n /** Pipeline configuration overrides */\n pipeline?: DrainPipelineOptions<DrainContext>\n /** Auto-register visibilitychange flush listener. @default true */\n autoFlush?: boolean\n}\n\n/**\n * Create a low-level HTTP drain transport function (fetch / sendBeacon).\n *\n * Returns a function compatible with `createDrainPipeline` that sends batches\n * to the configured endpoint via `fetch` (with `keepalive: true`) or\n * `navigator.sendBeacon` when the page is hidden.\n *\n * @example\n * ```ts\n * import { createHttpDrain } from 'evlog/http'\n * import { createDrainPipeline } from 'evlog/pipeline'\n *\n * const pipeline = createDrainPipeline({ batch: { size: 50 } })\n * const drain = pipeline(createHttpDrain({ endpoint: '/api/logs' }))\n * ```\n */\nexport function createHttpDrain(config: HttpDrainConfig): (batch: DrainContext[]) => Promise<void> {\n const { endpoint, headers: customHeaders, timeout = 5000, useBeacon = true, credentials = 'same-origin' } = config\n\n return async (batch: DrainContext[]): Promise<void> => {\n if (batch.length === 0) return\n\n const body = JSON.stringify(batch)\n\n if (\n useBeacon\n && isBrowser()\n && document.visibilityState === 'hidden'\n && typeof navigator.sendBeacon === 'function'\n ) {\n const queued = navigator.sendBeacon(endpoint, new Blob([body], { type: 'application/json' }))\n if (!queued) {\n throw new Error('[evlog/http] sendBeacon failed — payload may exceed browser limit')\n }\n return\n }\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n try {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'X-Evlog-Source': 'client', ...customHeaders },\n body,\n signal: controller.signal,\n keepalive: true,\n credentials,\n })\n\n if (!response.ok) {\n throw new Error(`[evlog/http] Server responded with ${response.status}`)\n }\n } finally {\n clearTimeout(timeoutId)\n }\n }\n}\n\n/**\n * Create a pre-composed HTTP log drain with pipeline, batching, and auto-flush.\n *\n * Returns a `PipelineDrainFn<DrainContext>` directly usable with `initLogger({ drain })`.\n *\n * @example\n * ```ts\n * import { initLogger, log } from 'evlog'\n * import { createHttpLogDrain } from 'evlog/http'\n *\n * const drain = createHttpLogDrain({\n * drain: { endpoint: '/api/logs' },\n * })\n * initLogger({ drain })\n *\n * log.info({ action: 'page_view', path: location.pathname })\n * ```\n */\nexport function createHttpLogDrain(options: HttpLogDrainOptions): PipelineDrainFn<DrainContext> & { dispose: () => void } {\n const { autoFlush = true } = options\n\n const pipeline = createDrainPipeline<DrainContext>({\n batch: { size: 25, intervalMs: 2000 },\n retry: { maxAttempts: 2 },\n ...options.pipeline,\n })\n\n const drain = pipeline(createHttpDrain(options.drain)) as PipelineDrainFn<DrainContext> & { dispose: () => void }\n\n let onVisibilityChange: (() => void) | undefined\n\n if (autoFlush && isBrowser()) {\n onVisibilityChange = () => {\n if (document.visibilityState === 'hidden') {\n drain.flush()\n }\n }\n document.addEventListener('visibilitychange', onVisibilityChange)\n }\n\n drain.dispose = () => {\n if (onVisibilityChange) {\n document.removeEventListener('visibilitychange', onVisibilityChange)\n onVisibilityChange = undefined\n }\n }\n\n return drain\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,gBAAgB,QAAmE;CACjG,MAAM,EAAE,UAAU,SAAS,eAAe,UAAU,KAAM,YAAY,MAAM,cAAc,kBAAkB;AAE5G,QAAO,OAAO,UAAyC;AACrD,MAAI,MAAM,WAAW,EAAG;EAExB,MAAM,OAAO,KAAK,UAAU,MAAM;AAElC,MACE,aACG,WAAW,IACX,SAAS,oBAAoB,YAC7B,OAAO,UAAU,eAAe,YACnC;AAEA,OAAI,CADW,UAAU,WAAW,UAAU,IAAI,KAAK,CAAC,KAAK,EAAE,EAAE,MAAM,oBAAoB,CAAC,CACjF,CACT,OAAM,IAAI,MAAM,oEAAoE;AAEtF;;EAGF,MAAM,aAAa,IAAI,iBAAiB;EACxC,MAAM,YAAY,iBAAiB,WAAW,OAAO,EAAE,QAAQ;AAE/D,MAAI;GACF,MAAM,WAAW,MAAM,MAAM,UAAU;IACrC,QAAQ;IACR,SAAS;KAAE,gBAAgB;KAAoB,kBAAkB;KAAU,GAAG;KAAe;IAC7F;IACA,QAAQ,WAAW;IACnB,WAAW;IACX;IACD,CAAC;AAEF,OAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MAAM,sCAAsC,SAAS,SAAS;YAElE;AACR,gBAAa,UAAU;;;;;;;;;;;;;;;;;;;;;;AAuB7B,SAAgB,mBAAmB,SAAuF;CACxH,MAAM,EAAE,YAAY,SAAS;CAQ7B,MAAM,QANW,oBAAkC;EACjD,OAAO;GAAE,MAAM;GAAI,YAAY;GAAM;EACrC,OAAO,EAAE,aAAa,GAAG;EACzB,GAAG,QAAQ;EACZ,CAEqB,CAAC,gBAAgB,QAAQ,MAAM,CAAC;CAEtD,IAAI;AAEJ,KAAI,aAAa,WAAW,EAAE;AAC5B,6BAA2B;AACzB,OAAI,SAAS,oBAAoB,SAC/B,OAAM,OAAO;;AAGjB,WAAS,iBAAiB,oBAAoB,mBAAmB;;AAGnE,OAAM,gBAAgB;AACpB,MAAI,oBAAoB;AACtB,YAAS,oBAAoB,oBAAoB,mBAAmB;AACpE,wBAAqB,KAAA;;;AAIzB,QAAO"}
@@ -0,0 +1,213 @@
1
+ import { N as AuditTarget, a as AuditInput } from "./audit-CC8nfazi.mjs";
2
+ import { t as EvlogError } from "./error-CpbbtyXL.mjs";
3
+ //#region src/catalog.d.ts
4
+ /**
5
+ * Static metadata for a single entry in an error catalog.
6
+ *
7
+ * `message` is either a constant string or a function that receives required
8
+ * params at the call site (typed). All other fields are templated defaults
9
+ * that can be overridden at the call site.
10
+ */
11
+ interface ErrorCatalogEntry {
12
+ /** HTTP status code (default: 500). */
13
+ status?: number;
14
+ /**
15
+ * Either a constant string or a typed function whose params become required
16
+ * arguments at the call site (`factory({ available, required })`).
17
+ */
18
+ message: string | ((params: never) => string);
19
+ /** Why this error occurred (technical reason). */
20
+ why?: string;
21
+ /** Actionable fix shown to the user. */
22
+ fix?: string;
23
+ /** Link to documentation. */
24
+ link?: string;
25
+ /** Free-form metadata for grouping / filtering (not surfaced on the wire). */
26
+ tags?: readonly string[];
27
+ /**
28
+ * Backend-only context defaults. Merged with call-site `internal` (call-site wins).
29
+ */
30
+ internal?: Record<string, unknown>;
31
+ }
32
+ /**
33
+ * Subset of {@link import('./types').ErrorOptions} that callers may override
34
+ * when invoking a catalog factory. `code` is always derived from the catalog
35
+ * and intentionally excluded — pass `cause` here for error chaining.
36
+ */
37
+ interface ErrorFactoryOverrides {
38
+ message?: string;
39
+ status?: number;
40
+ why?: string;
41
+ fix?: string;
42
+ link?: string;
43
+ internal?: Record<string, unknown>;
44
+ cause?: Error;
45
+ }
46
+ /** @internal Extract the params object type from a templated message function. */
47
+ type MessageParams<TMessage> = TMessage extends ((params: infer P) => string) ? P : Record<string, never>;
48
+ /**
49
+ * Call-site argument type for a catalog factory:
50
+ * - if `message` is a function: required params object merged with overrides
51
+ * - if `message` is a string: optional overrides only
52
+ */
53
+ type ErrorFactoryOpts<TEntry extends ErrorCatalogEntry> = TEntry['message'] extends ((params: infer _P) => string) ? MessageParams<TEntry['message']> & ErrorFactoryOverrides : ErrorFactoryOverrides;
54
+ /** @internal When message is a string, the call-site argument is optional. */
55
+ type FactoryArgs<TEntry extends ErrorCatalogEntry> = TEntry['message'] extends ((params: never) => string) ? [opts: ErrorFactoryOpts<TEntry>] : [opts?: ErrorFactoryOpts<TEntry>];
56
+ /**
57
+ * A factory produced by {@link defineError} or each entry of
58
+ * {@link defineErrorCatalog}. Calling it returns a fully-formed
59
+ * {@link EvlogError} with the catalog's defaults applied. Static metadata
60
+ * is exposed as readonly properties for introspection / refactor-safe
61
+ * comparisons (`err.code === MyError.code`).
62
+ */
63
+ type DefinedError<TCode extends string, TEntry extends ErrorCatalogEntry> = ((...args: FactoryArgs<TEntry>) => EvlogError) & {
64
+ readonly code: TCode;
65
+ readonly status: number;
66
+ readonly message: TEntry['message'];
67
+ readonly why: TEntry['why'];
68
+ readonly fix: TEntry['fix'];
69
+ readonly link: TEntry['link'];
70
+ readonly tags: TEntry['tags'];
71
+ readonly internal: TEntry['internal'];
72
+ };
73
+ /**
74
+ * Define a single, standalone error factory bound to a stable `code`.
75
+ *
76
+ * Each factory produces an {@link EvlogError} with the entry's defaults
77
+ * applied. Call-site overrides (`cause`, `internal`, `message`, ...) are
78
+ * shallow-merged onto those defaults.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * import { defineError } from 'evlog'
83
+ *
84
+ * export const PaymentDeclined = defineError('billing.PAYMENT_DECLINED', {
85
+ * status: 402,
86
+ * message: 'Card declined',
87
+ * why: 'Issuer declined the charge',
88
+ * fix: 'Try another card',
89
+ * })
90
+ *
91
+ * throw PaymentDeclined()
92
+ * throw PaymentDeclined({ cause: stripeErr, internal: { ref: 'ch_x' } })
93
+ * ```
94
+ *
95
+ * @example Templated message with typed params
96
+ * ```ts
97
+ * export const InsufficientFunds = defineError('billing.INSUFFICIENT_FUNDS', {
98
+ * status: 402,
99
+ * message: ({ available, required }: { available: number, required: number }) =>
100
+ * `Insufficient funds: $${available}/$${required}`,
101
+ * })
102
+ *
103
+ * throw InsufficientFunds({ available: 5, required: 100 })
104
+ * ```
105
+ */
106
+ declare function defineError<const TCode extends string, const TEntry extends ErrorCatalogEntry>(code: TCode, entry: TEntry): DefinedError<TCode, TEntry>;
107
+ /** Map of error catalog entries keyed by their (UPPER_SNAKE) name. */
108
+ interface ErrorCatalogMap {
109
+ readonly [key: string]: ErrorCatalogEntry;
110
+ }
111
+ /**
112
+ * The object returned by {@link defineErrorCatalog}. Each map key becomes a
113
+ * dot-accessed factory whose `code` is `${prefix}.${key}` (preserved casing).
114
+ *
115
+ * Catalog metadata (`_prefix`, `_codes`) is exposed as non-enumerable readonly
116
+ * properties so it does not pollute iteration but is available for typing
117
+ * (`declare module 'evlog'`) and runtime introspection.
118
+ */
119
+ type ErrorCatalog<TPrefix extends string, TMap extends ErrorCatalogMap> = { [K in keyof TMap & string]: DefinedError<`${TPrefix}.${K}`, TMap[K]> } & {
120
+ readonly _prefix: TPrefix;
121
+ readonly _codes: ReadonlyArray<`${TPrefix}.${keyof TMap & string}`>;
122
+ };
123
+ /**
124
+ * Define a bundle of errors that share a common prefix. The wire `code` for
125
+ * each entry is `${prefix}.${KEY}` (the key's casing is preserved — convention
126
+ * is `UPPER_SNAKE_CASE`).
127
+ *
128
+ * Pair with `declare module 'evlog'` to surface autocomplete + literal-typed
129
+ * `code` everywhere across the codebase.
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * import { defineErrorCatalog } from 'evlog'
134
+ *
135
+ * export const billingErrors = defineErrorCatalog('billing', {
136
+ * PAYMENT_DECLINED: { status: 402, message: 'Card declined' },
137
+ * INSUFFICIENT_FUNDS: {
138
+ * status: 402,
139
+ * message: ({ available, required }: { available: number, required: number }) =>
140
+ * `Insufficient funds: $${available}/$${required}`,
141
+ * },
142
+ * })
143
+ *
144
+ * declare module 'evlog' {
145
+ * interface RegisteredErrorCatalogs {
146
+ * billing: typeof billingErrors
147
+ * }
148
+ * }
149
+ *
150
+ * throw billingErrors.PAYMENT_DECLINED()
151
+ * throw billingErrors.INSUFFICIENT_FUNDS({ available: 5, required: 100 })
152
+ * ```
153
+ */
154
+ declare function defineErrorCatalog<const TPrefix extends string, const TMap extends ErrorCatalogMap>(prefix: TPrefix, map: TMap): ErrorCatalog<TPrefix, TMap>;
155
+ /** Static metadata for a single entry in an audit catalog. */
156
+ interface AuditCatalogEntry {
157
+ /** Default `target.type` for every audit emitted from this action. */
158
+ target?: string;
159
+ }
160
+ /** Map of audit catalog entries keyed by their (UPPER_SNAKE) name. */
161
+ interface AuditCatalogMap {
162
+ readonly [key: string]: AuditCatalogEntry;
163
+ }
164
+ /** A factory produced by an audit catalog entry. Returns an {@link AuditInput}. */
165
+ type DefinedCatalogAudit<TAction extends string, TEntry extends AuditCatalogEntry> = ((input: TEntry['target'] extends string ? Omit<AuditInput, 'action' | 'target'> & {
166
+ target?: Omit<AuditTarget, 'type'> & {
167
+ type?: TEntry['target'];
168
+ };
169
+ } : Omit<AuditInput, 'action'>) => AuditInput) & {
170
+ readonly action: TAction;
171
+ readonly target: TEntry['target'];
172
+ };
173
+ /**
174
+ * The object returned by {@link defineAuditCatalog}. Mirrors
175
+ * {@link ErrorCatalog} but each factory produces an {@link AuditInput}
176
+ * (typically passed to `log.audit(...)`).
177
+ */
178
+ type AuditCatalog<TPrefix extends string, TMap extends AuditCatalogMap> = { [K in keyof TMap & string]: DefinedCatalogAudit<`${TPrefix}.${K}`, TMap[K]> } & {
179
+ readonly _prefix: TPrefix;
180
+ readonly _actions: ReadonlyArray<`${TPrefix}.${keyof TMap & string}`>;
181
+ };
182
+ /**
183
+ * Define a bundle of audit actions that share a common prefix. The wire
184
+ * `action` for each entry is `${prefix}.${KEY}`.
185
+ *
186
+ * Each entry produces a thin wrapper around {@link defineAuditAction} (target
187
+ * type is fixed at definition time, action name is auto-prefixed).
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * import { defineAuditCatalog } from 'evlog'
192
+ *
193
+ * export const billingAudit = defineAuditCatalog('billing', {
194
+ * INVOICE_REFUND: { target: 'invoice' },
195
+ * INVOICE_CREATE: { target: 'invoice' },
196
+ * })
197
+ *
198
+ * declare module 'evlog' {
199
+ * interface RegisteredAuditCatalogs {
200
+ * billing: typeof billingAudit
201
+ * }
202
+ * }
203
+ *
204
+ * log.audit(billingAudit.INVOICE_REFUND({
205
+ * actor: { type: 'user', id: u.id },
206
+ * target: { id: 'inv_889' },
207
+ * }))
208
+ * ```
209
+ */
210
+ declare function defineAuditCatalog<const TPrefix extends string, const TMap extends AuditCatalogMap>(prefix: TPrefix, map: TMap): AuditCatalog<TPrefix, TMap>;
211
+ //#endregion
212
+ export { DefinedError as a, ErrorCatalogMap as c, defineAuditCatalog as d, defineError as f, DefinedCatalogAudit as i, ErrorFactoryOpts as l, AuditCatalogEntry as n, ErrorCatalog as o, defineErrorCatalog as p, AuditCatalogMap as r, ErrorCatalogEntry as s, AuditCatalog as t, ErrorFactoryO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Context, C as buildAuditFields, D as withAudit, E as signed, F as DrainContext, G as LoggerConfig, H as InternalFields, I as EnrichContext, K as ParsedError, L as EnvironmentContext, M as AuditTarget, N as BaseWideEvent, O as withAuditMethods, P as DeepPartial, Q as SamplingConfig, R as ErrorOptions, S as auditRedactPreset, T as mockAudit, U as Log, V as IngestPayload, W as LogLevel, X as RequestLoggerOptions, Y as RequestLogger, _ as WithAuditOptions, a as AuditInput, at as ClientLogContext, b as auditEnricher, c as AuditOnlyOptions, ct as PluginSetupContext, d as DefinedAuditAction, et as ServerEvent, f as DrainFn, ft as definePlugin, g as WithAuditContext, h as SignedOptions, i as AuditEnricherOptions, it as WideEvent, j as AuditLoggerMethod, k as AuditActor, l as AuditPatchOp, lt as RequestFinishContext, m as SignedChainState, mt as enricherPlugin, n as AuditDeniedError, nt as TailSamplingContext, o as AuditMatcher, ot as EvlogPlugin, p as MockAudit, pt as drainPlugin, q as RedactConfig, r as AuditDiffOptions, rt as TransportConfig, s as AuditMethod, st as PluginRunner, t as AUDIT_SCHEMA_VERSION, tt as TailSamplingCondition, u as AuditableLogger, ut as RequestLifecycleContext, v as audit, w as defineAuditAction, x as auditOnly, y as auditDiff, z as FieldContext } from "./audit-CJl-wZ10.mjs";
2
- import { n as createError, t as EvlogError } from "./error-C-66_G2M.mjs";
3
- import { c as isEnabled, d as shouldKeep, i as getEnvironment, n as createLogger, r as createRequestLogger, s as initLogger, t as _log } from "./logger-Brt5-WMK.mjs";
4
- import { m as isLevelEnabled } from "./utils-gQCeZMbg.mjs";
5
- import { t as useLogger } from "./useLogger-Cb1R6bQE.mjs";
6
- import { t as parseError } from "./parseError-B1zJZvQ5.mjs";
7
- import { i as toMiddlewareOptions, n as defineEvlog, r as toLoggerConfig, t as EvlogConfig } from "./define-Fp8TrdEB.mjs";
8
- export { AUDIT_SCHEMA_VERSION, type AuditActor, AuditDeniedError, type AuditDiffOptions, type AuditEnricherOptions, type AuditFields, type AuditInput, type AuditLoggerMethod, type AuditMatcher, type AuditMethod, type AuditOnlyOptions, type AuditPatchOp, type AuditTarget, type AuditableLogger, type BaseWideEvent, type ClientLogContext, type DeepPartial, type DefinedAuditAction, type DrainContext, type DrainFn, type EnrichContext, type EnvironmentContext, type ErrorOptions, type EvlogConfig, EvlogError, type EvlogPlugin, type FieldContext, type H3EventContext, type IngestPayload, type InternalFields, type Log, type LogLevel, type LoggerConfig, type MockAudit, type ParsedError, type PluginRunner, type PluginSetupContext, type RedactConfig, type RequestFinishContext, type RequestLifecycleContext, type RequestLogger, type RequestLoggerOptions, type SamplingConfig, type SamplingRates, type ServerEvent, type SignedChainState, type SignedOptions, type TailSamplingCondition, type TailSamplingContext, type TransportConfig, type WideEvent, type WithAuditContext, type WithAuditOptions, audit, auditDiff, auditEnricher, auditOnly, auditRedactPreset, buildAuditFields, createError, createError as createEvlogError, createLogger, createRequestLogger, defineAuditAction, defineEvlog, definePlugin, drainPlugin, enricherPlugin, getEnvironment, initLogger, isEnabled, isLevelEnabled, _log as log, mockAudit, parseError, shouldKeep, signed, toLoggerConfig, toMiddlewareOptions, useLogger, withAudit, withAuditMethods };
1
+ import { $ as RequestLogger, A as AuditActor, B as ErrorOptions, C as buildAuditFields, D as withAudit, E as signed, F as DeepPartial, G as Log, H as H3EventContext, I as DrainContext, J as ParsedError, K as LogLevel, L as EnrichContext, M as AuditLoggerMethod, N as AuditTarget, O as withAuditMethods, P as BaseWideEvent, R as EnvironmentContext, S as auditRedactPreset, T as mockAudit, U as IngestPayload, V as FieldContext, W as InternalFields, X as RegisteredAuditCatalogs, Y as RedactConfig, Z as RegisteredErrorCatalogs, _ as WithAuditOptions, _t as drainPlugin, a as AuditInput, at as TailSamplingCondition, b as auditEnricher, c as AuditOnlyOptions, ct as WideEvent, d as DefinedAuditAction, dt as PluginRunner, et as RequestLoggerOptions, f as DrainFn, ft as PluginSetupContext, g as WithAuditContext, gt as definePlugin, h as SignedOptions, i as AuditEnricherOptions, it as ServerEvent, j as AuditFields, k as AuditAction, l as AuditPatchOp, lt as ClientLogContext, m as SignedChainState, mt as RequestLifecycleContext, n as AuditDeniedError, nt as SamplingConfig, o as AuditMatcher, ot as TailSamplingContext, p as MockAudit, pt as RequestFinishContext, q as LoggerConfig, r as AuditDiffOptions, rt as SamplingRates, s as AuditMethod, st as TransportConfig, t as AUDIT_SCHEMA_VERSION, u as AuditableLogger, ut as EvlogPlugin, v as audit, vt as enricherPlugin, w as defineAuditAction, x as auditOnly, y as auditDiff, z as ErrorCode } from "./audit-CC8nfazi.mjs";
2
+ import { n as createError, t as EvlogError } from "./error-CpbbtyXL.mjs";
3
+ import { a as DefinedError, c as ErrorCatalogMap, d as defineAuditCatalog, f as defineError, i as DefinedCatalogAudit, l as ErrorFactoryOpts, n as AuditCatalogEntry, o as ErrorCatalog, p as defineErrorCatalog, r as AuditCatalogMap, s as ErrorCatalogEntry, t as AuditCatalog, u as ErrorFactoryOverrides } from "./index-o1_z4phv.mjs";
4
+ import { c as isEnabled, d as shouldKeep, i as getEnvironment, n as createLogger, r as createRequestLogger, s as initLogger, t as _log } from "./logger-DntcxxHg.mjs";
5
+ import { m as isLevelEnabled } from "./utils-DLCeShxL.mjs";
6
+ import { t as useLogger } from "./useLogger-BsPL4AQm.mjs";
7
+ import { t as parseError } from "./parseError-yVZ58wIK.mjs";
8
+ import { i as toMiddlewareOptions, n as defineEvlog, r as toLoggerConfig, t as EvlogConfig } from "./define-MSdhzmXn.mjs";
9
+ export { AUDIT_SCHEMA_VERSION, AuditAction, AuditActor, AuditCatalog, AuditCatalogEntry, AuditCatalogMap, AuditDeniedError, AuditDiffOptions, AuditEnricherOptions, AuditFields, AuditInput, AuditLoggerMethod, AuditMatcher, AuditMethod, AuditOnlyOptions, AuditPatchOp, AuditTarget, AuditableLogger, BaseWideEvent, ClientLogContext, DeepPartial, DefinedAuditAction, DefinedCatalogAudit, DefinedError, DrainContext, DrainFn, EnrichContext, EnvironmentContext, ErrorCatalog, ErrorCatalogEntry, ErrorCatalogMap, ErrorCode, ErrorFactoryOpts, ErrorFactoryOverrides, ErrorOptions, EvlogConfig, EvlogError, EvlogPlugin, FieldContext, H3EventContext, IngestPayload, InternalFields, Log, LogLevel, LoggerConfig, MockAudit, ParsedError, PluginRunner, PluginSetupContext, RedactConfig, RegisteredAuditCatalogs, RegisteredErrorCatalogs, RequestFinishContext, RequestLifecycleContext, RequestLogger, RequestLoggerOptions, SamplingConfig, SamplingRates, ServerEvent, SignedChainState, SignedOptions, TailSamplingCondition, TailSamplingContext, TransportConfig, WideEvent, WithAuditContext, WithAuditOptions, audit, auditDiff, auditEnricher, auditOnly, auditRedactPreset, buildAuditFields, createError, createError as createEvlogError, createLogger, createRequestLogger, defineAuditAction, defineAuditCatalog, defineError, defineErrorCatalog, defineEvlog, definePlugin, drainPlugin, enricherPlugin, getEnvironment, initLogger, isEnabled, isLevelEnabled, _log as log, mockAudit, parseError, shouldKeep, signed, toLoggerConfig, toMiddlewareOptions, useLogger, withAudit, withAuditMethods };
package/dist/index.mjs CHANGED
@@ -1,7 +1,215 @@
1
- import { D as drainPlugin, E as definePlugin, O as enricherPlugin, _ as getEnvironment, a as auditEnricher, b as initLogger, c as buildAuditFields, d as signed, f as withAudit, g as createRequestLogger, h as createLogger, i as auditDiff, l as defineAuditAction, m as _log, n as AuditDeniedError, o as auditOnly, p as withAuditMethods, r as audit, s as auditRedactPreset, t as AUDIT_SCHEMA_VERSION, u as mockAudit, w as shouldKeep, x as isEnabled } from "./audit--n0QRR2Y.mjs";
1
+ import { D as drainPlugin, E as definePlugin, O as enricherPlugin, _ as getEnvironment, a as auditEnricher, b as initLogger, c as buildAuditFields, d as signed, f as withAudit, g as createRequestLogger, h as createLogger, i as auditDiff, l as defineAuditAction, m as _log, n as AuditDeniedError, o as auditOnly, p as withAuditMethods, r as audit, s as auditRedactPreset, t as AUDIT_SCHEMA_VERSION, u as mockAudit, w as shouldKeep, x as isEnabled } from "./audit-pV5aLGP0.mjs";
2
2
  import { isLevelEnabled } from "./utils.mjs";
3
3
  import { EvlogError, createError } from "./error.mjs";
4
4
  import { useLogger } from "./runtime/server/useLogger.mjs";
5
5
  import { parseError } from "./runtime/utils/parseError.mjs";
6
6
  import { n as toLoggerConfig, r as toMiddlewareOptions, t as defineEvlog } from "./define-D6OJdSUH.mjs";
7
- export { AUDIT_SCHEMA_VERSION, AuditDeniedError, EvlogError, audit, auditDiff, auditEnricher, auditOnly, auditRedactPreset, buildAuditFields, createError, createError as createEvlogError, createLogger, createRequestLogger, defineAuditAction, defineEvlog, definePlugin, drainPlugin, enricherPlugin, getEnvironment, initLogger, isEnabled, isLevelEnabled, _log as log, mockAudit, parseError, shouldKeep, signed, toLoggerConfig, toMiddlewareOptions, useLogger, withAudit, withAuditMethods };
7
+ //#region src/catalog.ts
8
+ function buildEvlogError(code, entry, rawArgs) {
9
+ const { message: messageOverride, status, why, fix, link, cause, internal: callInternal, ...maybeParams } = rawArgs ?? {};
10
+ let message;
11
+ if (typeof messageOverride === "string") message = messageOverride;
12
+ else if (typeof entry.message === "function") message = entry.message(maybeParams);
13
+ else ({message} = entry);
14
+ let internal;
15
+ if (entry.internal || callInternal) internal = {
16
+ ...entry.internal ?? {},
17
+ ...callInternal ?? {}
18
+ };
19
+ return new EvlogError({
20
+ code,
21
+ message,
22
+ status: status ?? entry.status ?? 500,
23
+ why: why ?? entry.why,
24
+ fix: fix ?? entry.fix,
25
+ link: link ?? entry.link,
26
+ cause,
27
+ internal
28
+ });
29
+ }
30
+ /**
31
+ * Define a single, standalone error factory bound to a stable `code`.
32
+ *
33
+ * Each factory produces an {@link EvlogError} with the entry's defaults
34
+ * applied. Call-site overrides (`cause`, `internal`, `message`, ...) are
35
+ * shallow-merged onto those defaults.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * import { defineError } from 'evlog'
40
+ *
41
+ * export const PaymentDeclined = defineError('billing.PAYMENT_DECLINED', {
42
+ * status: 402,
43
+ * message: 'Card declined',
44
+ * why: 'Issuer declined the charge',
45
+ * fix: 'Try another card',
46
+ * })
47
+ *
48
+ * throw PaymentDeclined()
49
+ * throw PaymentDeclined({ cause: stripeErr, internal: { ref: 'ch_x' } })
50
+ * ```
51
+ *
52
+ * @example Templated message with typed params
53
+ * ```ts
54
+ * export const InsufficientFunds = defineError('billing.INSUFFICIENT_FUNDS', {
55
+ * status: 402,
56
+ * message: ({ available, required }: { available: number, required: number }) =>
57
+ * `Insufficient funds: $${available}/$${required}`,
58
+ * })
59
+ *
60
+ * throw InsufficientFunds({ available: 5, required: 100 })
61
+ * ```
62
+ */
63
+ function defineError(code, entry) {
64
+ const factory = ((...args) => buildEvlogError(code, entry, args[0]));
65
+ Object.defineProperties(factory, {
66
+ code: {
67
+ value: code,
68
+ enumerable: true
69
+ },
70
+ status: {
71
+ value: entry.status ?? 500,
72
+ enumerable: true
73
+ },
74
+ message: {
75
+ value: entry.message,
76
+ enumerable: true
77
+ },
78
+ why: {
79
+ value: entry.why,
80
+ enumerable: true
81
+ },
82
+ fix: {
83
+ value: entry.fix,
84
+ enumerable: true
85
+ },
86
+ link: {
87
+ value: entry.link,
88
+ enumerable: true
89
+ },
90
+ tags: {
91
+ value: entry.tags,
92
+ enumerable: true
93
+ },
94
+ internal: {
95
+ value: entry.internal,
96
+ enumerable: true
97
+ }
98
+ });
99
+ return factory;
100
+ }
101
+ /**
102
+ * Define a bundle of errors that share a common prefix. The wire `code` for
103
+ * each entry is `${prefix}.${KEY}` (the key's casing is preserved — convention
104
+ * is `UPPER_SNAKE_CASE`).
105
+ *
106
+ * Pair with `declare module 'evlog'` to surface autocomplete + literal-typed
107
+ * `code` everywhere across the codebase.
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * import { defineErrorCatalog } from 'evlog'
112
+ *
113
+ * export const billingErrors = defineErrorCatalog('billing', {
114
+ * PAYMENT_DECLINED: { status: 402, message: 'Card declined' },
115
+ * INSUFFICIENT_FUNDS: {
116
+ * status: 402,
117
+ * message: ({ available, required }: { available: number, required: number }) =>
118
+ * `Insufficient funds: $${available}/$${required}`,
119
+ * },
120
+ * })
121
+ *
122
+ * declare module 'evlog' {
123
+ * interface RegisteredErrorCatalogs {
124
+ * billing: typeof billingErrors
125
+ * }
126
+ * }
127
+ *
128
+ * throw billingErrors.PAYMENT_DECLINED()
129
+ * throw billingErrors.INSUFFICIENT_FUNDS({ available: 5, required: 100 })
130
+ * ```
131
+ */
132
+ function defineErrorCatalog(prefix, map) {
133
+ const out = {};
134
+ const codes = [];
135
+ for (const key of Object.keys(map)) {
136
+ const code = `${prefix}.${key}`;
137
+ out[key] = defineError(code, map[key]);
138
+ codes.push(code);
139
+ }
140
+ Object.defineProperties(out, {
141
+ _prefix: {
142
+ value: prefix,
143
+ enumerable: false
144
+ },
145
+ _codes: {
146
+ value: Object.freeze(codes),
147
+ enumerable: false
148
+ }
149
+ });
150
+ return out;
151
+ }
152
+ /**
153
+ * Define a bundle of audit actions that share a common prefix. The wire
154
+ * `action` for each entry is `${prefix}.${KEY}`.
155
+ *
156
+ * Each entry produces a thin wrapper around {@link defineAuditAction} (target
157
+ * type is fixed at definition time, action name is auto-prefixed).
158
+ *
159
+ * @example
160
+ * ```ts
161
+ * import { defineAuditCatalog } from 'evlog'
162
+ *
163
+ * export const billingAudit = defineAuditCatalog('billing', {
164
+ * INVOICE_REFUND: { target: 'invoice' },
165
+ * INVOICE_CREATE: { target: 'invoice' },
166
+ * })
167
+ *
168
+ * declare module 'evlog' {
169
+ * interface RegisteredAuditCatalogs {
170
+ * billing: typeof billingAudit
171
+ * }
172
+ * }
173
+ *
174
+ * log.audit(billingAudit.INVOICE_REFUND({
175
+ * actor: { type: 'user', id: u.id },
176
+ * target: { id: 'inv_889' },
177
+ * }))
178
+ * ```
179
+ */
180
+ function defineAuditCatalog(prefix, map) {
181
+ const out = {};
182
+ const actions = [];
183
+ for (const key of Object.keys(map)) {
184
+ const action = `${prefix}.${key}`;
185
+ const entry = map[key];
186
+ const fn = defineAuditAction(action, entry.target ? { target: entry.target } : void 0);
187
+ Object.defineProperties(fn, {
188
+ action: {
189
+ value: action,
190
+ enumerable: true
191
+ },
192
+ target: {
193
+ value: entry.target,
194
+ enumerable: true
195
+ }
196
+ });
197
+ out[key] = fn;
198
+ actions.push(action);
199
+ }
200
+ Object.defineProperties(out, {
201
+ _prefix: {
202
+ value: prefix,
203
+ enumerable: false
204
+ },
205
+ _actions: {
206
+ value: Object.freeze(actions),
207
+ enumerable: false
208
+ }
209
+ });
210
+ return out;
211
+ }
212
+ //#endregion
213
+ export { AUDIT_SCHEMA_VERSION, AuditDeniedError, EvlogError, audit, auditDiff, auditEnricher, auditOnly, auditRedactPreset, buildAuditFields, createError, createError as createEvlogError, createLogger, createRequestLogger, defineAuditAction, defineAuditCatalog, defineError, defineErrorCatalog, defineEvlog, definePlugin, drainPlugin, enricherPlugin, getEnvironment, initLogger, isEnabled, isLevelEnabled, _log as log, mockAudit, parseError, shouldKeep, signed, toLoggerConfig, toMiddlewareOptions, useLogger, withAudit, withAuditMethods };
214
+
215
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/catalog.ts"],"sourcesContent":["import type { AuditInput } from './audit'\nimport type { AuditTarget } from './types'\nimport { defineAuditAction } from './audit'\nimport { EvlogError } from './error'\n\n/**\n * Static metadata for a single entry in an error catalog.\n *\n * `message` is either a constant string or a function that receives required\n * params at the call site (typed). All other fields are templated defaults\n * that can be overridden at the call site.\n */\nexport interface ErrorCatalogEntry {\n /** HTTP status code (default: 500). */\n status?: number\n /**\n * Either a constant string or a typed function whose params become required\n * arguments at the call site (`factory({ available, required })`).\n */\n message: string | ((params: never) => string)\n /** Why this error occurred (technical reason). */\n why?: string\n /** Actionable fix shown to the user. */\n fix?: string\n /** Link to documentation. */\n link?: string\n /** Free-form metadata for grouping / filtering (not surfaced on the wire). */\n tags?: readonly string[]\n /**\n * Backend-only context defaults. Merged with call-site `internal` (call-site wins).\n */\n internal?: Record<string, unknown>\n}\n\n/**\n * Subset of {@link import('./types').ErrorOptions} that callers may override\n * when invoking a catalog factory. `code` is always derived from the catalog\n * and intentionally excluded — pass `cause` here for error chaining.\n */\nexport interface ErrorFactoryOverrides {\n message?: string\n status?: number\n why?: string\n fix?: string\n link?: string\n internal?: Record<string, unknown>\n cause?: Error\n}\n\n/** @internal Extract the params object type from a templated message function. */\ntype MessageParams<TMessage> = TMessage extends (params: infer P) => string ? P : Record<string, never>\n\n/**\n * Call-site argument type for a catalog factory:\n * - if `message` is a function: required params object merged with overrides\n * - if `message` is a string: optional overrides only\n */\nexport type ErrorFactoryOpts<TEntry extends ErrorCatalogEntry> =\n TEntry['message'] extends (params: infer _P) => string\n ? MessageParams<TEntry['message']> & ErrorFactoryOverrides\n : ErrorFactoryOverrides\n\n/** @internal When message is a string, the call-site argument is optional. */\ntype FactoryArgs<TEntry extends ErrorCatalogEntry> =\n TEntry['message'] extends (params: never) => string\n ? [opts: ErrorFactoryOpts<TEntry>]\n : [opts?: ErrorFactoryOpts<TEntry>]\n\n/**\n * A factory produced by {@link defineError} or each entry of\n * {@link defineErrorCatalog}. Calling it returns a fully-formed\n * {@link EvlogError} with the catalog's defaults applied. Static metadata\n * is exposed as readonly properties for introspection / refactor-safe\n * comparisons (`err.code === MyError.code`).\n */\nexport type DefinedError<TCode extends string, TEntry extends ErrorCatalogEntry> =\n & ((...args: FactoryArgs<TEntry>) => EvlogError)\n & {\n readonly code: TCode\n readonly status: number\n readonly message: TEntry['message']\n readonly why: TEntry['why']\n readonly fix: TEntry['fix']\n readonly link: TEntry['link']\n readonly tags: TEntry['tags']\n readonly internal: TEntry['internal']\n }\n\nfunction buildEvlogError(\n code: string,\n entry: ErrorCatalogEntry,\n rawArgs: Record<string, unknown> | undefined,\n): EvlogError {\n const args = rawArgs ?? {}\n const {\n message: messageOverride,\n status,\n why,\n fix,\n link,\n cause,\n internal: callInternal,\n ...maybeParams\n } = args as ErrorFactoryOverrides & Record<string, unknown>\n\n let message: string\n if (typeof messageOverride === 'string') {\n message = messageOverride\n } else if (typeof entry.message === 'function') {\n message = (entry.message as (p: unknown) => string)(maybeParams)\n } else {\n ({ message } = entry as { message: string })\n }\n\n let internal: Record<string, unknown> | undefined\n if (entry.internal || callInternal) {\n internal = { ...(entry.internal ?? {}), ...(callInternal ?? {}) }\n }\n\n return new EvlogError({\n code,\n message,\n status: status ?? entry.status ?? 500,\n why: why ?? entry.why,\n fix: fix ?? entry.fix,\n link: link ?? entry.link,\n cause: cause as Error | undefined,\n internal,\n })\n}\n\n/**\n * Define a single, standalone error factory bound to a stable `code`.\n *\n * Each factory produces an {@link EvlogError} with the entry's defaults\n * applied. Call-site overrides (`cause`, `internal`, `message`, ...) are\n * shallow-merged onto those defaults.\n *\n * @example\n * ```ts\n * import { defineError } from 'evlog'\n *\n * export const PaymentDeclined = defineError('billing.PAYMENT_DECLINED', {\n * status: 402,\n * message: 'Card declined',\n * why: 'Issuer declined the charge',\n * fix: 'Try another card',\n * })\n *\n * throw PaymentDeclined()\n * throw PaymentDeclined({ cause: stripeErr, internal: { ref: 'ch_x' } })\n * ```\n *\n * @example Templated message with typed params\n * ```ts\n * export const InsufficientFunds = defineError('billing.INSUFFICIENT_FUNDS', {\n * status: 402,\n * message: ({ available, required }: { available: number, required: number }) =>\n * `Insufficient funds: $${available}/$${required}`,\n * })\n *\n * throw InsufficientFunds({ available: 5, required: 100 })\n * ```\n */\nexport function defineError<\n const TCode extends string,\n const TEntry extends ErrorCatalogEntry,\n>(code: TCode, entry: TEntry): DefinedError<TCode, TEntry> {\n const factory = ((...args: unknown[]) =>\n buildEvlogError(code, entry, args[0] as Record<string, unknown> | undefined)) as DefinedError<TCode, TEntry>\n\n Object.defineProperties(factory, {\n code: { value: code, enumerable: true },\n status: { value: entry.status ?? 500, enumerable: true },\n message: { value: entry.message, enumerable: true },\n why: { value: entry.why, enumerable: true },\n fix: { value: entry.fix, enumerable: true },\n link: { value: entry.link, enumerable: true },\n tags: { value: entry.tags, enumerable: true },\n internal: { value: entry.internal, enumerable: true },\n })\n\n return factory\n}\n\n/** Map of error catalog entries keyed by their (UPPER_SNAKE) name. */\nexport interface ErrorCatalogMap {\n readonly [key: string]: ErrorCatalogEntry\n}\n\n/**\n * The object returned by {@link defineErrorCatalog}. Each map key becomes a\n * dot-accessed factory whose `code` is `${prefix}.${key}` (preserved casing).\n *\n * Catalog metadata (`_prefix`, `_codes`) is exposed as non-enumerable readonly\n * properties so it does not pollute iteration but is available for typing\n * (`declare module 'evlog'`) and runtime introspection.\n */\nexport type ErrorCatalog<TPrefix extends string, TMap extends ErrorCatalogMap> =\n & { [K in keyof TMap & string]: DefinedError<`${TPrefix}.${K}`, TMap[K]> }\n & {\n readonly _prefix: TPrefix\n readonly _codes: ReadonlyArray<`${TPrefix}.${keyof TMap & string}`>\n }\n\n/**\n * Define a bundle of errors that share a common prefix. The wire `code` for\n * each entry is `${prefix}.${KEY}` (the key's casing is preserved — convention\n * is `UPPER_SNAKE_CASE`).\n *\n * Pair with `declare module 'evlog'` to surface autocomplete + literal-typed\n * `code` everywhere across the codebase.\n *\n * @example\n * ```ts\n * import { defineErrorCatalog } from 'evlog'\n *\n * export const billingErrors = defineErrorCatalog('billing', {\n * PAYMENT_DECLINED: { status: 402, message: 'Card declined' },\n * INSUFFICIENT_FUNDS: {\n * status: 402,\n * message: ({ available, required }: { available: number, required: number }) =>\n * `Insufficient funds: $${available}/$${required}`,\n * },\n * })\n *\n * declare module 'evlog' {\n * interface RegisteredErrorCatalogs {\n * billing: typeof billingErrors\n * }\n * }\n *\n * throw billingErrors.PAYMENT_DECLINED()\n * throw billingErrors.INSUFFICIENT_FUNDS({ available: 5, required: 100 })\n * ```\n */\nexport function defineErrorCatalog<\n const TPrefix extends string,\n const TMap extends ErrorCatalogMap,\n>(prefix: TPrefix, map: TMap): ErrorCatalog<TPrefix, TMap> {\n const out: Record<string, unknown> = {}\n const codes: string[] = []\n\n for (const key of Object.keys(map)) {\n const code = `${prefix}.${key}`\n out[key] = defineError(code, map[key])\n codes.push(code)\n }\n\n Object.defineProperties(out, {\n _prefix: { value: prefix, enumerable: false },\n _codes: { value: Object.freeze(codes), enumerable: false },\n })\n\n return out as ErrorCatalog<TPrefix, TMap>\n}\n\n/** Static metadata for a single entry in an audit catalog. */\nexport interface AuditCatalogEntry {\n /** Default `target.type` for every audit emitted from this action. */\n target?: string\n}\n\n/** Map of audit catalog entries keyed by their (UPPER_SNAKE) name. */\nexport interface AuditCatalogMap {\n readonly [key: string]: AuditCatalogEntry\n}\n\n/** A factory produced by an audit catalog entry. Returns an {@link AuditInput}. */\nexport type DefinedCatalogAudit<TAction extends string, TEntry extends AuditCatalogEntry> =\n & ((\n input: TEntry['target'] extends string\n ? Omit<AuditInput, 'action' | 'target'> & { target?: Omit<AuditTarget, 'type'> & { type?: TEntry['target'] } }\n : Omit<AuditInput, 'action'>,\n ) => AuditInput)\n & {\n readonly action: TAction\n readonly target: TEntry['target']\n }\n\n/**\n * The object returned by {@link defineAuditCatalog}. Mirrors\n * {@link ErrorCatalog} but each factory produces an {@link AuditInput}\n * (typically passed to `log.audit(...)`).\n */\nexport type AuditCatalog<TPrefix extends string, TMap extends AuditCatalogMap> =\n & { [K in keyof TMap & string]: DefinedCatalogAudit<`${TPrefix}.${K}`, TMap[K]> }\n & {\n readonly _prefix: TPrefix\n readonly _actions: ReadonlyArray<`${TPrefix}.${keyof TMap & string}`>\n }\n\n/**\n * Define a bundle of audit actions that share a common prefix. The wire\n * `action` for each entry is `${prefix}.${KEY}`.\n *\n * Each entry produces a thin wrapper around {@link defineAuditAction} (target\n * type is fixed at definition time, action name is auto-prefixed).\n *\n * @example\n * ```ts\n * import { defineAuditCatalog } from 'evlog'\n *\n * export const billingAudit = defineAuditCatalog('billing', {\n * INVOICE_REFUND: { target: 'invoice' },\n * INVOICE_CREATE: { target: 'invoice' },\n * })\n *\n * declare module 'evlog' {\n * interface RegisteredAuditCatalogs {\n * billing: typeof billingAudit\n * }\n * }\n *\n * log.audit(billingAudit.INVOICE_REFUND({\n * actor: { type: 'user', id: u.id },\n * target: { id: 'inv_889' },\n * }))\n * ```\n */\nexport function defineAuditCatalog<\n const TPrefix extends string,\n const TMap extends AuditCatalogMap,\n>(prefix: TPrefix, map: TMap): AuditCatalog<TPrefix, TMap> {\n const out: Record<string, unknown> = {}\n const actions: string[] = []\n\n for (const key of Object.keys(map)) {\n const action = `${prefix}.${key}`\n const entry = map[key]\n const fn = defineAuditAction(action, entry.target ? { target: entry.target } : undefined) as ((input: unknown) => AuditInput) & { action: string, target?: string }\n Object.defineProperties(fn, {\n action: { value: action, enumerable: true },\n target: { value: entry.target, enumerable: true },\n })\n out[key] = fn\n actions.push(action)\n }\n\n Object.defineProperties(out, {\n _prefix: { value: prefix, enumerable: false },\n _actions: { value: Object.freeze(actions), enumerable: false },\n })\n\n return out as AuditCatalog<TPrefix, TMap>\n}\n"],"mappings":";;;;;;;AAwFA,SAAS,gBACP,MACA,OACA,SACY;CAEZ,MAAM,EACJ,SAAS,iBACT,QACA,KACA,KACA,MACA,OACA,UAAU,cACV,GAAG,gBATQ,WAAW,EAAE;CAY1B,IAAI;AACJ,KAAI,OAAO,oBAAoB,SAC7B,WAAU;UACD,OAAO,MAAM,YAAY,WAClC,WAAW,MAAM,QAAmC,YAAY;KAEhE,EAAC,CAAE,WAAY;CAGjB,IAAI;AACJ,KAAI,MAAM,YAAY,aACpB,YAAW;EAAE,GAAI,MAAM,YAAY,EAAE;EAAG,GAAI,gBAAgB,EAAE;EAAG;AAGnE,QAAO,IAAI,WAAW;EACpB;EACA;EACA,QAAQ,UAAU,MAAM,UAAU;EAClC,KAAK,OAAO,MAAM;EAClB,KAAK,OAAO,MAAM;EAClB,MAAM,QAAQ,MAAM;EACb;EACP;EACD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCJ,SAAgB,YAGd,MAAa,OAA4C;CACzD,MAAM,YAAY,GAAG,SACnB,gBAAgB,MAAM,OAAO,KAAK,GAA0C;AAE9E,QAAO,iBAAiB,SAAS;EAC/B,MAAM;GAAE,O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