logquill 0.1.2 → 0.3.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.
package/dist/index.mjs CHANGED
@@ -1,7 +1,9 @@
1
+ import { createHash } from 'crypto';
2
+ import { gzipSync } from 'zlib';
1
3
  import { mkdirSync, openSync, writeSync, fstatSync, closeSync, existsSync, unlinkSync, renameSync } from 'fs';
2
4
  import { dirname } from 'path';
3
5
 
4
- // src/levels.ts
6
+ // src/core/levels.ts
5
7
  var Level = /* @__PURE__ */ ((Level2) => {
6
8
  Level2[Level2["TRACE"] = 5] = "TRACE";
7
9
  Level2[Level2["DEBUG"] = 10] = "DEBUG";
@@ -36,7 +38,7 @@ function parseLevel(level) {
36
38
  return level;
37
39
  }
38
40
 
39
- // src/records.ts
41
+ // src/core/records.ts
40
42
  function utcTimestamp() {
41
43
  return (/* @__PURE__ */ new Date()).toISOString();
42
44
  }
@@ -50,14 +52,25 @@ function createRecord(params) {
50
52
  };
51
53
  }
52
54
 
53
- // src/formatter.ts
55
+ // src/core/formatter.ts
54
56
  var JSONFormatter = class {
55
57
  format(record) {
56
58
  return JSON.stringify(record);
57
59
  }
58
60
  };
59
61
 
60
- // src/context-plugin.ts
62
+ // src/core/plugin.ts
63
+ var FunctionPlugin = class {
64
+ func;
65
+ constructor(func) {
66
+ this.func = func;
67
+ }
68
+ beforeLog(record) {
69
+ return this.func(record);
70
+ }
71
+ };
72
+
73
+ // src/plugins/context-plugin.ts
61
74
  var ContextPlugin = class {
62
75
  context;
63
76
  constructor(context) {
@@ -68,7 +81,7 @@ var ContextPlugin = class {
68
81
  }
69
82
  };
70
83
 
71
- // src/redact-plugin.ts
84
+ // src/plugins/redact-plugin.ts
72
85
  var DEFAULT_REDACTED_KEYS = ["password", "token", "secret", "api_key", "authorization"];
73
86
  var RedactPlugin = class {
74
87
  keys;
@@ -86,23 +99,413 @@ var RedactPlugin = class {
86
99
  }
87
100
  };
88
101
 
89
- // src/sampling-plugin.ts
102
+ // src/plugins/pii-redact-plugin.ts
103
+ var DEFAULT_PII_PATTERNS = {
104
+ email: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
105
+ ssn: /\b\d{3}-\d{2}-\d{4}\b/g,
106
+ creditCard: /\b(?:\d[ -]?){13,16}\b/g,
107
+ phone: /\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g
108
+ };
109
+ var MAX_DEPTH = 50;
110
+ var PIIRedactPlugin = class {
111
+ patterns;
112
+ replacement;
113
+ constructor(options = {}) {
114
+ this.patterns = options.patterns ?? DEFAULT_PII_PATTERNS;
115
+ this.replacement = options.replacement ?? "***";
116
+ }
117
+ beforeLog(record) {
118
+ return { ...record, meta: this.redactValue(record.meta, /* @__PURE__ */ new Set(), 0) };
119
+ }
120
+ redactValue(value, seen, depth) {
121
+ if (depth > MAX_DEPTH) {
122
+ return value;
123
+ }
124
+ if (typeof value === "string") {
125
+ return this.redactText(value);
126
+ }
127
+ if (Array.isArray(value)) {
128
+ if (seen.has(value)) {
129
+ return value;
130
+ }
131
+ const nextSeen = new Set(seen).add(value);
132
+ return value.map((entry) => this.redactValue(entry, nextSeen, depth + 1));
133
+ }
134
+ if (value !== null && typeof value === "object") {
135
+ if (seen.has(value)) {
136
+ return value;
137
+ }
138
+ const nextSeen = new Set(seen).add(value);
139
+ const result = {};
140
+ for (const [key, entryValue] of Object.entries(value)) {
141
+ result[key] = this.redactValue(entryValue, nextSeen, depth + 1);
142
+ }
143
+ return result;
144
+ }
145
+ return value;
146
+ }
147
+ redactText(text) {
148
+ let redacted = text;
149
+ for (const pattern of Object.values(this.patterns)) {
150
+ const global = pattern.global ? pattern : new RegExp(pattern.source, `${pattern.flags}g`);
151
+ redacted = redacted.replace(global, this.replacement);
152
+ }
153
+ return redacted;
154
+ }
155
+ };
156
+
157
+ // src/plugins/sampling-plugin.ts
90
158
  var SamplingPlugin = class {
91
159
  rate;
160
+ traceKey;
161
+ elevateAt;
162
+ transports;
163
+ maxBufferedRecords;
164
+ maxTraces;
92
165
  rng;
166
+ buffer = /* @__PURE__ */ new Map();
167
+ bufferedCount = 0;
168
+ elevated = /* @__PURE__ */ new Set();
93
169
  constructor(rate, options = {}) {
94
170
  if (rate < 0 || rate > 1) {
95
171
  throw new Error(`rate must be between 0 and 1, got ${String(rate)}`);
96
172
  }
97
173
  this.rate = rate;
98
174
  this.rng = options.rng ?? Math.random;
175
+ this.traceKey = options.traceKey ?? "traceId";
176
+ this.elevateAt = parseLevel(options.elevateAt ?? 40 /* ERROR */);
177
+ this.transports = options.transports;
178
+ this.maxBufferedRecords = options.maxBufferedRecords ?? 1e3;
179
+ this.maxTraces = options.maxTraces ?? 200;
99
180
  }
100
181
  beforeLog(record) {
101
- return this.rng() < this.rate ? record : null;
182
+ const transports = this.transports;
183
+ if (transports === void 0) {
184
+ return this.rng() < this.rate ? record : null;
185
+ }
186
+ const traceId = record.meta[this.traceKey];
187
+ if (traceId !== void 0 && this.elevated.has(traceId)) {
188
+ return record;
189
+ }
190
+ const keep = this.rng() < this.rate;
191
+ const reachedElevateLevel = parseLevel(record.level) >= this.elevateAt;
192
+ if (traceId !== void 0 && reachedElevateLevel) {
193
+ this.elevate(traceId, transports);
194
+ return record;
195
+ }
196
+ if (keep) {
197
+ return record;
198
+ }
199
+ if (traceId !== void 0) {
200
+ this.bufferRecord(traceId, record);
201
+ }
202
+ return null;
203
+ }
204
+ elevate(traceId, transports) {
205
+ this.elevated.add(traceId);
206
+ const buffered = this.buffer.get(traceId) ?? [];
207
+ this.buffer.delete(traceId);
208
+ this.bufferedCount -= buffered.length;
209
+ for (const bufferedRecord of buffered) {
210
+ for (const transport of transports) {
211
+ transport.write(transport.format(bufferedRecord), bufferedRecord);
212
+ }
213
+ }
214
+ }
215
+ bufferRecord(traceId, record) {
216
+ let records = this.buffer.get(traceId);
217
+ if (records) {
218
+ this.buffer.delete(traceId);
219
+ this.buffer.set(traceId, records);
220
+ } else {
221
+ if (this.buffer.size >= this.maxTraces) {
222
+ this.evictOldestTrace();
223
+ }
224
+ records = [];
225
+ this.buffer.set(traceId, records);
226
+ }
227
+ records.push(record);
228
+ this.bufferedCount += 1;
229
+ while (this.bufferedCount > this.maxBufferedRecords && this.buffer.size > 0) {
230
+ this.evictOldestTrace();
231
+ }
232
+ }
233
+ evictOldestTrace() {
234
+ const oldest = this.buffer.entries().next();
235
+ if (oldest.done) {
236
+ return;
237
+ }
238
+ const [oldestKey, oldestRecords] = oldest.value;
239
+ this.buffer.delete(oldestKey);
240
+ this.bufferedCount -= oldestRecords.length;
241
+ }
242
+ };
243
+ var GENESIS_HASH = "0".repeat(64);
244
+ function canonicalStringify(value) {
245
+ if (Array.isArray(value)) {
246
+ return `[${value.map((entry) => canonicalStringify(entry)).join(",")}]`;
247
+ }
248
+ if (value !== null && typeof value === "object") {
249
+ const entries = Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
250
+ return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${canonicalStringify(entryValue)}`).join(",")}}`;
251
+ }
252
+ if (value === void 0) {
253
+ return "null";
254
+ }
255
+ return JSON.stringify(value);
256
+ }
257
+ function computeHash(record, prevHash) {
258
+ const restMeta = Object.fromEntries(Object.entries(record.meta).filter(([key]) => key !== "hash" && key !== "prevHash"));
259
+ const payload = canonicalStringify({
260
+ timestamp: record.timestamp,
261
+ level: record.level,
262
+ logger: record.logger,
263
+ message: record.message,
264
+ meta: restMeta
265
+ });
266
+ return createHash("sha256").update(`${prevHash}${payload}`).digest("hex");
267
+ }
268
+ var TamperEvidentPlugin = class {
269
+ genesisHash;
270
+ lastHash;
271
+ constructor(options = {}) {
272
+ this.genesisHash = options.genesisHash ?? GENESIS_HASH;
273
+ this.lastHash = this.genesisHash;
274
+ }
275
+ beforeLog(record) {
276
+ const prevHash = this.lastHash;
277
+ const digest = computeHash(record, prevHash);
278
+ const next = { ...record, meta: { ...record.meta, prevHash, hash: digest } };
279
+ this.lastHash = digest;
280
+ return next;
281
+ }
282
+ /**
283
+ * Returns `true` iff every record's hash matches its content plus the
284
+ * previous record's hash, in the given order. Returns `false` at the
285
+ * first break in the chain (an edited, removed, or reordered record).
286
+ */
287
+ static verifyChain(records, options = {}) {
288
+ let prevHash = options.genesisHash ?? GENESIS_HASH;
289
+ for (const record of records) {
290
+ const storedHash = record.meta.hash;
291
+ const storedPrevHash = record.meta.prevHash;
292
+ if (typeof storedHash !== "string" || storedPrevHash !== prevHash) {
293
+ return false;
294
+ }
295
+ if (computeHash(record, prevHash) !== storedHash) {
296
+ return false;
297
+ }
298
+ prevHash = storedHash;
299
+ }
300
+ return true;
301
+ }
302
+ };
303
+
304
+ // src/plugins/alerting-plugin.ts
305
+ function defaultDedupeKey(record) {
306
+ return `${record.level}:${record.logger}:${record.message}`;
307
+ }
308
+ var AlertingPlugin = class {
309
+ threshold;
310
+ dedupeWindowMs;
311
+ maxTrackedKeys;
312
+ dedupeKeyFn;
313
+ windows = /* @__PURE__ */ new Map();
314
+ constructor(options = {}) {
315
+ this.threshold = parseLevel(options.threshold ?? 40 /* ERROR */);
316
+ this.dedupeWindowMs = options.dedupeWindowMs ?? 3e5;
317
+ this.dedupeKeyFn = options.dedupeKey ?? defaultDedupeKey;
318
+ this.maxTrackedKeys = options.maxTrackedKeys ?? 500;
319
+ }
320
+ afterLog(record) {
321
+ if (parseLevel(record.level) < this.threshold) {
322
+ return;
323
+ }
324
+ const key = this.dedupeKeyFn(record);
325
+ const existing = this.windows.get(key);
326
+ if (existing) {
327
+ existing.count += 1;
328
+ return;
329
+ }
330
+ if (this.windows.size >= this.maxTrackedKeys) {
331
+ return;
332
+ }
333
+ const timer = setTimeout(() => {
334
+ this.flush(key);
335
+ }, this.dedupeWindowMs);
336
+ timer.unref();
337
+ this.windows.set(key, { record, count: 1, timer });
338
+ this.safeSend(record, 1);
339
+ }
340
+ flush(key) {
341
+ const window = this.windows.get(key);
342
+ this.windows.delete(key);
343
+ if (!window || window.count <= 1) {
344
+ return;
345
+ }
346
+ this.safeSend(window.record, window.count);
347
+ }
348
+ safeSend(record, occurrences) {
349
+ Promise.resolve().then(() => this.sendAlert(record, occurrences)).catch((error) => {
350
+ try {
351
+ this.onError?.(error, record);
352
+ } catch {
353
+ }
354
+ });
355
+ }
356
+ /** Cancel any pending dedupe-window timers. Call on logger shutdown. */
357
+ close() {
358
+ const windows = [...this.windows.values()];
359
+ this.windows.clear();
360
+ for (const window of windows) {
361
+ clearTimeout(window.timer);
362
+ }
363
+ }
364
+ };
365
+
366
+ // src/plugins/slack-alert-plugin.ts
367
+ async function fetchSlackSender(webhookUrl, body) {
368
+ const response = await fetch(webhookUrl, {
369
+ method: "POST",
370
+ headers: { "Content-Type": "application/json" },
371
+ body
372
+ });
373
+ if (!response.ok) {
374
+ throw new Error(
375
+ `SlackAlertPlugin: webhook returned HTTP ${String(response.status)} \u2014 check the webhook URL is still valid in Slack's app config`
376
+ );
377
+ }
378
+ }
379
+ function formatMessage(record, occurrences) {
380
+ const suffix = occurrences > 1 ? ` (x${String(occurrences)})` : "";
381
+ return `[${record.level}] ${record.logger}: ${record.message}${suffix}`;
382
+ }
383
+ var SlackAlertPlugin = class extends AlertingPlugin {
384
+ webhookUrl;
385
+ sender;
386
+ constructor(webhookUrl, options = {}) {
387
+ super(options);
388
+ this.webhookUrl = webhookUrl;
389
+ this.sender = options.sender ?? fetchSlackSender;
390
+ }
391
+ async sendAlert(record, occurrences) {
392
+ const body = JSON.stringify({ text: formatMessage(record, occurrences) });
393
+ await this.sender(this.webhookUrl, body);
394
+ }
395
+ };
396
+
397
+ // src/plugins/pagerduty-alert-plugin.ts
398
+ var ENDPOINT = "https://events.pagerduty.com/v2/enqueue";
399
+ var SEVERITY = { ERROR: "error", FATAL: "critical" };
400
+ async function fetchPagerDutySender(body) {
401
+ const response = await fetch(ENDPOINT, {
402
+ method: "POST",
403
+ headers: { "Content-Type": "application/json" },
404
+ body
405
+ });
406
+ if (!response.ok) {
407
+ throw new Error(
408
+ `PagerDutyAlertPlugin: Events API returned HTTP ${String(response.status)} \u2014 check the routing key is a valid Events API v2 integration key`
409
+ );
410
+ }
411
+ }
412
+ var PagerDutyAlertPlugin = class extends AlertingPlugin {
413
+ routingKey;
414
+ sender;
415
+ constructor(routingKey, options = {}) {
416
+ super(options);
417
+ this.routingKey = routingKey;
418
+ this.sender = options.sender ?? fetchPagerDutySender;
419
+ }
420
+ async sendAlert(record, occurrences) {
421
+ let summary = `${record.logger}: ${record.message}`;
422
+ if (occurrences > 1) {
423
+ summary += ` (x${String(occurrences)})`;
424
+ }
425
+ const body = JSON.stringify({
426
+ routing_key: this.routingKey,
427
+ event_action: "trigger",
428
+ payload: {
429
+ summary,
430
+ severity: SEVERITY[record.level] ?? "error",
431
+ source: record.logger,
432
+ timestamp: record.timestamp,
433
+ custom_details: { occurrences, ...record.meta }
434
+ }
435
+ });
436
+ await this.sender(body);
437
+ }
438
+ };
439
+
440
+ // src/plugins/email-alert-plugin.ts
441
+ var EmailAlertPlugin = class extends AlertingPlugin {
442
+ smtpHost;
443
+ smtpPort;
444
+ fromAddr;
445
+ toAddrs;
446
+ username;
447
+ password;
448
+ useTls;
449
+ injectedSender;
450
+ transporter;
451
+ constructor(options) {
452
+ super(options);
453
+ this.smtpHost = options.smtpHost;
454
+ this.smtpPort = options.smtpPort;
455
+ this.fromAddr = options.fromAddr;
456
+ this.toAddrs = options.toAddrs;
457
+ this.username = options.username;
458
+ this.password = options.password;
459
+ this.useTls = options.useTls ?? true;
460
+ this.injectedSender = options.sender;
461
+ }
462
+ async sendAlert(record, occurrences) {
463
+ let subject = `[${record.level}] ${record.logger}`;
464
+ if (occurrences > 1) {
465
+ subject += ` (x${String(occurrences)})`;
466
+ }
467
+ const text = [
468
+ record.message,
469
+ "",
470
+ `occurrences: ${String(occurrences)}`,
471
+ `timestamp: ${record.timestamp}`,
472
+ `meta: ${JSON.stringify(record.meta)}`
473
+ ].join("\n");
474
+ const message = { from: this.fromAddr, to: this.toAddrs, subject, text };
475
+ if (this.injectedSender) {
476
+ await this.injectedSender(message);
477
+ return;
478
+ }
479
+ const transporter = this.transporter ?? await this.importTransporter();
480
+ await transporter.sendMail({ from: message.from, to: message.to.join(", "), subject: message.subject, text: message.text });
481
+ }
482
+ async importTransporter() {
483
+ let createTransport;
484
+ try {
485
+ const moduleName = "nodemailer";
486
+ const mod = await import(moduleName);
487
+ const resolved = mod.default?.createTransport ?? mod.createTransport;
488
+ if (!resolved) {
489
+ throw new Error("no createTransport export found");
490
+ }
491
+ createTransport = resolved;
492
+ } catch {
493
+ throw new Error(
494
+ "EmailAlertPlugin: install `nodemailer` to use this plugin without providing a `sender` \u2014 `npm install nodemailer`"
495
+ );
496
+ }
497
+ this.transporter = createTransport({
498
+ host: this.smtpHost,
499
+ port: this.smtpPort,
500
+ secure: false,
501
+ requireTLS: this.useTls,
502
+ auth: this.username && this.password ? { user: this.username, pass: this.password } : void 0
503
+ });
504
+ return this.transporter;
102
505
  }
103
506
  };
104
507
 
105
- // src/transport.ts
508
+ // src/transports/transport.ts
106
509
  var Transport = class {
107
510
  formatter;
108
511
  constructor(formatter = new JSONFormatter()) {
@@ -128,7 +531,1050 @@ var CollectingTransport = class extends Transport {
128
531
  }
129
532
  };
130
533
 
131
- // src/console-transport.ts
534
+ // src/transports/batching-transport.ts
535
+ var BatchingTransport = class extends Transport {
536
+ maxRecords;
537
+ maxBytes;
538
+ buffer = [];
539
+ bufferBytes = 0;
540
+ constructor(options = {}) {
541
+ super(options.formatter);
542
+ this.maxRecords = options.maxRecords ?? 100;
543
+ this.maxBytes = options.maxBytes ?? 1e6;
544
+ }
545
+ /** Converts a written record into the buffered item type. Defaults to the record itself. */
546
+ toItem(formatted, record) {
547
+ return record;
548
+ }
549
+ /** Estimated byte size of one buffered item, used for the `maxBytes` bound. */
550
+ sizeOf(item) {
551
+ return JSON.stringify(item).length;
552
+ }
553
+ write(formatted, record) {
554
+ const item = this.toItem(formatted, record);
555
+ this.buffer.push(item);
556
+ this.bufferBytes += this.sizeOf(item);
557
+ if (this.buffer.length >= this.maxRecords || this.bufferBytes >= this.maxBytes) {
558
+ this.flush();
559
+ }
560
+ }
561
+ /** Send the current batch now, even if it hasn't reached a bound. */
562
+ flush() {
563
+ if (this.buffer.length === 0) {
564
+ return;
565
+ }
566
+ const batch = this.buffer;
567
+ this.buffer = [];
568
+ this.bufferBytes = 0;
569
+ const result = this.sendBatch(batch);
570
+ if (result) {
571
+ result.catch((error) => {
572
+ console.error(`${this.constructor.name}: failed to send log batch`, error);
573
+ });
574
+ }
575
+ }
576
+ close() {
577
+ this.flush();
578
+ }
579
+ };
580
+
581
+ // src/transports/sql/base-sql-transport.ts
582
+ function metaString(meta, key) {
583
+ const value = meta[key];
584
+ return typeof value === "string" ? value : null;
585
+ }
586
+ var BaseSQLTransport = class extends BatchingTransport {
587
+ tableName;
588
+ ensureSchema;
589
+ schemaEnsured = false;
590
+ constructor(options = {}) {
591
+ super(options);
592
+ this.tableName = options.tableName ?? "logs";
593
+ this.ensureSchema = options.ensureSchema ?? false;
594
+ }
595
+ toItem(_formatted, record) {
596
+ return {
597
+ timestamp: record.timestamp,
598
+ level: record.level,
599
+ logger: record.logger,
600
+ message: record.message,
601
+ meta: JSON.stringify(record.meta),
602
+ runId: metaString(record.meta, "runId"),
603
+ spanId: metaString(record.meta, "spanId"),
604
+ parentSpanId: metaString(record.meta, "parentSpanId"),
605
+ traceId: metaString(record.meta, "traceId")
606
+ };
607
+ }
608
+ sizeOf(row) {
609
+ return row.message.length + row.meta.length + 96;
610
+ }
611
+ /**
612
+ * Minimal, dialect-generic `CREATE TABLE IF NOT EXISTS` for dev/test use via
613
+ * `ensureSchema: true`. Production deployments should manage this table with
614
+ * a real migration instead — override in a subclass for dialect-correct
615
+ * column types (e.g. `JSONB` on Postgres).
616
+ */
617
+ createTableSQL() {
618
+ return `CREATE TABLE IF NOT EXISTS ${this.tableName} (
619
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
620
+ timestamp TEXT NOT NULL,
621
+ level TEXT NOT NULL,
622
+ logger TEXT NOT NULL,
623
+ message TEXT NOT NULL,
624
+ meta TEXT NOT NULL,
625
+ runId TEXT,
626
+ spanId TEXT,
627
+ parentSpanId TEXT,
628
+ traceId TEXT
629
+ )`;
630
+ }
631
+ async sendBatch(rows) {
632
+ if (this.ensureSchema && !this.schemaEnsured) {
633
+ this.schemaEnsured = true;
634
+ await this.ensureTable();
635
+ }
636
+ await this.insertRows(rows);
637
+ }
638
+ };
639
+
640
+ // src/transports/sql/sqlite-transport.ts
641
+ var SQLiteTransport = class extends BaseSQLTransport {
642
+ injectedClient;
643
+ filename;
644
+ client;
645
+ constructor(options = {}) {
646
+ super(options);
647
+ this.injectedClient = options.client;
648
+ this.filename = options.filename ?? ":memory:";
649
+ }
650
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
651
+ resolvedClient() {
652
+ return this.injectedClient ?? this.client;
653
+ }
654
+ async importClient() {
655
+ let DatabaseCtor;
656
+ try {
657
+ const moduleName = "better-sqlite3";
658
+ const mod = await import(moduleName);
659
+ DatabaseCtor = mod.default;
660
+ } catch {
661
+ throw new Error(
662
+ "SQLiteTransport: install `better-sqlite3` to use this transport without providing a client \u2014 `npm install better-sqlite3`"
663
+ );
664
+ }
665
+ this.client = new DatabaseCtor(this.filename);
666
+ return this.client;
667
+ }
668
+ async ensureTable() {
669
+ const client = this.resolvedClient() ?? await this.importClient();
670
+ client.exec(this.createTableSQL());
671
+ }
672
+ async insertRows(rows) {
673
+ const client = this.resolvedClient() ?? await this.importClient();
674
+ const stmt = client.prepare(
675
+ `INSERT INTO ${this.tableName} (timestamp, level, logger, message, meta, runId, spanId, parentSpanId, traceId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
676
+ );
677
+ const insertMany = client.transaction((batch) => {
678
+ for (const row of batch) {
679
+ stmt.run(
680
+ row.timestamp,
681
+ row.level,
682
+ row.logger,
683
+ row.message,
684
+ row.meta,
685
+ row.runId,
686
+ row.spanId,
687
+ row.parentSpanId,
688
+ row.traceId
689
+ );
690
+ }
691
+ });
692
+ insertMany(rows);
693
+ }
694
+ };
695
+
696
+ // src/transports/sql/postgres-transport.ts
697
+ var PostgresTransport = class extends BaseSQLTransport {
698
+ injectedClient;
699
+ connectionString;
700
+ connectionConfig;
701
+ client;
702
+ constructor(options = {}) {
703
+ super(options);
704
+ this.injectedClient = options.client;
705
+ this.connectionString = options.connectionString;
706
+ this.connectionConfig = options.connectionConfig;
707
+ }
708
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
709
+ resolvedClient() {
710
+ return this.injectedClient ?? this.client;
711
+ }
712
+ async importClient() {
713
+ let PoolCtor;
714
+ try {
715
+ const moduleName = "pg";
716
+ const mod = await import(moduleName);
717
+ const resolved = mod.default?.Pool ?? mod.Pool;
718
+ if (!resolved) {
719
+ throw new Error("no Pool export found");
720
+ }
721
+ PoolCtor = resolved;
722
+ } catch {
723
+ throw new Error(
724
+ "PostgresTransport: install `pg` to use this transport without providing a client \u2014 `npm install pg`"
725
+ );
726
+ }
727
+ const config = this.connectionString ? { connectionString: this.connectionString } : this.connectionConfig ?? {};
728
+ this.client = new PoolCtor(config);
729
+ return this.client;
730
+ }
731
+ /** Postgres-correct `CREATE TABLE IF NOT EXISTS`: `SERIAL` primary key, `JSONB` for `meta`. */
732
+ createTableSQL() {
733
+ return `CREATE TABLE IF NOT EXISTS ${this.tableName} (
734
+ id SERIAL PRIMARY KEY,
735
+ timestamp TEXT NOT NULL,
736
+ level TEXT NOT NULL,
737
+ logger TEXT NOT NULL,
738
+ message TEXT NOT NULL,
739
+ meta JSONB NOT NULL,
740
+ "runId" TEXT,
741
+ "spanId" TEXT,
742
+ "parentSpanId" TEXT,
743
+ "traceId" TEXT
744
+ )`;
745
+ }
746
+ async ensureTable() {
747
+ const client = this.resolvedClient() ?? await this.importClient();
748
+ await client.query(this.createTableSQL(), []);
749
+ }
750
+ async insertRows(rows) {
751
+ const client = this.resolvedClient() ?? await this.importClient();
752
+ const columns = 9;
753
+ const values = [];
754
+ const placeholders = [];
755
+ rows.forEach((row, rowIndex) => {
756
+ const base = rowIndex * columns;
757
+ placeholders.push(
758
+ `(${Array.from({ length: columns }, (_, col) => `$${String(base + col + 1)}`).join(", ")})`
759
+ );
760
+ values.push(
761
+ row.timestamp,
762
+ row.level,
763
+ row.logger,
764
+ row.message,
765
+ row.meta,
766
+ row.runId,
767
+ row.spanId,
768
+ row.parentSpanId,
769
+ row.traceId
770
+ );
771
+ });
772
+ const sql = `INSERT INTO ${this.tableName} (timestamp, level, logger, message, meta, "runId", "spanId", "parentSpanId", "traceId") VALUES ${placeholders.join(", ")}`;
773
+ await client.query(sql, values);
774
+ }
775
+ };
776
+
777
+ // src/transports/sql/mysql-transport.ts
778
+ var MySQLTransport = class extends BaseSQLTransport {
779
+ injectedClient;
780
+ connectionString;
781
+ connectionConfig;
782
+ client;
783
+ constructor(options = {}) {
784
+ super(options);
785
+ this.injectedClient = options.client;
786
+ this.connectionString = options.connectionString;
787
+ this.connectionConfig = options.connectionConfig;
788
+ }
789
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
790
+ resolvedClient() {
791
+ return this.injectedClient ?? this.client;
792
+ }
793
+ async importClient() {
794
+ let createPool;
795
+ try {
796
+ const moduleName = "mysql2/promise";
797
+ const mod = await import(moduleName);
798
+ const resolved = mod.default?.createPool ?? mod.createPool;
799
+ if (!resolved) {
800
+ throw new Error("no createPool export found");
801
+ }
802
+ createPool = resolved;
803
+ } catch {
804
+ throw new Error(
805
+ "MySQLTransport: install `mysql2` to use this transport without providing a client \u2014 `npm install mysql2`"
806
+ );
807
+ }
808
+ const target = this.connectionString ?? this.connectionConfig ?? {};
809
+ this.client = createPool(target);
810
+ return this.client;
811
+ }
812
+ /** MySQL-correct `CREATE TABLE IF NOT EXISTS`: `AUTO_INCREMENT` primary key, `JSON` column type for `meta`. */
813
+ createTableSQL() {
814
+ return `CREATE TABLE IF NOT EXISTS ${this.tableName} (
815
+ id INT AUTO_INCREMENT PRIMARY KEY,
816
+ timestamp VARCHAR(64) NOT NULL,
817
+ level VARCHAR(16) NOT NULL,
818
+ logger VARCHAR(255) NOT NULL,
819
+ message TEXT NOT NULL,
820
+ meta JSON NOT NULL,
821
+ runId VARCHAR(255),
822
+ spanId VARCHAR(255),
823
+ parentSpanId VARCHAR(255),
824
+ traceId VARCHAR(255)
825
+ )`;
826
+ }
827
+ async ensureTable() {
828
+ const client = this.resolvedClient() ?? await this.importClient();
829
+ await client.execute(this.createTableSQL(), []);
830
+ }
831
+ async insertRows(rows) {
832
+ const client = this.resolvedClient() ?? await this.importClient();
833
+ const columns = 9;
834
+ const values = [];
835
+ const placeholders = [];
836
+ for (const row of rows) {
837
+ placeholders.push(`(${Array.from({ length: columns }, () => "?").join(", ")})`);
838
+ values.push(
839
+ row.timestamp,
840
+ row.level,
841
+ row.logger,
842
+ row.message,
843
+ row.meta,
844
+ row.runId,
845
+ row.spanId,
846
+ row.parentSpanId,
847
+ row.traceId
848
+ );
849
+ }
850
+ const sql = `INSERT INTO ${this.tableName} (timestamp, level, logger, message, meta, runId, spanId, parentSpanId, traceId) VALUES ${placeholders.join(", ")}`;
851
+ await client.execute(sql, values);
852
+ }
853
+ };
854
+
855
+ // src/transports/nosql/mongodb-transport.ts
856
+ var MongoDBTransport = class extends BatchingTransport {
857
+ injectedCollection;
858
+ connectionString;
859
+ database;
860
+ collectionName;
861
+ collection;
862
+ constructor(options = {}) {
863
+ super(options);
864
+ this.injectedCollection = options.collection;
865
+ this.connectionString = options.connectionString;
866
+ this.database = options.database ?? "logquill";
867
+ this.collectionName = options.collectionName ?? "logs";
868
+ }
869
+ /** Synchronously available collection, if one was injected or already connected — avoids an unnecessary microtask hop on the hot path. */
870
+ resolvedCollection() {
871
+ return this.injectedCollection ?? this.collection;
872
+ }
873
+ async importCollection() {
874
+ if (!this.connectionString) {
875
+ throw new Error(
876
+ "MongoDBTransport: provide either a `collection` or a `connectionString` to connect with \u2014 neither was given"
877
+ );
878
+ }
879
+ let MongoClientCtor;
880
+ try {
881
+ const moduleName = "mongodb";
882
+ const mod = await import(moduleName);
883
+ MongoClientCtor = mod.MongoClient;
884
+ } catch {
885
+ throw new Error(
886
+ "MongoDBTransport: install `mongodb` to use this transport without providing a client \u2014 `npm install mongodb`"
887
+ );
888
+ }
889
+ const client = new MongoClientCtor(this.connectionString);
890
+ await client.connect();
891
+ this.collection = client.db(this.database).collection(this.collectionName);
892
+ return this.collection;
893
+ }
894
+ async sendBatch(batch) {
895
+ const collection = this.resolvedCollection() ?? await this.importCollection();
896
+ await collection.insertMany(batch.map((record) => ({ ...record })));
897
+ }
898
+ };
899
+
900
+ // src/transports/nosql/dynamodb-transport.ts
901
+ var DYNAMO_BATCH_LIMIT = 25;
902
+ function toAttributeValue(value) {
903
+ if (value === null || value === void 0) {
904
+ return { NULL: true };
905
+ }
906
+ if (typeof value === "string") {
907
+ return { S: value };
908
+ }
909
+ if (typeof value === "number") {
910
+ return { N: String(value) };
911
+ }
912
+ if (typeof value === "boolean") {
913
+ return { BOOL: value };
914
+ }
915
+ if (typeof value === "bigint") {
916
+ return { N: value.toString() };
917
+ }
918
+ if (Array.isArray(value)) {
919
+ return { L: value.map((entry) => toAttributeValue(entry)) };
920
+ }
921
+ if (typeof value === "object") {
922
+ const m = {};
923
+ for (const [key, entryValue] of Object.entries(value)) {
924
+ m[key] = toAttributeValue(entryValue);
925
+ }
926
+ return { M: m };
927
+ }
928
+ return { NULL: true };
929
+ }
930
+ function marshallItem(item) {
931
+ return toAttributeValue({ ...item }).M;
932
+ }
933
+ var DynamoDBTransport = class extends BatchingTransport {
934
+ injectedClient;
935
+ tableName;
936
+ region;
937
+ client;
938
+ constructor(options = {}) {
939
+ super(options);
940
+ this.injectedClient = options.client;
941
+ this.tableName = options.tableName ?? "logs";
942
+ this.region = options.region;
943
+ }
944
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
945
+ resolvedClient() {
946
+ return this.injectedClient ?? this.client;
947
+ }
948
+ async importClient() {
949
+ let DynamoDBClientCtor;
950
+ let BatchWriteItemCommandCtor;
951
+ try {
952
+ const moduleName = "@aws-sdk/client-dynamodb";
953
+ const mod = await import(moduleName);
954
+ DynamoDBClientCtor = mod.DynamoDBClient;
955
+ BatchWriteItemCommandCtor = mod.BatchWriteItemCommand;
956
+ } catch {
957
+ throw new Error(
958
+ "DynamoDBTransport: install `@aws-sdk/client-dynamodb` to use this transport without providing a client \u2014 `npm install @aws-sdk/client-dynamodb`"
959
+ );
960
+ }
961
+ const sdkClient = new DynamoDBClientCtor(this.region ? { region: this.region } : {});
962
+ this.client = {
963
+ async batchWriteItems(tableName, items) {
964
+ const requestItems = {
965
+ [tableName]: items.map((item) => ({ PutRequest: { Item: marshallItem(item) } }))
966
+ };
967
+ return sdkClient.send(new BatchWriteItemCommandCtor({ RequestItems: requestItems }));
968
+ }
969
+ };
970
+ return this.client;
971
+ }
972
+ /** `meta.runId`, else `meta.traceId`, else the logger name — see the class doc for why. */
973
+ partitionKey(record) {
974
+ const runId = record.meta.runId;
975
+ if (typeof runId === "string" && runId.length > 0) {
976
+ return runId;
977
+ }
978
+ const traceId = record.meta.traceId;
979
+ if (typeof traceId === "string" && traceId.length > 0) {
980
+ return traceId;
981
+ }
982
+ return record.logger;
983
+ }
984
+ toDynamoItem(record) {
985
+ const spanId = record.meta.spanId;
986
+ const parentSpanId = record.meta.parentSpanId;
987
+ const traceId = record.meta.traceId;
988
+ return {
989
+ runId: this.partitionKey(record),
990
+ timestamp: record.timestamp,
991
+ level: record.level,
992
+ logger: record.logger,
993
+ message: record.message,
994
+ meta: record.meta,
995
+ ...typeof spanId === "string" ? { spanId } : {},
996
+ ...typeof parentSpanId === "string" ? { parentSpanId } : {},
997
+ ...typeof traceId === "string" ? { traceId } : {}
998
+ };
999
+ }
1000
+ async sendBatch(batch) {
1001
+ const client = this.resolvedClient() ?? await this.importClient();
1002
+ const items = batch.map((record) => this.toDynamoItem(record));
1003
+ const chunks = [];
1004
+ for (let offset = 0; offset < items.length; offset += DYNAMO_BATCH_LIMIT) {
1005
+ chunks.push(items.slice(offset, offset + DYNAMO_BATCH_LIMIT));
1006
+ }
1007
+ await Promise.all(chunks.map((chunk) => client.batchWriteItems(this.tableName, chunk)));
1008
+ }
1009
+ };
1010
+
1011
+ // src/transports/nosql/redis-transport.ts
1012
+ var RedisTransport = class extends BatchingTransport {
1013
+ injectedClient;
1014
+ url;
1015
+ stream;
1016
+ client;
1017
+ constructor(options = {}) {
1018
+ super(options);
1019
+ this.injectedClient = options.client;
1020
+ this.url = options.url ?? "redis://localhost:6379";
1021
+ this.stream = options.stream ?? "logquill:logs";
1022
+ }
1023
+ /** Synchronously available client, if one was injected or already connected — avoids an unnecessary microtask hop on the hot path. */
1024
+ resolvedClient() {
1025
+ return this.injectedClient ?? this.client;
1026
+ }
1027
+ async importClient() {
1028
+ let createClient;
1029
+ try {
1030
+ const moduleName = "redis";
1031
+ const mod = await import(moduleName);
1032
+ createClient = mod.createClient;
1033
+ } catch {
1034
+ throw new Error(
1035
+ "RedisTransport: install `redis` to use this transport without providing a client \u2014 `npm install redis`"
1036
+ );
1037
+ }
1038
+ const client = createClient({ url: this.url });
1039
+ await client.connect();
1040
+ this.client = client;
1041
+ return client;
1042
+ }
1043
+ toFields(record) {
1044
+ return {
1045
+ timestamp: record.timestamp,
1046
+ level: record.level,
1047
+ logger: record.logger,
1048
+ message: record.message,
1049
+ meta: JSON.stringify(record.meta)
1050
+ };
1051
+ }
1052
+ async sendBatch(batch) {
1053
+ const client = this.resolvedClient() ?? await this.importClient();
1054
+ await Promise.all(batch.map((record) => client.xAdd(this.stream, "*", this.toFields(record))));
1055
+ }
1056
+ };
1057
+
1058
+ // src/transports/queue/base-queue-transport.ts
1059
+ var BaseQueueTransport = class extends BatchingTransport {
1060
+ topic;
1061
+ constructor(options) {
1062
+ super(options);
1063
+ this.topic = options.topic;
1064
+ }
1065
+ sendBatch(batch) {
1066
+ return this.publishBatch(batch);
1067
+ }
1068
+ };
1069
+
1070
+ // src/transports/queue/kafka-transport.ts
1071
+ function metaKey(meta, key) {
1072
+ const value = meta[key];
1073
+ return typeof value === "string" ? value : void 0;
1074
+ }
1075
+ var KafkaTransport = class extends BaseQueueTransport {
1076
+ injectedClient;
1077
+ brokers;
1078
+ client;
1079
+ constructor(options) {
1080
+ super(options);
1081
+ this.injectedClient = options.client;
1082
+ this.brokers = options.brokers ?? ["localhost:9092"];
1083
+ }
1084
+ /** Synchronously available producer, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
1085
+ resolvedClient() {
1086
+ return this.injectedClient ?? this.client;
1087
+ }
1088
+ /**
1089
+ * Builds the real `kafkajs` producer and connects it. Connection happens
1090
+ * here, once, as part of acquiring the driver — not on every
1091
+ * `publishBatch()` call — so an injected `client` (tests, or a caller's
1092
+ * own already-connected producer) is trusted to already be ready and is
1093
+ * never re-connected.
1094
+ */
1095
+ async importClient() {
1096
+ let producer;
1097
+ try {
1098
+ const moduleName = "kafkajs";
1099
+ const mod = await import(moduleName);
1100
+ producer = new mod.Kafka({ brokers: this.brokers }).producer();
1101
+ await producer.connect?.();
1102
+ } catch {
1103
+ throw new Error(
1104
+ "KafkaTransport: install `kafkajs` to use this transport without providing a client \u2014 `npm install kafkajs`"
1105
+ );
1106
+ }
1107
+ this.client = producer;
1108
+ return producer;
1109
+ }
1110
+ async publishBatch(records) {
1111
+ const client = this.resolvedClient() ?? await this.importClient();
1112
+ await client.send({
1113
+ topic: this.topic,
1114
+ messages: records.map((record) => ({
1115
+ key: metaKey(record.meta, "runId") ?? metaKey(record.meta, "traceId") ?? null,
1116
+ value: JSON.stringify(record)
1117
+ }))
1118
+ });
1119
+ }
1120
+ };
1121
+
1122
+ // src/transports/queue/rabbitmq-transport.ts
1123
+ var RabbitMQTransport = class extends BaseQueueTransport {
1124
+ injectedClient;
1125
+ url;
1126
+ client;
1127
+ constructor(options) {
1128
+ super(options);
1129
+ this.injectedClient = options.client;
1130
+ this.url = options.url ?? "amqp://localhost";
1131
+ }
1132
+ /** Synchronously available channel, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
1133
+ resolvedClient() {
1134
+ return this.injectedClient ?? this.client;
1135
+ }
1136
+ /**
1137
+ * Opens the real `amqplib` connection/channel and asserts the queue
1138
+ * exists. Both happen here, once, as part of acquiring the driver — not on
1139
+ * every `publishBatch()` call — so an injected `client` (tests, or a
1140
+ * caller's own already-open channel) is trusted to already have its queue
1141
+ * set up and is never re-asserted.
1142
+ */
1143
+ async importClient() {
1144
+ let channel;
1145
+ try {
1146
+ const moduleName = "amqplib";
1147
+ const mod = await import(moduleName);
1148
+ const connection = await mod.connect(this.url);
1149
+ channel = await connection.createChannel();
1150
+ await channel.assertQueue?.(this.topic);
1151
+ } catch {
1152
+ throw new Error(
1153
+ "RabbitMQTransport: install `amqplib` to use this transport without providing a client \u2014 `npm install amqplib`"
1154
+ );
1155
+ }
1156
+ this.client = channel;
1157
+ return channel;
1158
+ }
1159
+ async publishBatch(records) {
1160
+ const client = this.resolvedClient() ?? await this.importClient();
1161
+ for (const record of records) {
1162
+ client.sendToQueue(this.topic, Buffer.from(JSON.stringify(record)));
1163
+ }
1164
+ }
1165
+ };
1166
+
1167
+ // src/transports/queue/sqs-transport.ts
1168
+ var SQS_BATCH_LIMIT = 10;
1169
+ var SQSTransport = class extends BaseQueueTransport {
1170
+ injectedClient;
1171
+ region;
1172
+ client;
1173
+ constructor(options) {
1174
+ super(options);
1175
+ this.injectedClient = options.client;
1176
+ this.region = options.region;
1177
+ }
1178
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
1179
+ resolvedClient() {
1180
+ return this.injectedClient ?? this.client;
1181
+ }
1182
+ async importClient() {
1183
+ let client;
1184
+ try {
1185
+ const moduleName = "@aws-sdk/client-sqs";
1186
+ const mod = await import(moduleName);
1187
+ const sdkClient = new mod.SQSClient({ region: this.region });
1188
+ const CommandCtor = mod.SendMessageBatchCommand;
1189
+ client = {
1190
+ sendMessageBatch: (queueUrl, entries) => sdkClient.send(
1191
+ new CommandCtor({
1192
+ QueueUrl: queueUrl,
1193
+ Entries: entries.map((entry) => ({ Id: entry.id, MessageBody: entry.body }))
1194
+ })
1195
+ )
1196
+ };
1197
+ } catch {
1198
+ throw new Error(
1199
+ "SQSTransport: install `@aws-sdk/client-sqs` to use this transport without providing a client \u2014 `npm install @aws-sdk/client-sqs`"
1200
+ );
1201
+ }
1202
+ this.client = client;
1203
+ return client;
1204
+ }
1205
+ async publishBatch(records) {
1206
+ const client = this.resolvedClient() ?? await this.importClient();
1207
+ const chunks = [];
1208
+ for (let start = 0; start < records.length; start += SQS_BATCH_LIMIT) {
1209
+ chunks.push(records.slice(start, start + SQS_BATCH_LIMIT));
1210
+ }
1211
+ await Promise.all(
1212
+ chunks.map(
1213
+ (chunk) => client.sendMessageBatch(
1214
+ this.topic,
1215
+ chunk.map((record, index) => ({ id: String(index), body: JSON.stringify(record) }))
1216
+ )
1217
+ )
1218
+ );
1219
+ }
1220
+ };
1221
+
1222
+ // src/transports/queue/pubsub-transport.ts
1223
+ var PubSubTransport = class extends BaseQueueTransport {
1224
+ injectedClient;
1225
+ projectId;
1226
+ client;
1227
+ constructor(options) {
1228
+ super(options);
1229
+ this.injectedClient = options.client;
1230
+ this.projectId = options.projectId;
1231
+ }
1232
+ /** Synchronously available topic reference, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
1233
+ resolvedClient() {
1234
+ return this.injectedClient ?? this.client;
1235
+ }
1236
+ async importClient() {
1237
+ let topic;
1238
+ try {
1239
+ const moduleName = "@google-cloud/pubsub";
1240
+ const mod = await import(moduleName);
1241
+ topic = new mod.PubSub({ projectId: this.projectId }).topic(this.topic);
1242
+ } catch {
1243
+ throw new Error(
1244
+ "PubSubTransport: install `@google-cloud/pubsub` to use this transport without providing a client \u2014 `npm install @google-cloud/pubsub`"
1245
+ );
1246
+ }
1247
+ this.client = topic;
1248
+ return topic;
1249
+ }
1250
+ async publishBatch(records) {
1251
+ const client = this.resolvedClient() ?? await this.importClient();
1252
+ await Promise.all(records.map((record) => client.publishMessage({ data: Buffer.from(JSON.stringify(record)) })));
1253
+ }
1254
+ };
1255
+
1256
+ // src/transports/cloud/cloudwatch-transport.ts
1257
+ var CloudWatchTransport = class extends BatchingTransport {
1258
+ logGroupName;
1259
+ logStreamName;
1260
+ region;
1261
+ injectedClient;
1262
+ client;
1263
+ constructor(options) {
1264
+ super(options);
1265
+ this.logGroupName = options.logGroupName;
1266
+ this.logStreamName = options.logStreamName;
1267
+ this.region = options.region;
1268
+ this.injectedClient = options.client;
1269
+ }
1270
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
1271
+ resolvedClient() {
1272
+ return this.injectedClient ?? this.client;
1273
+ }
1274
+ async importClient() {
1275
+ let ClientCtor;
1276
+ let PutLogEventsCommandCtor;
1277
+ try {
1278
+ const moduleName = "@aws-sdk/client-cloudwatch-logs";
1279
+ const mod = await import(moduleName);
1280
+ ClientCtor = mod.CloudWatchLogsClient;
1281
+ PutLogEventsCommandCtor = mod.PutLogEventsCommand;
1282
+ } catch {
1283
+ throw new Error(
1284
+ "CloudWatchTransport: install `@aws-sdk/client-cloudwatch-logs` to use this transport without providing a client \u2014 `npm install @aws-sdk/client-cloudwatch-logs`"
1285
+ );
1286
+ }
1287
+ const sdkClient = new ClientCtor({ region: this.region });
1288
+ this.client = {
1289
+ putLogEvents: (logGroupName, logStreamName, events) => sdkClient.send(
1290
+ new PutLogEventsCommandCtor({
1291
+ logGroupName,
1292
+ logStreamName,
1293
+ logEvents: events
1294
+ })
1295
+ )
1296
+ };
1297
+ return this.client;
1298
+ }
1299
+ async sendBatch(batch) {
1300
+ const client = this.resolvedClient() ?? await this.importClient();
1301
+ const events = batch.map((record) => ({
1302
+ timestamp: Date.parse(record.timestamp),
1303
+ message: this.format(record)
1304
+ })).sort((a, b) => a.timestamp - b.timestamp);
1305
+ await client.putLogEvents(this.logGroupName, this.logStreamName, events);
1306
+ }
1307
+ };
1308
+
1309
+ // src/transports/cloud/cloud-logging-transport.ts
1310
+ function gcpSeverity(levelValue) {
1311
+ const level = parseLevel(levelValue);
1312
+ switch (level) {
1313
+ case 5 /* TRACE */:
1314
+ case 10 /* DEBUG */:
1315
+ return "DEBUG";
1316
+ case 20 /* INFO */:
1317
+ return "INFO";
1318
+ case 30 /* WARN */:
1319
+ return "WARNING";
1320
+ case 40 /* ERROR */:
1321
+ return "ERROR";
1322
+ case 50 /* FATAL */:
1323
+ return "CRITICAL";
1324
+ }
1325
+ }
1326
+ var CloudLoggingTransport = class extends BatchingTransport {
1327
+ logName;
1328
+ projectId;
1329
+ injectedClient;
1330
+ client;
1331
+ constructor(options = {}) {
1332
+ super(options);
1333
+ this.logName = options.logName ?? "logquill";
1334
+ this.projectId = options.projectId;
1335
+ this.injectedClient = options.client;
1336
+ }
1337
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
1338
+ resolvedClient() {
1339
+ return this.injectedClient ?? this.client;
1340
+ }
1341
+ async importClient() {
1342
+ let LoggingCtor;
1343
+ try {
1344
+ const moduleName = "@google-cloud/logging";
1345
+ const mod = await import(moduleName);
1346
+ LoggingCtor = mod.Logging;
1347
+ } catch {
1348
+ throw new Error(
1349
+ "CloudLoggingTransport: install `@google-cloud/logging` to use this transport without providing a client \u2014 `npm install @google-cloud/logging`"
1350
+ );
1351
+ }
1352
+ const logging = new LoggingCtor({ projectId: this.projectId });
1353
+ const log = logging.log(this.logName);
1354
+ this.client = {
1355
+ writeLogEntries: (entries) => log.write(entries)
1356
+ };
1357
+ return this.client;
1358
+ }
1359
+ async sendBatch(batch) {
1360
+ const client = this.resolvedClient() ?? await this.importClient();
1361
+ const entries = batch.map((record) => ({
1362
+ severity: gcpSeverity(record.level),
1363
+ timestamp: record.timestamp,
1364
+ jsonPayload: JSON.parse(this.format(record))
1365
+ }));
1366
+ await client.writeLogEntries(entries);
1367
+ }
1368
+ };
1369
+
1370
+ // src/transports/cloud/app-insights-transport.ts
1371
+ function appInsightsSeverity(levelValue) {
1372
+ const level = parseLevel(levelValue);
1373
+ switch (level) {
1374
+ case 5 /* TRACE */:
1375
+ case 10 /* DEBUG */:
1376
+ return 0;
1377
+ // Verbose
1378
+ case 20 /* INFO */:
1379
+ return 1;
1380
+ // Information
1381
+ case 30 /* WARN */:
1382
+ return 2;
1383
+ // Warning
1384
+ case 40 /* ERROR */:
1385
+ return 3;
1386
+ // Error
1387
+ case 50 /* FATAL */:
1388
+ return 4;
1389
+ }
1390
+ }
1391
+ var AppInsightsTransport = class extends BatchingTransport {
1392
+ connectionString;
1393
+ injectedClient;
1394
+ client;
1395
+ constructor(options = {}) {
1396
+ super(options);
1397
+ this.connectionString = options.connectionString;
1398
+ this.injectedClient = options.client;
1399
+ }
1400
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
1401
+ resolvedClient() {
1402
+ return this.injectedClient ?? this.client;
1403
+ }
1404
+ async importClient() {
1405
+ let TelemetryClientCtor;
1406
+ try {
1407
+ const moduleName = "applicationinsights";
1408
+ const mod = await import(moduleName);
1409
+ TelemetryClientCtor = mod.TelemetryClient;
1410
+ } catch {
1411
+ throw new Error(
1412
+ "AppInsightsTransport: install `applicationinsights` to use this transport without providing a client \u2014 `npm install applicationinsights`"
1413
+ );
1414
+ }
1415
+ const telemetryClient = new TelemetryClientCtor(this.connectionString);
1416
+ this.client = {
1417
+ trackTraceBatch: (traces) => {
1418
+ for (const trace of traces) {
1419
+ telemetryClient.trackTrace(trace);
1420
+ }
1421
+ telemetryClient.flush();
1422
+ return Promise.resolve();
1423
+ }
1424
+ };
1425
+ return this.client;
1426
+ }
1427
+ async sendBatch(batch) {
1428
+ const client = this.resolvedClient() ?? await this.importClient();
1429
+ const traces = batch.map((record) => ({
1430
+ message: this.format(record),
1431
+ severity: appInsightsSeverity(record.level)
1432
+ }));
1433
+ await client.trackTraceBatch(traces);
1434
+ }
1435
+ };
1436
+
1437
+ // src/transports/cloud/datadog-transport.ts
1438
+ async function fetchDatadogSender(url, apiKey, batch) {
1439
+ const response = await fetch(url, {
1440
+ method: "POST",
1441
+ headers: { "Content-Type": "application/json", "DD-API-KEY": apiKey },
1442
+ body: `[${batch.join(",")}]`
1443
+ });
1444
+ if (!response.ok) {
1445
+ throw new Error(
1446
+ `DatadogTransport: request to ${url} failed with status ${String(response.status)} \u2014 check the API key and site region`
1447
+ );
1448
+ }
1449
+ }
1450
+ var DatadogTransport = class extends BatchingTransport {
1451
+ url;
1452
+ apiKey;
1453
+ site;
1454
+ sender;
1455
+ constructor(options) {
1456
+ super(options);
1457
+ this.apiKey = options.apiKey;
1458
+ this.site = options.site ?? "datadoghq.com";
1459
+ this.url = `https://http-intake.logs.${this.site}/api/v2/logs`;
1460
+ this.sender = options.sender ?? fetchDatadogSender;
1461
+ }
1462
+ sendBatch(batch) {
1463
+ const formatted = batch.map((record) => this.format(record));
1464
+ return this.sender(this.url, this.apiKey, formatted);
1465
+ }
1466
+ };
1467
+
1468
+ // src/transports/cloud/elasticsearch-transport.ts
1469
+ async function fetchElasticsearchSender(url, headers, body) {
1470
+ const response = await fetch(url, {
1471
+ method: "POST",
1472
+ headers: { ...headers, "Content-Type": "application/x-ndjson" },
1473
+ body
1474
+ });
1475
+ if (!response.ok) {
1476
+ throw new Error(`ElasticsearchTransport: request to ${url} failed with status ${String(response.status)}`);
1477
+ }
1478
+ }
1479
+ var ElasticsearchTransport = class extends BatchingTransport {
1480
+ url;
1481
+ index;
1482
+ apiKey;
1483
+ sender;
1484
+ constructor(options) {
1485
+ super(options);
1486
+ this.index = options.index ?? "logs";
1487
+ this.url = `${options.node.replace(/\/+$/, "")}/_bulk`;
1488
+ this.apiKey = options.apiKey;
1489
+ this.sender = options.sender ?? fetchElasticsearchSender;
1490
+ }
1491
+ sendBatch(batch) {
1492
+ const lines = [];
1493
+ for (const record of batch) {
1494
+ lines.push(JSON.stringify({ index: { _index: this.index } }));
1495
+ lines.push(this.format(record));
1496
+ }
1497
+ const body = `${lines.join("\n")}
1498
+ `;
1499
+ const headers = {};
1500
+ if (this.apiKey !== void 0) {
1501
+ headers.Authorization = `ApiKey ${this.apiKey}`;
1502
+ }
1503
+ return this.sender(this.url, headers, body);
1504
+ }
1505
+ };
1506
+ async function fetchNewRelicSender(url, headers, body) {
1507
+ const response = await fetch(url, { method: "POST", headers, body });
1508
+ return {
1509
+ ok: response.ok,
1510
+ status: response.status,
1511
+ retryAfter: response.headers.get("retry-after")
1512
+ };
1513
+ }
1514
+ function withoutEventType(record) {
1515
+ const meta = { ...record.meta };
1516
+ delete meta.eventType;
1517
+ return { ...record, meta };
1518
+ }
1519
+ function resumeTimestamp(retryAfter, now) {
1520
+ if (retryAfter === null) {
1521
+ return now + 6e4;
1522
+ }
1523
+ const seconds = Number(retryAfter);
1524
+ if (Number.isFinite(seconds)) {
1525
+ return now + seconds * 1e3;
1526
+ }
1527
+ const dateMs = Date.parse(retryAfter);
1528
+ return Number.isNaN(dateMs) ? now + 6e4 : dateMs;
1529
+ }
1530
+ var NewRelicTransport = class extends BatchingTransport {
1531
+ url;
1532
+ region;
1533
+ licenseKey;
1534
+ sender;
1535
+ clock;
1536
+ pausedUntil = null;
1537
+ constructor(options) {
1538
+ super(options);
1539
+ this.licenseKey = options.licenseKey;
1540
+ this.region = options.region ?? "US";
1541
+ this.url = this.region === "EU" ? "https://log-api.eu.newrelic.com/log/v1" : "https://log-api.newrelic.com/log/v1";
1542
+ this.sender = options.sender ?? fetchNewRelicSender;
1543
+ this.clock = options.clock ?? Date.now;
1544
+ }
1545
+ async sendBatch(batch) {
1546
+ const now = this.clock();
1547
+ if (this.pausedUntil !== null && now < this.pausedUntil) {
1548
+ console.error(
1549
+ `NewRelicTransport: sends paused until ${new Date(this.pausedUntil).toISOString()} after a 429 rate-limit response \u2014 skipping this batch rather than making a doomed request`
1550
+ );
1551
+ return;
1552
+ }
1553
+ this.pausedUntil = null;
1554
+ const records = batch.map((record) => withoutEventType(record));
1555
+ const body = gzipSync(Buffer.from(JSON.stringify(records)));
1556
+ const headers = {
1557
+ "Content-Type": "application/json",
1558
+ "Content-Encoding": "gzip",
1559
+ "Api-Key": this.licenseKey
1560
+ };
1561
+ const result = await this.sender(this.url, headers, body);
1562
+ if (result.status === 429) {
1563
+ this.pausedUntil = resumeTimestamp(result.retryAfter, now);
1564
+ console.error(
1565
+ `NewRelicTransport: received 429 from New Relic \u2014 pausing sends until ${new Date(this.pausedUntil).toISOString()}. Reduce log volume or increase batching to stay under the rate limit.`
1566
+ );
1567
+ return;
1568
+ }
1569
+ if (!result.ok) {
1570
+ throw new Error(
1571
+ `NewRelicTransport: request to ${this.url} failed with status ${String(result.status)} \u2014 check the license key and region`
1572
+ );
1573
+ }
1574
+ }
1575
+ };
1576
+
1577
+ // src/transports/console-transport.ts
132
1578
  var COLORS = {
133
1579
  [5 /* TRACE */]: "\x1B[90m",
134
1580
  // gray
@@ -216,7 +1662,7 @@ var FileTransport = class extends Transport {
216
1662
  }
217
1663
  };
218
1664
 
219
- // src/http-transport.ts
1665
+ // src/transports/http-transport.ts
220
1666
  async function fetchSender(url, batch) {
221
1667
  const response = await fetch(url, {
222
1668
  method: "POST",
@@ -263,7 +1709,7 @@ var HTTPTransport = class extends Transport {
263
1709
  }
264
1710
  };
265
1711
 
266
- // src/logger.ts
1712
+ // src/core/logger.ts
267
1713
  var Logger = class _Logger {
268
1714
  name;
269
1715
  transports;
@@ -274,7 +1720,10 @@ var Logger = class _Logger {
274
1720
  this.name = name;
275
1721
  this.currentLevel = parseLevel(options.level ?? 20 /* INFO */);
276
1722
  this.transports = options.transports ? [...options.transports] : [];
277
- this.plugins = options.plugins ? [...options.plugins] : [];
1723
+ this.plugins = [];
1724
+ for (const plugin of options.plugins ?? []) {
1725
+ this.use(plugin);
1726
+ }
278
1727
  this.baseMeta = options.meta ? { ...options.meta } : {};
279
1728
  }
280
1729
  get level() {
@@ -283,9 +1732,14 @@ var Logger = class _Logger {
283
1732
  setLevel(level) {
284
1733
  this.currentLevel = parseLevel(level);
285
1734
  }
286
- /** Register a plugin. Returns `this` so calls can be chained. */
1735
+ /**
1736
+ * Register a plugin, or a plain `beforeLog`-style function. A function is
1737
+ * wrapped internally as an anonymous `Plugin` (`FunctionPlugin`) — the
1738
+ * same middleware ergonomics as Express/Koa, without needing to read the
1739
+ * `Plugin` interface first. Returns `this` so calls can be chained.
1740
+ */
287
1741
  use(plugin) {
288
- this.plugins.push(plugin);
1742
+ this.plugins.push(typeof plugin === "function" ? new FunctionPlugin(plugin) : plugin);
289
1743
  return this;
290
1744
  }
291
1745
  /** Close every attached transport. Call on shutdown to flush buffered writes. */
@@ -365,8 +1819,8 @@ var Logger = class _Logger {
365
1819
  };
366
1820
 
367
1821
  // src/index.ts
368
- var VERSION = "0.1.2";
1822
+ var VERSION = "0.3.0";
369
1823
 
370
- export { CollectingTransport, ConsoleTransport, ContextPlugin, DEFAULT_REDACTED_KEYS, FileTransport, HTTPTransport, JSONFormatter, Level, Logger, RedactPlugin, SamplingPlugin, Transport, VERSION, createRecord, levelName, parseLevel, utcTimestamp };
1824
+ export { AlertingPlugin, AppInsightsTransport, BaseQueueTransport, BaseSQLTransport, BatchingTransport, CloudLoggingTransport, CloudWatchTransport, CollectingTransport, ConsoleTransport, ContextPlugin, DEFAULT_PII_PATTERNS, DEFAULT_REDACTED_KEYS, DatadogTransport, DynamoDBTransport, ElasticsearchTransport, EmailAlertPlugin, FileTransport, FunctionPlugin, GENESIS_HASH, HTTPTransport, JSONFormatter, KafkaTransport, Level, Logger, MongoDBTransport, MySQLTransport, NewRelicTransport, PIIRedactPlugin, PagerDutyAlertPlugin, PostgresTransport, PubSubTransport, RabbitMQTransport, RedactPlugin, RedisTransport, SQLiteTransport, SQSTransport, SamplingPlugin, SlackAlertPlugin, TamperEvidentPlugin, Transport, VERSION, createRecord, levelName, parseLevel, utcTimestamp };
371
1825
  //# sourceMappingURL=index.mjs.map
372
1826
  //# sourceMappingURL=index.mjs.map