halua 1.1.0 → 2.0.1

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
@@ -21,14 +21,14 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  Level: () => Level,
24
+ NewConsoleHandler: () => NewConsoleHandler,
24
25
  NewJSONHandler: () => NewJSONHandler,
25
26
  NewTextHandler: () => NewTextHandler,
26
- NewWebConsoleHandler: () => NewWebConsoleHandler,
27
27
  halua: () => halua
28
28
  });
29
29
  module.exports = __toCommonJS(index_exports);
30
30
 
31
- // src/handlers/types.ts
31
+ // src/types/log.ts
32
32
  var Level = /* @__PURE__ */ ((Level2) => {
33
33
  Level2["Trace"] = "TRACE";
34
34
  Level2["Debug"] = "DEBUG";
@@ -40,82 +40,51 @@ var Level = /* @__PURE__ */ ((Level2) => {
40
40
  return Level2;
41
41
  })(Level || {});
42
42
 
43
- // src/util/level.ts
44
- function toLevel(v) {
45
- return {
46
- trace: "TRACE" /* Trace */,
47
- debug: "DEBUG" /* Debug */,
48
- info: "INFO" /* Info */,
49
- warn: "WARN" /* Warn */,
50
- notice: "NOTICE" /* Notice */,
51
- error: "ERROR" /* Error */,
52
- fatal: "FATAL" /* Fatal */,
53
- assert: "ERROR" /* Error */
54
- }[v];
55
- }
56
-
57
- // src/util/string.ts
58
- var defaultIgnored = /* @__PURE__ */ new Set();
59
- function stringMatchesVar(str, ignoredStrings = defaultIgnored) {
60
- return !ignoredStrings.has(str) && str.trim().indexOf(" ") === -1;
61
- }
62
- var messageFormatExcludes = /* @__PURE__ */ new Set([" ", "%a", "%w", "%t", "%l"]);
63
- function extractNonFormatChars(f) {
64
- let total = /* @__PURE__ */ new Set();
65
- for (let char of f) {
66
- if (!messageFormatExcludes.has(char)) {
67
- total.add(char);
68
- }
43
+ // src/main/getType.ts
44
+ function getType(arg) {
45
+ if (typeof arg === "undefined") {
46
+ return "undefined";
69
47
  }
70
- return total;
71
- }
72
- function extractTaken(f) {
73
- let total = [];
74
- let seq = "";
75
- for (let rune of f) {
76
- if (seq && (rune === "%" || rune === " ")) {
77
- total.push(seq);
78
- seq = "";
79
- if (rune === "%") {
80
- seq += rune;
81
- }
82
- continue;
83
- }
84
- seq += rune;
48
+ if (typeof arg === "object" && String(arg) === "null") {
49
+ return "null";
85
50
  }
86
- if (seq) {
87
- total.push(seq);
51
+ if (Array.isArray(arg)) {
52
+ return "array";
88
53
  }
89
- return total;
90
- }
91
- function removeTailingUndefinedValues(format, log) {
92
- if (!argsInDisposition(format) || log.withArgs) {
93
- return format;
54
+ if (ArrayBuffer.isView(arg)) {
55
+ return "typedarray";
94
56
  }
95
- let argsIndex = format.indexOf("%a");
96
- let withArgsIndex = format.indexOf("%w");
97
- if (withArgsIndex < argsIndex) {
98
- return format;
57
+ if (arg instanceof ArrayBuffer) {
58
+ return "arraybuffer";
99
59
  }
100
- return format.slice(0, argsIndex + 2);
101
- }
102
- function argsInDisposition(format) {
103
- let indexOfArgs = format.indexOf("%a");
104
- let indexOfWithArgs = format.indexOf("%w");
105
- let indexOfTimestamp = format.indexOf("%t");
106
- let indexOfLevel = format.indexOf("l");
107
- return Math.max(indexOfTimestamp, indexOfLevel) < Math.min(indexOfArgs, indexOfWithArgs);
108
- }
109
- function getConvertStartingIndex(format) {
110
- let sum = format.indexOf("%t") + format.indexOf("%l");
111
- if (sum === -2) {
112
- return 0;
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";
113
74
  }
114
- if (sum === 0) {
115
- return 1;
75
+ if (arg instanceof Error) {
76
+ return "error";
116
77
  }
117
- return 2;
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;
118
85
  }
86
+
87
+ // src/main/util/string.ts
119
88
  function extractLevels(level) {
120
89
  if (typeof level !== "string") {
121
90
  return ["INFO" /* Info */, 0];
@@ -132,11 +101,33 @@ function extractLevels(level) {
132
101
  return [data[0], Math.trunc(data[1]) || 0];
133
102
  }
134
103
 
135
- // src/errors.ts
136
- var FailedToCallHandlerLog = class extends Error {
104
+ // src/main/errors.ts
105
+ var HaluaFailedToCallHandler = class extends Error {
106
+ constructor(message, options = {}) {
107
+ super(`HaluaFailedToCallHandlerError: ${message}`, options);
108
+ }
109
+ };
110
+ var HaluaUnableToDetermineHandler = class extends Error {
111
+ constructor(message, options = {}) {
112
+ super(`HaluaUnableToDetermineHandlerError: ${message}`, options);
113
+ }
114
+ };
115
+ var HaluaParse = class extends Error {
116
+ constructor(message, options = {}) {
117
+ super(`HaluaParseError: ${message}`, options);
118
+ }
137
119
  };
138
120
 
139
- // src/HandlersBalancer.ts
121
+ // src/main/util/errors.ts
122
+ function tryReportAnError(err) {
123
+ try {
124
+ let log = "self" in window ? self.console : console;
125
+ log.error(err);
126
+ } catch (_) {
127
+ }
128
+ }
129
+
130
+ // src/main/handlers/Balancer.ts
140
131
  var MajorLevelMap = /* @__PURE__ */ new Map([
141
132
  ["FATAL" /* Fatal */, /* @__PURE__ */ new Set(["FATAL" /* Fatal */])],
142
133
  ["ERROR" /* Error */, /* @__PURE__ */ new Set(["FATAL" /* Fatal */, "ERROR" /* Error */])],
@@ -147,14 +138,17 @@ var MajorLevelMap = /* @__PURE__ */ new Map([
147
138
  ["TRACE" /* Trace */, /* @__PURE__ */ new Set(["FATAL" /* Fatal */, "ERROR" /* Error */, "WARN" /* Warn */, "NOTICE" /* Notice */, "INFO" /* Info */, "DEBUG" /* Debug */, "TRACE" /* Trace */])]
148
139
  ]);
149
140
  var HandlersBalancer = class {
150
- constructor(level, handlers) {
141
+ constructor(level, handlers, format2) {
151
142
  this.level = level;
152
143
  this.handlers = handlers;
144
+ this.format = format2;
145
+ this.sendLog = this.sendLog.bind(this);
146
+ this.reset = this.reset.bind(this);
153
147
  }
154
148
  map = /* @__PURE__ */ new Map();
155
- sendLog(log) {
156
- this.discover(log.level);
157
- this.send(log);
149
+ sendLog(meta, args) {
150
+ this.discover(meta.level);
151
+ this.send(meta, args);
158
152
  }
159
153
  reset() {
160
154
  this.map.clear();
@@ -172,23 +166,44 @@ var HandlersBalancer = class {
172
166
  }
173
167
  continue;
174
168
  }
175
- if (this.canSend(extractLevels(level), h.level)) {
169
+ if (this.canSend(level, h.level ?? this.level)) {
176
170
  discovered.push(h);
177
171
  }
178
172
  }
179
173
  }
180
- send(log) {
174
+ send(meta, args) {
181
175
  try {
182
- for (let h of this.map.get(log.level) || []) {
183
- h.skipDeepCopyWhenSendingLog ? h.log(log) : h.log(structuredClone(log));
184
- }
176
+ this.sendToHandlers(meta, args);
185
177
  } catch (e) {
186
- throw new FailedToCallHandlerLog(`Unable to call .log method of a handler, ${e}`, { cause: 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
+ });
187
197
  }
198
+ generators.forEach((e, i) => {
199
+ e.next({ type: "done", value: null, prev: state[i] });
200
+ });
201
+ state = [];
188
202
  }
189
203
  canSend(l, to = this.level || "TRACE" /* Trace */) {
190
- let tol = extractLevels(to);
191
- return this.majorLevelCheck(l[0], tol[0]) + this.minorLevelCheck(l[1], tol[1]) > 0;
204
+ let lvl = extractLevels(l);
205
+ let toLvl = extractLevels(to);
206
+ return this.majorLevelCheck(lvl[0], toLvl[0]) + this.minorLevelCheck(lvl[1], toLvl[1]) > 0;
192
207
  }
193
208
  majorLevelCheck(l, to) {
194
209
  if (!MajorLevelMap.get(to).has(l)) {
@@ -201,516 +216,478 @@ var HandlersBalancer = class {
201
216
  }
202
217
  };
203
218
 
204
- // src/main.ts
219
+ // src/util/spacing.ts
220
+ var Spacing = /* @__PURE__ */ ((Spacing2) => {
221
+ Spacing2["Space"] = " ";
222
+ Spacing2["Tab"] = " ";
223
+ Spacing2["Empty"] = "";
224
+ Spacing2["Line"] = "\n";
225
+ return Spacing2;
226
+ })(Spacing || {});
227
+ var EmptySpacing = /* @__PURE__ */ ((EmptySpacing2) => {
228
+ EmptySpacing2["Space"] = " ";
229
+ EmptySpacing2["Tab"] = "";
230
+ EmptySpacing2["Empty"] = "";
231
+ EmptySpacing2["Line"] = "";
232
+ return EmptySpacing2;
233
+ })(EmptySpacing || {});
234
+
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;
240
+ }
241
+ return str;
242
+ }
243
+
244
+ // src/main/format.ts
245
+ var FormatAsIs = [
246
+ "undefined",
247
+ "null",
248
+ "string",
249
+ "number",
250
+ "boolean",
251
+ "symbol",
252
+ "typedarray",
253
+ "bigint",
254
+ "date",
255
+ "nan",
256
+ "infinity"
257
+ ];
258
+ var FormatNeeded = [
259
+ "array",
260
+ "object",
261
+ "arraybuffer",
262
+ "map",
263
+ "set",
264
+ "weakmap",
265
+ "weakset",
266
+ "function",
267
+ "error"
268
+ ];
269
+ function format(arg, spacing = true) {
270
+ try {
271
+ const SpacingEnum = spacing ? Spacing : EmptySpacing;
272
+ if (FormatAsIs.some((f) => f === arg.type)) {
273
+ return formatAsIs(arg.value, arg.type);
274
+ }
275
+ if (FormatNeeded.some((f) => f === arg.type)) {
276
+ return formatComplex(arg.value, arg.type, SpacingEnum);
277
+ }
278
+ } catch (err) {
279
+ return new HaluaParse(err?.message || "").message;
280
+ }
281
+ return arg.value;
282
+ }
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
+ function formatAsIs(arg, type) {
290
+ if (type === "number") {
291
+ return arg;
292
+ }
293
+ if (type === "boolean") {
294
+ return arg;
295
+ }
296
+ return String(arg);
297
+ }
298
+ function formatComplex(arg, type, spacing, nestingLevel = 1) {
299
+ if (type === "set") {
300
+ return `Set${formatArray(convertSetToArray(arg), spacing)}`;
301
+ }
302
+ if (type === "weakset") {
303
+ return `WeakSet [inaccessible]`;
304
+ }
305
+ if (type === "weakmap") {
306
+ return `WeakMap {inaccessible}`;
307
+ }
308
+ if (type === "function") {
309
+ let name = arg.name;
310
+ return `Function ${name === "value" ? "anonymous" : name}`;
311
+ }
312
+ if (type === "array") {
313
+ return formatArray(arg, spacing);
314
+ }
315
+ if (type === "arraybuffer") {
316
+ return `ArrayBuffer []`;
317
+ }
318
+ if (type === "map") {
319
+ return formatObject(convertMapToObj(arg), spacing, nestingLevel, ` => `);
320
+ }
321
+ if (type === "error") {
322
+ return `${arg.toString()} stack: ${arg.stack}`;
323
+ }
324
+ if (type === "object") {
325
+ return formatObject(arg, spacing, nestingLevel);
326
+ }
327
+ return arg;
328
+ }
329
+ function formatArray(arg, spacing) {
330
+ let stringify = "[";
331
+ let len = arg.length;
332
+ for (let entry of arg) {
333
+ len -= 1;
334
+ let entryType = getType(entry);
335
+ let formatted = format({ type: entryType, value: entry });
336
+ let entryValue = entryType === "string" ? `"${formatted}"` : formatted;
337
+ stringify += `${entryValue}${len ? `,${spacing.Space}` : spacing.Empty}`;
338
+ }
339
+ stringify += "]";
340
+ return stringify;
341
+ }
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
+ });
352
+ let entryValue = entryType === "string" ? `"${formatted}"` : formatted;
353
+ stringify += `${printTimes(nestingLevel, spacing.Tab)}"${key}"${delimiter}${entryValue}${len ? `,${spacing.Line}` : spacing.Empty}`;
354
+ }
355
+ let level = nestingLevel - 1;
356
+ stringify += `${spacing.Line}${printTimes(level, spacing.Tab)}}`;
357
+ return stringify;
358
+ }
359
+ function convertMapToObj(value) {
360
+ let obj = {};
361
+ for (let [key, v] of value) {
362
+ 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 });
366
+ }
367
+ return obj;
368
+ }
369
+ function convertSetToArray(value) {
370
+ let arr = [];
371
+ for (let entry of value) {
372
+ arr.push(entry);
373
+ }
374
+ return arr;
375
+ }
376
+
377
+ // src/main/util/cast.ts
378
+ function toarray(value) {
379
+ return Array.isArray(value) ? value : typeof value === "undefined" ? [] : [value];
380
+ }
381
+
382
+ // src/main/halua.ts
205
383
  var Halua = class _Halua {
206
384
  constructor(passed, options = {}) {
207
385
  this.options = options;
208
386
  this.passedHandlers = passed;
209
- this.options.messageFormat ??= "%t %l %a | %w";
210
- this.validateHandlers(this.buildHandlers(passed));
211
387
  this.handlers = this.buildHandlers(passed);
212
- this.balancer = new HandlersBalancer(this.options.level || "TRACE" /* Trace */, this.handlers);
388
+ this.balancer = new HandlersBalancer(this.options.level || "TRACE" /* Trace */, this.handlers, format);
389
+ this.bindMethods();
213
390
  }
391
+ passedHandlers = [];
214
392
  handlers = [];
215
- passedHandlers;
216
393
  balancer;
217
394
  New(arg1 = this.passedHandlers, arg2 = this.options) {
218
395
  if (Array.isArray(arg1)) {
219
- this.validateHandlers(this.buildHandlers(arg1));
220
396
  return new _Halua(arg1, { ...arg2 });
221
397
  }
222
- if (this.supposeIsHandler(arg1)) {
398
+ if (this.supposeIsHandler(arg1, false)) {
223
399
  return new _Halua(arg1, { ...arg2 });
224
400
  }
225
401
  if (Object.keys(arg1).length) {
226
402
  return new _Halua(this.passedHandlers, { ...arg1 });
227
403
  }
228
- this.validateHandlers(this.buildHandlers(arg1));
229
404
  return new _Halua(arg1, { ...arg2 });
230
405
  }
231
406
  With(...args) {
232
407
  return new _Halua(this.passedHandlers, { ...this.options, withArgs: (this.options.withArgs || []).concat(args) });
233
408
  }
234
- withMessageFormat(f) {
235
- this.unlinkInheritance();
236
- this.options.messageFormat = f;
237
- return this;
238
- }
239
- setHandler(handler) {
240
- this.validateHandlers(this.buildHandlers(handler));
409
+ setHandlers(handler) {
241
410
  this.handlers = this.buildHandlers(handler);
242
411
  this.updateBalancer();
243
412
  }
244
- appendHandler(handler) {
245
- this.validateHandlers(this.buildHandlers(handler));
246
- this.handlers.push(...this.buildHandlers(handler));
413
+ appendHandlers(handler) {
414
+ let handlers = this.buildHandlers(handler);
415
+ this.handlers.push(...handlers);
247
416
  this.updateBalancer();
248
417
  }
249
418
  logTo(level, ...args) {
250
- this.balancer.sendLog(this.composeLog(level, true, ...args));
419
+ this.sendToBalancer(level, args);
251
420
  }
252
421
  trace(...args) {
253
- this.sendToHandler("trace", true, ...args);
422
+ this.sendToBalancer("TRACE" /* Trace */, args);
254
423
  }
255
424
  debug(...args) {
256
- this.sendToHandler("debug", true, ...args);
425
+ this.sendToBalancer("DEBUG" /* Debug */, args);
257
426
  }
258
427
  info(...args) {
259
- this.sendToHandler("info", true, ...args);
428
+ this.sendToBalancer("INFO" /* Info */, args);
260
429
  }
261
430
  warn(...args) {
262
- this.sendToHandler("warn", true, ...args);
431
+ this.sendToBalancer("WARN" /* Warn */, args);
263
432
  }
264
433
  notice(...args) {
265
- this.sendToHandler("notice", true, ...args);
434
+ this.sendToBalancer("NOTICE" /* Notice */, args);
266
435
  }
267
436
  error(...args) {
268
- this.sendToHandler("error", true, ...args);
437
+ this.sendToBalancer("ERROR" /* Error */, args);
269
438
  }
270
439
  fatal(...args) {
271
- this.sendToHandler("fatal", true, ...args);
440
+ this.sendToBalancer("FATAL" /* Fatal */, args);
272
441
  }
273
442
  assert(assertion, ...args) {
274
443
  if (assertion) {
275
444
  return;
276
445
  }
277
- this.sendToHandler("assert", assertion, ...args);
446
+ this.sendToBalancer("ERROR" /* Error */, args);
278
447
  }
279
448
  updateBalancer() {
280
- this.balancer = new HandlersBalancer(this.options.level || "TRACE" /* Trace */, this.handlers);
281
- }
282
- sendToHandler(field, assertion = true, ...args) {
283
- this.balancer.sendLog(this.composeLog(toLevel(field), assertion, ...args));
284
- }
285
- composeLog(level, assertion, ...args) {
286
- return {
287
- timestamp: Date.now(),
288
- args: args || [],
289
- withArgs: this.options?.withArgs || null,
290
- messageFormat: this.options.messageFormat,
291
- assertion,
292
- level,
293
- leveling: extractLevels(level)
294
- };
295
- }
296
- validateHandlers(v) {
297
- let handlers = Array.isArray(v) ? v : [v];
298
- if (this.options.errorPolicy === "throw") {
299
- for (let h of handlers) {
300
- if (!this.supposeIsHandler(h)) {
301
- throw new Error("Passed handlers does not satisfy Handler interface");
302
- }
303
- }
304
- }
449
+ this.balancer = new HandlersBalancer(this.options.level || "TRACE" /* Trace */, this.handlers, format);
305
450
  }
306
- supposeIsHandler(v) {
307
- return Object.prototype.hasOwnProperty.call(v.__proto__, "log") || Object.prototype.hasOwnProperty.call(v, "log");
451
+ sendToBalancer(level, args) {
452
+ this.balancer.sendLog({ level, timestamp: Date.now() }, args.concat(this.options.withArgs ?? []));
308
453
  }
309
- unlinkInheritance() {
310
- this.options = structuredClone(this.options);
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`));
458
+ }
459
+ return isHandler;
311
460
  }
312
461
  buildHandlers(passed) {
313
- let entries = Array.isArray(passed) ? passed : [passed];
314
- return entries.map((v) => v());
462
+ let entries = toarray(passed);
463
+ return entries.map((b) => b()).filter((h) => this.supposeIsHandler(h));
464
+ }
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);
315
480
  }
316
481
  };
317
482
 
318
- // src/handlers/WebConsoleHandler/webConsoleUtils.ts
319
- function getColorKey(level) {
320
- return {
321
- ["TRACE" /* Trace */]: "grey",
322
- ["DEBUG" /* Debug */]: "purple",
323
- ["INFO" /* Info */]: "blue",
324
- ["WARN" /* Warn */]: "orange",
325
- ["NOTICE" /* Notice */]: "orange",
326
- ["ERROR" /* Error */]: "red",
327
- ["FATAL" /* Fatal */]: "red"
328
- }[level];
329
- }
330
-
331
- // src/util/array.ts
332
- function arrayed(v) {
333
- return Array.isArray(v) ? v : typeof v === "undefined" ? [] : [v];
334
- }
335
-
336
- // src/util/date.ts
337
- function getPrettyDate(t) {
338
- let d = new Date(t);
339
- return `${d.toLocaleDateString()} ${d.toLocaleTimeString()}`;
340
- }
341
-
342
- // src/handlers/WebConsoleHandler/WebConsoleHandler.ts
343
- function NewWebConsoleHandler(c = console, options = {}) {
344
- return () => new class WebConsoleLog {
345
- constructor(options2) {
346
- this.options = options2;
347
- this.level = options2.level;
348
- this.exact = options2.exact ? arrayed(options2.exact) : void 0;
349
- this.options = options2 || {};
350
- this.options.fetchBrowserThemeOnInstanceCreation ??= true;
351
- this.messageFormatRaw = options2.messageFormat ?? this.messageFormatRaw;
352
- this.messageFormat = Array.from(extractTaken(this.messageFormatRaw));
353
- if (!this.options.pretty) {
354
- return;
355
- }
356
- if (this.options.fetchBrowserThemeOnInstanceCreation) {
357
- if (window?.matchMedia && window?.matchMedia("(prefers-color-scheme: dark)").matches) {
358
- this.colors = new Map(this.darkColors);
359
- } else {
360
- this.colors = new Map(this.lightColors);
361
- }
362
- delete this.options.fetchBrowserThemeOnInstanceCreation;
363
- } else {
364
- this.colors = new Map(this.lightColors);
365
- }
366
- }
367
- skipDeepCopyWhenSendingLog = false;
368
- messageFormat = [];
369
- level;
370
- exact;
371
- messageFormatRaw = "%t %l %a | %w";
372
- colors = /* @__PURE__ */ new Map([]);
373
- // bg chrome #fefbff
374
- lightColors = /* @__PURE__ */ new Map([
375
- ["grey", "#565656"],
376
- ["green", "#224912"],
377
- ["blue", "#195367"],
378
- ["purple", "#8A228A"],
379
- ["orange", "#7F3E1E"],
380
- ["red", "#A51818"]
381
- ]);
382
- // bg chrome #27242a
383
- darkColors = /* @__PURE__ */ new Map([
384
- ["grey", "#C9C9C9"],
385
- ["green", "#73CE73"],
386
- ["blue", "#93B9E7"],
387
- ["purple", "#DCA4E9"],
388
- ["orange", "#EEC5A8"],
389
- ["red", "#FC9292"]
390
- ]);
391
- get linkArguments() {
392
- return this.options.linkArguments !== void 0 && !this.options.linkArguments;
393
- }
394
- log(log) {
395
- this.sendLog(log);
396
- }
397
- setDateGetter(dateGetter) {
398
- this.options.dateGetter = dateGetter;
399
- }
400
- sendLog(log) {
401
- let args = this.insertInternalEntries(log);
402
- if (log.level === "DEBUG" /* Debug */) {
403
- c.debug(this.composeConsoleSubstitution(args), ...args);
404
- return;
405
- }
406
- if (log.level === "WARN" /* Warn */ && this.options.useWarn) {
407
- c.warn(this.composeConsoleSubstitution(args), ...args);
408
- return;
409
- }
410
- if (log.level === "ERROR" /* Error */ && this.options.useError) {
411
- c.error(this.composeConsoleSubstitution(args), ...args);
412
- return;
483
+ // src/main/handlers/HandlerBase.ts
484
+ var HandlerBase = class {
485
+ sendMethod;
486
+ formatArg = void 0;
487
+ level;
488
+ exact = null;
489
+ printTimestamp = true;
490
+ 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" };
499
+ if (this.printTimestamp) {
500
+ arg += `${this.formatTimestamp(meta.timestamp)}`;
501
+ }
502
+ if (this.printLevel) {
503
+ arg += ` ${meta.level}`;
504
+ }
505
+ while (true) {
506
+ if (current.type === "init") {
507
+ current = yield { type: "init" };
413
508
  }
414
- c.info(this.composeConsoleSubstitution(args), ...args);
415
- }
416
- insertInternalEntries(log) {
417
- if (this.options.pretty) {
418
- return this.prepareMessagePretty(log);
509
+ if (current.prev) {
510
+ arg += " " + current.prev;
419
511
  }
420
- return this.prepareMessage(log);
421
- }
422
- composeConsoleSubstitution(data, startingVarConvertIndex = 2) {
423
- let str = "";
424
- startingVarConvertIndex = getConvertStartingIndex(this.messageFormatRaw);
425
- if (this.options.pretty) {
426
- startingVarConvertIndex = 3;
512
+ if (current.type === "done") {
513
+ break;
427
514
  }
428
- for (let i = this.options.pretty ? startingVarConvertIndex : 0; i < data.length; i++) {
429
- let last = i === data.length - 1;
430
- let v = data[i];
431
- let takenNames = extractTaken(this.messageFormatRaw);
432
- let vWithEqualSign = typeof v === "string" && stringMatchesVar(v, /* @__PURE__ */ new Set([]));
433
- let nextVWithEqualSign = !last && typeof data[i + 1] === "string" && stringMatchesVar(data[i + 1], /* @__PURE__ */ new Set([]));
434
- if (nextVWithEqualSign) {
435
- startingVarConvertIndex = Math.max(startingVarConvertIndex, i);
436
- }
437
- if (!this.linkArguments && !takenNames.includes(v) && !last && i > startingVarConvertIndex && vWithEqualSign) {
438
- data[i] = `${v} =`;
439
- }
440
- if (typeof v === "string") {
441
- str += `%s${last ? "" : " "}`;
442
- continue;
443
- }
444
- if (typeof v === "number") {
445
- str += `%d${last ? "" : " "}`;
515
+ if (current.type === "arg") {
516
+ if (typeof this.formatArg === "function") {
517
+ arg += " " + this.formatArg(current.value);
518
+ current = yield { type: "done" };
446
519
  continue;
447
520
  }
448
- str += `%o${last ? "" : " "}`;
449
521
  }
450
- return str;
522
+ current = yield { type: "pass" };
523
+ }
524
+ this.sendMethod(arg.trimStart());
525
+ }
526
+ formatTimestamp(t) {
527
+ let d = new Date(t);
528
+ return `${d.toLocaleDateString()} ${d.toLocaleTimeString()}`;
529
+ }
530
+ };
531
+
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;
451
541
  }
452
- prepareMessagePretty(log) {
453
- let format = [...this.messageFormat];
454
- if (!log.withArgs) {
455
- format = format.slice(0, format.indexOf("%a") + 1);
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) {
550
+ let args = [];
551
+ let current = { value: null, type: "init" };
552
+ if (this.printTimestamp) {
553
+ args.push(`${this.formatTimestamp(meta.timestamp)}`);
456
554
  }
457
- let message = [];
458
- let colors = "";
459
- let colorKeys = [];
460
- for (let i = 0; i <= format.length - 1; i++) {
461
- if (format[i] === "%w") {
462
- message.push(...log.withArgs || []);
463
- continue;
555
+ if (this.printLevel) {
556
+ let margin = this.printTimestamp ? " " : "";
557
+ args.push(`${margin}${meta.level}`);
558
+ }
559
+ while (true) {
560
+ if (current.type === "init") {
561
+ current = yield { type: "init" };
464
562
  }
465
- if (format[i] === "%t") {
466
- colors += `%c${this.prepareDate(log.timestamp)} `;
467
- colorKeys.push(`color:${this.options.customColors?.get("grey") || this.colors.get("grey")}`);
468
- continue;
563
+ if (current.prev) {
564
+ args.push(current.prev);
469
565
  }
470
- if (format[i] === "%a") {
471
- colors += "%c";
472
- colorKeys.push(`color:${this.options.customColors?.get("green") || this.colors.get("green")}`);
473
- message.push(...log.args);
474
- continue;
566
+ if (current.type === "done") {
567
+ break;
475
568
  }
476
- if (format[i] === "%l") {
477
- colors += `%c${log.level}`;
478
- let colorKey = getColorKey(log.leveling[0]);
479
- colorKeys.push(`color:${this.options.customColors?.get(colorKey) || this.colors.get(colorKey)}`);
480
- continue;
569
+ if (current.type === "arg") {
570
+ if (typeof this.formatArg === "function") {
571
+ args.push(current.value);
572
+ current = yield { type: "done" };
573
+ continue;
574
+ }
481
575
  }
482
- message.push(format[i]);
576
+ current = yield { type: "pass" };
483
577
  }
484
- return [colors, ...colorKeys, ...message];
485
- }
486
- prepareMessage(log) {
487
- let format = [...this.messageFormat];
488
- if (!log.withArgs) {
489
- format = format.slice(0, format.indexOf("%a") + 1);
578
+ if (meta.level.startsWith("DEBUG")) {
579
+ this.console.debug(...args);
580
+ return;
490
581
  }
491
- let message = [];
492
- for (let i = 0; i <= format.length - 1; i++) {
493
- if (format[i] === "%w") {
494
- message.push(...log.withArgs || []);
495
- continue;
496
- }
497
- if (format[i] === "%t") {
498
- message.push(this.prepareDate(log.timestamp));
499
- continue;
500
- }
501
- if (format[i] === "%a") {
502
- message.push(...log.args);
503
- continue;
504
- }
505
- if (format[i] === "%l") {
506
- message.push(log.level);
507
- continue;
508
- }
509
- message.push(format[i]);
582
+ if (meta.level.startsWith("WARN")) {
583
+ this.console.warn(...args);
584
+ return;
510
585
  }
511
- return message;
512
- }
513
- prepareDate(t) {
514
- if (this.options.dateGetter) {
515
- return this.options.dateGetter(t);
586
+ if (meta.level.startsWith("ERROR") || meta.level.startsWith("FATAL")) {
587
+ this.console.error(...args);
588
+ return;
516
589
  }
517
- return getPrettyDate(t);
590
+ this.console.info(...args);
518
591
  }
519
- }(options);
520
- }
521
-
522
- // src/util/dataReplacer.ts
523
- function replaceDataBeforeStringify(value) {
524
- if (typeof value === "symbol") {
525
- return value.toString();
526
- }
527
- if (value instanceof Set) {
528
- return Array.from(value);
529
- }
530
- if (value instanceof Map) {
531
- let obj = {};
532
- for (let key of value.keys()) {
533
- obj[key] = value.get(key);
534
- }
535
- return obj;
536
- }
537
- if (value instanceof Error) {
538
- return value.toString();
539
- }
540
- return value;
592
+ }(console2, options);
541
593
  }
542
594
 
543
- // src/handlers/JSONHandler/JSONHandler.ts
544
- function NewJSONHandler(send, options = {}) {
545
- return () => new class JSONLog {
546
- constructor(options2) {
547
- this.options = options2;
548
- this.level = options2.level;
549
- this.exact = options2.exact ? arrayed(options2.exact) : void 0;
550
- this.options = options2 || {};
551
- }
595
+ // src/main/handlers/JSONHandler.ts
596
+ function NewJSONHandler(send, options) {
597
+ return () => new class JSONHandler extends HandlerBase {
552
598
  level;
553
- exact;
554
- takenNames = /* @__PURE__ */ new Set(["timestamp", "level", "args"]);
555
- log(log) {
556
- this.sendLog(log);
557
- }
558
- setDateGetter(getter) {
559
- this.options.dateGetter = getter;
560
- }
561
- sendLog(log) {
562
- try {
563
- delete log.assertion;
564
- delete log.messageFormat;
565
- delete log.leveling;
566
- log.timestamp = this.formatDate(log.timestamp);
567
- send(JSON.stringify(this.flattenLinkedArguments(log), this.replacer.bind(this)));
568
- } catch (err) {
569
- if (log.level !== "ERROR" /* Error */) {
570
- this.log({
571
- args: [`err while trying to stringify JSON ${err}`],
572
- timestamp: log.timestamp,
573
- level: "ERROR" /* Error */,
574
- leveling: ["ERROR" /* Error */, 0]
575
- });
576
- }
577
- }
599
+ exact = null;
600
+ constructor(send2, options2 = {}) {
601
+ super(send2);
602
+ this.applyOptionalOptions(options2);
603
+ this.level = options2.level;
604
+ this.exact = options2.exact ? toarray(options2.exact) : null;
578
605
  }
579
- formatDate(timestamp) {
580
- if (this.options?.dateGetter) {
581
- return this.options.dateGetter(timestamp);
606
+ formatArg = (arg) => {
607
+ let type = getType(arg);
608
+ let formatted = formatJSON({ type, value: arg });
609
+ if (type !== "object" && type !== "map") {
610
+ return `"${formatted}"`;
582
611
  }
583
- return new Date(timestamp).toISOString();
584
- }
585
- flattenLinkedArguments(log) {
586
- if (this.options?.linkArguments !== void 0 && this.options?.linkArguments === false) {
587
- return log;
612
+ return formatted;
613
+ };
614
+ *execute(meta) {
615
+ let arg = "{";
616
+ let current = { value: null, type: "init" };
617
+ if (this.printTimestamp) {
618
+ arg += `"timestamp":"${this.formatTimestamp(meta.timestamp)}",`;
588
619
  }
589
- if (log.withArgs) {
590
- this.composeLogWithArgsFlattened(log);
620
+ if (this.printLevel) {
621
+ arg += `"level":"${meta.level}",`;
591
622
  }
592
- delete log.withArgs;
593
- return log;
594
- }
595
- composeLogWithArgsFlattened(log) {
596
- let composedLog = log;
597
- let name = "";
598
- for (let arg of log.withArgs) {
599
- if (typeof arg === "string" && stringMatchesVar(arg)) {
600
- name = arg;
601
- continue;
623
+ arg += `"args":[`;
624
+ while (true) {
625
+ if (current.type === "init") {
626
+ current = yield { type: "init" };
602
627
  }
603
- if (name && !this.takenNames.has(name)) {
604
- composedLog[name] = arg;
605
- name = "";
606
- continue;
628
+ if (current.prev) {
629
+ arg += `"${current.prev}",`;
607
630
  }
608
- log.args?.push(arg);
609
- }
610
- return log;
611
- }
612
- replacer(_, value) {
613
- if (this.options.replaceBeforeStringify) {
614
- let v = this.options.replaceBeforeStringify(value);
615
- if (v !== null) {
616
- return v;
631
+ if (current.type === "done") {
632
+ break;
617
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);
618
645
  }
619
- return replaceDataBeforeStringify(value);
646
+ arg += `]}`;
647
+ this.sendMethod(arg);
620
648
  }
621
- }(options);
622
- }
623
-
624
- // src/util/stringify.ts
625
- function stringifyValue(value, stringifier = JSON.stringify) {
626
- if (typeof value === "symbol") {
627
- return value.toString();
628
- }
629
- if (value instanceof Set) {
630
- return `Set[${Array.from(value)}]`;
631
- }
632
- if (value instanceof Error) {
633
- return value.toString();
634
- }
635
- if (Array.isArray(value)) {
636
- return `[${value}]`;
637
- }
638
- if (typeof value === "string") {
639
- return `${value}`;
640
- }
641
- return stringifier(value, (_, data) => replaceDataBeforeStringify(data));
649
+ formatTimestamp(t) {
650
+ return new Date(t).toISOString();
651
+ }
652
+ applyOptionalOptions(options2) {
653
+ this.printTimestamp = options2.printTimestamp ?? true;
654
+ this.printLevel = options2.printLevel ?? true;
655
+ }
656
+ }(send, options);
642
657
  }
643
658
 
644
- // src/handlers/TextHandler/TextHandler.ts
645
- function NewTextHandler(send, options = {}) {
646
- return () => new class TextLog {
647
- constructor(options2) {
648
- this.options = options2;
649
- this.level = options2.level;
650
- this.exact = options2.exact ? arrayed(options2.exact) : void 0;
651
- }
652
- skipDeepCopyWhenSendingLog = true;
659
+ // src/main/handlers/TextHandler.ts
660
+ function NewTextHandler(send, options) {
661
+ return () => new class TextHandler extends HandlerBase {
653
662
  level;
654
- exact;
655
- get linkArguments() {
656
- return this.options.linkArguments !== void 0 && !this.options.linkArguments;
657
- }
658
- log(log) {
659
- this.sendLog(log);
660
- }
661
- sendLog(log) {
662
- let args = "";
663
- let withArgs = "";
664
- let msg = this.options.messageFormat || log.messageFormat;
665
- if (log.args) {
666
- args = this.composeVariablesString(msg, log.args);
667
- }
668
- if (log.withArgs) {
669
- withArgs = this.composeVariablesString(msg, log.withArgs);
670
- }
671
- msg = removeTailingUndefinedValues(msg, log);
672
- send(
673
- msg.replace("%w", withArgs).replace("%a", args).replace("%l", log.level).replace(
674
- "%t",
675
- this.options.dateGetter?.(log.timestamp) ?? getPrettyDate(log.timestamp)
676
- )
677
- );
678
- }
679
- composeVariablesString(format, data) {
680
- let str = "";
681
- let excluded = extractNonFormatChars(format);
682
- for (let i = 0; i < data.length; i++) {
683
- let last = i === data.length - 1;
684
- let nextIsNotLinked = typeof data[i + 1] === "string" && stringMatchesVar(data[i + 1], excluded);
685
- let v = data[i];
686
- if (!this.linkArguments && !last && typeof v === "string" && stringMatchesVar(v, excluded) && !nextIsNotLinked) {
687
- str += `${v}=${this.formatValue(data[i + 1])} `;
688
- i += 1;
689
- continue;
690
- }
691
- str += `${this.formatValue(v)}${last ? "" : " "}`;
692
- }
693
- return str.trim();
663
+ exact = null;
664
+ formatArg;
665
+ constructor(send2, options2 = {}) {
666
+ super(send2);
667
+ this.applyOptionalOptions(options2);
668
+ this.level = options2.level;
669
+ this.exact = options2.exact ? toarray(options2.exact) : null;
670
+ this.formatArg = (value) => format({ type: getType(value), value }, options2.spacing);
694
671
  }
695
- formatValue(v) {
696
- if (this.options.replaceBeforeStringify) {
697
- let val = this.options.replaceBeforeStringify(v);
698
- if (val !== null) {
699
- return val;
700
- }
701
- }
702
- return stringifyValue(v, this.options.stringifier);
672
+ applyOptionalOptions(options2) {
673
+ this.printTimestamp = options2.printTimestamp ?? true;
674
+ this.printLevel = options2.printLevel ?? true;
703
675
  }
704
- }(options);
676
+ }(send, options);
705
677
  }
706
678
 
707
679
  // src/index.ts
708
- var halua = new Halua(NewWebConsoleHandler());
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) : []);
709
686
  // Annotate the CommonJS export names for ESM import in node:
710
687
  0 && (module.exports = {
711
688
  Level,
689
+ NewConsoleHandler,
712
690
  NewJSONHandler,
713
691
  NewTextHandler,
714
- NewWebConsoleHandler,
715
692
  halua
716
693
  });