halua 2.0.2 → 4.0.2

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/lib/index.js CHANGED
@@ -1,4 +1,3 @@
1
- // src/types/log.ts
2
1
  var Level = /* @__PURE__ */ ((Level2) => {
3
2
  Level2["Trace"] = "TRACE";
4
3
  Level2["Debug"] = "DEBUG";
@@ -10,118 +9,89 @@ var Level = /* @__PURE__ */ ((Level2) => {
10
9
  return Level2;
11
10
  })(Level || {});
12
11
 
13
- // src/main/getType.ts
14
- function getType(arg) {
15
- if (typeof arg === "undefined") {
16
- return "undefined";
17
- }
18
- if (typeof arg === "object" && String(arg) === "null") {
19
- return "null";
20
- }
21
- if (Array.isArray(arg)) {
22
- return "array";
23
- }
24
- if (ArrayBuffer.isView(arg)) {
25
- return "typedarray";
26
- }
27
- if (arg instanceof ArrayBuffer) {
28
- return "arraybuffer";
29
- }
30
- if (arg instanceof Map) {
31
- return "map";
32
- }
33
- if (arg instanceof Set) {
34
- return "set";
35
- }
36
- if (arg instanceof WeakMap) {
37
- return "weakmap";
38
- }
39
- if (arg instanceof WeakSet) {
40
- return "weakset";
41
- }
42
- if (arg instanceof Date) {
43
- return "date";
44
- }
45
- if (arg instanceof Error) {
46
- return "error";
47
- }
48
- if (Number.isNaN(arg)) {
49
- return "nan";
50
- }
51
- if (typeof arg === "number" && !Number.isFinite(arg)) {
52
- return "infinity";
53
- }
54
- return typeof arg;
55
- }
56
-
57
- // src/main/util/string.ts
58
12
  function extractLevels(level) {
59
13
  if (typeof level !== "string") {
60
- return ["INFO" /* Info */, 0];
61
- }
62
- let data = level.split("+");
63
- if (data.length !== 2) {
64
- let levels = ["TRACE" /* Trace */, "DEBUG" /* Debug */, "INFO" /* Info */, "WARN" /* Warn */, "NOTICE" /* Notice */, "ERROR" /* Error */, "FATAL" /* Fatal */];
65
- for (let l of levels) {
66
- if (level.includes(l)) {
67
- return [l, Math.trunc(level.split(l)[1])];
68
- }
69
- }
14
+ return [Level.Info, 0];
15
+ }
16
+ let s = level.toUpperCase().trim();
17
+ let data = s.split("+");
18
+ let major;
19
+ let minor;
20
+ if (data.length >= 2) {
21
+ major = data[0].trim() || Level.Info;
22
+ let n = Number(data[1].trim());
23
+ minor = Number.isFinite(n) ? Math.trunc(n) : 0;
24
+ } else {
25
+ major = s || Level.Info;
26
+ minor = 0;
27
+ }
28
+ if (minor < 0) minor = 0;
29
+ return [major, minor];
30
+ }
31
+ function printTimes(n, value) {
32
+ if (n <= 0) {
33
+ return "";
70
34
  }
71
- return [data[0], Math.trunc(data[1]) || 0];
35
+ return value.repeat(n);
72
36
  }
73
37
 
74
- // src/main/errors.ts
75
- var HaluaFailedToCallHandler = class extends Error {
38
+ function unknownToError(err) {
39
+ if (err instanceof Error) {
40
+ return err;
41
+ }
42
+ if (typeof err === "string") {
43
+ return new Error(err);
44
+ }
45
+ let error = "";
46
+ try {
47
+ error = JSON.stringify(err);
48
+ } catch (_) {
49
+ }
50
+ return new Error(error, { cause: err });
51
+ }
52
+ class HaluaFailedToCallDispatcher extends Error {
76
53
  constructor(message, options = {}) {
77
- super(`HaluaFailedToCallHandlerError: ${message}`, options);
54
+ super(`HaluaFailedToCallDispatcherError: ${message}`, options);
78
55
  }
79
- };
80
- var HaluaUnableToDetermineHandler = class extends Error {
56
+ }
57
+ class HaluaUnableToDetermineDispatcher extends Error {
81
58
  constructor(message, options = {}) {
82
- super(`HaluaUnableToDetermineHandlerError: ${message}`, options);
59
+ super(`HaluaUnableToDetermineDispatcherError: ${message}`, options);
83
60
  }
84
- };
85
- var HaluaParse = class extends Error {
61
+ }
62
+ class HaluaParse extends Error {
86
63
  constructor(message, options = {}) {
87
64
  super(`HaluaParseError: ${message}`, options);
88
65
  }
89
- };
66
+ }
90
67
 
91
- // src/main/util/errors.ts
92
68
  function tryReportAnError(err) {
93
69
  try {
94
- let log = "self" in window ? self.console : console;
70
+ let log = typeof self !== "undefined" ? self.console : console;
95
71
  log.error(err);
96
72
  } catch (_) {
97
73
  }
98
74
  }
99
75
 
100
- // src/main/handlers/Balancer.ts
101
- var MajorLevelMap = /* @__PURE__ */ new Map([
102
- ["FATAL" /* Fatal */, /* @__PURE__ */ new Set(["FATAL" /* Fatal */])],
103
- ["ERROR" /* Error */, /* @__PURE__ */ new Set(["FATAL" /* Fatal */, "ERROR" /* Error */])],
104
- ["WARN" /* Warn */, /* @__PURE__ */ new Set(["FATAL" /* Fatal */, "ERROR" /* Error */, "WARN" /* Warn */])],
105
- ["NOTICE" /* Notice */, /* @__PURE__ */ new Set(["FATAL" /* Fatal */, "ERROR" /* Error */, "WARN" /* Warn */, "NOTICE" /* Notice */])],
106
- ["INFO" /* Info */, /* @__PURE__ */ new Set(["FATAL" /* Fatal */, "ERROR" /* Error */, "WARN" /* Warn */, "NOTICE" /* Notice */, "INFO" /* Info */])],
107
- ["DEBUG" /* Debug */, /* @__PURE__ */ new Set(["FATAL" /* Fatal */, "ERROR" /* Error */, "WARN" /* Warn */, "NOTICE" /* Notice */, "INFO" /* Info */, "DEBUG" /* Debug */])],
108
- ["TRACE" /* Trace */, /* @__PURE__ */ new Set(["FATAL" /* Fatal */, "ERROR" /* Error */, "WARN" /* Warn */, "NOTICE" /* Notice */, "INFO" /* Info */, "DEBUG" /* Debug */, "TRACE" /* Trace */])]
76
+ const MajorLevelMap = /* @__PURE__ */ new Map([
77
+ [Level.Fatal, /* @__PURE__ */ new Set([Level.Fatal])],
78
+ [Level.Error, /* @__PURE__ */ new Set([Level.Fatal, Level.Error])],
79
+ [Level.Warn, /* @__PURE__ */ new Set([Level.Fatal, Level.Error, Level.Warn])],
80
+ [Level.Notice, /* @__PURE__ */ new Set([Level.Fatal, Level.Error, Level.Warn, Level.Notice])],
81
+ [Level.Info, /* @__PURE__ */ new Set([Level.Fatal, Level.Error, Level.Warn, Level.Notice, Level.Info])],
82
+ [Level.Debug, /* @__PURE__ */ new Set([Level.Fatal, Level.Error, Level.Warn, Level.Notice, Level.Info, Level.Debug])],
83
+ [Level.Trace, /* @__PURE__ */ new Set([Level.Fatal, Level.Error, Level.Warn, Level.Notice, Level.Info, Level.Debug, Level.Trace])]
109
84
  ]);
110
- var HandlersBalancer = class {
111
- constructor(level, handlers, format2) {
85
+ class DispatchersBalancer {
86
+ constructor(level, dispatchers) {
112
87
  this.level = level;
113
- this.handlers = handlers;
114
- this.format = format2;
88
+ this.dispatchers = dispatchers;
115
89
  this.sendLog = this.sendLog.bind(this);
116
- this.reset = this.reset.bind(this);
117
90
  }
118
91
  map = /* @__PURE__ */ new Map();
119
- sendLog(meta, args) {
92
+ sendLog(meta, args, errorMeta) {
120
93
  this.discover(meta.level);
121
- this.send(meta, args);
122
- }
123
- reset() {
124
- this.map.clear();
94
+ this.send(meta, args, errorMeta);
125
95
  }
126
96
  discover(level) {
127
97
  if (this.map.get(level)) {
@@ -129,7 +99,7 @@ var HandlersBalancer = class {
129
99
  }
130
100
  let discovered = [];
131
101
  this.map.set(level, discovered);
132
- for (let h of this.handlers) {
102
+ for (let h of this.dispatchers) {
133
103
  if (h.exact) {
134
104
  if (h.exact.some((l) => l === level)) {
135
105
  discovered.push(h);
@@ -141,52 +111,202 @@ var HandlersBalancer = class {
141
111
  }
142
112
  }
143
113
  }
144
- send(meta, args) {
114
+ send(meta, args, errorMeta) {
145
115
  try {
146
- this.sendToHandlers(meta, args);
116
+ this.sendToDispatchers(meta, args, errorMeta);
147
117
  } catch (e) {
148
- tryReportAnError(new HaluaFailedToCallHandler(`Unable to call execution method of a handler`, { cause: e }));
149
- }
150
- }
151
- sendToHandlers(meta, args) {
152
- let generators = (this.map.get(meta.level) ?? []).map((h) => h.execute(meta));
153
- generators.forEach((e) => e.next({ type: "init", value: null }));
154
- let state = Array.from({ length: generators.length }).fill(void 0);
155
- for (let arg of args) {
156
- generators.forEach((e, i) => {
157
- try {
158
- let result = e.next({ type: "arg", value: arg, prev: state[i] });
159
- state[i] = void 0;
160
- if (result.value?.type === "pass") {
161
- state[i] = this.format({ type: getType(arg), value: arg });
162
- }
163
- } catch (e2) {
164
- tryReportAnError(new HaluaParse(`Failed to parse an argument`, { cause: e2 }));
165
- }
166
- });
118
+ tryReportAnError(
119
+ new HaluaFailedToCallDispatcher(`Unable to call dispatch method of a dispatcher`, { cause: e })
120
+ );
121
+ }
122
+ }
123
+ sendToDispatchers(meta, args, errorMeta) {
124
+ let hs = this.map.get(meta.level) ?? [];
125
+ for (let h of hs) {
126
+ try {
127
+ h.dispatch(meta, args, errorMeta);
128
+ } catch (e) {
129
+ tryReportAnError(
130
+ new HaluaFailedToCallDispatcher(`Unable to call dispatch method of a dispatcher`, { cause: e })
131
+ );
132
+ }
167
133
  }
168
- generators.forEach((e, i) => {
169
- e.next({ type: "done", value: null, prev: state[i] });
170
- });
171
- state = [];
172
134
  }
173
- canSend(l, to = this.level || "TRACE" /* Trace */) {
135
+ canSend(l, to = this.level || Level.Trace) {
174
136
  let lvl = extractLevels(l);
175
137
  let toLvl = extractLevels(to);
176
138
  return this.majorLevelCheck(lvl[0], toLvl[0]) + this.minorLevelCheck(lvl[1], toLvl[1]) > 0;
177
139
  }
178
140
  majorLevelCheck(l, to) {
179
- if (!MajorLevelMap.get(to).has(l)) {
141
+ if (l === to) {
142
+ return 0;
143
+ }
144
+ let toSet = MajorLevelMap.get(to);
145
+ if (!toSet || !toSet.has(l)) {
180
146
  return -1;
181
147
  }
182
- return l === to ? 0 : 1;
148
+ return 1;
183
149
  }
184
150
  minorLevelCheck(l, to) {
185
151
  return l >= to ? 1 : 0;
186
152
  }
187
- };
153
+ }
154
+
155
+ function toarray(value) {
156
+ return Array.isArray(value) ? value : typeof value === "undefined" ? [] : [value];
157
+ }
158
+
159
+ class Halua {
160
+ constructor(passed, options = {}) {
161
+ this.options = options;
162
+ this.passedDispatchers = passed;
163
+ this.dispatchers = this.buildDispatchers(passed);
164
+ this.balancer = new DispatchersBalancer(this.options.level || Level.Trace, this.dispatchers);
165
+ this.bindMethods();
166
+ }
167
+ passedDispatchers = [];
168
+ dispatchers = [];
169
+ balancer;
170
+ stamps = /* @__PURE__ */ new Map();
171
+ create(arg1 = this.passedDispatchers, arg2 = this.options) {
172
+ if (this.isDispatcherSpec(arg1)) {
173
+ return new Halua(arg1, { ...arg2 ?? this.options });
174
+ }
175
+ return new Halua(this.passedDispatchers, { ...arg1 });
176
+ }
177
+ child(...args) {
178
+ return new Halua(this.passedDispatchers, {
179
+ ...this.options,
180
+ withArgs: (this.options.withArgs || []).concat(args)
181
+ });
182
+ }
183
+ setDispatchers(dispatcher) {
184
+ this.dispatchers = this.buildDispatchers(dispatcher);
185
+ this.updateBalancer();
186
+ }
187
+ appendDispatchers(dispatcher) {
188
+ let dispatchers = this.buildDispatchers(dispatcher);
189
+ this.dispatchers.push(...dispatchers);
190
+ this.updateBalancer();
191
+ }
192
+ logTo(level, ...args) {
193
+ this.sendToBalancer(level, args);
194
+ }
195
+ trace(...args) {
196
+ this.sendToBalancer(Level.Trace, args);
197
+ }
198
+ debug(...args) {
199
+ this.sendToBalancer(Level.Debug, args);
200
+ }
201
+ info(...args) {
202
+ this.sendToBalancer(Level.Info, args);
203
+ }
204
+ warn(...args) {
205
+ this.sendToBalancer(Level.Warn, args);
206
+ }
207
+ notice(...args) {
208
+ this.sendToBalancer(Level.Notice, args);
209
+ }
210
+ error(error, meta) {
211
+ let e = unknownToError(error);
212
+ let payload = [e];
213
+ let finalMeta = meta != null ? { ...meta, error: e } : void 0;
214
+ this.sendToBalancer(Level.Error, payload, finalMeta);
215
+ }
216
+ fatal(...args) {
217
+ this.sendToBalancer(Level.Fatal, args);
218
+ }
219
+ assert(assertion, error, meta) {
220
+ if (assertion) {
221
+ return;
222
+ }
223
+ let e = unknownToError(error);
224
+ let payload = [e];
225
+ let finalMeta = meta != null ? { ...meta, error: e } : void 0;
226
+ this.sendToBalancer(Level.Error, payload, finalMeta);
227
+ }
228
+ stamp(label, id) {
229
+ let start = performance.now();
230
+ if (id != null) {
231
+ this.stamps.set(id, { label, start });
232
+ }
233
+ let ended = false;
234
+ const ender = () => {
235
+ if (ended) {
236
+ return;
237
+ }
238
+ ended = true;
239
+ if (id != null) {
240
+ let current = this.stamps.get(id);
241
+ if (current && current.start === start) {
242
+ this.stamps.delete(id);
243
+ }
244
+ }
245
+ this.endStamp(label, start);
246
+ };
247
+ return ender;
248
+ }
249
+ stampEnd(id) {
250
+ let entry = this.stamps.get(id);
251
+ if (!entry) {
252
+ return;
253
+ }
254
+ this.stamps.delete(id);
255
+ this.endStamp(entry.label, entry.start);
256
+ }
257
+ endStamp(label, start) {
258
+ let duration = performance.now() - start;
259
+ let ms = duration.toFixed(2);
260
+ this.info(label, `took ${ms}ms`);
261
+ }
262
+ updateBalancer() {
263
+ this.balancer = new DispatchersBalancer(this.options.level || Level.Trace, this.dispatchers);
264
+ }
265
+ sendToBalancer(level, args, errorMeta) {
266
+ let finalArgs = args.concat(this.options.withArgs ?? []);
267
+ let dispatchMeta = { level, timestamp: Date.now() };
268
+ if (this.options.redactDataRegExp) {
269
+ dispatchMeta.redactDataRegExp = this.options.redactDataRegExp;
270
+ }
271
+ this.balancer.sendLog(dispatchMeta, finalArgs, errorMeta);
272
+ }
273
+ supposeIsDispatcher(v, reportError = true) {
274
+ let isDispatcher = typeof v?.dispatch === "function";
275
+ if (!isDispatcher && reportError) {
276
+ tryReportAnError(new HaluaUnableToDetermineDispatcher(`Unable to find dispatch method of a dispatcher`));
277
+ }
278
+ return isDispatcher;
279
+ }
280
+ isDispatcherSpec(v) {
281
+ if (Array.isArray(v)) {
282
+ return v.every((x) => typeof x === "function");
283
+ }
284
+ return typeof v === "function";
285
+ }
286
+ buildDispatchers(passed) {
287
+ let entries = toarray(passed);
288
+ return entries.map((b) => b()).filter((h) => this.supposeIsDispatcher(h));
289
+ }
290
+ bindMethods() {
291
+ this.create = this.create.bind(this);
292
+ this.child = this.child.bind(this);
293
+ this.setDispatchers = this.setDispatchers.bind(this);
294
+ this.appendDispatchers = this.appendDispatchers.bind(this);
295
+ this.logTo = this.logTo.bind(this);
296
+ this.trace = this.trace.bind(this);
297
+ this.debug = this.debug.bind(this);
298
+ this.info = this.info.bind(this);
299
+ this.warn = this.warn.bind(this);
300
+ this.notice = this.notice.bind(this);
301
+ this.error = this.error.bind(this);
302
+ this.fatal = this.fatal.bind(this);
303
+ this.assert = this.assert.bind(this);
304
+ this.stamp = this.stamp.bind(this);
305
+ this.stampEnd = this.stampEnd.bind(this);
306
+ this.supposeIsDispatcher = this.supposeIsDispatcher.bind(this);
307
+ }
308
+ }
188
309
 
189
- // src/util/spacing.ts
190
310
  var Spacing = /* @__PURE__ */ ((Spacing2) => {
191
311
  Spacing2["Space"] = " ";
192
312
  Spacing2["Tab"] = " ";
@@ -202,17 +322,50 @@ var EmptySpacing = /* @__PURE__ */ ((EmptySpacing2) => {
202
322
  return EmptySpacing2;
203
323
  })(EmptySpacing || {});
204
324
 
205
- // src/util/string.ts
206
- function printTimes(n, value) {
207
- let str = "";
208
- for (let i = n; i !== 0; i -= 1) {
209
- str += value;
325
+ function getType(arg) {
326
+ if (typeof arg === "undefined") {
327
+ return "undefined";
328
+ }
329
+ if (typeof arg === "object" && String(arg) === "null") {
330
+ return "null";
331
+ }
332
+ if (Array.isArray(arg)) {
333
+ return "array";
334
+ }
335
+ if (ArrayBuffer.isView(arg)) {
336
+ return "typedarray";
337
+ }
338
+ if (arg instanceof ArrayBuffer) {
339
+ return "arraybuffer";
340
+ }
341
+ if (arg instanceof Map) {
342
+ return "map";
343
+ }
344
+ if (arg instanceof Set) {
345
+ return "set";
346
+ }
347
+ if (arg instanceof WeakMap) {
348
+ return "weakmap";
349
+ }
350
+ if (arg instanceof WeakSet) {
351
+ return "weakset";
352
+ }
353
+ if (arg instanceof Date) {
354
+ return "date";
210
355
  }
211
- return str;
356
+ if (arg instanceof Error) {
357
+ return "error";
358
+ }
359
+ if (Number.isNaN(arg)) {
360
+ return "nan";
361
+ }
362
+ if (typeof arg === "number" && !Number.isFinite(arg)) {
363
+ return "infinity";
364
+ }
365
+ return typeof arg;
212
366
  }
213
367
 
214
- // src/main/format.ts
215
- var FormatAsIs = [
368
+ const FormatAsIs = [
216
369
  "undefined",
217
370
  "null",
218
371
  "string",
@@ -225,7 +378,7 @@ var FormatAsIs = [
225
378
  "nan",
226
379
  "infinity"
227
380
  ];
228
- var FormatNeeded = [
381
+ const FormatNeeded = [
229
382
  "array",
230
383
  "object",
231
384
  "arraybuffer",
@@ -238,24 +391,19 @@ var FormatNeeded = [
238
391
  ];
239
392
  function format(arg, spacing = true) {
240
393
  try {
241
- const SpacingEnum = spacing ? Spacing : EmptySpacing;
394
+ let SpacingEnum = spacing ? Spacing : EmptySpacing;
395
+ let seen = /* @__PURE__ */ new WeakSet();
242
396
  if (FormatAsIs.some((f) => f === arg.type)) {
243
397
  return formatAsIs(arg.value, arg.type);
244
398
  }
245
399
  if (FormatNeeded.some((f) => f === arg.type)) {
246
- return formatComplex(arg.value, arg.type, SpacingEnum);
400
+ return formatComplex(arg.value, arg.type, SpacingEnum, 1, seen);
247
401
  }
248
402
  } catch (err) {
249
403
  return new HaluaParse(err?.message || "").message;
250
404
  }
251
405
  return arg.value;
252
406
  }
253
- function formatJSON(arg) {
254
- if (arg.type === "error") {
255
- return `${arg.value.toString()} stack: ${arg.value.stack?.replace("\n", "")}`;
256
- }
257
- return format(arg, false);
258
- }
259
407
  function formatAsIs(arg, type) {
260
408
  if (type === "number") {
261
409
  return arg;
@@ -265,9 +413,25 @@ function formatAsIs(arg, type) {
265
413
  }
266
414
  return String(arg);
267
415
  }
268
- function formatComplex(arg, type, spacing, nestingLevel = 1) {
416
+ function formatValue(value, spacing, seen) {
417
+ let type = getType(value);
418
+ if (FormatAsIs.some((f) => f === type)) {
419
+ return formatAsIs(value, type);
420
+ }
421
+ if (FormatNeeded.some((f) => f === type)) {
422
+ return formatComplex(value, type, spacing, 1, seen);
423
+ }
424
+ return value;
425
+ }
426
+ function formatComplex(arg, type, spacing, nestingLevel = 1, seen) {
269
427
  if (type === "set") {
270
- return `Set${formatArray(convertSetToArray(arg), spacing)}`;
428
+ if (seen.has(arg)) {
429
+ return "[Circular]";
430
+ }
431
+ seen.add(arg);
432
+ let r = `Set${formatArray(convertSetToArray(arg), spacing, seen)}`;
433
+ seen.delete(arg);
434
+ return r;
271
435
  }
272
436
  if (type === "weakset") {
273
437
  return `WeakSet [inaccessible]`;
@@ -280,59 +444,72 @@ function formatComplex(arg, type, spacing, nestingLevel = 1) {
280
444
  return `Function ${name === "value" ? "anonymous" : name}`;
281
445
  }
282
446
  if (type === "array") {
283
- return formatArray(arg, spacing);
447
+ if (seen.has(arg)) {
448
+ return "[Circular]";
449
+ }
450
+ seen.add(arg);
451
+ let r = formatArray(arg, spacing, seen);
452
+ seen.delete(arg);
453
+ return r;
284
454
  }
285
455
  if (type === "arraybuffer") {
286
456
  return `ArrayBuffer []`;
287
457
  }
288
458
  if (type === "map") {
289
- return formatObject(convertMapToObj(arg), spacing, nestingLevel, ` => `);
459
+ if (seen.has(arg)) {
460
+ return "[Circular]";
461
+ }
462
+ seen.add(arg);
463
+ let r = formatObject(convertMapToObj(arg, spacing, seen), spacing, nestingLevel, ` => `, seen);
464
+ seen.delete(arg);
465
+ return r;
290
466
  }
291
467
  if (type === "error") {
292
468
  return `${arg.toString()} stack: ${arg.stack}`;
293
469
  }
294
470
  if (type === "object") {
295
- return formatObject(arg, spacing, nestingLevel);
471
+ if (seen.has(arg)) {
472
+ return "[Circular]";
473
+ }
474
+ seen.add(arg);
475
+ let r = formatObject(arg, spacing, nestingLevel, `: `, seen);
476
+ seen.delete(arg);
477
+ return r;
296
478
  }
297
479
  return arg;
298
480
  }
299
- function formatArray(arg, spacing) {
300
- let stringify = "[";
301
- let len = arg.length;
481
+ function formatArray(arg, spacing, seen) {
482
+ let items = [];
302
483
  for (let entry of arg) {
303
- len -= 1;
304
484
  let entryType = getType(entry);
305
- let formatted = format({ type: entryType, value: entry });
485
+ let formatted = formatValue(entry, spacing, seen);
306
486
  let entryValue = entryType === "string" ? `"${formatted}"` : formatted;
307
- stringify += `${entryValue}${len ? `,${spacing.Space}` : spacing.Empty}`;
487
+ items.push(entryValue);
308
488
  }
309
- stringify += "]";
310
- return stringify;
489
+ let sep = `,${spacing.Space}`;
490
+ return `[${items.join(sep)}]`;
311
491
  }
312
- function formatObject(arg, spacing, nestingLevel = 1, delimiter = `: `) {
313
- let stringify = `{${spacing.Line}`;
314
- let len = Object.keys(arg).length;
315
- for (let key in arg) {
316
- len -= 1;
317
- let entryType = getType(arg[key]);
318
- let formatted = entryType === "object" ? formatComplex(arg[key], entryType, spacing, nestingLevel + 1) : format({
319
- type: entryType,
320
- value: arg[key]
321
- });
492
+ function formatObject(arg, spacing, nestingLevel = 1, delimiter = `: `, seen) {
493
+ let keys = Object.keys(arg);
494
+ let kvParts = [];
495
+ for (let key of keys) {
496
+ let val = arg[key];
497
+ let entryType = getType(val);
498
+ let formatted = entryType === "object" ? formatComplex(val, entryType, spacing, nestingLevel + 1, seen) : formatValue(val, spacing, seen);
322
499
  let entryValue = entryType === "string" ? `"${formatted}"` : formatted;
323
- stringify += `${printTimes(nestingLevel, spacing.Tab)}"${key}"${delimiter}${entryValue}${len ? `,${spacing.Line}` : spacing.Empty}`;
500
+ kvParts.push(`${printTimes(nestingLevel, spacing.Tab)}"${key}"${delimiter}${entryValue}`);
324
501
  }
502
+ let body = kvParts.join(`,${spacing.Line}`);
325
503
  let level = nestingLevel - 1;
326
- stringify += `${spacing.Line}${printTimes(level, spacing.Tab)}}`;
327
- return stringify;
504
+ let closeIndent = printTimes(level, spacing.Tab);
505
+ return `{${spacing.Line}${kvParts.length ? body + spacing.Line : ""}${closeIndent}}`;
328
506
  }
329
- function convertMapToObj(value) {
507
+ function convertMapToObj(value, spacing, seen) {
330
508
  let obj = {};
331
509
  for (let [key, v] of value) {
332
510
  let keyType = getType(key);
333
- let objKey = keyType === "string" ? key : format({ type: keyType, value: key });
334
- let valueType = getType(v);
335
- obj[objKey] = format({ type: valueType, value: v });
511
+ let objKey = keyType === "string" ? key : formatValue(key, spacing, seen);
512
+ obj[objKey] = formatValue(v, spacing, seen);
336
513
  }
337
514
  return obj;
338
515
  }
@@ -343,182 +520,300 @@ function convertSetToArray(value) {
343
520
  }
344
521
  return arr;
345
522
  }
346
-
347
- // src/main/util/cast.ts
348
- function toarray(value) {
349
- return Array.isArray(value) ? value : typeof value === "undefined" ? [] : [value];
523
+ function toJSONValue(value) {
524
+ return convertToJSONValue(value, /* @__PURE__ */ new WeakSet());
350
525
  }
351
-
352
- // src/main/halua.ts
353
- var Halua = class _Halua {
354
- constructor(passed, options = {}) {
355
- this.options = options;
356
- this.passedHandlers = passed;
357
- this.handlers = this.buildHandlers(passed);
358
- this.balancer = new HandlersBalancer(this.options.level || "TRACE" /* Trace */, this.handlers, format);
359
- this.bindMethods();
526
+ function convertToJSONValue(value, seen) {
527
+ if (value == null) {
528
+ return null;
360
529
  }
361
- passedHandlers = [];
362
- handlers = [];
363
- balancer;
364
- New(arg1 = this.passedHandlers, arg2 = this.options) {
365
- if (Array.isArray(arg1)) {
366
- return new _Halua(arg1, { ...arg2 });
367
- }
368
- if (this.supposeIsHandler(arg1, false)) {
369
- return new _Halua(arg1, { ...arg2 });
370
- }
371
- if (Object.keys(arg1).length) {
372
- return new _Halua(this.passedHandlers, { ...arg1 });
373
- }
374
- return new _Halua(arg1, { ...arg2 });
530
+ let type = getType(value);
531
+ if (type === "boolean" || type === "number" || type === "string") {
532
+ return value;
375
533
  }
376
- With(...args) {
377
- return new _Halua(this.passedHandlers, { ...this.options, withArgs: (this.options.withArgs || []).concat(args) });
534
+ if (type === "symbol" || type === "function" || type === "bigint") {
535
+ return value.toString();
378
536
  }
379
- setHandlers(handler) {
380
- this.handlers = this.buildHandlers(handler);
381
- this.updateBalancer();
537
+ if (type === "date") {
538
+ return value.toISOString();
382
539
  }
383
- appendHandlers(handler) {
384
- let handlers = this.buildHandlers(handler);
385
- this.handlers.push(...handlers);
386
- this.updateBalancer();
540
+ if (type === "nan" || type === "infinity") {
541
+ return String(value);
387
542
  }
388
- logTo(level, ...args) {
389
- this.sendToBalancer(level, args);
543
+ if (type === "error") {
544
+ let stack = value.stack ? value.stack.split(/\r?\n/) : [];
545
+ return { name: value.name || "Error", message: value.message || "", stack };
390
546
  }
391
- trace(...args) {
392
- this.sendToBalancer("TRACE" /* Trace */, args);
547
+ if (type === "weakmap" || type === "weakset") {
548
+ return `[${type} inaccessible]`;
393
549
  }
394
- debug(...args) {
395
- this.sendToBalancer("DEBUG" /* Debug */, args);
550
+ if (type === "arraybuffer") {
551
+ return { __type: "ArrayBuffer", byteLength: value.byteLength };
396
552
  }
397
- info(...args) {
398
- this.sendToBalancer("INFO" /* Info */, args);
553
+ if (type === "typedarray") {
554
+ return Array.from(value);
399
555
  }
400
- warn(...args) {
401
- this.sendToBalancer("WARN" /* Warn */, args);
556
+ if (type === "array" || type === "object" || type === "map" || type === "set") {
557
+ if (seen.has(value)) {
558
+ return { __circular: true };
559
+ }
560
+ seen.add(value);
561
+ let result;
562
+ if (type === "array") {
563
+ result = value.map((item) => convertToJSONValue(item, seen));
564
+ } else if (type === "object") {
565
+ result = {};
566
+ for (let key of Object.keys(value)) {
567
+ result[key] = convertToJSONValue(value[key], seen);
568
+ }
569
+ } else if (type === "map") {
570
+ result = {};
571
+ for (let [k, v] of value) {
572
+ let jk = convertToJSONValue(k, seen);
573
+ let keyStr = typeof jk === "string" ? jk : String(jk ?? "");
574
+ result[keyStr] = convertToJSONValue(v, seen);
575
+ }
576
+ } else if (type === "set") {
577
+ result = Array.from(value, (item) => convertToJSONValue(item, seen));
578
+ }
579
+ seen.delete(value);
580
+ return result;
402
581
  }
403
- notice(...args) {
404
- this.sendToBalancer("NOTICE" /* Notice */, args);
582
+ return String(value);
583
+ }
584
+ const REDACTION_TOKEN = "^_^";
585
+ const DefaultRedactRegExp = /pass(?:word|wd)?|secret|token|api[_-]?key|access[_-]?token|auth(?:orization)?|private[_-]?key|credential|session(?:[_-]?id)?|cookie|ssn|social[_-]?sec(?:urity)?|credit[_-]?card|cc[_-]?num(?:ber)?|cvv|cvc|pin|email|phone|mobile|tel|bearer|eyJ[0-9a-zA-Z_-]{10,}\.[0-9a-zA-Z_-]{10,}|\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b|\b\d{3}[-.\s]?\d{2}[-.\s]?\d{4}\b|\b(?:\d[ -]*){13,16}\b/i;
586
+ function redact(value, regexp) {
587
+ if (!regexp) {
588
+ return value;
405
589
  }
406
- error(...args) {
407
- this.sendToBalancer("ERROR" /* Error */, args);
590
+ return redactRec(value, regexp, /* @__PURE__ */ new WeakSet());
591
+ }
592
+ function redactRec(value, re, seen) {
593
+ if (value == null) {
594
+ return value;
408
595
  }
409
- fatal(...args) {
410
- this.sendToBalancer("FATAL" /* Fatal */, args);
596
+ let type = getType(value);
597
+ if (type === "string") {
598
+ return redactString(value, re);
411
599
  }
412
- assert(assertion, ...args) {
413
- if (assertion) {
414
- return;
600
+ if (type === "array") {
601
+ if (seen.has(value)) {
602
+ return "[Circular]";
603
+ }
604
+ seen.add(value);
605
+ let result = [];
606
+ for (let entry of value) {
607
+ result.push(redactRec(entry, re, seen));
415
608
  }
416
- this.sendToBalancer("ERROR" /* Error */, args);
609
+ seen.delete(value);
610
+ return result;
417
611
  }
418
- updateBalancer() {
419
- this.balancer = new HandlersBalancer(this.options.level || "TRACE" /* Trace */, this.handlers, format);
612
+ if (type === "object") {
613
+ if (seen.has(value)) {
614
+ return "[Circular]";
615
+ }
616
+ seen.add(value);
617
+ let result = {};
618
+ for (let key of Object.keys(value)) {
619
+ let k = key;
620
+ re.lastIndex = 0;
621
+ if (re.test(k)) {
622
+ result[k] = REDACTION_TOKEN;
623
+ } else {
624
+ result[k] = redactRec(value[k], re, seen);
625
+ }
626
+ }
627
+ seen.delete(value);
628
+ return result;
420
629
  }
421
- sendToBalancer(level, args) {
422
- this.balancer.sendLog({ level, timestamp: Date.now() }, args.concat(this.options.withArgs ?? []));
630
+ if (type === "map") {
631
+ if (seen.has(value)) {
632
+ return "[Circular]";
633
+ }
634
+ seen.add(value);
635
+ let result = /* @__PURE__ */ new Map();
636
+ for (let [k, v] of value) {
637
+ let keyStr = typeof k === "string" ? k : String(k ?? "");
638
+ re.lastIndex = 0;
639
+ if (re.test(keyStr)) {
640
+ result.set(k, REDACTION_TOKEN);
641
+ } else {
642
+ result.set(k, redactRec(v, re, seen));
643
+ }
644
+ }
645
+ seen.delete(value);
646
+ return result;
423
647
  }
424
- supposeIsHandler(v, reportError = true) {
425
- const isHandler = Object.prototype.hasOwnProperty.call(v.__proto__, "execute") || Object.prototype.hasOwnProperty.call(v, "execute");
426
- if (!isHandler && reportError) {
427
- tryReportAnError(new HaluaUnableToDetermineHandler(`Unable to find execute method of a handler`));
648
+ if (type === "set") {
649
+ if (seen.has(value)) {
650
+ return "[Circular]";
428
651
  }
429
- return isHandler;
652
+ seen.add(value);
653
+ let result = /* @__PURE__ */ new Set();
654
+ for (let item of value) {
655
+ result.add(redactRec(item, re, seen));
656
+ }
657
+ seen.delete(value);
658
+ return result;
430
659
  }
431
- buildHandlers(passed) {
432
- let entries = toarray(passed);
433
- return entries.map((b) => b()).filter((h) => this.supposeIsHandler(h));
660
+ if (type === "error") {
661
+ let msg = value.message;
662
+ if (typeof msg === "string") {
663
+ msg = redactString(msg, re);
664
+ }
665
+ let Ctor = value.constructor || Error;
666
+ let redacted;
667
+ try {
668
+ redacted = new Ctor(msg);
669
+ if (value.name) {
670
+ redacted.name = value.name;
671
+ }
672
+ if (value.stack) {
673
+ redacted.stack = value.stack;
674
+ }
675
+ } catch (_) {
676
+ redacted = value;
677
+ }
678
+ return redacted;
434
679
  }
435
- bindMethods() {
436
- this.New = this.New.bind(this);
437
- this.With = this.With.bind(this);
438
- this.setHandlers = this.setHandlers.bind(this);
439
- this.appendHandlers = this.appendHandlers.bind(this);
440
- this.logTo = this.logTo.bind(this);
441
- this.trace = this.trace.bind(this);
442
- this.debug = this.debug.bind(this);
443
- this.info = this.info.bind(this);
444
- this.warn = this.warn.bind(this);
445
- this.notice = this.notice.bind(this);
446
- this.error = this.error.bind(this);
447
- this.fatal = this.fatal.bind(this);
448
- this.assert = this.assert.bind(this);
449
- this.supposeIsHandler = this.supposeIsHandler.bind(this);
680
+ return value;
681
+ }
682
+ function redactString(str, re) {
683
+ if (!re || typeof str !== "string") {
684
+ return str;
450
685
  }
451
- };
686
+ let flags = re.flags || "";
687
+ if (!flags.includes("g")) {
688
+ flags = flags + "g";
689
+ }
690
+ let searchRe;
691
+ try {
692
+ searchRe = new RegExp(re.source, flags);
693
+ } catch (_) {
694
+ return str;
695
+ }
696
+ searchRe.lastIndex = 0;
697
+ let result = "";
698
+ let last = 0;
699
+ let match;
700
+ while ((match = searchRe.exec(str)) !== null) {
701
+ let matchEnd = searchRe.lastIndex;
702
+ let replacement = REDACTION_TOKEN;
703
+ let newLast = matchEnd;
704
+ let tail = str.slice(matchEnd);
705
+ let assign = tail.match(/^(\s*[=:]\s*)(".*?"|'.*?'|\S+)?/);
706
+ if (assign) {
707
+ newLast = matchEnd + assign[0].length;
708
+ replacement = REDACTION_TOKEN;
709
+ searchRe.lastIndex = newLast;
710
+ }
711
+ result += str.slice(last, match.index) + replacement;
712
+ last = newLast;
713
+ }
714
+ result += str.slice(last);
715
+ return result;
716
+ }
452
717
 
453
- // src/main/handlers/HandlerBase.ts
454
- var HandlerBase = class {
718
+ class DispatcherBase {
455
719
  sendMethod;
456
720
  formatArg = void 0;
457
721
  level;
458
722
  exact = null;
459
723
  printTimestamp = true;
460
724
  printLevel = true;
461
- constructor(send) {
462
- this.execute = this.execute.bind(this);
463
- this.sendMethod = send ?? (() => {
464
- });
465
- }
466
- *execute(meta) {
467
- let arg = "";
468
- let current = { value: null, type: "init" };
725
+ redactDataRegExp;
726
+ _lastTimestampSec = -1;
727
+ _lastTimestampStr = "";
728
+ constructor(send = () => {
729
+ }, options = {}) {
730
+ this.dispatch = this.dispatch.bind(this);
731
+ this.sendMethod = send;
732
+ this.printTimestamp = options.printTimestamp ?? true;
733
+ this.printLevel = options.printLevel ?? true;
734
+ this.level = options.level;
735
+ this.exact = options.exact ? toarray(options.exact) : null;
736
+ this.redactDataRegExp = options.redactDataRegExp;
737
+ }
738
+ dispatch(meta, args, errorMeta) {
739
+ let effectiveRe = this.redactDataRegExp || meta.redactDataRegExp;
740
+ let processedArgs = effectiveRe ? args.map((v) => redact(v, effectiveRe)) : args;
741
+ let processedErrorMeta = errorMeta;
742
+ if (effectiveRe && errorMeta != null) {
743
+ processedErrorMeta = redact(errorMeta, effectiveRe);
744
+ }
745
+ let parts = [];
469
746
  if (this.printTimestamp) {
470
- arg += `${this.formatTimestamp(meta.timestamp)}`;
747
+ parts.push(this.formatTimestamp(meta.timestamp));
471
748
  }
472
749
  if (this.printLevel) {
473
- arg += ` ${meta.level}`;
750
+ parts.push(meta.level);
474
751
  }
475
- while (true) {
476
- if (current.type === "init") {
477
- current = yield { type: "init" };
478
- }
479
- if (current.prev) {
480
- arg += " " + current.prev;
481
- }
482
- if (current.type === "done") {
483
- break;
484
- }
485
- if (current.type === "arg") {
486
- if (typeof this.formatArg === "function") {
487
- arg += " " + this.formatArg(current.value);
488
- current = yield { type: "done" };
489
- continue;
490
- }
752
+ for (let value of processedArgs) {
753
+ let formatted;
754
+ if (typeof this.formatArg === "function") {
755
+ formatted = this.formatArg(value);
756
+ } else {
757
+ formatted = value;
491
758
  }
492
- current = yield { type: "pass" };
759
+ parts.push(formatted);
493
760
  }
494
- this.sendMethod(arg.trimStart());
761
+ this.sendMethod(parts.join(" "), processedErrorMeta);
495
762
  }
496
763
  formatTimestamp(t) {
764
+ let sec = Math.floor(t / 1e3);
765
+ if (sec === this._lastTimestampSec) {
766
+ return this._lastTimestampStr;
767
+ }
497
768
  let d = new Date(t);
498
- return `${d.toLocaleDateString()} ${d.toLocaleTimeString()}`;
769
+ let s = `${d.toLocaleDateString()} ${d.toLocaleTimeString()}`;
770
+ this._lastTimestampSec = sec;
771
+ this._lastTimestampStr = s;
772
+ return s;
499
773
  }
500
- };
774
+ }
501
775
 
502
- // src/main/handlers/ConsoleHandler.ts
503
- function NewConsoleHandler(console2, options) {
504
- return () => new class ConsoleHandler extends HandlerBase {
505
- constructor(console3, options2 = {}) {
506
- super();
507
- this.console = console3;
508
- this.applyOptionalOptions(options2);
509
- this.level = options2.level;
510
- this.exact = options2.exact ? toarray(options2.exact) : null;
511
- }
512
- level;
513
- exact = null;
514
- formatArg = (arg) => arg;
515
- applyOptionalOptions(options2) {
516
- this.printTimestamp = options2.printTimestamp ?? true;
517
- this.printLevel = options2.printLevel ?? true;
518
- }
519
- *execute(meta) {
776
+ function prepareDispatchArgs(redactDataRegExp, meta, rawArgs, errorMeta) {
777
+ let effectiveRe = redactDataRegExp || meta.redactDataRegExp;
778
+ let processedRawArgs = effectiveRe ? rawArgs.map((v) => redact(v, effectiveRe)) : rawArgs;
779
+ let processedErrorMeta = errorMeta;
780
+ if (effectiveRe && errorMeta != null) {
781
+ processedErrorMeta = redact(errorMeta, effectiveRe);
782
+ }
783
+ return { processedRawArgs, processedErrorMeta };
784
+ }
785
+ function routeConsoleCall(target, level, args) {
786
+ let ul = level.toUpperCase();
787
+ if (ul.startsWith("DEBUG")) {
788
+ target.debug(...args);
789
+ return;
790
+ }
791
+ if (ul.startsWith("WARN")) {
792
+ target.warn(...args);
793
+ return;
794
+ }
795
+ if (ul.startsWith("ERROR") || ul.startsWith("FATAL")) {
796
+ target.error(...args);
797
+ return;
798
+ }
799
+ target.info(...args);
800
+ }
801
+
802
+ function NewConsoleDispatcher(console, options) {
803
+ return () => new class ConsoleDispatcher extends DispatcherBase {
804
+ constructor(console2, options2 = {}) {
805
+ super(() => {
806
+ }, options2);
807
+ this.console = console2;
808
+ }
809
+ dispatch(meta, rawArgs, errorMeta) {
810
+ let { processedRawArgs, processedErrorMeta } = prepareDispatchArgs(
811
+ this.redactDataRegExp,
812
+ meta,
813
+ rawArgs,
814
+ errorMeta
815
+ );
520
816
  let args = [];
521
- let current = { value: null, type: "init" };
522
817
  if (this.printTimestamp) {
523
818
  args.push(`${this.formatTimestamp(meta.timestamp)}`);
524
819
  }
@@ -526,137 +821,178 @@ function NewConsoleHandler(console2, options) {
526
821
  let margin = this.printTimestamp ? " " : "";
527
822
  args.push(`${margin}${meta.level}`);
528
823
  }
529
- while (true) {
530
- if (current.type === "init") {
531
- current = yield { type: "init" };
824
+ for (let value of processedRawArgs) {
825
+ let formatted;
826
+ if (typeof this.formatArg === "function") {
827
+ formatted = this.formatArg(value);
828
+ } else {
829
+ formatted = value;
532
830
  }
533
- if (current.prev) {
534
- args.push(current.prev);
831
+ args.push(formatted);
832
+ }
833
+ if (processedErrorMeta !== void 0) {
834
+ let m = typeof this.formatArg === "function" ? this.formatArg(processedErrorMeta) : processedErrorMeta;
835
+ args.push(m);
836
+ }
837
+ routeConsoleCall(this.console, meta.level, args);
838
+ }
839
+ }(console, options);
840
+ }
841
+
842
+ const isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
843
+ const ANSI = {
844
+ purple: "\x1B[35m",
845
+ blue: "\x1B[34m",
846
+ orange: "\x1B[38;5;208m",
847
+ red: "\x1B[31m",
848
+ reset: "\x1B[0m"
849
+ };
850
+ const CSS = {
851
+ purple: "color:#a855f7;font-weight:bold",
852
+ blue: "color:#3b82f6;font-weight:bold",
853
+ orange: "color:#f97316;font-weight:bold",
854
+ red: "color:#ef4444;font-weight:bold"
855
+ };
856
+ const getColorForLevel = (level) => {
857
+ let l = level.toUpperCase();
858
+ if (l.startsWith("TRACE") || l.startsWith("DEBUG")) {
859
+ return "purple";
860
+ }
861
+ if (l.startsWith("INFO")) {
862
+ return "blue";
863
+ }
864
+ if (l.startsWith("NOTICE")) {
865
+ return "orange";
866
+ }
867
+ if (l.startsWith("WARN") || l.startsWith("ERROR") || l.startsWith("FATAL")) {
868
+ return "red";
869
+ }
870
+ return "blue";
871
+ };
872
+ function NewConsoleColoredDispatcher(console, options) {
873
+ return () => new class ConsoleColoredDispatcher extends DispatcherBase {
874
+ constructor(console2, options2 = {}) {
875
+ super(() => {
876
+ }, options2);
877
+ this.console = console2;
878
+ }
879
+ dispatch(meta, rawArgs, errorMeta) {
880
+ let { processedRawArgs, processedErrorMeta } = prepareDispatchArgs(
881
+ this.redactDataRegExp,
882
+ meta,
883
+ rawArgs,
884
+ errorMeta
885
+ );
886
+ let colorKey = getColorForLevel(meta.level);
887
+ if (isNode) {
888
+ let args = [];
889
+ if (this.printTimestamp) {
890
+ args.push(`${this.formatTimestamp(meta.timestamp)}`);
535
891
  }
536
- if (current.type === "done") {
537
- break;
892
+ if (this.printLevel) {
893
+ let margin = this.printTimestamp ? " " : "";
894
+ let c = ANSI[colorKey];
895
+ let r = ANSI.reset;
896
+ args.push(`${margin}${c}${meta.level}${r}`);
538
897
  }
539
- if (current.type === "arg") {
898
+ for (let value of processedRawArgs) {
899
+ let formatted;
540
900
  if (typeof this.formatArg === "function") {
541
- args.push(current.value);
542
- current = yield { type: "done" };
543
- continue;
901
+ formatted = this.formatArg(value);
902
+ } else {
903
+ formatted = value;
544
904
  }
905
+ args.push(formatted);
545
906
  }
546
- current = yield { type: "pass" };
547
- }
548
- if (meta.level.startsWith("DEBUG")) {
549
- this.console.debug(...args);
907
+ if (processedErrorMeta !== void 0) {
908
+ let m = typeof this.formatArg === "function" ? this.formatArg(processedErrorMeta) : processedErrorMeta;
909
+ args.push(m);
910
+ }
911
+ routeConsoleCall(this.console, meta.level, args);
550
912
  return;
551
913
  }
552
- if (meta.level.startsWith("WARN")) {
553
- this.console.warn(...args);
554
- return;
914
+ let cargs;
915
+ if (!this.printTimestamp && !this.printLevel) {
916
+ cargs = [];
917
+ } else {
918
+ let formatStr = "";
919
+ let styleArgs = [];
920
+ if (this.printTimestamp) {
921
+ formatStr += "%s";
922
+ styleArgs.push(`${this.formatTimestamp(meta.timestamp)}`);
923
+ }
924
+ if (this.printLevel) {
925
+ let css = CSS[colorKey];
926
+ if (formatStr) {
927
+ formatStr += " ";
928
+ }
929
+ formatStr += "%c%s%c";
930
+ styleArgs.push(css, meta.level, "");
931
+ }
932
+ cargs = [formatStr, ...styleArgs];
555
933
  }
556
- if (meta.level.startsWith("ERROR") || meta.level.startsWith("FATAL")) {
557
- this.console.error(...args);
558
- return;
934
+ for (let value of processedRawArgs) {
935
+ let formatted;
936
+ if (typeof this.formatArg === "function") {
937
+ formatted = this.formatArg(value);
938
+ } else {
939
+ formatted = value;
940
+ }
941
+ cargs.push(formatted);
559
942
  }
560
- this.console.info(...args);
943
+ if (processedErrorMeta !== void 0) {
944
+ let m = typeof this.formatArg === "function" ? this.formatArg(processedErrorMeta) : processedErrorMeta;
945
+ cargs.push(m);
946
+ }
947
+ routeConsoleCall(this.console, meta.level, cargs);
561
948
  }
562
- }(console2, options);
949
+ }(console, options);
563
950
  }
564
951
 
565
- // src/main/handlers/JSONHandler.ts
566
- function NewJSONHandler(send, options) {
567
- return () => new class JSONHandler extends HandlerBase {
568
- level;
569
- exact = null;
952
+ function NewJSONDispatcher(send, options) {
953
+ return () => new class JSONDispatcher extends DispatcherBase {
570
954
  constructor(send2, options2 = {}) {
571
- super(send2);
572
- this.applyOptionalOptions(options2);
573
- this.level = options2.level;
574
- this.exact = options2.exact ? toarray(options2.exact) : null;
575
- }
576
- formatArg = (arg) => {
577
- let type = getType(arg);
578
- let formatted = formatJSON({ type, value: arg });
579
- if (type !== "object" && type !== "map") {
580
- return `"${formatted}"`;
581
- }
582
- return formatted;
583
- };
584
- *execute(meta) {
585
- let arg = "{";
586
- let current = { value: null, type: "init" };
955
+ super(send2, options2);
956
+ }
957
+ dispatch(meta, rawArgs, errorMeta) {
958
+ let { processedRawArgs, processedErrorMeta } = prepareDispatchArgs(
959
+ this.redactDataRegExp,
960
+ meta,
961
+ rawArgs,
962
+ errorMeta
963
+ );
964
+ let obj = {};
587
965
  if (this.printTimestamp) {
588
- arg += `"timestamp":"${this.formatTimestamp(meta.timestamp)}",`;
966
+ obj.timestamp = this.formatTimestamp(meta.timestamp);
589
967
  }
590
968
  if (this.printLevel) {
591
- arg += `"level":"${meta.level}",`;
592
- }
593
- arg += `"args":[`;
594
- while (true) {
595
- if (current.type === "init") {
596
- current = yield { type: "init" };
597
- }
598
- if (current.prev) {
599
- arg += `"${current.prev}",`;
600
- }
601
- if (current.type === "done") {
602
- break;
603
- }
604
- if (current.type === "arg") {
605
- if (typeof this.formatArg === "function") {
606
- arg += `${this.formatArg(current.value)},`;
607
- current = yield { type: "done" };
608
- continue;
609
- }
610
- }
611
- current = yield { type: "pass" };
612
- }
613
- if (arg.at(-1) === ",") {
614
- arg = arg.slice(0, arg.length - 1);
969
+ obj.level = meta.level;
615
970
  }
616
- arg += `]}`;
617
- this.sendMethod(arg);
971
+ obj.args = processedRawArgs.map((a) => toJSONValue(a));
972
+ this.sendMethod(JSON.stringify(obj), processedErrorMeta);
618
973
  }
619
974
  formatTimestamp(t) {
620
975
  return new Date(t).toISOString();
621
976
  }
622
- applyOptionalOptions(options2) {
623
- this.printTimestamp = options2.printTimestamp ?? true;
624
- this.printLevel = options2.printLevel ?? true;
625
- }
626
977
  }(send, options);
627
978
  }
628
979
 
629
- // src/main/handlers/TextHandler.ts
630
- function NewTextHandler(send, options) {
631
- return () => new class TextHandler extends HandlerBase {
632
- level;
633
- exact = null;
634
- formatArg;
980
+ function NewTextDispatcher(send, options) {
981
+ return () => new class TextDispatcher extends DispatcherBase {
635
982
  constructor(send2, options2 = {}) {
636
- super(send2);
637
- this.applyOptionalOptions(options2);
638
- this.level = options2.level;
639
- this.exact = options2.exact ? toarray(options2.exact) : null;
983
+ super(send2, options2);
640
984
  this.formatArg = (value) => format({ type: getType(value), value }, options2.spacing);
641
985
  }
642
- applyOptionalOptions(options2) {
643
- this.printTimestamp = options2.printTimestamp ?? true;
644
- this.printLevel = options2.printLevel ?? true;
645
- }
646
986
  }(send, options);
647
987
  }
648
988
 
649
- // src/index.ts
650
- var logConsole = null;
651
- try {
652
- logConsole = typeof self !== "undefined" ? self.console : console;
653
- } catch (_) {
654
- }
655
- var halua = new Halua(logConsole ? NewConsoleHandler(logConsole) : []);
656
- export {
657
- Level,
658
- NewConsoleHandler,
659
- NewJSONHandler,
660
- NewTextHandler,
661
- halua
662
- };
989
+ const logConsole = (() => {
990
+ try {
991
+ return typeof self !== "undefined" ? self.console : console;
992
+ } catch (_) {
993
+ return null;
994
+ }
995
+ })();
996
+ const halua = new Halua(logConsole ? NewConsoleDispatcher(logConsole) : []);
997
+
998
+ export { DefaultRedactRegExp, DispatcherBase, Level, NewConsoleColoredDispatcher, NewConsoleDispatcher, NewJSONDispatcher, NewTextDispatcher, format, getType, halua, redact, toJSONValue };