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