@faasjs/node-utils 8.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1082 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let node_fs = require("node:fs");
3
+ let node_path = require("node:path");
4
+ let node_process = require("node:process");
5
+
6
+ //#region src/deep_merge.ts
7
+ const shouldMerge = (item) => {
8
+ const type = Object.prototype.toString.call(item);
9
+ return type === "[object Object]" || type === "[object Array]";
10
+ };
11
+ /**
12
+ * Deep merge two objects or arrays.
13
+ *
14
+ * Features:
15
+ * * All objects will be cloned before merging.
16
+ * * Merging order is from right to left.
17
+ * * If an array include same objects, it will be unique to one.
18
+ *
19
+ * ```ts
20
+ * deepMerge({ a: 1 }, { a: 2 }) // { a: 2 }
21
+ * deepMerge([1, 2], [2, 3]) // [1, 2, 3]
22
+ * ```
23
+ */
24
+ function deepMerge(...sources) {
25
+ let acc = Object.create(null);
26
+ for (const source of sources) {
27
+ if (Array.isArray(source)) {
28
+ if (!Array.isArray(acc)) acc = [];
29
+ acc = [...new Set(source.concat(...acc))];
30
+ continue;
31
+ }
32
+ if (!shouldMerge(source)) continue;
33
+ for (const [key, value] of Object.entries(source)) acc = {
34
+ ...acc,
35
+ [key]: shouldMerge(value) ? deepMerge(acc[key], value) : value
36
+ };
37
+ }
38
+ return acc;
39
+ }
40
+
41
+ //#endregion
42
+ //#region src/color.ts
43
+ const Color = {
44
+ DEFAULT: 39,
45
+ BLACK: 30,
46
+ RED: 31,
47
+ GREEN: 32,
48
+ ORANGE: 33,
49
+ BLUE: 34,
50
+ MAGENTA: 35,
51
+ CYAN: 36,
52
+ GRAY: 90
53
+ };
54
+ const LevelColor = {
55
+ debug: Color.GRAY,
56
+ info: Color.GREEN,
57
+ warn: Color.ORANGE,
58
+ error: Color.RED
59
+ };
60
+ /**
61
+ * Apply ANSI color codes to a message based on the log level.
62
+ *
63
+ * @param level - The log level to determine the color.
64
+ * @param message - The message to be colorized.
65
+ * @returns The colorized message string.
66
+ */
67
+ function colorfy(level, message) {
68
+ return `\u001b[0${LevelColor[level]}m${message}\u001b[39m`;
69
+ }
70
+
71
+ //#endregion
72
+ //#region src/format.ts
73
+ /**
74
+ * Formats a string using placeholders and arguments.
75
+ *
76
+ * The function supports the following placeholders:
77
+ * - `%o`: Formats the argument as a JSON string if it's an array, otherwise falls through to `%s`.
78
+ * - `%s`: Converts the argument to a string.
79
+ * - `%d`: Converts the argument to a number.
80
+ * - `%j`: Formats the argument as a JSON string.
81
+ */
82
+ function format(fmt, ...args) {
83
+ const re = /(%?)(%([ojds]))/g;
84
+ let fmtString;
85
+ if (typeof fmt !== "string") if (fmt instanceof Error) fmtString = `Error: ${fmt.message}\n${fmt.stack}`;
86
+ else if (fmt instanceof Object) fmtString = JSON.stringify(fmt);
87
+ else fmtString = String(fmt);
88
+ else fmtString = fmt;
89
+ if (args.length) fmtString = fmtString.replace(re, (match, escaped, _, flag) => {
90
+ let arg = args.shift();
91
+ switch (flag) {
92
+ case "o": if (Array.isArray(arg)) {
93
+ arg = JSON.stringify(arg);
94
+ break;
95
+ }
96
+ case "s":
97
+ arg = `${arg}`;
98
+ break;
99
+ case "d":
100
+ arg = Number(arg);
101
+ break;
102
+ case "j":
103
+ arg = JSON.stringify(arg);
104
+ break;
105
+ }
106
+ if (!escaped) return arg;
107
+ args.unshift(arg);
108
+ return match;
109
+ });
110
+ if (args.length) fmtString += ` ${args.join(" ")}`;
111
+ fmtString = fmtString.replace(/%{2,2}/g, "%");
112
+ return fmtString;
113
+ }
114
+
115
+ //#endregion
116
+ //#region src/transport.ts
117
+ /**
118
+ * The transport class that manages the transport handlers and log messages.
119
+ *
120
+ * **Note: This class is not meant to be used directly. Use the {@link getTransport} instead.**
121
+ *
122
+ * @example
123
+ * ```typescript
124
+ * import { getTransport } from '@faasjs/node-utils'
125
+ *
126
+ * const transport = getTransport()
127
+ *
128
+ * transport.register('test', async (messages) => {
129
+ * for (const { level, message } of messages)
130
+ * console.log(level, message)
131
+ * })
132
+ *
133
+ * transport.config({ label: 'test', debug: true })
134
+ *
135
+ * // If you using Logger, it will automatically insert messages to the transport.
136
+ * // Otherwise, you can insert messages manually.
137
+ * transport.insert({
138
+ * level: 'info',
139
+ * labels: ['server'],
140
+ * message: 'test message',
141
+ * timestamp: Date.now()
142
+ * })
143
+ *
144
+ * process.on('SIGINT', async () => {
145
+ * await transport.stop()
146
+ * process.exit(0)
147
+ * })
148
+ * ```
149
+ */
150
+ var Transport = class {
151
+ enabled = true;
152
+ handlers = /* @__PURE__ */ new Map();
153
+ logger;
154
+ messages = [];
155
+ flushing = false;
156
+ interval;
157
+ intervalTime = 5e3;
158
+ constructor() {
159
+ this.logger = new Logger("LoggerTransport");
160
+ this.logger.level = "info";
161
+ this.flush = this.flush.bind(this);
162
+ this.interval = setInterval(this.flush, this.intervalTime);
163
+ }
164
+ /**
165
+ * Registers a new transport handler.
166
+ *
167
+ * @param name - The name of the transport handler.
168
+ * @param handler - The transport handler function to be registered.
169
+ */
170
+ register(name, handler) {
171
+ this.logger.info("register", name);
172
+ this.handlers.set(name, handler);
173
+ if (!this.enabled) this.enabled = true;
174
+ }
175
+ /**
176
+ * Unregister a handler by its name.
177
+ *
178
+ * This method logs the unregistration process, removes the handler from the internal collection,
179
+ * and disables the logger if no handlers remain.
180
+ *
181
+ * @param name - The name of the handler to unregister.
182
+ */
183
+ unregister(name) {
184
+ this.logger.info("unregister", name);
185
+ this.handlers.delete(name);
186
+ if (this.handlers.size === 0) this.enabled = false;
187
+ }
188
+ /**
189
+ * Inserts a log message into the transport if it is enabled.
190
+ *
191
+ * @param message - The log message to be inserted.
192
+ */
193
+ insert(message) {
194
+ if (!this.enabled) return;
195
+ this.messages.push(message);
196
+ }
197
+ /**
198
+ * Flushes the current messages by processing them with the registered handlers.
199
+ *
200
+ * If the transport is already flushing, it will wait until the current flush is complete.
201
+ * If the transport is disabled or there are no messages to flush, it will return immediately.
202
+ * If there are no handlers registered, it will log a warning, clear the messages, disable the transport, and stop the interval.
203
+ *
204
+ * The method processes all messages with each handler and logs any errors encountered during the process.
205
+ *
206
+ * @returns {Promise<void>} A promise that resolves when the flush operation is complete.
207
+ */
208
+ async flush() {
209
+ if (this.flushing) return new Promise((resolve) => {
210
+ const interval = setInterval(() => {
211
+ if (!this.flushing) {
212
+ clearInterval(interval);
213
+ resolve();
214
+ }
215
+ }, 100);
216
+ });
217
+ if (!this.enabled || this.messages.length === 0) return;
218
+ if (this.handlers.size === 0) {
219
+ this.logger.warn("no handlers to flush, disable transport");
220
+ this.messages.splice(0, this.messages.length);
221
+ this.enabled = false;
222
+ clearInterval(this.interval);
223
+ return;
224
+ }
225
+ this.flushing = true;
226
+ const messages = this.messages.splice(0, this.messages.length);
227
+ this.logger.debug("flushing %d messages with %d handlers", messages.length, this.handlers.size);
228
+ for (const handler of this.handlers.values()) try {
229
+ await handler(messages);
230
+ } catch (error) {
231
+ this.logger.error(handler.name, error);
232
+ }
233
+ this.flushing = false;
234
+ }
235
+ /**
236
+ * Stops the logger transport.
237
+ *
238
+ * This method performs the following actions:
239
+ * 1. Logs a 'stopping' message.
240
+ * 2. Clears the interval if it is set.
241
+ * 3. Flushes any remaining logs.
242
+ * 4. Disables the transport.
243
+ *
244
+ * @returns {Promise<void>} A promise that resolves when the transport has been stopped.
245
+ */
246
+ async stop() {
247
+ this.logger.info("stopping");
248
+ if (this.interval) {
249
+ clearInterval(this.interval);
250
+ this.interval = void 0;
251
+ }
252
+ await this.flush();
253
+ this.enabled = false;
254
+ }
255
+ /**
256
+ * Resets the transport by clearing handlers, emptying messages, and re-enabling the transport.
257
+ * If an interval is set, it will be cleared.
258
+ */
259
+ reset() {
260
+ this.handlers.clear();
261
+ this.messages.splice(0, this.messages.length);
262
+ this.enabled = true;
263
+ if (this.interval) {
264
+ clearInterval(this.interval);
265
+ this.interval = void 0;
266
+ }
267
+ }
268
+ /**
269
+ * Configure the transport options for the logger.
270
+ *
271
+ * @param {TransportOptions} options - The configuration options for the transport.
272
+ * @param {string} [options.label] - The label to be used by the logger.
273
+ * @param {boolean} [options.debug] - If true, sets the logger level to 'debug', otherwise sets it to 'info'.
274
+ * @param {number} [options.interval] - The interval time in milliseconds for flushing the logs. If different from the current interval, it updates the interval and resets the timer.
275
+ */
276
+ config(options) {
277
+ if (options.label) this.logger.label = options.label;
278
+ if (typeof options.debug === "boolean") this.logger.level = options.debug ? "debug" : "info";
279
+ if (options.interval && options.interval !== this.intervalTime) {
280
+ this.intervalTime = options.interval;
281
+ clearInterval(this.interval);
282
+ this.interval = setInterval(this.flush, this.intervalTime);
283
+ }
284
+ if (!this.enabled) this.enabled = true;
285
+ }
286
+ };
287
+ let current;
288
+ function getTransport() {
289
+ current ||= new Transport();
290
+ return current;
291
+ }
292
+
293
+ //#endregion
294
+ //#region src/logger.ts
295
+ const LevelPriority = {
296
+ debug: 0,
297
+ info: 1,
298
+ warn: 2,
299
+ error: 3
300
+ };
301
+ /**
302
+ * Formats the provided arguments into a string, filtering out any objects
303
+ * with a `__hidden__` property set to `true`. If formatting fails, it attempts
304
+ * to stringify each argument individually.
305
+ *
306
+ * @param {...any[]} args - The arguments to format.
307
+ * @returns {string} The formatted string.
308
+ */
309
+ function formatLogger(fmt, ...args) {
310
+ try {
311
+ return format(fmt, ...args.filter((a) => !a || typeof a !== "object" || a.__hidden__ !== true));
312
+ } catch (e) {
313
+ return `[Unable to format] ${e?.message}`;
314
+ }
315
+ }
316
+ /**
317
+ * Logger Class
318
+ *
319
+ * @example
320
+ * ```ts
321
+ * const logger = new Logger()
322
+ *
323
+ * logger.debug('debug message')
324
+ * logger.info('info message')
325
+ * logger.warn('warn message')
326
+ * logger.error('error message')
327
+ *
328
+ * logger.time('timer name')
329
+ * logger.timeEnd('timer name', 'message') // => 'message +1ms'
330
+ * ```
331
+ */
332
+ var Logger = class {
333
+ silent = false;
334
+ level = "debug";
335
+ colorfyOutput = true;
336
+ label;
337
+ size = 1e3;
338
+ disableTransport = false;
339
+ stdout = console.log;
340
+ stderr = console.error;
341
+ cachedTimers = {};
342
+ /**
343
+ * @param label {string} Prefix label
344
+ */
345
+ constructor(label) {
346
+ if (label) this.label = label;
347
+ if (typeof process === "undefined") return;
348
+ if (!process.env.FaasLog && process.env.npm_config_argv && JSON.parse(process.env.npm_config_argv).original.includes("--silent")) this.silent = true;
349
+ if (process.env.FaasLogTransport !== "true" && (process.env.VITEST || process.env.FaasLogTransport === "false")) this.disableTransport = true;
350
+ switch (process.env.FaasLogMode) {
351
+ case "plain":
352
+ this.colorfyOutput = false;
353
+ break;
354
+ case "pretty":
355
+ this.colorfyOutput = true;
356
+ break;
357
+ default:
358
+ this.colorfyOutput = process.env.FaasMode !== "remote";
359
+ break;
360
+ }
361
+ if (process.env.FaasLog) this.level = process.env.FaasLog.toLowerCase();
362
+ if (process.env.FaasLogSize) this.size = Number(process.env.FaasLogSize);
363
+ }
364
+ /**
365
+ * @param message {string} message
366
+ * @param args {...any=} arguments
367
+ */
368
+ debug(message, ...args) {
369
+ this.log("debug", message, ...args);
370
+ return this;
371
+ }
372
+ /**
373
+ * @param message {string} message
374
+ * @param args {...any=} arguments
375
+ */
376
+ info(message, ...args) {
377
+ this.log("info", message, ...args);
378
+ return this;
379
+ }
380
+ /**
381
+ * @param message {string} message
382
+ * @param args {...any=} arguments
383
+ */
384
+ warn(message, ...args) {
385
+ this.log("warn", message, ...args);
386
+ return this;
387
+ }
388
+ /**
389
+ * @param message {any} message or Error object
390
+ * @param args {...any=} arguments
391
+ */
392
+ error(message, ...args) {
393
+ this.log("error", message, ...args);
394
+ return this;
395
+ }
396
+ /**
397
+ * Start a timer with a specific key and log level.
398
+ *
399
+ * @param key - The unique identifier for the timer.
400
+ * @param level - The log level for the timer. Defaults to 'debug'.
401
+ * @returns The Logger instance for chaining.
402
+ */
403
+ time(key, level = "debug") {
404
+ this.cachedTimers[key] = {
405
+ level,
406
+ time: Date.now()
407
+ };
408
+ return this;
409
+ }
410
+ /**
411
+ * End a timer with a specific key and log the elapsed time.
412
+ *
413
+ * @param key - The unique identifier for the timer.
414
+ * @param message - The message to log with the elapsed time.
415
+ * @param args - Additional arguments to log with the message.
416
+ * @returns The Logger instance for chaining.
417
+ */
418
+ timeEnd(key, message, ...args) {
419
+ if (this.cachedTimers[key]) {
420
+ const timer = this.cachedTimers[key];
421
+ const duration = Date.now() - timer.time;
422
+ message = `${message} +${duration}ms`;
423
+ args.push({
424
+ __hidden__: true,
425
+ performance: {
426
+ name: key,
427
+ startTime: timer.time,
428
+ duration
429
+ }
430
+ });
431
+ this[timer.level](message, ...args);
432
+ delete this.cachedTimers[key];
433
+ } else {
434
+ this.warn("timeEnd not found key %s", key);
435
+ this.debug(message);
436
+ }
437
+ return this;
438
+ }
439
+ /**
440
+ * @param message {string} message
441
+ * @param args {...any=} arguments
442
+ */
443
+ raw(message, ...args) {
444
+ if (this.silent) return this;
445
+ this.stdout(formatLogger(message, ...args));
446
+ return this;
447
+ }
448
+ log(level, message, ...args) {
449
+ if (this.silent) return this;
450
+ if (LevelPriority[level] < LevelPriority[this.level]) return this;
451
+ const formattedMessage = formatLogger(message, ...args);
452
+ if (!formattedMessage && !args.length) return this;
453
+ if (!this.disableTransport) getTransport().insert({
454
+ level,
455
+ labels: this.label?.split(/\]\s*\[/) || [],
456
+ message: formattedMessage,
457
+ timestamp: Date.now(),
458
+ extra: args
459
+ });
460
+ let output = `${level.toUpperCase()} ${this.label ? `[${this.label}] ` : ""}${formattedMessage}`;
461
+ if (this.colorfyOutput) output = colorfy(level, output);
462
+ else if (!this.colorfyOutput) output = output.replace(/\n/g, "");
463
+ if (!output) return this;
464
+ if (this.size > 0 && output.length > this.size && !["error", "warn"].includes(level)) output = `${output.slice(0, this.size - 100)}...[truncated]...${output.slice(output.length - 100)}`;
465
+ if (level === "error") this.stderr(output);
466
+ else this.stdout(output);
467
+ return this;
468
+ }
469
+ };
470
+
471
+ //#endregion
472
+ //#region src/parse_yaml.ts
473
+ function createParseError(line, reason) {
474
+ return Error(`[parseYaml] ${reason} at line ${line}`);
475
+ }
476
+ function isSequenceLine(content) {
477
+ return /^-(\s|$)/.test(content);
478
+ }
479
+ function isMappingValue(value) {
480
+ return !!value && typeof value === "object" && !Array.isArray(value);
481
+ }
482
+ function stripInlineComment(content) {
483
+ let inSingleQuote = false;
484
+ let inDoubleQuote = false;
485
+ let escaped = false;
486
+ for (let i = 0; i < content.length; i++) {
487
+ const char = content[i];
488
+ if (inDoubleQuote) {
489
+ if (escaped) {
490
+ escaped = false;
491
+ continue;
492
+ }
493
+ if (char === "\\") {
494
+ escaped = true;
495
+ continue;
496
+ }
497
+ if (char === "\"") inDoubleQuote = false;
498
+ continue;
499
+ }
500
+ if (inSingleQuote) {
501
+ if (char === "'") {
502
+ if (content[i + 1] === "'") {
503
+ i++;
504
+ continue;
505
+ }
506
+ inSingleQuote = false;
507
+ }
508
+ continue;
509
+ }
510
+ if (char === "\"") {
511
+ inDoubleQuote = true;
512
+ continue;
513
+ }
514
+ if (char === "'") {
515
+ inSingleQuote = true;
516
+ continue;
517
+ }
518
+ if (char === "#" && (i === 0 || /\s/.test(content[i - 1]))) return content.slice(0, i).trimEnd();
519
+ }
520
+ return content.trimEnd();
521
+ }
522
+ function normalizeLines(content) {
523
+ const lines = content.replace(/\r\n?/g, "\n").split("\n");
524
+ const normalized = [];
525
+ for (let i = 0; i < lines.length; i++) {
526
+ const line = lines[i];
527
+ const lineNumber = i + 1;
528
+ const leading = line.match(/^[ \t]*/)?.[0] || "";
529
+ if (leading.includes(" ")) throw createParseError(lineNumber, "Tabs are not supported for indentation");
530
+ const indent = leading.length;
531
+ const contentWithoutComment = stripInlineComment(line.slice(indent));
532
+ if (!contentWithoutComment.trim()) continue;
533
+ if (contentWithoutComment === "---" || contentWithoutComment === "...") throw createParseError(lineNumber, "Multiple YAML documents are not supported");
534
+ normalized.push({
535
+ content: contentWithoutComment,
536
+ indent,
537
+ line: lineNumber
538
+ });
539
+ }
540
+ return normalized;
541
+ }
542
+ function findMappingSeparator(content) {
543
+ let inSingleQuote = false;
544
+ let inDoubleQuote = false;
545
+ let escaped = false;
546
+ for (let i = 0; i < content.length; i++) {
547
+ const char = content[i];
548
+ if (inDoubleQuote) {
549
+ if (escaped) {
550
+ escaped = false;
551
+ continue;
552
+ }
553
+ if (char === "\\") {
554
+ escaped = true;
555
+ continue;
556
+ }
557
+ if (char === "\"") inDoubleQuote = false;
558
+ continue;
559
+ }
560
+ if (inSingleQuote) {
561
+ if (char === "'") {
562
+ if (content[i + 1] === "'") {
563
+ i++;
564
+ continue;
565
+ }
566
+ inSingleQuote = false;
567
+ }
568
+ continue;
569
+ }
570
+ if (char === "\"") {
571
+ inDoubleQuote = true;
572
+ continue;
573
+ }
574
+ if (char === "'") {
575
+ inSingleQuote = true;
576
+ continue;
577
+ }
578
+ if (char !== ":") continue;
579
+ const next = content[i + 1];
580
+ if (typeof next === "undefined" || /\s/.test(next)) return i;
581
+ }
582
+ return -1;
583
+ }
584
+ function parseDoubleQuotedScalar(value, line) {
585
+ let result = "";
586
+ for (let i = 1; i < value.length; i++) {
587
+ const char = value[i];
588
+ if (char === "\"") {
589
+ if (i !== value.length - 1) throw createParseError(line, "Invalid double quoted string");
590
+ return result;
591
+ }
592
+ if (char !== "\\") {
593
+ result += char;
594
+ continue;
595
+ }
596
+ const escaped = value[++i];
597
+ if (typeof escaped === "undefined") throw createParseError(line, "Invalid escape sequence");
598
+ switch (escaped) {
599
+ case "\"":
600
+ case "\\":
601
+ case "/":
602
+ result += escaped;
603
+ break;
604
+ case "b":
605
+ result += "\b";
606
+ break;
607
+ case "f":
608
+ result += "\f";
609
+ break;
610
+ case "n":
611
+ result += "\n";
612
+ break;
613
+ case "r":
614
+ result += "\r";
615
+ break;
616
+ case "t":
617
+ result += " ";
618
+ break;
619
+ case "u": {
620
+ const hex = value.slice(i + 1, i + 5);
621
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) throw createParseError(line, "Invalid unicode escape sequence");
622
+ result += String.fromCharCode(Number.parseInt(hex, 16));
623
+ i += 4;
624
+ break;
625
+ }
626
+ default: throw createParseError(line, `Unsupported escape sequence \\${escaped}`);
627
+ }
628
+ }
629
+ throw createParseError(line, "Unterminated double quoted string");
630
+ }
631
+ function parseSingleQuotedScalar(value, line) {
632
+ let result = "";
633
+ for (let i = 1; i < value.length; i++) {
634
+ const char = value[i];
635
+ if (char === "'") {
636
+ if (value[i + 1] === "'") {
637
+ result += "'";
638
+ i++;
639
+ continue;
640
+ }
641
+ if (i !== value.length - 1) throw createParseError(line, "Invalid single quoted string");
642
+ return result;
643
+ }
644
+ result += char;
645
+ }
646
+ throw createParseError(line, "Unterminated single quoted string");
647
+ }
648
+ function parseQuotedScalar(value, line) {
649
+ if (value.startsWith("\"")) return parseDoubleQuotedScalar(value, line);
650
+ if (value.startsWith("'")) return parseSingleQuotedScalar(value, line);
651
+ throw createParseError(line, "Invalid quoted string");
652
+ }
653
+ function parsePlainScalar(value) {
654
+ if (value === "~") return null;
655
+ const lower = value.toLowerCase();
656
+ if (lower === "null") return null;
657
+ if (lower === "true") return true;
658
+ if (lower === "false") return false;
659
+ if (/^[-+]?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][-+]?\d+)?$/.test(value)) return Number(value);
660
+ return value;
661
+ }
662
+ function parseInlineValue(value, line) {
663
+ if (value.startsWith("|") || value.startsWith(">")) throw createParseError(line, "Block scalar is not supported");
664
+ if (value.startsWith("!")) throw createParseError(line, "YAML tags are not supported");
665
+ if (value === "[]") return [];
666
+ if (value === "{}") return Object.create(null);
667
+ if (value.startsWith("[") || value.startsWith("{")) throw createParseError(line, "Flow collection is not supported");
668
+ if (value.startsWith("\"") || value.startsWith("'")) return parseQuotedScalar(value, line);
669
+ return parsePlainScalar(value);
670
+ }
671
+ function parseKey(rawKey, line) {
672
+ if (!rawKey.length) throw createParseError(line, "Missing mapping key");
673
+ if (rawKey.startsWith("\"") || rawKey.startsWith("'")) return parseQuotedScalar(rawKey, line);
674
+ if (rawKey.startsWith("[") || rawKey.startsWith("{")) throw createParseError(line, "Complex mapping key is not supported");
675
+ return rawKey;
676
+ }
677
+ function parseReferenceToken(value, line, marker) {
678
+ let index = 1;
679
+ while (index < value.length && !/\s/.test(value[index])) index++;
680
+ const name = value.slice(1, index);
681
+ if (!name.length) throw createParseError(line, marker === "&" ? "Missing anchor name" : "Missing alias name");
682
+ if (!/^[^\s\[\]\{\},]+$/.test(name)) throw createParseError(line, marker === "&" ? "Invalid anchor name" : "Invalid alias name");
683
+ return {
684
+ name,
685
+ rest: value.slice(index).trimStart()
686
+ };
687
+ }
688
+ function setAnchor(context, anchorName, value) {
689
+ if (!anchorName) return;
690
+ context.anchors.set(anchorName, value);
691
+ }
692
+ function parseValueToken(token, line, context) {
693
+ let anchorName;
694
+ let rest = token;
695
+ if (rest.startsWith("&")) {
696
+ const anchor = parseReferenceToken(rest, line, "&");
697
+ anchorName = anchor.name;
698
+ rest = anchor.rest;
699
+ if (!rest.length) return {
700
+ anchorName,
701
+ kind: "nested"
702
+ };
703
+ }
704
+ if (rest.startsWith("*")) {
705
+ const alias = parseReferenceToken(rest, line, "*");
706
+ if (alias.rest.length) throw createParseError(line, "Unexpected token after alias");
707
+ if (!context.anchors.has(alias.name)) throw createParseError(line, `Unknown alias "*${alias.name}"`);
708
+ return {
709
+ anchorName,
710
+ kind: "alias",
711
+ value: context.anchors.get(alias.name)
712
+ };
713
+ }
714
+ return {
715
+ anchorName,
716
+ kind: "inline",
717
+ raw: rest
718
+ };
719
+ }
720
+ function parseNode(lines, index, indent, context) {
721
+ const current = lines[index];
722
+ if (!current) return {
723
+ value: null,
724
+ nextIndex: index
725
+ };
726
+ if (current.indent !== indent) throw createParseError(current.line, `Unexpected indentation: expected ${indent} spaces but got ${current.indent}`);
727
+ if (isSequenceLine(current.content)) return parseSequence(lines, index, indent, context);
728
+ return parseMapping(lines, index, indent, context);
729
+ }
730
+ function parseNestedBlockOrNull(lines, index, parentIndent, context) {
731
+ const next = lines[index + 1];
732
+ if (!next || next.indent <= parentIndent) return {
733
+ value: null,
734
+ nextIndex: index + 1
735
+ };
736
+ return parseNode(lines, index + 1, next.indent, context);
737
+ }
738
+ function parseMappingEntry(lines, index, content, entryIndent, line, context) {
739
+ const separator = findMappingSeparator(content);
740
+ if (separator < 0) throw createParseError(line, "Invalid mapping entry, expected \"key: value\"");
741
+ const key = parseKey(content.slice(0, separator).trim(), line);
742
+ const valueToken = content.slice(separator + 1).trimStart();
743
+ if (!valueToken.length) {
744
+ const nested = parseNestedBlockOrNull(lines, index, entryIndent, context);
745
+ return {
746
+ key,
747
+ value: nested.value,
748
+ nextIndex: nested.nextIndex
749
+ };
750
+ }
751
+ const token = parseValueToken(valueToken, line, context);
752
+ if (token.kind === "alias") {
753
+ setAnchor(context, token.anchorName, token.value);
754
+ return {
755
+ key,
756
+ value: token.value,
757
+ nextIndex: index + 1
758
+ };
759
+ }
760
+ if (token.kind === "nested") {
761
+ const nested = parseNestedBlockOrNull(lines, index, entryIndent, context);
762
+ setAnchor(context, token.anchorName, nested.value);
763
+ return {
764
+ key,
765
+ value: nested.value,
766
+ nextIndex: nested.nextIndex
767
+ };
768
+ }
769
+ const inlineValue = parseInlineValue(token.raw, line);
770
+ setAnchor(context, token.anchorName, inlineValue);
771
+ return {
772
+ key,
773
+ value: inlineValue,
774
+ nextIndex: index + 1
775
+ };
776
+ }
777
+ function applyMergeKey(target, source, line) {
778
+ if (Array.isArray(source)) {
779
+ for (const value of source) applyMergeKey(target, value, line);
780
+ return;
781
+ }
782
+ if (!isMappingValue(source)) throw createParseError(line, "Merge key \"<<\" expects a mapping or sequence of mappings");
783
+ for (const key in source) {
784
+ if (Object.hasOwn(target, key)) continue;
785
+ target[key] = source[key];
786
+ }
787
+ }
788
+ function parseMapping(lines, index, indent, context) {
789
+ const value = Object.create(null);
790
+ let currentIndex = index;
791
+ while (currentIndex < lines.length) {
792
+ const line = lines[currentIndex];
793
+ if (line.indent < indent) break;
794
+ if (line.indent > indent) throw createParseError(line.line, `Unexpected indentation in mapping: expected ${indent} spaces but got ${line.indent}`);
795
+ if (isSequenceLine(line.content)) throw createParseError(line.line, "Cannot mix sequence item with mapping at the same indentation");
796
+ const entry = parseMappingEntry(lines, currentIndex, line.content, indent, line.line, context);
797
+ if (entry.key === "<<") applyMergeKey(value, entry.value, line.line);
798
+ else value[entry.key] = entry.value;
799
+ currentIndex = entry.nextIndex;
800
+ }
801
+ return {
802
+ value,
803
+ nextIndex: currentIndex
804
+ };
805
+ }
806
+ function parseSequenceItem(lines, index, indent, context) {
807
+ const line = lines[index];
808
+ const rest = line.content.slice(1);
809
+ if (rest.length && !/^\s/.test(rest)) throw createParseError(line.line, "Missing whitespace after sequence marker \"-\"");
810
+ const token = rest.trimStart();
811
+ if (!token.length) return parseNestedBlockOrNull(lines, index, indent, context);
812
+ const parsedToken = parseValueToken(token, line.line, context);
813
+ if (parsedToken.kind === "alias") {
814
+ setAnchor(context, parsedToken.anchorName, parsedToken.value);
815
+ return {
816
+ value: parsedToken.value,
817
+ nextIndex: index + 1
818
+ };
819
+ }
820
+ if (parsedToken.kind === "nested") {
821
+ const nested = parseNestedBlockOrNull(lines, index, indent, context);
822
+ setAnchor(context, parsedToken.anchorName, nested.value);
823
+ return nested;
824
+ }
825
+ if (findMappingSeparator(parsedToken.raw) < 0) {
826
+ const inlineValue = parseInlineValue(parsedToken.raw, line.line);
827
+ setAnchor(context, parsedToken.anchorName, inlineValue);
828
+ return {
829
+ value: inlineValue,
830
+ nextIndex: index + 1
831
+ };
832
+ }
833
+ const itemIndent = indent + 2;
834
+ const item = Object.create(null);
835
+ const firstEntry = parseMappingEntry(lines, index, parsedToken.raw, itemIndent, line.line, context);
836
+ if (firstEntry.key === "<<") applyMergeKey(item, firstEntry.value, line.line);
837
+ else item[firstEntry.key] = firstEntry.value;
838
+ let currentIndex = firstEntry.nextIndex;
839
+ while (currentIndex < lines.length) {
840
+ const next = lines[currentIndex];
841
+ if (next.indent < itemIndent) break;
842
+ if (next.indent > itemIndent) throw createParseError(next.line, `Unexpected indentation in sequence mapping: expected ${itemIndent} spaces but got ${next.indent}`);
843
+ if (isSequenceLine(next.content)) throw createParseError(next.line, "Cannot mix sequence item with mapping at the same indentation");
844
+ const entry = parseMappingEntry(lines, currentIndex, next.content, itemIndent, next.line, context);
845
+ if (entry.key === "<<") applyMergeKey(item, entry.value, next.line);
846
+ else item[entry.key] = entry.value;
847
+ currentIndex = entry.nextIndex;
848
+ }
849
+ setAnchor(context, parsedToken.anchorName, item);
850
+ return {
851
+ value: item,
852
+ nextIndex: currentIndex
853
+ };
854
+ }
855
+ function parseSequence(lines, index, indent, context) {
856
+ const value = [];
857
+ let currentIndex = index;
858
+ while (currentIndex < lines.length) {
859
+ const line = lines[currentIndex];
860
+ if (line.indent < indent) break;
861
+ if (line.indent > indent) throw createParseError(line.line, `Unexpected indentation in sequence: expected ${indent} spaces but got ${line.indent}`);
862
+ if (!isSequenceLine(line.content)) throw createParseError(line.line, "Cannot mix mapping entry with sequence at the same indentation");
863
+ const item = parseSequenceItem(lines, currentIndex, indent, context);
864
+ value.push(item.value);
865
+ currentIndex = item.nextIndex;
866
+ }
867
+ return {
868
+ value,
869
+ nextIndex: currentIndex
870
+ };
871
+ }
872
+ function parseYaml(content) {
873
+ const lines = normalizeLines(content);
874
+ if (!lines.length) return void 0;
875
+ const context = { anchors: /* @__PURE__ */ new Map() };
876
+ const parsed = parseNode(lines, 0, lines[0].indent, context);
877
+ if (parsed.nextIndex < lines.length) throw createParseError(lines[parsed.nextIndex].line, "Unexpected trailing content");
878
+ return parsed.value;
879
+ }
880
+
881
+ //#endregion
882
+ //#region src/load_config.ts
883
+ function isObject(value) {
884
+ return !!value && typeof value === "object" && !Array.isArray(value);
885
+ }
886
+ function createConfigError(filePath, keyPath, reason) {
887
+ return Error(`[loadConfig] Invalid faas.yaml ${filePath} at "${keyPath}": ${reason}`);
888
+ }
889
+ function validateServerConfig(filePath, staging, server) {
890
+ if (!isObject(server)) throw createConfigError(filePath, `${staging}.server`, "must be an object");
891
+ if (typeof server.root !== "undefined" && typeof server.root !== "string") throw createConfigError(filePath, `${staging}.server.root`, "must be a string");
892
+ if (typeof server.base !== "undefined" && typeof server.base !== "string") throw createConfigError(filePath, `${staging}.server.base`, "must be a string");
893
+ }
894
+ function validateFaasYaml(filePath, config) {
895
+ if (typeof config === "undefined" || config === null) return Object.create(null);
896
+ if (!isObject(config)) throw createConfigError(filePath, "<root>", "must be an object");
897
+ for (const staging in config) {
898
+ if (staging === "types") throw createConfigError(filePath, "types", "has been removed, move related settings out of faas.yaml");
899
+ const stageConfig = config[staging];
900
+ if (typeof stageConfig === "undefined" || stageConfig === null) continue;
901
+ if (!isObject(stageConfig)) throw createConfigError(filePath, staging, "must be an object");
902
+ if (Object.hasOwn(stageConfig, "types")) throw createConfigError(filePath, `${staging}.types`, "has been removed, move related settings out of faas.yaml");
903
+ if (Object.hasOwn(stageConfig, "server")) validateServerConfig(filePath, staging, stageConfig.server);
904
+ }
905
+ return config;
906
+ }
907
+ function assignPluginNames(config) {
908
+ if (!config.plugins) return;
909
+ for (const pluginKey in config.plugins) {
910
+ const plugin = config.plugins[pluginKey];
911
+ plugin.name = pluginKey;
912
+ }
913
+ }
914
+ /**
915
+ * Load configuration from faas.yaml
916
+ */
917
+ var Config = class {
918
+ root;
919
+ filename;
920
+ origin;
921
+ defaults;
922
+ logger;
923
+ constructor(root, filename, logger) {
924
+ this.logger = new Logger(logger?.label ? `${logger.label}] [config` : "config");
925
+ this.root = root;
926
+ if (!this.root.endsWith(node_path.sep)) this.root += node_path.sep;
927
+ this.filename = filename;
928
+ this.logger.debug("load %s in %s", filename, root);
929
+ const configs = [];
930
+ const paths = [this.root, "."].concat((0, node_path.dirname)(filename.replace(root, "")).split(node_path.sep));
931
+ let base = paths[0];
932
+ for (const path of paths.slice(1)) {
933
+ const currentRoot = (0, node_path.join)(base, path);
934
+ if (currentRoot === base) continue;
935
+ const faas = (0, node_path.join)(currentRoot, "faas.yaml");
936
+ if ((0, node_fs.existsSync)(faas)) configs.push(validateFaasYaml(faas, parseYaml((0, node_fs.readFileSync)(faas, "utf8"))));
937
+ base = currentRoot;
938
+ }
939
+ this.origin = deepMerge(...configs);
940
+ this.defaults = deepMerge(this.origin.defaults || {});
941
+ for (const key in this.origin) {
942
+ const data = key === "defaults" ? this.defaults : deepMerge(this.defaults, this.origin[key]);
943
+ if (key !== "defaults") this[key] = data;
944
+ assignPluginNames(data);
945
+ }
946
+ }
947
+ get(key) {
948
+ return this[key] || this.defaults || Object.create(null);
949
+ }
950
+ };
951
+ /**
952
+ * Load configuration from faas.yaml
953
+ */
954
+ function loadConfig(root, filename, staging, logger) {
955
+ return new Config(root, filename, logger).get(staging);
956
+ }
957
+
958
+ //#endregion
959
+ //#region src/load_env.ts
960
+ /**
961
+ * Load a dotenv file if it exists.
962
+ *
963
+ * - Defaults to `${process.cwd()}/.env`.
964
+ * - Existing environment variables are preserved (Node.js behavior).
965
+ */
966
+ function loadEnvFileIfExists(options = {}) {
967
+ const filePath = (0, node_path.resolve)(options.cwd || process.cwd(), options.filename || ".env");
968
+ if (!(0, node_fs.existsSync)(filePath)) return null;
969
+ (0, node_process.loadEnvFile)(filePath);
970
+ return filePath;
971
+ }
972
+
973
+ //#endregion
974
+ //#region src/load_package.ts
975
+ let _runtime = null;
976
+ function resetRuntime() {
977
+ _runtime = null;
978
+ }
979
+ /**
980
+ * Detect current JavaScript runtime environment.
981
+ *
982
+ * This function checks for presence of `require` first, then falls back to
983
+ * Node.js ESM detection via `process.versions.node`.
984
+ *
985
+ * @returns {NodeRuntime} Returns `module` for ESM and `commonjs` for CJS.
986
+ * @throws {Error} Throws an error if runtime cannot be determined.
987
+ */
988
+ function detectNodeRuntime() {
989
+ if (_runtime) return _runtime;
990
+ if (typeof globalThis.require === "function" && typeof module !== "undefined") return _runtime = "commonjs";
991
+ if (typeof process !== "undefined" && process.versions?.node) return _runtime = "module";
992
+ throw Error("Unknown runtime");
993
+ }
994
+ /**
995
+ * Asynchronously loads a package by its name, supporting both ESM and CJS.
996
+ *
997
+ * @template T The type of module to be loaded.
998
+ * @param name The package name to load.
999
+ * @param defaultNames Preferred export keys used to resolve default values.
1000
+ * @returns Loaded module or resolved default export.
1001
+ */
1002
+ async function loadPackage(name, defaultNames = "default") {
1003
+ const runtime = detectNodeRuntime();
1004
+ let module;
1005
+ if (runtime === "module") module = await import(name);
1006
+ else if (runtime === "commonjs") module = globalThis.require(name);
1007
+ else throw Error("Unknown runtime");
1008
+ if (typeof defaultNames === "string") return defaultNames in module ? module[defaultNames] : module;
1009
+ for (const key of defaultNames) if (key in module) return module[key];
1010
+ return module;
1011
+ }
1012
+
1013
+ //#endregion
1014
+ //#region src/load_func.ts
1015
+ /**
1016
+ * Load a FaasJS function and its configuration, returning the handler.
1017
+ *
1018
+ * @param root Project root directory used to resolve configuration.
1019
+ * @param filename Path to the packaged FaasJS function file to load.
1020
+ * @param staging Staging directory name (used when locating config).
1021
+ * @returns A promise that resolves to the function handler.
1022
+ *
1023
+ * @example
1024
+ * ```ts
1025
+ * import { loadFunc } from '@faasjs/node-utils'
1026
+ *
1027
+ * const handler = await loadFunc(
1028
+ * process.cwd(),
1029
+ * __dirname + '/example.func.ts',
1030
+ * 'development'
1031
+ * )
1032
+ *
1033
+ * const result = await handler(event, context)
1034
+ * console.log(result)
1035
+ * ```
1036
+ */
1037
+ async function loadFunc(root, filename, staging) {
1038
+ const func = await loadPackage(filename);
1039
+ func.config = await loadConfig(root, filename, staging);
1040
+ return func.export().handler;
1041
+ }
1042
+
1043
+ //#endregion
1044
+ //#region src/stream.ts
1045
+ /**
1046
+ * Convert ReadableStream to text.
1047
+ *
1048
+ * @throws {TypeError} If stream is not a ReadableStream instance.
1049
+ */
1050
+ async function streamToText(stream) {
1051
+ if (!(stream instanceof ReadableStream)) throw new TypeError("stream must be a ReadableStream instance");
1052
+ return new Response(stream).text();
1053
+ }
1054
+ /**
1055
+ * Convert ReadableStream to object.
1056
+ *
1057
+ * @throws {TypeError} If stream is not a ReadableStream instance.
1058
+ */
1059
+ async function streamToObject(stream) {
1060
+ if (!(stream instanceof ReadableStream)) throw new TypeError("stream must be a ReadableStream instance");
1061
+ return new Response(stream).json();
1062
+ }
1063
+ const streamToString = streamToText;
1064
+
1065
+ //#endregion
1066
+ exports.Color = Color;
1067
+ exports.LevelColor = LevelColor;
1068
+ exports.Logger = Logger;
1069
+ exports.Transport = Transport;
1070
+ exports.colorfy = colorfy;
1071
+ exports.deepMerge = deepMerge;
1072
+ exports.detectNodeRuntime = detectNodeRuntime;
1073
+ exports.formatLogger = formatLogger;
1074
+ exports.getTransport = getTransport;
1075
+ exports.loadConfig = loadConfig;
1076
+ exports.loadEnvFileIfExists = loadEnvFileIfExists;
1077
+ exports.loadFunc = loadFunc;
1078
+ exports.loadPackage = loadPackage;
1079
+ exports.resetRuntime = resetRuntime;
1080
+ exports.streamToObject = streamToObject;
1081
+ exports.streamToString = streamToString;
1082
+ exports.streamToText = streamToText;