logixia 2.0.4 → 2.0.7

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 (218) hide show
  1. package/README.md +172 -2614
  2. package/dist/{async-context-B05ArHgM.mjs → async-context-COuvmwsS.mjs} +4 -6
  3. package/dist/async-context-COuvmwsS.mjs.map +1 -0
  4. package/dist/{async-context-DTQgi8f7.js → async-context-Dv0bmPC-.js} +4 -6
  5. package/dist/async-context-Dv0bmPC-.js.map +1 -0
  6. package/dist/{azure-monitor.transport-DV03Z5P4.d.ts → azure-monitor.transport-Bvf7Xegt.d.ts} +2 -2
  7. package/dist/{azure-monitor.transport-DV03Z5P4.d.ts.map → azure-monitor.transport-Bvf7Xegt.d.ts.map} +1 -1
  8. package/dist/{azure-monitor.transport-C7kYyZUW.d.mts → azure-monitor.transport-CbSHOnNX.d.mts} +2 -2
  9. package/dist/{azure-monitor.transport-C7kYyZUW.d.mts.map → azure-monitor.transport-CbSHOnNX.d.mts.map} +1 -1
  10. package/dist/{azure-monitor.transport-BPbgjATu.mjs → azure-monitor.transport-Coz5Gesu.mjs} +5 -5
  11. package/dist/azure-monitor.transport-Coz5Gesu.mjs.map +1 -0
  12. package/dist/{azure-monitor.transport-CwbOLZHB.js → azure-monitor.transport-D6ryi8rA.js} +5 -5
  13. package/dist/azure-monitor.transport-D6ryi8rA.js.map +1 -0
  14. package/dist/azure.d.mts +1 -1
  15. package/dist/azure.d.ts +1 -1
  16. package/dist/azure.js +1 -1
  17. package/dist/azure.mjs +1 -1
  18. package/dist/{batch-buffer-DT4gdXmf.js → batch-buffer-CFzKnuNZ.js} +3 -3
  19. package/dist/{batch-buffer-DT4gdXmf.js.map → batch-buffer-CFzKnuNZ.js.map} +1 -1
  20. package/dist/{batch-buffer-0fgLmIPn.mjs → batch-buffer-CQUWDMYq.mjs} +3 -3
  21. package/dist/{batch-buffer-0fgLmIPn.mjs.map → batch-buffer-CQUWDMYq.mjs.map} +1 -1
  22. package/dist/browser.d.mts +5 -5
  23. package/dist/browser.d.mts.map +1 -1
  24. package/dist/browser.d.ts +5 -5
  25. package/dist/browser.d.ts.map +1 -1
  26. package/dist/browser.js +72 -13
  27. package/dist/browser.js.map +1 -1
  28. package/dist/browser.mjs +72 -13
  29. package/dist/browser.mjs.map +1 -1
  30. package/dist/{builder-D70z6kjj.mjs → builder-C_TgxEOW.mjs} +106 -153
  31. package/dist/builder-C_TgxEOW.mjs.map +1 -0
  32. package/dist/{builder-M7NoaugM.js → builder-CzmM_4Ub.js} +110 -180
  33. package/dist/builder-CzmM_4Ub.js.map +1 -0
  34. package/dist/cli/index.js +157 -66
  35. package/dist/cloudwatch.d.mts +1 -1
  36. package/dist/cloudwatch.d.ts +1 -1
  37. package/dist/cloudwatch.js +1 -1
  38. package/dist/cloudwatch.mjs +1 -1
  39. package/dist/{cloudwatch.transport-Bf7L4I59.d.ts → cloudwatch.transport-CQyT6U91.d.ts} +2 -2
  40. package/dist/{cloudwatch.transport-Bf7L4I59.d.ts.map → cloudwatch.transport-CQyT6U91.d.ts.map} +1 -1
  41. package/dist/{cloudwatch.transport-Rj4yTpRn.d.mts → cloudwatch.transport-CjVrI6S4.d.mts} +2 -2
  42. package/dist/{cloudwatch.transport-Rj4yTpRn.d.mts.map → cloudwatch.transport-CjVrI6S4.d.mts.map} +1 -1
  43. package/dist/{cloudwatch.transport-BTvYfLs9.mjs → cloudwatch.transport-Cr1aeTGj.mjs} +6 -6
  44. package/dist/cloudwatch.transport-Cr1aeTGj.mjs.map +1 -0
  45. package/dist/{cloudwatch.transport-B2wKQFF7.js → cloudwatch.transport-D4G5xYfG.js} +6 -6
  46. package/dist/cloudwatch.transport-D4G5xYfG.js.map +1 -0
  47. package/dist/correlation.d.mts +10 -55
  48. package/dist/correlation.d.mts.map +1 -1
  49. package/dist/correlation.d.ts +10 -55
  50. package/dist/correlation.d.ts.map +1 -1
  51. package/dist/correlation.js +15 -13
  52. package/dist/correlation.js.map +1 -1
  53. package/dist/correlation.mjs +15 -13
  54. package/dist/correlation.mjs.map +1 -1
  55. package/dist/{entry-fields-RLd1jCoR.js → entry-fields-CVwoQplO.js} +8 -3
  56. package/dist/entry-fields-CVwoQplO.js.map +1 -0
  57. package/dist/{entry-fields-CGuvT2R0.mjs → entry-fields-DNTKQxoU.mjs} +8 -3
  58. package/dist/entry-fields-DNTKQxoU.mjs.map +1 -0
  59. package/dist/gcp.d.mts +1 -1
  60. package/dist/gcp.d.ts +1 -1
  61. package/dist/gcp.js +1 -1
  62. package/dist/gcp.mjs +1 -1
  63. package/dist/{gcp.transport-CFQfdAOK.d.ts → gcp.transport-BCIvdFV-.d.ts} +4 -4
  64. package/dist/{gcp.transport-CFQfdAOK.d.ts.map → gcp.transport-BCIvdFV-.d.ts.map} +1 -1
  65. package/dist/{gcp.transport-KZe9hCAR.js → gcp.transport-CVuRpchl.js} +20 -16
  66. package/dist/gcp.transport-CVuRpchl.js.map +1 -0
  67. package/dist/{gcp.transport-C5D72b1g.d.mts → gcp.transport-D9SdLPwP.d.mts} +4 -4
  68. package/dist/{gcp.transport-C5D72b1g.d.mts.map → gcp.transport-D9SdLPwP.d.mts.map} +1 -1
  69. package/dist/{gcp.transport-CGKopAhQ.mjs → gcp.transport-LLK2bw2-.mjs} +20 -16
  70. package/dist/gcp.transport-LLK2bw2-.mjs.map +1 -0
  71. package/dist/http-shapes-BnBkJcid.d.mts +32 -0
  72. package/dist/http-shapes-BnBkJcid.d.mts.map +1 -0
  73. package/dist/http-shapes-BnBkJcid.d.ts +32 -0
  74. package/dist/http-shapes-BnBkJcid.d.ts.map +1 -0
  75. package/dist/{index-xqaJtAZn.d.mts → index-BAkPHp5D.d.mts} +150 -8
  76. package/dist/index-BAkPHp5D.d.mts.map +1 -0
  77. package/dist/{index-DwozbmB4.d.ts → index-e7LowmAu.d.ts} +150 -8
  78. package/dist/index-e7LowmAu.d.ts.map +1 -0
  79. package/dist/index.d.mts +21 -65
  80. package/dist/index.d.mts.map +1 -1
  81. package/dist/index.d.ts +21 -65
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +26 -26
  84. package/dist/index.js.map +1 -1
  85. package/dist/index.mjs +21 -21
  86. package/dist/index.mjs.map +1 -1
  87. package/dist/{internal-log-uCSd1PMc.mjs → internal-log-Cy5nF1ZL.mjs} +2 -81
  88. package/dist/internal-log-Cy5nF1ZL.mjs.map +1 -0
  89. package/dist/{internal-log-b0Vp4qrB.js → internal-log-DwqTjhpb.js} +1 -104
  90. package/dist/internal-log-DwqTjhpb.js.map +1 -0
  91. package/dist/{logitron-logger-D2B75Oc7.d.ts → logitron-logger-Qh3y9-WH.d.ts} +13 -100
  92. package/dist/logitron-logger-Qh3y9-WH.d.ts.map +1 -0
  93. package/dist/{logitron-logger-oEd6wNhf.d.mts → logitron-logger-sYuk8fOb.d.mts} +13 -100
  94. package/dist/logitron-logger-sYuk8fOb.d.mts.map +1 -0
  95. package/dist/middleware.d.mts +4 -17
  96. package/dist/middleware.d.mts.map +1 -1
  97. package/dist/middleware.d.ts +4 -17
  98. package/dist/middleware.d.ts.map +1 -1
  99. package/dist/middleware.js +9 -39
  100. package/dist/middleware.js.map +1 -1
  101. package/dist/middleware.mjs +7 -37
  102. package/dist/middleware.mjs.map +1 -1
  103. package/dist/nest.d.mts +24 -8
  104. package/dist/nest.d.mts.map +1 -1
  105. package/dist/nest.d.ts +24 -8
  106. package/dist/nest.d.ts.map +1 -1
  107. package/dist/nest.js +140 -27
  108. package/dist/nest.js.map +1 -1
  109. package/dist/nest.mjs +140 -27
  110. package/dist/nest.mjs.map +1 -1
  111. package/dist/{transport.manager-DkcEOlqV.js → otel-ChnVYRLA.js} +214 -23
  112. package/dist/otel-ChnVYRLA.js.map +1 -0
  113. package/dist/{transport.manager-eZ_EeC00.mjs → otel-DOuwGPCd.mjs} +173 -24
  114. package/dist/otel-DOuwGPCd.mjs.map +1 -0
  115. package/dist/{request-trace-C_fvIDv4.mjs → request-trace-BgNykH9M.mjs} +1 -5
  116. package/dist/{request-trace-C_fvIDv4.mjs.map → request-trace-BgNykH9M.mjs.map} +1 -1
  117. package/dist/{request-trace-wTJdKp6-.js → request-trace-ByujsUZk.js} +1 -5
  118. package/dist/{request-trace-wTJdKp6-.js.map → request-trace-ByujsUZk.js.map} +1 -1
  119. package/dist/{safe-stringify-BMRl3EX3.mjs → safe-stringify--7gbe95n.mjs} +37 -12
  120. package/dist/safe-stringify--7gbe95n.mjs.map +1 -0
  121. package/dist/{safe-stringify-DLz1Kz3o.js → safe-stringify-CN7icp8S.js} +37 -12
  122. package/dist/safe-stringify-CN7icp8S.js.map +1 -0
  123. package/dist/{search-DUfWuzFP.js → search-CRjhHxe9.js} +269 -25
  124. package/dist/search-CRjhHxe9.js.map +1 -0
  125. package/dist/{search-CazwyX5Z.d.ts → search-D-8HJADE.d.mts} +5 -2
  126. package/dist/search-D-8HJADE.d.mts.map +1 -0
  127. package/dist/{search-CWMVYC-R.mjs → search-DAXKE-P9.mjs} +269 -25
  128. package/dist/search-DAXKE-P9.mjs.map +1 -0
  129. package/dist/{search-BH33XhuU.d.mts → search-DPwTKPve.d.ts} +5 -2
  130. package/dist/search-DPwTKPve.d.ts.map +1 -0
  131. package/dist/search.d.mts +1 -1
  132. package/dist/search.d.ts +1 -1
  133. package/dist/search.js +1 -1
  134. package/dist/search.mjs +1 -1
  135. package/dist/{secret-config-CBZBs0p1.js → secret-config-BvFl2dC8.js} +7 -7
  136. package/dist/secret-config-BvFl2dC8.js.map +1 -0
  137. package/dist/{secret-config-BegMLkYl.mjs → secret-config-ByGq7kJd.mjs} +5 -5
  138. package/dist/secret-config-ByGq7kJd.mjs.map +1 -0
  139. package/dist/sensitive-names-CHMowujD.js +276 -0
  140. package/dist/sensitive-names-CHMowujD.js.map +1 -0
  141. package/dist/sensitive-names-o__1PUUR.mjs +217 -0
  142. package/dist/sensitive-names-o__1PUUR.mjs.map +1 -0
  143. package/dist/{slack.transport-DxHOXlLu.d.mts → slack.transport-BDyENuR0.d.mts} +2 -2
  144. package/dist/{slack.transport-DxHOXlLu.d.mts.map → slack.transport-BDyENuR0.d.mts.map} +1 -1
  145. package/dist/{slack.transport-DrirgDNy.d.ts → slack.transport-C6E0l4kw.d.ts} +2 -2
  146. package/dist/{slack.transport-DrirgDNy.d.ts.map → slack.transport-C6E0l4kw.d.ts.map} +1 -1
  147. package/dist/{slack.transport-Ce96JBDk.mjs → slack.transport-CSj1j0_X.mjs} +66 -15
  148. package/dist/slack.transport-CSj1j0_X.mjs.map +1 -0
  149. package/dist/{slack.transport-Dlx3xvb7.js → slack.transport-zLQ9MGxS.js} +67 -16
  150. package/dist/slack.transport-zLQ9MGxS.js.map +1 -0
  151. package/dist/testing.d.mts +11 -4
  152. package/dist/testing.d.mts.map +1 -1
  153. package/dist/testing.d.ts +11 -4
  154. package/dist/testing.d.ts.map +1 -1
  155. package/dist/testing.js +38 -3
  156. package/dist/testing.js.map +1 -1
  157. package/dist/testing.mjs +38 -3
  158. package/dist/testing.mjs.map +1 -1
  159. package/dist/{transport.types-BJVL1QQl.d.ts → transport.types-CzJq4IrF.d.mts} +14 -3
  160. package/dist/transport.types-CzJq4IrF.d.mts.map +1 -0
  161. package/dist/{transport.types-BJVL1QQl.d.mts → transport.types-CzJq4IrF.d.ts} +14 -3
  162. package/dist/transport.types-CzJq4IrF.d.ts.map +1 -0
  163. package/dist/transports.d.mts +25 -13
  164. package/dist/transports.d.mts.map +1 -1
  165. package/dist/transports.d.ts +25 -13
  166. package/dist/transports.d.ts.map +1 -1
  167. package/dist/transports.js +15 -15
  168. package/dist/transports.mjs +6 -6
  169. package/dist/worker-entry.js +130 -25
  170. package/dist/worker.d.mts +1 -1
  171. package/dist/worker.d.ts +1 -1
  172. package/dist/worker.js +1 -1
  173. package/dist/worker.mjs +1 -1
  174. package/dist/{worker.transport-BuPwBi3d.d.ts → worker.transport-B9mCQSM1.d.ts} +7 -2
  175. package/dist/worker.transport-B9mCQSM1.d.ts.map +1 -0
  176. package/dist/{worker.transport-hJay1wxA.d.mts → worker.transport-Bl8lFRck.d.mts} +7 -2
  177. package/dist/worker.transport-Bl8lFRck.d.mts.map +1 -0
  178. package/dist/{worker.transport-DLVA4y2e.mjs → worker.transport-D78xhNhB.mjs} +13 -10
  179. package/dist/worker.transport-D78xhNhB.mjs.map +1 -0
  180. package/dist/{worker.transport-C6GNl_r2.js → worker.transport-DQDv1nAJ.js} +13 -10
  181. package/dist/worker.transport-DQDv1nAJ.js.map +1 -0
  182. package/package.json +33 -65
  183. package/dist/async-context-B05ArHgM.mjs.map +0 -1
  184. package/dist/async-context-DTQgi8f7.js.map +0 -1
  185. package/dist/azure-monitor.transport-BPbgjATu.mjs.map +0 -1
  186. package/dist/azure-monitor.transport-CwbOLZHB.js.map +0 -1
  187. package/dist/builder-D70z6kjj.mjs.map +0 -1
  188. package/dist/builder-M7NoaugM.js.map +0 -1
  189. package/dist/cloudwatch.transport-B2wKQFF7.js.map +0 -1
  190. package/dist/cloudwatch.transport-BTvYfLs9.mjs.map +0 -1
  191. package/dist/entry-fields-CGuvT2R0.mjs.map +0 -1
  192. package/dist/entry-fields-RLd1jCoR.js.map +0 -1
  193. package/dist/gcp.transport-CGKopAhQ.mjs.map +0 -1
  194. package/dist/gcp.transport-KZe9hCAR.js.map +0 -1
  195. package/dist/index-DwozbmB4.d.ts.map +0 -1
  196. package/dist/index-xqaJtAZn.d.mts.map +0 -1
  197. package/dist/internal-log-b0Vp4qrB.js.map +0 -1
  198. package/dist/internal-log-uCSd1PMc.mjs.map +0 -1
  199. package/dist/logitron-logger-D2B75Oc7.d.ts.map +0 -1
  200. package/dist/logitron-logger-oEd6wNhf.d.mts.map +0 -1
  201. package/dist/safe-stringify-BMRl3EX3.mjs.map +0 -1
  202. package/dist/safe-stringify-DLz1Kz3o.js.map +0 -1
  203. package/dist/search-BH33XhuU.d.mts.map +0 -1
  204. package/dist/search-CWMVYC-R.mjs.map +0 -1
  205. package/dist/search-CazwyX5Z.d.ts.map +0 -1
  206. package/dist/search-DUfWuzFP.js.map +0 -1
  207. package/dist/secret-config-BegMLkYl.mjs.map +0 -1
  208. package/dist/secret-config-CBZBs0p1.js.map +0 -1
  209. package/dist/slack.transport-Ce96JBDk.mjs.map +0 -1
  210. package/dist/slack.transport-Dlx3xvb7.js.map +0 -1
  211. package/dist/transport.manager-DkcEOlqV.js.map +0 -1
  212. package/dist/transport.manager-eZ_EeC00.mjs.map +0 -1
  213. package/dist/transport.types-BJVL1QQl.d.mts.map +0 -1
  214. package/dist/transport.types-BJVL1QQl.d.ts.map +0 -1
  215. package/dist/worker.transport-BuPwBi3d.d.ts.map +0 -1
  216. package/dist/worker.transport-C6GNl_r2.js.map +0 -1
  217. package/dist/worker.transport-DLVA4y2e.mjs.map +0 -1
  218. package/dist/worker.transport-hJay1wxA.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.transport-DQDv1nAJ.js","names":["Worker","path"],"sources":["../src/transports/worker.transport.ts"],"sourcesContent":["/**\n * logixia — Worker Thread Transport\n *\n * Offloads JSON serialization and all I/O to a Node.js worker thread,\n * completely eliminating any event-loop impact from logging. The main thread\n * only posts a raw message to the worker — it never calls JSON.stringify or\n * any I/O syscalls on the hot path.\n *\n * Architecture:\n * Main thread → MessageChannel → Worker thread → Wrapped transport\n *\n * The worker runs an ordinary logixia transport (file, database, console…)\n * inside its own event loop. If the worker crashes it is restarted automatically\n * (up to `maxRestarts` times) and buffered messages are replayed.\n *\n * @example\n * ```ts\n * import { WorkerTransport } from 'logixia/worker';\n *\n * const logger = createLogger({\n * transports: {\n * // Run file transport inside a worker thread — zero event-loop impact\n * custom: [\n * new WorkerTransport({\n * transportType: 'file',\n * transportConfig: { filename: 'app.log', dirname: './logs' },\n * bufferSize: 500,\n * maxRestarts: 3,\n * }),\n * ],\n * },\n * });\n * ```\n */\n\nimport path from 'node:path';\nimport { Worker } from 'node:worker_threads';\n\nimport type { ITransport, TransportLogEntry } from '../types/transport.types';\nimport { internalError, internalWarn } from '../utils/internal-log';\nimport { protectSecrets } from './secret-config';\n\nexport interface WorkerTransportConfig {\n /**\n * Which built-in logixia transport to run inside the worker thread.\n * The worker resolves the correct module automatically.\n */\n transportType: 'file' | 'database' | 'console';\n /** Config forwarded verbatim to the wrapped transport constructor. */\n transportConfig: Record<string, unknown>;\n /**\n * Max log entries to buffer in the main thread while the worker is starting\n * or restarting. Entries beyond this limit are dropped with a warning.\n * @default 1000\n */\n bufferSize?: number;\n /**\n * How many times to restart the worker if it crashes unexpectedly.\n * @default 3\n */\n maxRestarts?: number;\n /**\n * Custom level severities (`levelOptions.levels`) the wrapped transport's own\n * `level` is compared against inside the worker. Built-in levels need no entry.\n */\n levels?: Record<string, number>;\n /**\n * Log level filter — only entries at or above this level are forwarded.\n * Useful for routing only errors to an expensive transport in a worker.\n */\n level?: string;\n}\n\n/**\n * Transport that runs a wrapped transport inside a dedicated Node.js worker\n * thread, completely removing JSON serialization and I/O from the main event loop.\n */\nexport class WorkerTransport implements ITransport {\n public readonly name = 'worker';\n public readonly level: string | undefined;\n public readonly batchSize = 1;\n public readonly flushInterval = 0;\n\n private worker: Worker | null = null;\n private ready = false;\n private readonly buffer: TransportLogEntry[] = [];\n private readonly bufferSize: number;\n private restarts = 0;\n private readonly maxRestarts: number;\n private readonly config: WorkerTransportConfig;\n /** Pending restart-backoff timer, so close() can cancel a queued restart. */\n private restartTimer: NodeJS.Timeout | null = null;\n /** Set once close() begins, so a worker 'exit' no longer triggers a restart. */\n private closing = false;\n /** Max time to wait for the worker's 'flushed' ack before giving up. */\n private readonly FLUSH_TIMEOUT_MS = 5000;\n /** Max time to wait for a graceful worker exit before force-terminating. */\n private readonly SHUTDOWN_TIMEOUT_MS = 5000;\n\n constructor(config: WorkerTransportConfig) {\n this.config = config;\n this.bufferSize = config.bufferSize ?? 1000;\n this.maxRestarts = config.maxRestarts ?? 3;\n this.level = config.level;\n protectSecrets(this, ['config']);\n this.startWorker();\n }\n\n private startWorker(): void {\n try {\n this.worker = new Worker(this.workerFile(), {\n workerData: {\n transportType: this.config.transportType,\n transportConfig: this.config.transportConfig,\n levels: this.config.levels,\n },\n });\n\n this.worker.on('message', (msg: { type: string; error?: string }) => {\n if (msg.type === 'ready') {\n this.ready = true;\n this.drainBuffer();\n } else if (msg.type === 'error' || msg.type === 'write-error') {\n internalError(\n `WorkerTransport [${this.config.transportType}]: ${msg.error ?? 'unknown'}`\n );\n }\n });\n\n this.worker.on('error', (err) => {\n internalError('WorkerTransport worker error', err);\n this.handleWorkerExit();\n });\n\n this.worker.on('exit', (code) => {\n if (code !== 0) {\n internalWarn(`WorkerTransport worker exited with code ${code}`);\n this.handleWorkerExit();\n }\n });\n } catch (err) {\n internalError('WorkerTransport failed to start', err);\n }\n }\n\n /** The worker entry is always built as CommonJS, next to this module's output. */\n protected workerFile(): string {\n return path.join(__dirname, 'worker-entry.js');\n }\n\n private handleWorkerExit(): void {\n this.ready = false;\n // Don't resurrect a worker we're intentionally shutting down — close() sets\n // `closing` and nulls the worker, so a late 'exit'/'error' event must not\n // queue a restart (which would spawn a fresh leaked thread post-shutdown).\n if (this.closing) return;\n if (this.restarts < this.maxRestarts) {\n this.restarts++;\n internalWarn(`WorkerTransport restarting (attempt ${this.restarts}/${this.maxRestarts})`);\n // Small backoff before restart. unref() so a perpetually-failing worker's\n // pending restart never keeps the process alive on its own.\n this.restartTimer = setTimeout(() => {\n this.restartTimer = null;\n this.startWorker();\n }, 500 * this.restarts);\n if (this.restartTimer.unref) this.restartTimer.unref();\n } else {\n internalError(\n `WorkerTransport exhausted ${this.maxRestarts} restart attempts — transport disabled`\n );\n }\n }\n\n private drainBuffer(): void {\n while (this.buffer.length > 0 && this.ready && this.worker) {\n const entry = this.buffer.shift();\n if (entry) {\n this.worker.postMessage({ type: 'write', entry });\n }\n }\n }\n\n write(entry: TransportLogEntry): void {\n if (this.ready && this.worker) {\n this.worker.postMessage({ type: 'write', entry });\n } else {\n if (this.buffer.length >= this.bufferSize) {\n internalWarn('WorkerTransport buffer full — dropping oldest entry');\n this.buffer.shift();\n }\n this.buffer.push(entry);\n }\n }\n\n async flush(): Promise<void> {\n if (!this.ready || !this.worker) return;\n const worker = this.worker;\n return new Promise<void>((resolve) => {\n // Time-box the flush: if the worker dies or restarts before answering,\n // the 'flushed' message would never arrive and this promise would hang\n // forever, blocking shutdown until the force-exit timer kills the process\n // (losing everything). Resolve on timeout so close() can still terminate.\n const timer = setTimeout(() => {\n worker.off('message', handler);\n resolve();\n }, this.FLUSH_TIMEOUT_MS);\n if (timer.unref) timer.unref();\n\n const handler = (msg: { type: string }) => {\n if (msg.type === 'flushed') {\n clearTimeout(timer);\n worker.off('message', handler);\n resolve();\n }\n };\n worker.on('message', handler);\n worker.postMessage({ type: 'flush' });\n });\n }\n\n /**\n * Flush the worker's buffer and terminate the thread on shutdown.\n *\n * This MUST be named close() — TransportManager.close() invokes\n * transport.close(), so a method named only shutdown() was never called on\n * graceful exit, leaking the worker thread and dropping its buffered logs.\n */\n async close(): Promise<void> {\n // Stop the restart loop first: cancel any queued backoff restart and flag\n // that further worker exits are expected (so handleWorkerExit no-ops).\n this.closing = true;\n if (this.restartTimer) {\n clearTimeout(this.restartTimer);\n this.restartTimer = null;\n }\n\n if (!this.worker) return;\n const worker = this.worker;\n this.worker = null;\n\n // Push any locally-buffered (pre-ready) entries first: the worker's port\n // queues them until its listener attaches, so they are handled before the\n // shutdown message, which flushes the wrapped transport and exits.\n this.drainBufferTo(worker);\n worker.postMessage({ type: 'shutdown' });\n\n await new Promise<void>((resolve) => {\n // Don't wait forever for a wedged worker — terminate() it after a timeout.\n const timer = setTimeout(() => {\n worker.terminate().finally(() => resolve());\n }, this.SHUTDOWN_TIMEOUT_MS);\n if (timer.unref) timer.unref();\n\n worker.once('exit', () => {\n clearTimeout(timer);\n resolve();\n });\n });\n }\n\n /** Back-compat alias — prefer close(). */\n async shutdown(): Promise<void> {\n await this.close();\n }\n\n private drainBufferTo(worker: Worker): void {\n while (this.buffer.length > 0) {\n const entry = this.buffer.shift();\n if (ent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,KAAK;KAClB,OAAO,IAAI,WAAW,OAAO;KAC7B,QAAQ;IACV;GACF;GACA,OAAO,GAAG,WAAW,OAAO;GAC5B,OAAO,YAAY,EAAE,MAAM,QAAQ,CAAC;EACtC,CAAC;CACH;;;;;;;;CASA,MAAM,QAAuB;EAG3B,KAAK,UAAU;EACf,IAAI,KAAK,cAAc;GACrB,aAAa,KAAK,YAAY;GAC9B,KAAK,eAAe;EACtB;EAEA,IAAI,CAAC,KAAK,QAAQ;EAClB,MAAM,SAAS,KAAK;EACpB,KAAK,SAAS;EAKd,KAAK,cAAc,MAAM;EACzB,OAAO,YAAY,EAAE,MAAM,WAAW,CAAC;EAEvC,MAAM,IAAI,SAAe,YAAY;GAEnC,MAAM,QAAQ,iBAAiB;IAC7B,OAAO,UAAU,CAAC,CAAC,cAAc,QAAQ,CAAC;GAC5C,GAAG,KAAK,mBAAmB;GAC3B,IAAI,MAAM,OAAO,MAAM,MAAM;GAE7B,OAAO,KAAK,cAAc;IACxB,aAAa,KAAK;IAClB,QAAQ;GACV,CAAC;EACH,CAAC;CACH;;CAGA,MAAM,WAA0B;EAC9B,MAAM,KAAK,MAAM;CACnB;CAEA,cAAsB,QAAsB;EAC1C,OAAO,KAAK,OAAO,SAAS,GAAG;GAC7B,MAAM,QAAQ,KAAK,OAAO,MAAM;GAChC,IAAI,OAAO,OAAO,YAAY;IAAE,MAAM;IAAS;GAAM,CAAC;EACxD;CACF;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "logixia",
3
- "version": "2.0.4",
4
- "description": "Async-first TypeScript logger: wide events / canonical log lines, OTLP OpenTelemetry export, runtime log levels, redaction, adaptive sampling, NestJS, multi-transport (file, DB, cloud), tracing & log search. A fast Winston/Pino alternative.",
3
+ "version": "2.0.7",
4
+ "description": "Async-first TypeScript logger for Node, NestJS and the edge: request tracing, redaction, OpenTelemetry/OTLP export, file/database/cloud transports, sampling and log search. Winston/Pino alternative.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
7
7
  "types": "dist/index.d.ts",
@@ -151,6 +151,7 @@
151
151
  "format:check": "prettier --check .",
152
152
  "typecheck": "tsc --noEmit",
153
153
  "typecheck:examples": "tsc -p tsconfig.examples.json && tsc -p examples/cloudflare-worker/tsconfig.json",
154
+ "typecheck:consumer": "npm run build && tsc -p tests/consumer/tsconfig.json",
154
155
  "typecheck:express4": "node scripts/typecheck-express4.mjs",
155
156
  "check": "npm run typecheck && npm run lint:check",
156
157
  "ci": "npm run typecheck && npm run lint:check && npm run test:ci",
@@ -181,81 +182,41 @@
181
182
  "logging",
182
183
  "typescript",
183
184
  "typescript-logger",
185
+ "structured-logging",
186
+ "json-logging",
184
187
  "nestjs",
185
188
  "nestjs-logger",
186
- "nestjs-logging",
187
- "nestjs-module",
188
189
  "winston-alternative",
189
190
  "pino-alternative",
190
- "structured-logging",
191
- "json-logging",
192
- "custom-log-levels",
193
- "log-levels",
194
- "request-tracing",
191
+ "request-id",
195
192
  "trace-id",
196
- "opentelemetry",
197
- "w3c-trace-context",
198
- "multi-transport",
199
- "console-transport",
200
- "file-transport",
201
- "log-rotation",
202
- "database-logging",
203
- "mongodb-logger",
204
- "postgresql-logger",
205
- "analytics-logging",
206
- "datadog",
207
- "mixpanel",
208
- "segment",
209
- "log-search",
210
- "log-analysis",
211
- "log-aggregation",
212
- "nodejs",
213
- "bun",
214
- "express",
215
- "microservices",
193
+ "request-tracing",
194
+ "correlation-id",
216
195
  "distributed-tracing",
217
- "observability",
218
- "developer-tools",
219
- "enterprise-logging",
220
- "wide-events",
221
- "canonical-log-lines",
222
- "observability-2.0",
196
+ "opentelemetry",
223
197
  "otlp",
224
- "otlp-logs",
225
- "opentelemetry-logs",
226
- "otel-logs",
227
- "log-correlation",
228
- "trace-log-correlation",
229
- "log-redaction",
198
+ "w3c-trace-context",
199
+ "redaction",
230
200
  "pii-redaction",
231
- "secret-redaction",
232
201
  "log-sampling",
233
- "adaptive-sampling",
234
- "dynamic-log-level",
235
- "runtime-log-level",
236
- "prometheus",
237
- "metrics",
238
- "prometheus-metrics",
239
- "graceful-shutdown",
240
- "flush-on-exit",
202
+ "log-levels",
203
+ "wide-events",
204
+ "express",
205
+ "fastify",
206
+ "cloudflare-workers",
207
+ "edge",
208
+ "browser-logger",
209
+ "datadog",
241
210
  "cloudwatch",
242
211
  "gcp-logging",
243
212
  "azure-monitor",
244
- "fastify",
245
- "fastify-logger",
246
- "fastify-logging",
247
- "browser-logger",
248
- "edge-logging",
249
- "correlation-id",
250
- "async-logger",
251
- "non-blocking-logger",
252
- "fast-logger",
253
- "high-performance-logging",
254
- "log-management",
255
- "structured-logs",
256
- "json-logger",
257
- "typescript-logging",
258
- "bunyan-alternative"
213
+ "slack",
214
+ "discord",
215
+ "database-logging",
216
+ "log-rotation",
217
+ "log-search",
218
+ "prometheus",
219
+ "observability"
259
220
  ],
260
221
  "author": {
261
222
  "name": "Sanjeev Sharma",
@@ -284,6 +245,7 @@
284
245
  ],
285
246
  "peerDependencies": {
286
247
  "@nestjs/common": "^10.0.0 || ^11.0.0",
248
+ "@opentelemetry/api": "^1.0.0",
287
249
  "express": "^4.0.0 || ^5.0.0",
288
250
  "reflect-metadata": "^0.1.13 || ^0.2.0"
289
251
  },
@@ -291,6 +253,9 @@
291
253
  "@nestjs/common": {
292
254
  "optional": true
293
255
  },
256
+ "@opentelemetry/api": {
257
+ "optional": true
258
+ },
294
259
  "express": {
295
260
  "optional": true
296
261
  },
@@ -310,6 +275,9 @@
310
275
  "@nestjs/platform-express": "^11.1.17",
311
276
  "@nestjs/platform-socket.io": "^11.1.17",
312
277
  "@nestjs/websockets": "^11.1.17",
278
+ "@opentelemetry/api": "1.9.1",
279
+ "@opentelemetry/context-async-hooks": "3.0.0",
280
+ "@opentelemetry/sdk-trace-base": "2.12.0",
313
281
  "@semantic-release/commit-analyzer": "13.0.1",
314
282
  "@semantic-release/github": "12.0.10",
315
283
  "@semantic-release/npm": "13.2.0",
@@ -1 +0,0 @@
1
- {"version":3,"file":"async-context-B05ArHgM.mjs","names":[],"sources":["../src/context/async-context.ts"],"sourcesContent":["/**\n * LogixiaContext — Zero-boilerplate AsyncLocalStorage context propagation.\n *\n * Lets every `logger.info()` call inside a context automatically pick up stored\n * fields (requestId, userId, tenantId, …) without passing them through every function.\n *\n * Works across `Promise.all`, `setTimeout`, and event emitters — anything that\n * inherits the async execution context.\n *\n * @example\n * ```ts\n * import { LogixiaContext } from 'logixia';\n *\n * // Wrap a request handler:\n * app.use((req, res, next) => {\n * LogixiaContext.run({ requestId: req.id, userId: req.user?.id }, next);\n * });\n *\n * // Anywhere deeper in the call tree:\n * async function processOrder(orderId: string) {\n * const ctx = LogixiaContext.get(); // { requestId, userId, orderId }\n * logger.info('Processing order', { orderId, ...ctx });\n * }\n * ```\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nimport {\n type ContextRequestLike,\n resolveRequestTraceId,\n resolveTraceHeaders,\n type TraceHeaderOption,\n} from '../utils/request-trace';\nimport { TraceContext } from '../utils/trace.utils';\n\nexport interface LogContext {\n traceId?: string;\n spanId?: string;\n userId?: string;\n tenantId?: string;\n sessionId?: string;\n [key: string]: unknown;\n}\n\n// Module-level singleton so all loggers share the same ALS store.\nconst _storage = new AsyncLocalStorage<LogContext>();\n\nexport const LogixiaContext = {\n /**\n * Run `callback` inside an async context that carries `store` fields.\n * All loggers queried within `callback` (and its async descendants) will\n * automatically see these fields.\n *\n * @example\n * ```ts\n * LogixiaContext.run({ requestId: 'abc', userId: '42' }, async () => {\n * await processOrder(); // sees requestId + userId in every log\n * });\n * ```\n */\n run<T>(store: LogContext, callback: () => T): T {\n const parent = _storage.getStore() ?? {};\n const scoped = (): T => _storage.run({ ...parent, ...store }, callback);\n const traceId = store.traceId;\n if (typeof traceId !== 'string' || traceId === '') return scoped();\n // An explicit traceId also becomes the TraceContext ID, so getCurrentTraceId(),\n // the logger, outbound propagation and the OTel bridge all see the same value.\n const trace = TraceContext.instance;\n return trace.storage.run({ ...trace.storage.getStore(), [trace.contextKey]: traceId }, scoped);\n },\n\n /**\n * Return the context fields active in the current async scope.\n * Returns `undefined` when called outside any `LogixiaContext.run()`.\n */\n get(): LogContext | undefined {\n return _storage.getStore();\n },\n\n /**\n * Merge `fields` into the **existing** context for the current scope.\n * If called outside a `run()` context this is a no-op (logs a dev warning).\n */\n set(fields: Partial<LogContext>): void {\n const store = _storage.getStore();\n if (!store) {\n // Silently ignore — avoids crashing in code that may call setContext\n // before a request context is established (e.g. background jobs).\n return;\n }\n for (const key of Object.keys(fields)) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;\n store[key] = fields[key];\n }\n },\n\n /**\n * Retrieve the underlying `AsyncLocalStorage` instance.\n * Useful for advanced use-cases like custom middleware.\n */\n getStorage(): AsyncLocalStorage<LogContext> {\n return _storage;\n },\n};\n\nexport type { ContextRequestLike };\n\ninterface ContextHelperOptions<Req extends ContextRequestLike> {\n /**\n * Extract additional fields from the request. A `traceId` returned here is ignored:\n * the resolved request trace ID always wins.\n */\n enrich?: (request: Req & Record<string, unknown>) => Partial<LogContext>;\n /**\n * Header name, or list of names tried in order, to read the trace ID from.\n * Default: `DEFAULT_TRACE_HEADERS` (traceparent is parsed to its 32-hex trace id).\n */\n traceIdHeader?: TraceHeaderOption;\n /**\n * Echo the resolved trace ID on the response under this header name.\n * Default: `false` (no response header is set).\n */\n responseHeader?: string | false;\n}\n\nfunction buildScope<Req extends ContextRequestLike>(\n request: Req,\n options: ContextHelperOptions<Req>,\n headers: readonly string[]\n): LogContext {\n const extra = options.enrich ? options.enrich(request as Req & Record<string, unknown>) : {};\n return { ...extra, traceId: resolveRequestTraceId(request, headers) };\n}\n\n/**\n * Create an Express/Connect-compatible middleware that wraps each request in\n * a `LogixiaContext.run()` scope populated with common request fields.\n *\n * Trace ID: the first present header of `traceIdHeader` (default\n * `DEFAULT_TRACE_HEADERS`, `traceparent` parsed), else `request.id`, else a\n * generated UUID. It is available via `getCurrentTraceId()` and is the logger's\n * top-level `traceId` inside the request. No response header is set unless\n * `responseHeader` is given.\n *\n * @example\n * ```ts\n * import { createExpressContextMiddleware } from 'logixia';\n * app.use(createExpressContextMiddleware({ responseHeader: 'x-trace-id' }));\n * ```\n */\nexport function createExpressContextMiddleware<Req extends ContextRequestLike = ContextRequestLike>(\n options: ContextHelperOptions<Req> = {}\n) {\n const headers = resolveTraceHeaders(options.traceIdHeader);\n\n return function logixiaContextMiddleware(\n req: Req,\n res: { setHeader?: (name: string, value: string) => unknown },\n next: () => void\n ): void {\n const scope = buildScope(req, options, headers);\n if (options.responseHeader) res.setHeader?.(options.responseHeader, scope.traceId as string);\n LogixiaContext.run(scope, next);\n };\n}\n\n/**\n * Create a Fastify lifecycle hook that wraps each request in a context scope.\n *\n * Register with `fastify.addHook('onRequest', createFastifyContextHook())`.\n * Resolves the trace ID exactly like {@link createExpressContextMiddleware} and\n * shares it with `createFastifyPlugin()` from `logixia/middleware`. Fastify's\n * default counter `request.id` (`req-1`, ...) is never used as a trace ID.\n */\nexport function createFastifyContextHook<Req extends ContextRequestLike = ContextRequestLike>(\n options: ContextHelperOptions<Req> = {}\n) {\n const headers = resolveTraceHeaders(options.traceIdHeader);\n\n return function logixiaFastifyHook(\n request: Req,\n reply: { header?: (name: string, value: string) => unknown },\n done: () => void\n ): void {\n const scope = buildScope(request, options, headers);\n if (options.responseHeader) reply.header?.(options.responseHeader, scope.traceId as string);\n LogixiaContext.run(scope, done);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,WAAW,IAAI,kBAA8B;AAEnD,MAAa,iBAAiB;;;;;;;;;;;;;CAa5B,IAAO,OAAmB,UAAsB;EAC9C,MAAM,SAAS,SAAS,SAAS,KAAK,CAAC;EACvC,MAAM,eAAkB,SAAS,IAAI;GAAE,GAAG;GAAQ,GAAG;EAAM,GAAG,QAAQ;EACtE,MAAM,UAAU,MAAM;EACtB,IAAI,OAAO,YAAY,YAAY,YAAY,IAAI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,MAAM,OAAiB;EAC1F,eAAe,IAAI,OAAO,IAAI;CAChC;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"async-context-DTQgi8f7.js","names":["AsyncLocalStorage","TraceContext","resolveRequestTraceId","resolveTraceHeaders"],"sources":["../src/context/async-context.ts"],"sourcesContent":["/**\n * LogixiaContext — Zero-boilerplate AsyncLocalStorage context propagation.\n *\n * Lets every `logger.info()` call inside a context automatically pick up stored\n * fields (requestId, userId, tenantId, …) without passing them through every function.\n *\n * Works across `Promise.all`, `setTimeout`, and event emitters — anything that\n * inherits the async execution context.\n *\n * @example\n * ```ts\n * import { LogixiaContext } from 'logixia';\n *\n * // Wrap a request handler:\n * app.use((req, res, next) => {\n * LogixiaContext.run({ requestId: req.id, userId: req.user?.id }, next);\n * });\n *\n * // Anywhere deeper in the call tree:\n * async function processOrder(orderId: string) {\n * const ctx = LogixiaContext.get(); // { requestId, userId, orderId }\n * logger.info('Processing order', { orderId, ...ctx });\n * }\n * ```\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nimport {\n type ContextRequestLike,\n resolveRequestTraceId,\n resolveTraceHeaders,\n type TraceHeaderOption,\n} from '../utils/request-trace';\nimport { TraceContext } from '../utils/trace.utils';\n\nexport interface LogContext {\n traceId?: string;\n spanId?: string;\n userId?: string;\n tenantId?: string;\n sessionId?: string;\n [key: string]: unknown;\n}\n\n// Module-level singleton so all loggers share the same ALS store.\nconst _storage = new AsyncLocalStorage<LogContext>();\n\nexport const LogixiaContext = {\n /**\n * Run `callback` inside an async context that carries `store` fields.\n * All loggers queried within `callback` (and its async descendants) will\n * automatically see these fields.\n *\n * @example\n * ```ts\n * LogixiaContext.run({ requestId: 'abc', userId: '42' }, async () => {\n * await processOrder(); // sees requestId + userId in every log\n * });\n * ```\n */\n run<T>(store: LogContext, callback: () => T): T {\n const parent = _storage.getStore() ?? {};\n const scoped = (): T => _storage.run({ ...parent, ...store }, callback);\n const traceId = store.traceId;\n if (typeof traceId !== 'string' || traceId === '') return scoped();\n // An explicit traceId also becomes the TraceContext ID, so getCurrentTraceId(),\n // the logger, outbound propagation and the OTel bridge all see the same value.\n const trace = TraceContext.instance;\n return trace.storage.run({ ...trace.storage.getStore(), [trace.contextKey]: traceId }, scoped);\n },\n\n /**\n * Return the context fields active in the current async scope.\n * Returns `undefined` when called outside any `LogixiaContext.run()`.\n */\n get(): LogContext | undefined {\n return _storage.getStore();\n },\n\n /**\n * Merge `fields` into the **existing** context for the current scope.\n * If called outside a `run()` context this is a no-op (logs a dev warning).\n */\n set(fields: Partial<LogContext>): void {\n const store = _storage.getStore();\n if (!store) {\n // Silently ignore — avoids crashing in code that may call setContext\n // before a request context is established (e.g. background jobs).\n return;\n }\n for (const key of Object.keys(fields)) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;\n store[key] = fields[key];\n }\n },\n\n /**\n * Retrieve the underlying `AsyncLocalStorage` instance.\n * Useful for advanced use-cases like custom middleware.\n */\n getStorage(): AsyncLocalStorage<LogContext> {\n return _storage;\n },\n};\n\nexport type { ContextRequestLike };\n\ninterface ContextHelperOptions<Req extends ContextRequestLike> {\n /**\n * Extract additional fields from the request. A `traceId` returned here is ignored:\n * the resolved request trace ID always wins.\n */\n enrich?: (request: Req & Record<string, unknown>) => Partial<LogContext>;\n /**\n * Header name, or list of names tried in order, to read the trace ID from.\n * Default: `DEFAULT_TRACE_HEADERS` (traceparent is parsed to its 32-hex trace id).\n */\n traceIdHeader?: TraceHeaderOption;\n /**\n * Echo the resolved trace ID on the response under this header name.\n * Default: `false` (no response header is set).\n */\n responseHeader?: string | false;\n}\n\nfunction buildScope<Req extends ContextRequestLike>(\n request: Req,\n options: ContextHelperOptions<Req>,\n headers: readonly string[]\n): LogContext {\n const extra = options.enrich ? options.enrich(request as Req & Record<string, unknown>) : {};\n return { ...extra, traceId: resolveRequestTraceId(request, headers) };\n}\n\n/**\n * Create an Express/Connect-compatible middleware that wraps each request in\n * a `LogixiaContext.run()` scope populated with common request fields.\n *\n * Trace ID: the first present header of `traceIdHeader` (default\n * `DEFAULT_TRACE_HEADERS`, `traceparent` parsed), else `request.id`, else a\n * generated UUID. It is available via `getCurrentTraceId()` and is the logger's\n * top-level `traceId` inside the request. No response header is set unless\n * `responseHeader` is given.\n *\n * @example\n * ```ts\n * import { createExpressContextMiddleware } from 'logixia';\n * app.use(createExpressContextMiddleware({ responseHeader: 'x-trace-id' }));\n * ```\n */\nexport function createExpressContextMiddleware<Req extends ContextRequestLike = ContextRequestLike>(\n options: ContextHelperOptions<Req> = {}\n) {\n const headers = resolveTraceHeaders(options.traceIdHeader);\n\n return function logixiaContextMiddleware(\n req: Req,\n res: { setHeader?: (name: string, value: string) => unknown },\n next: () => void\n ): void {\n const scope = buildScope(req, options, headers);\n if (options.responseHeader) res.setHeader?.(options.responseHeader, scope.traceId as string);\n LogixiaContext.run(scope, next);\n };\n}\n\n/**\n * Create a Fastify lifecycle hook that wraps each request in a context scope.\n *\n * Register with `fastify.addHook('onRequest', createFastifyContextHook())`.\n * Resolves the trace ID exactly like {@link createExpressContextMiddleware} and\n * shares it with `createFastifyPlugin()` from `logixia/middleware`. Fastify's\n * default counter `request.id` (`req-1`, ...) is never used as a trace ID.\n */\nexport function createFastifyContextHook<Req extends ContextRequestLike = ContextRequestLike>(\n options: ContextHelperOptions<Req> = {}\n) {\n const headers = resolveTraceHeaders(options.traceIdHeader);\n\n return function logixiaFastifyHook(\n request: Req,\n reply: { header?: (name: string, value: string) => unknown },\n done: () => void\n ): void {\n const scope = buildScope(request, options, headers);\n if (options.responseHeader) reply.header?.(options.responseHeader, scope.traceId as string);\n LogixiaContext.run(scope, done);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,WAAW,K,0BAAIA,EAAAA,CAAAA,kBAA8B;AAEnD,MAAa,iBAAiB;;;;;;;;;;;;;CAa5B,IAAO,OAAmB,UAAsB;EAC9C,MAAM,SAAS,SAAS,SAAS,KAAK,CAAC;EACvC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ACd,SACA,OACA,MACM;;EACN,MAAM,QAAQ,WAAW,SAAS,SAAS,OAAO;EAClD,IAAI,QAAQ,gBAAgB,CAAA,gBAAA,MAAM,YAAA,QAAA,kBAAA,KAAA,KAAA,cAAA,KAAA,OAAS,QAAQ,gBAAgB,MAAM,OAAiB;EAC1F,eAAe,IAAI,OAAO,IAAI;CAChC;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"azure-monitor.transport-BPbgjATu.mjs","names":[],"sources":["../src/transports/azure-monitor.transport.ts"],"sourcesContent":["/**\n * logixia — Azure Monitor / Application Insights transport\n *\n * Sends log entries to Azure Monitor via the Data Collection Rules (DCR) API\n * using the Logs Ingestion API (the modern replacement for the legacy HTTP\n * Data Collector API).\n *\n * Maps logixia levels to Application Insights severity levels:\n * verbose → 0, debug → 1, info → 1, warn → 2, error → 3, critical → 4\n *\n * @example\n * ```ts\n * import { AzureMonitorTransport } from 'logixia';\n *\n * const logger = createLogger({\n * transports: {\n * azure: new AzureMonitorTransport({\n * // Logs Ingestion API endpoint (from your DCR)\n * endpoint: 'https://<dce>.ingest.monitor.azure.com',\n * ruleId: 'dcr-xxxxxxxxxxxxxxxx',\n * streamName: 'Custom-LogixiaLogs',\n * // Client credentials (or managed identity via no-credential mode)\n * tenantId: process.env.AZURE_TENANT_ID,\n * clientId: process.env.AZURE_CLIENT_ID,\n * clientSecret: process.env.AZURE_CLIENT_SECRET,\n * }),\n * },\n * });\n * ```\n */\n\nimport type { IAsyncTransport, TransportLogEntry } from '../types/transport.types';\nimport { internalError, internalWarn } from '../utils/internal-log';\nimport { stringifyForLog } from '../utils/safe-stringify';\nimport {\n BatchBuffer,\n DEFAULT_MAX_BUFFER_SIZE,\n DEFAULT_REQUEST_TIMEOUT_MS,\n httpRequest,\n} from './batch-buffer';\nimport { protectSecrets, scrubError, scrubSecrets, urlSecrets } from './secret-config';\n\n/**\n * Azure AD tenant IDs are either a GUID or a verified domain (e.g. `contoso.onmicrosoft.com`).\n * This pattern is deliberately permissive on structure but strict on character\n * set — it rejects the breakout characters (`/`, `@`, `:`, `?`, `#`, whitespace)\n * that would let a hostile config smuggle a different host, path, or query into\n * the OAuth token URL.\n */\nconst AZURE_TENANT_RE = /^[a-z0-9][a-z0-9.-]{1,253}$/i;\n\nexport interface AzureMonitorTransportConfig {\n /** DCE (Data Collection Endpoint) URL, e.g. `https://<name>.ingest.monitor.azure.com`. */\n endpoint: string;\n /** Data Collection Rule immutable ID (from Azure portal). */\n ruleId: string;\n /** Stream name defined in the DCR, e.g. `'Custom-LogixiaLogs_CL'`. */\n streamName: string;\n /** Azure AD tenant ID for OAuth2 client-credentials flow. */\n tenantId?: string;\n /** Azure AD app (service principal) client ID. */\n clientId?: string;\n /** Azure AD app client secret. */\n clientSecret?: string;\n /** Number of entries to batch. @default 200 */\n batchSize?: number;\n /** Flush interval in ms. @default 5000 */\n flushIntervalMs?: number;\n /** Abort a request that has not finished after this many ms. @default 10000 */\n requestTimeoutMs?: number;\n /** Max buffered entries; the oldest are dropped past this. @default 10000 */\n maxBufferSize?: number;\n level?: string;\n}\n\nconst SEVERITY_MAP: Record<string, number> = {\n verbose: 0,\n trace: 0,\n debug: 1,\n info: 1,\n log: 1,\n warn: 2,\n warning: 2,\n error: 3,\n critical: 4,\n fatal: 4,\n};\n\n/**\n * Azure Monitor Logs Ingestion transport.\n */\nexport class AzureMonitorTransport implements IAsyncTransport {\n public readonly name = 'azure-monitor';\n public readonly batchSize: number;\n public readonly flushInterval: number;\n public readonly level: string | undefined;\n\n private readonly buffer: BatchBuffer<TransportLogEntry>;\n private readonly requestTimeoutMs: number;\n private flushTimer: NodeJS.Timeout | null = null;\n private accessToken: string | null = null;\n private tokenExpiry = 0;\n\n private readonly endpoint: string;\n private readonly ruleId: string;\n private readonly streamName: string;\n private readonly tenantId: string | undefined;\n private readonly clientId: string | undefined;\n private readonly clientSecret: string | undefined;\n\n constructor(config: AzureMonitorTransportConfig) {\n protectSecrets(this, ['clientSecret', 'accessToken']);\n this.endpoint = config.endpoint.replace(/\\/$/, '');\n this.ruleId = config.ruleId;\n this.streamName = config.streamName;\n this.tenantId = config.tenantId ?? process.env['AZURE_TENANT_ID'];\n this.clientId = config.clientId ?? process.env['AZURE_CLIENT_ID'];\n this.clientSecret = config.clientSecret ?? process.env['AZURE_CLIENT_SECRET'];\n this.batchSize = config.batchSize ?? 200;\n this.flushInterval = config.flushIntervalMs ?? 5000;\n this.level = config.level;\n this.requestTimeoutMs = config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n this.buffer = new BatchBuffer<TransportLogEntry>({\n name: 'AzureMonitorTransport',\n batchSize: this.batchSize,\n maxBufferSize: config.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE,\n send: (entries) => this.sendEntries(entries),\n secrets: () => this.secretValues(),\n });\n\n this.flushTimer = setInterval(() => {\n this.flush().catch(() => {});\n }, this.flushInterval);\n if (this.flushTimer.unref) this.flushTimer.unref();\n }\n\n write(entry: TransportLogEntry): void {\n this.buffer.push(entry);\n this.buffer.flushIfFull();\n }\n\n flush(): Promise<void> {\n return this.buffer.flush();\n }\n\n /**\n * Flush remaining entries and stop the interval timer on shutdown. Without\n * this the manager's close() skipped the transport (close was undefined) and\n * buffered entries were lost on deploy. Waits for any in-flight send first.\n */\n async close(): Promise<void> {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n await this.buffer.close();\n }\n\n private toAzureRecord(entry: TransportLogEntry): Record<string, unknown> {\n return {\n TimeGenerated: entry.timestamp ?? new Date().toISOString(),\n SeverityLevel: SEVERITY_MAP[entry.level.toLowerCase()] ?? 1,\n Message: entry.message,\n AppName: entry.appName,\n Context: entry.context ?? '',\n TraceId: entry.traceId ?? '',\n Properties: stringifyForLog(entry.data ?? {}),\n };\n }\n\n private secretValues(token?: string): (string | undefined)[] {\n return [this.clientSecret, this.accessToken ?? undefined, token, ...urlSecrets(this.endpoint)];\n }\n\n private async getAccessToken(): Promise<string | null> {\n if (this.accessToken && Date.now() < this.tokenExpiry) return this.accessToken;\n\n if (!this.tenantId || !this.clientId || !this.clientSecret) {\n internalWarn(\n 'AzureMonitorTransport: missing credentials — set tenantId, clientId, clientSecret'\n );\n return null;\n }\n\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret,\n scope: 'https://monitor.azure.com/.default',\n }).toString();\n\n const tenantId = this.tenantId;\n if (!AZURE_TENANT_RE.test(tenantId)) {\n internalWarn(\n `AzureMonitorTransport: refusing to request token — tenantId \"${tenantId}\" is not a valid GUID or domain`\n );\n return null;\n }\n\n const reqUrl = new URL(\n `https://login.microsoftonline.com/${encodeURIComponent(tenantId)}/oauth2/v2.0/token`\n );\n try {\n const res = await httpRequest({\n url: reqUrl,\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n timeoutMs: this.requestTimeoutMs,\n label: 'Azure token request',\n secrets: () => this.secretValues(),\n });\n const parsed = JSON.parse(res.body) as { access_token?: string; expires_in?: number };\n if (!parsed.access_token) return null;\n this.accessToken = parsed.access_token;\n this.tokenExpiry = Date.now() + (parsed.expires_in ?? 3600) * 1000 - 60_000;\n return this.accessToken;\n } catch (err) {\n internalError('AzureMonitorTransport token request failed', err);\n return null;\n }\n }\n\n private async sendEntries(entries: TransportLogEntry[]): Promise<void> {\n const token = await this.getAccessToken();\n if (!token) throw new Error('AzureMonitorTransport: no access token available');\n\n const records = entries.map((e) => this.toAzureRecord(e));\n const body = stringifyForLog(records);\n let reqUrl: URL;\n try {\n // Build from the user-configured DCE endpoint; encodeURIComponent-ing the\n // ruleId/streamName stops a hostile config from smuggling extra path\n // segments or query params into the request.\n reqUrl = new URL(\n `dataCollectionRules/${encodeURIComponent(this.ruleId)}/streams/${encodeURIComponent(this.streamName)}?api-version=2023-01-01`,\n this.endpoint.endsWith('/') ? this.endpoint : `${this.endpoint}/`\n );\n } catch (error) {\n internalError(\n `AzureMonitorTransport: invalid endpoint \"${scrubSecrets(this.endpoint, urlSecrets(this.endpoint))}\"`,\n scrubError(error, urlSecrets(this.endpoint))\n );\n return;\n }\n if (reqUrl.protocol !== 'https:') {\n internalError(`AzureMonitorTransport: endpoint must use https (got ${reqUrl.protocol})`);\n return;\n }\n\n await httpRequest({\n url: reqUrl,\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body,\n timeoutMs: this.requestTimeoutMs,\n label: 'Azure Monitor API',\n secrets: () => this.secretValues(token),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AAiDA,MAAM,kBAAkB;AA0BxB,MAAM,eAAuC;CAC3C,SAAS;CACT,OAAO;CACP,OAAO;CACP,MAAM;CACN,KAAK;CACL,MAAM;CACN,SAAS;CACT,OAAO;CACP,UAAU;CACV,OAAO;AACT;;;;AAKA,IAAa,wBAAb,MAA8D;CAmB5D,YAAY,QAAqC;EAlB1B,KAAA,OAAA;EAOqB,KAAA,aAAA;EACP,KAAA,cAAA;EACf,KAAA,cAAA;EAUpB,eAAe,MAAM,CAAC,gBAAgB,aAAa,CAAC;EACpD,KAAK,WAAW,OAAO,SAAS,QAAQ,OAAO,EAAE;EACjD,KAAK,SAAS,OAAO;EACrB,KAAK,aAAa,OAAO;EACzB,KAAK,WAAW,OAAO,YAAY,QAAQ,IAAI;EAC/C,KAAK,WAAW,OAAO,YAAY,QAAQ,IAAI;EAC/C,KAAK,eAAe,OAAO,gBAAgB,QAAQ,IAAI;EACvD,KAAK,YAAY,OAAO,aAAa;EACrC,KAAK,gBAAgB,OAAO,mBAAmB;EAC/C,KAAK,QAAQ,OAAO;EACpB,KAAK,mBAAmB,OAAO,oBAAA;EAC/B,KAAK,SAAS,IAAI,YAA+B;GAC/C,MAAM;GACN,WAAW,KAAK;GAChB,eAAe,OAAO,iBAAA;GACtB,OAAO,YAAY,KAAK,YAAY,OAAO;GAC3C,eAAe,KAAK,aAAa;EACnC,CAAC;EAED,KAAK,aAAa,kBAAkB;GAClC,KAAK,MAAM,CAAC,CAAC,YAA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{"version":3,"file":"azure-monitor.transport-CwbOLZHB.js","names":["BatchBuffer","stringifyForLog","urlSecrets","httpRequest","scrubSecrets","scrubError"],"sources":["../src/transports/azure-monitor.transport.ts"],"sourcesContent":["/**\n * logixia — Azure Monitor / Application Insights transport\n *\n * Sends log entries to Azure Monitor via the Data Collection Rules (DCR) API\n * using the Logs Ingestion API (the modern replacement for the legacy HTTP\n * Data Collector API).\n *\n * Maps logixia levels to Application Insights severity levels:\n * verbose → 0, debug → 1, info → 1, warn → 2, error → 3, critical → 4\n *\n * @example\n * ```ts\n * import { AzureMonitorTransport } from 'logixia';\n *\n * const logger = createLogger({\n * transports: {\n * azure: new AzureMonitorTransport({\n * // Logs Ingestion API endpoint (from your DCR)\n * endpoint: 'https://<dce>.ingest.monitor.azure.com',\n * ruleId: 'dcr-xxxxxxxxxxxxxxxx',\n * streamName: 'Custom-LogixiaLogs',\n * // Client credentials (or managed identity via no-credential mode)\n * tenantId: process.env.AZURE_TENANT_ID,\n * clientId: process.env.AZURE_CLIENT_ID,\n * clientSecret: process.env.AZURE_CLIENT_SECRET,\n * }),\n * },\n * });\n * ```\n */\n\nimport type { IAsyncTransport, TransportLogEntry } from '../types/transport.types';\nimport { internalError, internalWarn } from '../utils/internal-log';\nimport { stringifyForLog } from '../utils/safe-stringify';\nimport {\n BatchBuffer,\n DEFAULT_MAX_BUFFER_SIZE,\n DEFAULT_REQUEST_TIMEOUT_MS,\n httpRequest,\n} from './batch-buffer';\nimport { protectSecrets, scrubError, scrubSecrets, urlSecrets } from './secret-config';\n\n/**\n * Azure AD tenant IDs are either a GUID or a verified domain (e.g. `contoso.onmicrosoft.com`).\n * This pattern is deliberately permissive on structure but strict on character\n * set — it rejects the breakout characters (`/`, `@`, `:`, `?`, `#`, whitespace)\n * that would let a hostile config smuggle a different host, path, or query into\n * the OAuth token URL.\n */\nconst AZURE_TENANT_RE = /^[a-z0-9][a-z0-9.-]{1,253}$/i;\n\nexport interface AzureMonitorTransportConfig {\n /** DCE (Data Collection Endpoint) URL, e.g. `https://<name>.ingest.monitor.azure.com`. */\n endpoint: string;\n /** Data Collection Rule immutable ID (from Azure portal). */\n ruleId: string;\n /** Stream name defined in the DCR, e.g. `'Custom-LogixiaLogs_CL'`. */\n streamName: string;\n /** Azure AD tenant ID for OAuth2 client-credentials flow. */\n tenantId?: string;\n /** Azure AD app (service principal) client ID. */\n clientId?: string;\n /** Azure AD app client secret. */\n clientSecret?: string;\n /** Number of entries to batch. @default 200 */\n batchSize?: number;\n /** Flush interval in ms. @default 5000 */\n flushIntervalMs?: number;\n /** Abort a request that has not finished after this many ms. @default 10000 */\n requestTimeoutMs?: number;\n /** Max buffered entries; the oldest are dropped past this. @default 10000 */\n maxBufferSize?: number;\n level?: string;\n}\n\nconst SEVERITY_MAP: Record<string, number> = {\n verbose: 0,\n trace: 0,\n debug: 1,\n info: 1,\n log: 1,\n warn: 2,\n warning: 2,\n error: 3,\n critical: 4,\n fatal: 4,\n};\n\n/**\n * Azure Monitor Logs Ingestion transport.\n */\nexport class AzureMonitorTransport implements IAsyncTransport {\n public readonly name = 'azure-monitor';\n public readonly batchSize: number;\n public readonly flushInterval: number;\n public readonly level: string | undefined;\n\n private readonly buffer: BatchBuffer<TransportLogEntry>;\n private readonly requestTimeoutMs: number;\n private flushTimer: NodeJS.Timeout | null = null;\n private accessToken: string | null = null;\n private tokenExpiry = 0;\n\n private readonly endpoint: string;\n private readonly ruleId: string;\n private readonly streamName: string;\n private readonly tenantId: string | undefined;\n private readonly clientId: string | undefined;\n private readonly clientSecret: string | undefined;\n\n constructor(config: AzureMonitorTransportConfig) {\n protectSecrets(this, ['clientSecret', 'accessToken']);\n this.endpoint = config.endpoint.replace(/\\/$/, '');\n this.ruleId = config.ruleId;\n this.streamName = config.streamName;\n this.tenantId = config.tenantId ?? process.env['AZURE_TENANT_ID'];\n this.clientId = config.clientId ?? process.env['AZURE_CLIENT_ID'];\n this.clientSecret = config.clientSecret ?? process.env['AZURE_CLIENT_SECRET'];\n this.batchSize = config.batchSize ?? 200;\n this.flushInterval = config.flushIntervalMs ?? 5000;\n this.level = config.level;\n this.requestTimeoutMs = config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n this.buffer = new BatchBuffer<TransportLogEntry>({\n name: 'AzureMonitorTransport',\n batchSize: this.batchSize,\n maxBufferSize: config.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE,\n send: (entries) => this.sendEntries(entries),\n secrets: () => this.secretValues(),\n });\n\n this.flushTimer = setInterval(() => {\n this.flush().catch(() => {});\n }, this.flushInterval);\n if (this.flushTimer.unref) this.flushTimer.unref();\n }\n\n write(entry: TransportLogEntry): void {\n this.buffer.push(entry);\n this.buffer.flushIfFull();\n }\n\n flush(): Promise<void> {\n return this.buffer.flush();\n }\n\n /**\n * Flush remaining entries and stop the interval timer on shutdown. Without\n * this the manager's close() skipped the transport (close was undefined) and\n * buffered entries were lost on deploy. Waits for any in-flight send first.\n */\n async close(): Promise<void> {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n await this.buffer.close();\n }\n\n private toAzureRecord(entry: TransportLogEntry): Record<string, unknown> {\n return {\n TimeGenerated: entry.timestamp ?? new Date().toISOString(),\n SeverityLevel: SEVERITY_MAP[entry.level.toLowerCase()] ?? 1,\n Message: entry.message,\n AppName: entry.appName,\n Context: entry.context ?? '',\n TraceId: entry.traceId ?? '',\n Properties: stringifyForLog(entry.data ?? {}),\n };\n }\n\n private secretValues(token?: string): (string | undefined)[] {\n return [this.clientSecret, this.accessToken ?? undefined, token, ...urlSecrets(this.endpoint)];\n }\n\n private async getAccessToken(): Promise<string | null> {\n if (this.accessToken && Date.now() < this.tokenExpiry) return this.accessToken;\n\n if (!this.tenantId || !this.clientId || !this.clientSecret) {\n internalWarn(\n 'AzureMonitorTransport: missing credentials — set tenantId, clientId, clientSecret'\n );\n return null;\n }\n\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret,\n scope: 'https://monitor.azure.com/.default',\n }).toString();\n\n const tenantId = this.tenantId;\n if (!AZURE_TENANT_RE.test(tenantId)) {\n internalWarn(\n `AzureMonitorTransport: refusing to request token — tenantId \"${tenantId}\" is not a valid GUID or domain`\n );\n return null;\n }\n\n const reqUrl = new URL(\n `https://login.microsoftonline.com/${encodeURIComponent(tenantId)}/oauth2/v2.0/token`\n );\n try {\n const res = await httpRequest({\n url: reqUrl,\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n timeoutMs: this.requestTimeoutMs,\n label: 'Azure token request',\n secrets: () => this.secretValues(),\n });\n const parsed = JSON.parse(res.body) as { access_token?: string; expires_in?: number };\n if (!parsed.access_token) return null;\n this.accessToken = parsed.access_token;\n this.tokenExpiry = Date.now() + (parsed.expires_in ?? 3600) * 1000 - 60_000;\n return this.accessToken;\n } catch (err) {\n internalError('AzureMonitorTransport token request failed', err);\n return null;\n }\n }\n\n private async sendEntries(entries: TransportLogEntry[]): Promise<void> {\n const token = await this.getAccessToken();\n if (!token) throw new Error('AzureMonitorTransport: no access token available');\n\n const records = entries.map((e) => this.toAzureRecord(e));\n const body = stringifyForLog(records);\n let reqUrl: URL;\n try {\n // Build from the user-configured DCE endpoint; encodeURIComponent-ing the\n // ruleId/streamName stops a hostile config from smuggling extra path\n // segments or query params into the request.\n reqUrl = new URL(\n `dataCollectionRules/${encodeURIComponent(this.ruleId)}/streams/${encodeURIComponent(this.streamName)}?api-version=2023-01-01`,\n this.endpoint.endsWith('/') ? this.endpoint : `${this.endpoint}/`\n );\n } catch (error) {\n internalError(\n `AzureMonitorTransport: invalid endpoint \"${scrubSecrets(this.endpoint, urlSecrets(this.endpoint))}\"`,\n scrubError(error, urlSecrets(this.endpoint))\n );\n return;\n }\n if (reqUrl.protocol !== 'https:') {\n internalError(`AzureMonitorTransport: endpoint must use https (got ${reqUrl.protocol})`);\n return;\n }\n\n await httpRequest({\n url: reqUrl,\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body,\n timeoutMs: this.requestTimeoutMs,\n label: 'Azure Monitor API',\n secrets: () => this.secretValues(token),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AAiDA,MAAM,kBAAkB;AA0BxB,MAAM,eAAuC;CAC3C,SAAS;CACT,OAAO;CACP,OAAO;CACP,MAAM;CACN,KAAK;CACL,MAAM;CACN,SAAS;CACT,OAAO;CACP,UAAU;CACV,OAAO;AACT;;;;AAKA,IAAa,wBAAb,MAA8D;CAmB5D,YAAY,QAAqC;EAlB1B,KAAA,OAAA;EAOqB,KAAA,aAAA;EACP,KAAA,cAAA;EACf,KAAA,cAAA;EAUpB,sBAAA,eAAe,MAAM,CAAC,gBAAgB,aAAa,CAAC;EACpD,KAAK,WAAW,OAAO,SAAS,QAAQ,OAAO,EAAE;EACjD,KAAK,SAAS,OAAO;EACrB,KAAK,aAAa,OAAO;EACzB,KAAK,WAAW,OAAO,YAAY,QAAQ,IAAI;EAC/C,KAAK,WAAW,OAAO,YAAY,QAAQ,IAAI;EAC/C,KAAK,eAAe,OAAO,gBAAgB,QAAQ,IAAI;EACvD,KAAK,YAAY,OAAO,aAAa;EACrC,KAAK,gBAAgB,OAAO,mBAAmB;EAC/C,KAAK,QAAQ,OAAO;EACpB,KAAK,mBAAmB,OAAO,oBAAA;EAC/B,KAAK,SAAS,IAAIA,qBAAAA,YAA+B;GAC/C,MAAM;GACN,WAAW,KAAK;GAChB,eAAe,OAAO,iBAAA;GACtB,OAAO,YAAY,KAAK,YAAY,OAAO;GAC3C,eAAe,KAAK,aAAa;EACnC,CAAC;EAED,KAAK,aAAa,kBAAkB;GAClC,KAAK,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC;EAC7B,GAAG,KAAK,aAAa;EACrB,IAAI,KAAK,WAAW,OAAO,KAAK,WAAW,MAAM;CACnD;CAEA,MAAM,OAAgC;EACpC,KAAK,OAAO,KAAK,KAAK;EACtB,KAAK,OAAO,YAAY;CAC1B;CAEA,QAAu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