@gera2ld/common 0.1.2 → 0.1.3

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.js CHANGED
@@ -256,9 +256,29 @@ var P = class {
256
256
  async put(e, t = 0) {
257
257
  this.maxSize && this.data.length >= this.maxSize && await this.defer(this.putQueue, t), this.data.push(e), this.resolve(this.getQueue);
258
258
  }
259
- }, F = class e {
259
+ }, F = {
260
+ debug: 10,
261
+ info: 20,
262
+ warn: 30,
263
+ error: 40
264
+ }, I = {
265
+ debug: "debug",
266
+ info: "info",
267
+ warn: "warn",
268
+ error: "error"
269
+ };
270
+ function L(e) {
271
+ return typeof e == "function" ? e() || "" : e || "";
272
+ }
273
+ function R(e, t) {
274
+ return e && t ? `${e}:${t}` : t || e;
275
+ }
276
+ function z(e, t) {
277
+ return typeof e == "string" ? w(e, ...t) : w("%o", e, ...t);
278
+ }
279
+ var B = class e {
260
280
  static defaultOptions = {};
261
- output;
281
+ collectors = [];
262
282
  options;
263
283
  constructor(t) {
264
284
  this.options = {
@@ -266,24 +286,79 @@ var P = class {
266
286
  ...typeof t == "string" ? { prefix: t } : t
267
287
  };
268
288
  }
289
+ setOptions(e) {
290
+ return Object.assign(this.options, e), this;
291
+ }
292
+ clone(t) {
293
+ return new e({
294
+ ...this.options,
295
+ ...t
296
+ });
297
+ }
298
+ child(t) {
299
+ let n = this.options.prefix, r = new e({
300
+ ...this.options,
301
+ prefix: () => R(L(n), L(t))
302
+ });
303
+ return r.collectors = this.collectors, r;
304
+ }
269
305
  getPrefix() {
270
- let { prefix: e } = this.options;
271
- return typeof e == "function" && (e = e()), e || "";
272
- }
273
- collect() {
274
- return this.output = [], () => {
275
- let { output: e } = this;
276
- if (this.output = void 0, !e) throw Error("Logs already collected");
277
- return e;
306
+ return L(this.options.prefix);
307
+ }
308
+ getLevel() {
309
+ return this.options.level || "debug";
310
+ }
311
+ setLevel(e) {
312
+ return this.setOptions({ level: e });
313
+ }
314
+ isEnabledFor(e) {
315
+ return this.options.enabled !== !1 && F[e] >= F[this.getLevel()];
316
+ }
317
+ resolveTimestamp() {
318
+ let { timestamp: e } = this.options;
319
+ if (e) return typeof e == "function" ? e() : (/* @__PURE__ */ new Date()).toISOString();
320
+ }
321
+ defaultSink(e) {
322
+ let t = I[e.level];
323
+ (console[t] || console.log)(...[
324
+ e.timestamp,
325
+ e.prefix,
326
+ e.message
327
+ ].filter(Boolean));
328
+ }
329
+ collect(e) {
330
+ let t = {
331
+ entries: [],
332
+ silent: e?.silent
333
+ };
334
+ return this.collectors.push(t), () => {
335
+ let e = this.collectors.indexOf(t);
336
+ if (e < 0) throw Error("Logs already collected");
337
+ return this.collectors.splice(e, 1), t.entries;
278
338
  };
279
339
  }
280
340
  log(e, t, ...n) {
281
- let r = w(t, ...n);
282
- this.output && this.output.push(r), console[e](this.getPrefix(), r);
341
+ if (!this.isEnabledFor(e)) return;
342
+ let r = {
343
+ level: e,
344
+ prefix: this.getPrefix(),
345
+ message: z(t, n),
346
+ timestamp: this.resolveTimestamp(),
347
+ args: n
348
+ };
349
+ for (let e of this.collectors) e.entries.push(r);
350
+ let i = this.collectors[this.collectors.length - 1];
351
+ this.options.silent || i?.silent || (this.options.sink ? this.options.sink(r) : this.defaultSink(r));
352
+ }
353
+ debug(e, ...t) {
354
+ return this.log("debug", e, ...t);
283
355
  }
284
356
  info(e, ...t) {
285
357
  return this.log("info", e, ...t);
286
358
  }
359
+ warn(e, ...t) {
360
+ return this.log("warn", e, ...t);
361
+ }
287
362
  error(e, ...t) {
288
363
  return this.log("error", e, ...t);
289
364
  }
@@ -296,13 +371,13 @@ var P = class {
296
371
  };
297
372
  //#endregion
298
373
  //#region src/number.ts
299
- function I(t, n) {
374
+ function V(t, n) {
300
375
  return BigInt(e(t).multipliedBy(e(10).exponentiatedBy(n)).toFixed(0));
301
376
  }
302
- function L(t, n) {
377
+ function H(t, n) {
303
378
  return e(t).dividedBy(e(10).exponentiatedBy(n)).toNumber();
304
379
  }
305
- var R = {
380
+ var U = {
306
381
  maximumFractionDigits: 4,
307
382
  exponentialThresholdLarge: 1e6,
308
383
  exponentialThresholdSmall: 1e-6,
@@ -311,12 +386,12 @@ var R = {
311
386
  quantizationStep: 0,
312
387
  keepTrailingZeros: !1
313
388
  };
314
- function z(e, t) {
389
+ function W(e, t) {
315
390
  if (e == null || e === "") return "";
316
391
  let n = +e;
317
392
  if (Number.isNaN(n)) return "";
318
393
  let r = {
319
- ...R,
394
+ ...U,
320
395
  ...t
321
396
  };
322
397
  r.quantizationStep > 0 && (n = Math.round(n / r.quantizationStep) * r.quantizationStep);
@@ -333,19 +408,19 @@ function z(e, t) {
333
408
  let s = new Intl.NumberFormat("en-US", o).format(n);
334
409
  return !r.keepTrailingZeros && s.includes(".") && (s = s.replace(/\.?0+$/, "")), s;
335
410
  }
336
- function B(e, t) {
337
- return z(e * 100, t) + "%";
411
+ function G(e, t) {
412
+ return W(e * 100, t) + "%";
338
413
  }
339
414
  //#endregion
340
415
  //#region src/rate-limiter.ts
341
- var V = {
416
+ var K = {
342
417
  interval: 2e3,
343
418
  maxRetry: 6,
344
419
  maxInterval: 0
345
420
  };
346
- function H(e) {
421
+ function q(e) {
347
422
  let n = {
348
- ...V,
423
+ ...K,
349
424
  ...e
350
425
  }, { interval: r, maxInterval: i } = n;
351
426
  i && i < r && (i = r);
@@ -365,9 +440,9 @@ function H(e) {
365
440
  return a = o.catch(() => {}).then(() => t(r)), o;
366
441
  };
367
442
  }
368
- async function U(e, n) {
443
+ async function J(e, n) {
369
444
  let r = {
370
- ...V,
445
+ ...K,
371
446
  ...n
372
447
  }, { interval: i, maxInterval: a } = r;
373
448
  a && a < i && (a = i);
@@ -377,14 +452,14 @@ async function U(e, n) {
377
452
  }
378
453
  //#endregion
379
454
  //#region src/request.ts
380
- var W = class extends Error {
455
+ var Y = class extends Error {
381
456
  request;
382
457
  response;
383
458
  constructor(e, t, n, r) {
384
459
  super(e, { cause: r }), this.request = t, this.response = n;
385
460
  }
386
461
  };
387
- function G(e) {
462
+ function X(e) {
388
463
  let t = new URLSearchParams();
389
464
  return Array.isArray(e) || e instanceof URLSearchParams ? new URLSearchParams(e).forEach((e, n) => {
390
465
  t.append(n, e);
@@ -397,11 +472,11 @@ function G(e) {
397
472
  } else t.append(e, n);
398
473
  }), t;
399
474
  }
400
- function K(e, t) {
475
+ function Z(e, t) {
401
476
  let { json: n, timeout: r = 1e4, searchParams: i, signal: a = AbortSignal.timeout(r), ...o } = t || {}, s = new Headers(o.headers);
402
477
  n != null && (o.body = JSON.stringify(n), s.set("content-type", "application/json"));
403
478
  let c = new URL(e);
404
- i && (c.search = G(i).toString());
479
+ i && (c.search = X(i).toString());
405
480
  async function l(e) {
406
481
  let n;
407
482
  try {
@@ -411,14 +486,14 @@ function K(e, t) {
411
486
  signal: a
412
487
  });
413
488
  let r = await e(n);
414
- if (!n.ok) throw new W(n.statusText, {
489
+ if (!n.ok) throw new Y(n.statusText, {
415
490
  url: c.toString(),
416
491
  method: o.method || "GET",
417
492
  options: t
418
493
  }, n, r);
419
494
  return r;
420
495
  } catch (e) {
421
- throw e instanceof W ? e : new W(e?.message || `${e}`, {
496
+ throw e instanceof Y ? e : new Y(e?.message || `${e}`, {
422
497
  url: c.toString(),
423
498
  method: o.method || "GET",
424
499
  options: t
@@ -442,7 +517,7 @@ function K(e, t) {
442
517
  }
443
518
  //#endregion
444
519
  //#region src/time.ts
445
- var q = [
520
+ var Q = [
446
521
  ["ms", 1],
447
522
  ["s", 1e3],
448
523
  ["m", 60],
@@ -450,7 +525,7 @@ var q = [
450
525
  ["d", 24],
451
526
  ["mo", 30],
452
527
  ["y", 365 / 30]
453
- ], J = [
528
+ ], $ = [
454
529
  ["year", 365 * 24 * 60 * 60 * 1e3],
455
530
  ["month", 720 * 60 * 60 * 1e3],
456
531
  ["week", 10080 * 60 * 1e3],
@@ -459,10 +534,10 @@ var q = [
459
534
  ["minute", 60 * 1e3],
460
535
  ["second", 1e3]
461
536
  ];
462
- function Y(e) {
537
+ function ee(e) {
463
538
  let t = `${e}`.match(/[a-zA-Z]+$/)?.[0] || "", n = t ? +`${e}`.slice(0, -t.length) : +e;
464
539
  if (t) {
465
- for (let [e, r] of q) if (n *= r, e === t) {
540
+ for (let [e, r] of Q) if (n *= r, e === t) {
466
541
  t = "";
467
542
  break;
468
543
  }
@@ -470,9 +545,9 @@ function Y(e) {
470
545
  if (t || isNaN(n)) throw Error(`Invalid interval: ${e}`);
471
546
  return n;
472
547
  }
473
- function X(e, t) {
548
+ function te(e, t) {
474
549
  let { locale: n, style: r = "long" } = t ?? {}, i = Math.abs(e);
475
- for (let [e, t] of J) if (i >= t) return new Intl.NumberFormat(n, {
550
+ for (let [e, t] of $) if (i >= t) return new Intl.NumberFormat(n, {
476
551
  style: "unit",
477
552
  unit: e,
478
553
  unitDisplay: r
@@ -483,22 +558,22 @@ function X(e, t) {
483
558
  unitDisplay: r
484
559
  }).format(Math.round(i / 1e3));
485
560
  }
486
- function Z(e) {
561
+ function ne(e) {
487
562
  return [
488
563
  e.getFullYear(),
489
564
  e.getMonth() + 1,
490
565
  e.getDate()
491
566
  ].map((e) => `${e}`.padStart(2, "0")).join("-");
492
567
  }
493
- function Q(e) {
568
+ function re(e) {
494
569
  return new Intl.DateTimeFormat("en-GB", {
495
570
  dateStyle: "short",
496
571
  timeStyle: "medium"
497
572
  }).format(new Date(e));
498
573
  }
499
- function $(e, t) {
574
+ function ie(e, t) {
500
575
  let n = new Date(e).getTime() - Date.now(), r = Math.abs(n), { locale: i, numeric: a = "auto", style: o = "long" } = t ?? {};
501
- for (let [e, t] of J) if (r >= t) return new Intl.RelativeTimeFormat(i, {
576
+ for (let [e, t] of $) if (r >= t) return new Intl.RelativeTimeFormat(i, {
502
577
  numeric: a,
503
578
  style: o
504
579
  }).format(Math.round(n / t), e);
@@ -508,4 +583,4 @@ function $(e, t) {
508
583
  }).format(Math.round(n / 1e3), "second");
509
584
  }
510
585
  //#endregion
511
- export { A as BufferReader, k as CrLf, F as Logger, P as Queue, W as SimpleRequestError, h as b64decode, m as b64encode, _ as b64urlDecode, g as b64urlEncode, G as buildSearchParams, D as bytesToHex, j as concatBuffer, y as decodeText, T as defer, L as deflateNumber, v as encodeText, X as formatDuration, Z as formatISODate, z as formatNumber, B as formatPercentage, w as formatString, I as inflateNumber, N as limitConcurrency, O as loadJS, Y as normalizeInterval, H as rateLimiter, b as replacerBigInt, Q as reprDate, C as reprJson, M as searchBuffer, K as simpleRequest, $ as timeAgo, S as truncateString, U as waitUntil, E as wrapFunction };
586
+ export { A as BufferReader, k as CrLf, B as Logger, P as Queue, Y as SimpleRequestError, h as b64decode, m as b64encode, _ as b64urlDecode, g as b64urlEncode, X as buildSearchParams, D as bytesToHex, j as concatBuffer, y as decodeText, T as defer, H as deflateNumber, v as encodeText, te as formatDuration, ne as formatISODate, W as formatNumber, G as formatPercentage, w as formatString, V as inflateNumber, N as limitConcurrency, O as loadJS, ee as normalizeInterval, q as rateLimiter, b as replacerBigInt, re as reprDate, C as reprJson, M as searchBuffer, Z as simpleRequest, ie as timeAgo, S as truncateString, J as waitUntil, E as wrapFunction };
package/dist/logger.d.ts CHANGED
@@ -1,16 +1,63 @@
1
- interface ILoggerOptions {
1
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
2
+ export interface LogEntry {
3
+ level: LogLevel;
4
+ prefix: string;
5
+ message: string;
6
+ timestamp?: string;
7
+ /** Raw args passed to the log call, useful for custom sinks. */
8
+ args: unknown[];
9
+ }
10
+ export interface LoggerOptions {
2
11
  prefix?: string | (() => string);
12
+ /** Minimum level to emit. Defaults to 'debug'. */
13
+ level?: LogLevel;
14
+ /** When false, nothing is emitted or collected. Defaults to true. */
15
+ enabled?: boolean;
16
+ /** When true, console/sink output is skipped but collectors still capture. */
17
+ silent?: boolean;
18
+ /** Include timestamp in entries. `true` uses `toISOString()`. */
19
+ timestamp?: boolean | (() => string);
20
+ /**
21
+ * Custom output. Replaces the default console output.
22
+ * Useful for file/memory/remote outputs or adapters like
23
+ * `entry => pino[entry.level](entry.message)`.
24
+ */
25
+ sink?: (entry: LogEntry) => void;
3
26
  }
27
+ /** @deprecated Use `LoggerOptions` instead. */
28
+ export type ILoggerOptions = LoggerOptions;
4
29
  export declare class Logger {
5
- static defaultOptions: ILoggerOptions;
6
- private output?;
7
- options: ILoggerOptions;
8
- constructor(opts?: string | Partial<ILoggerOptions>);
30
+ static defaultOptions: LoggerOptions;
31
+ private collectors;
32
+ options: LoggerOptions;
33
+ constructor(opts?: string | Partial<LoggerOptions>);
34
+ /** Update options in place. Returns `this` for chaining. */
35
+ setOptions(patch: Partial<LoggerOptions>): this;
36
+ /** Copy this logger, optionally overriding options. Collectors are not shared. */
37
+ clone(extra?: Partial<LoggerOptions>): Logger;
38
+ /**
39
+ * Create a sub-logger with an extended prefix.
40
+ * Collectors are shared so `parent.collect()` also captures child logs.
41
+ */
42
+ child(prefix: string | (() => string)): Logger;
9
43
  getPrefix(): string;
10
- collect(): () => string[];
11
- log(type: 'info' | 'error', pattern: string, ...args: unknown[]): void;
12
- info(pattern: string, ...args: unknown[]): void;
13
- error(pattern: string, ...args: unknown[]): void;
44
+ getLevel(): LogLevel;
45
+ setLevel(level: LogLevel): this;
46
+ isEnabledFor(level: LogLevel): boolean;
47
+ private resolveTimestamp;
48
+ private defaultSink;
49
+ /**
50
+ * Capture subsequent `LogEntry` objects.
51
+ * Supports nesting; each call gets its own buffer.
52
+ * With `{ silent: true }`, console/sink output is suppressed while capturing.
53
+ */
54
+ collect(opts?: {
55
+ silent?: boolean;
56
+ }): () => LogEntry[];
57
+ log(level: LogLevel, pattern: unknown, ...args: unknown[]): void;
58
+ debug(pattern: unknown, ...args: unknown[]): void;
59
+ info(pattern: unknown, ...args: unknown[]): void;
60
+ warn(pattern: unknown, ...args: unknown[]): void;
61
+ error(pattern: unknown, ...args: unknown[]): void;
14
62
  wrap<U extends unknown[], V, T>(fn: (this: T, ...args: U) => V, wrapper: (logger: Logger, fn: (this: T, ...args: U) => V, ...args: U) => V): (this: T, ...args: U) => V;
15
63
  }
16
- export {};
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gera2ld/common",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "exports": {