@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.
@@ -0,0 +1,347 @@
1
+ //#region src/deep_merge.d.ts
2
+ /**
3
+ * Deep merge two objects or arrays.
4
+ *
5
+ * Features:
6
+ * * All objects will be cloned before merging.
7
+ * * Merging order is from right to left.
8
+ * * If an array include same objects, it will be unique to one.
9
+ *
10
+ * ```ts
11
+ * deepMerge({ a: 1 }, { a: 2 }) // { a: 2 }
12
+ * deepMerge([1, 2], [2, 3]) // [1, 2, 3]
13
+ * ```
14
+ */
15
+ declare function deepMerge(...sources: any[]): any;
16
+ //#endregion
17
+ //#region src/logger.d.ts
18
+ /** Logger Level */
19
+ type Level = 'debug' | 'info' | 'warn' | 'error';
20
+ /**
21
+ * Formats the provided arguments into a string, filtering out any objects
22
+ * with a `__hidden__` property set to `true`. If formatting fails, it attempts
23
+ * to stringify each argument individually.
24
+ *
25
+ * @param {...any[]} args - The arguments to format.
26
+ * @returns {string} The formatted string.
27
+ */
28
+ declare function formatLogger(fmt: any, ...args: any[]): string;
29
+ /**
30
+ * Logger Class
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * const logger = new Logger()
35
+ *
36
+ * logger.debug('debug message')
37
+ * logger.info('info message')
38
+ * logger.warn('warn message')
39
+ * logger.error('error message')
40
+ *
41
+ * logger.time('timer name')
42
+ * logger.timeEnd('timer name', 'message') // => 'message +1ms'
43
+ * ```
44
+ */
45
+ declare class Logger {
46
+ silent: boolean;
47
+ level: Level;
48
+ colorfyOutput: boolean;
49
+ label?: string;
50
+ size: number;
51
+ disableTransport: boolean;
52
+ stdout: (text: string) => void;
53
+ stderr: (text: string) => void;
54
+ private cachedTimers;
55
+ /**
56
+ * @param label {string} Prefix label
57
+ */
58
+ constructor(label?: string);
59
+ /**
60
+ * @param message {string} message
61
+ * @param args {...any=} arguments
62
+ */
63
+ debug(message: string, ...args: any[]): Logger;
64
+ /**
65
+ * @param message {string} message
66
+ * @param args {...any=} arguments
67
+ */
68
+ info(message: string, ...args: any[]): Logger;
69
+ /**
70
+ * @param message {string} message
71
+ * @param args {...any=} arguments
72
+ */
73
+ warn(message: string, ...args: any[]): Logger;
74
+ /**
75
+ * @param message {any} message or Error object
76
+ * @param args {...any=} arguments
77
+ */
78
+ error(message: string | Error | unknown, ...args: any[]): Logger;
79
+ /**
80
+ * Start a timer with a specific key and log level.
81
+ *
82
+ * @param key - The unique identifier for the timer.
83
+ * @param level - The log level for the timer. Defaults to 'debug'.
84
+ * @returns The Logger instance for chaining.
85
+ */
86
+ time(key: string, level?: Level): Logger;
87
+ /**
88
+ * End a timer with a specific key and log the elapsed time.
89
+ *
90
+ * @param key - The unique identifier for the timer.
91
+ * @param message - The message to log with the elapsed time.
92
+ * @param args - Additional arguments to log with the message.
93
+ * @returns The Logger instance for chaining.
94
+ */
95
+ timeEnd(key: string, message: string, ...args: any[]): Logger;
96
+ /**
97
+ * @param message {string} message
98
+ * @param args {...any=} arguments
99
+ */
100
+ raw(message: string, ...args: any[]): Logger;
101
+ private log;
102
+ }
103
+ //#endregion
104
+ //#region src/color.d.ts
105
+ declare const Color: {
106
+ DEFAULT: number;
107
+ BLACK: number;
108
+ RED: number;
109
+ GREEN: number;
110
+ ORANGE: number;
111
+ BLUE: number;
112
+ MAGENTA: number;
113
+ CYAN: number;
114
+ GRAY: number;
115
+ };
116
+ declare const LevelColor: {
117
+ debug: number;
118
+ info: number;
119
+ warn: number;
120
+ error: number;
121
+ };
122
+ /**
123
+ * Apply ANSI color codes to a message based on the log level.
124
+ *
125
+ * @param level - The log level to determine the color.
126
+ * @param message - The message to be colorized.
127
+ * @returns The colorized message string.
128
+ */
129
+ declare function colorfy(level: Level, message: string): string;
130
+ //#endregion
131
+ //#region src/load_config.d.ts
132
+ type FuncPluginConfig = {
133
+ [key: string]: any;
134
+ type?: string;
135
+ config?: {
136
+ [key: string]: any;
137
+ };
138
+ name?: string;
139
+ };
140
+ type FuncConfig = {
141
+ [key: string]: any;
142
+ plugins?: {
143
+ [key: string]: FuncPluginConfig;
144
+ };
145
+ };
146
+ /**
147
+ * Load configuration from faas.yaml
148
+ */
149
+ declare function loadConfig(root: string, filename: string, staging: string, logger?: Logger): FuncConfig;
150
+ //#endregion
151
+ //#region src/load_env.d.ts
152
+ type LoadEnvFileIfExistsOptions = {
153
+ cwd?: string;
154
+ filename?: string;
155
+ };
156
+ /**
157
+ * Load a dotenv file if it exists.
158
+ *
159
+ * - Defaults to `${process.cwd()}/.env`.
160
+ * - Existing environment variables are preserved (Node.js behavior).
161
+ */
162
+ declare function loadEnvFileIfExists(options?: LoadEnvFileIfExistsOptions): string | null;
163
+ //#endregion
164
+ //#region src/load_func.d.ts
165
+ type ExportedHandler<TEvent = any, TContext = any, TResult = any> = (event?: TEvent, context?: TContext, callback?: (...args: any) => any) => Promise<TResult>;
166
+ /**
167
+ * Load a FaasJS function and its configuration, returning the handler.
168
+ *
169
+ * @param root Project root directory used to resolve configuration.
170
+ * @param filename Path to the packaged FaasJS function file to load.
171
+ * @param staging Staging directory name (used when locating config).
172
+ * @returns A promise that resolves to the function handler.
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * import { loadFunc } from '@faasjs/node-utils'
177
+ *
178
+ * const handler = await loadFunc(
179
+ * process.cwd(),
180
+ * __dirname + '/example.func.ts',
181
+ * 'development'
182
+ * )
183
+ *
184
+ * const result = await handler(event, context)
185
+ * console.log(result)
186
+ * ```
187
+ */
188
+ declare function loadFunc<TEvent = any, TContext = any, TResult = any>(root: string, filename: string, staging: string): Promise<ExportedHandler<TEvent, TContext, TResult>>;
189
+ //#endregion
190
+ //#region src/load_package.d.ts
191
+ type NodeRuntime = 'commonjs' | 'module';
192
+ declare function resetRuntime(): void;
193
+ /**
194
+ * Detect current JavaScript runtime environment.
195
+ *
196
+ * This function checks for presence of `require` first, then falls back to
197
+ * Node.js ESM detection via `process.versions.node`.
198
+ *
199
+ * @returns {NodeRuntime} Returns `module` for ESM and `commonjs` for CJS.
200
+ * @throws {Error} Throws an error if runtime cannot be determined.
201
+ */
202
+ declare function detectNodeRuntime(): NodeRuntime;
203
+ /**
204
+ * Asynchronously loads a package by its name, supporting both ESM and CJS.
205
+ *
206
+ * @template T The type of module to be loaded.
207
+ * @param name The package name to load.
208
+ * @param defaultNames Preferred export keys used to resolve default values.
209
+ * @returns Loaded module or resolved default export.
210
+ */
211
+ declare function loadPackage<T = unknown>(name: string, defaultNames?: string | string[]): Promise<T>;
212
+ //#endregion
213
+ //#region src/stream.d.ts
214
+ /**
215
+ * Convert ReadableStream to text.
216
+ *
217
+ * @throws {TypeError} If stream is not a ReadableStream instance.
218
+ */
219
+ declare function streamToText(stream: ReadableStream<Uint8Array>): Promise<string>;
220
+ /**
221
+ * Convert ReadableStream to object.
222
+ *
223
+ * @throws {TypeError} If stream is not a ReadableStream instance.
224
+ */
225
+ declare function streamToObject<T = any>(stream: ReadableStream<Uint8Array>): Promise<T>;
226
+ declare const streamToString: typeof streamToText;
227
+ //#endregion
228
+ //#region src/transport.d.ts
229
+ type LoggerMessage = {
230
+ level: Level;
231
+ labels: string[];
232
+ message: string;
233
+ timestamp: number;
234
+ extra?: any[];
235
+ };
236
+ type TransportHandler = (messages: LoggerMessage[]) => Promise<void>;
237
+ type TransportOptions = {
238
+ /** @default 'LoggerTransport' */label?: string; /** @default 5000 */
239
+ interval?: number; /** @default false */
240
+ debug?: boolean;
241
+ };
242
+ /**
243
+ * The transport class that manages the transport handlers and log messages.
244
+ *
245
+ * **Note: This class is not meant to be used directly. Use the {@link getTransport} instead.**
246
+ *
247
+ * @example
248
+ * ```typescript
249
+ * import { getTransport } from '@faasjs/node-utils'
250
+ *
251
+ * const transport = getTransport()
252
+ *
253
+ * transport.register('test', async (messages) => {
254
+ * for (const { level, message } of messages)
255
+ * console.log(level, message)
256
+ * })
257
+ *
258
+ * transport.config({ label: 'test', debug: true })
259
+ *
260
+ * // If you using Logger, it will automatically insert messages to the transport.
261
+ * // Otherwise, you can insert messages manually.
262
+ * transport.insert({
263
+ * level: 'info',
264
+ * labels: ['server'],
265
+ * message: 'test message',
266
+ * timestamp: Date.now()
267
+ * })
268
+ *
269
+ * process.on('SIGINT', async () => {
270
+ * await transport.stop()
271
+ * process.exit(0)
272
+ * })
273
+ * ```
274
+ */
275
+ declare class Transport {
276
+ private enabled;
277
+ handlers: Map<string, TransportHandler>;
278
+ private logger;
279
+ messages: LoggerMessage[];
280
+ private flushing;
281
+ private interval;
282
+ private intervalTime;
283
+ constructor();
284
+ /**
285
+ * Registers a new transport handler.
286
+ *
287
+ * @param name - The name of the transport handler.
288
+ * @param handler - The transport handler function to be registered.
289
+ */
290
+ register(name: string, handler: TransportHandler): void;
291
+ /**
292
+ * Unregister a handler by its name.
293
+ *
294
+ * This method logs the unregistration process, removes the handler from the internal collection,
295
+ * and disables the logger if no handlers remain.
296
+ *
297
+ * @param name - The name of the handler to unregister.
298
+ */
299
+ unregister(name: string): void;
300
+ /**
301
+ * Inserts a log message into the transport if it is enabled.
302
+ *
303
+ * @param message - The log message to be inserted.
304
+ */
305
+ insert(message: LoggerMessage): void;
306
+ /**
307
+ * Flushes the current messages by processing them with the registered handlers.
308
+ *
309
+ * If the transport is already flushing, it will wait until the current flush is complete.
310
+ * If the transport is disabled or there are no messages to flush, it will return immediately.
311
+ * If there are no handlers registered, it will log a warning, clear the messages, disable the transport, and stop the interval.
312
+ *
313
+ * The method processes all messages with each handler and logs any errors encountered during the process.
314
+ *
315
+ * @returns {Promise<void>} A promise that resolves when the flush operation is complete.
316
+ */
317
+ flush(): Promise<void>;
318
+ /**
319
+ * Stops the logger transport.
320
+ *
321
+ * This method performs the following actions:
322
+ * 1. Logs a 'stopping' message.
323
+ * 2. Clears the interval if it is set.
324
+ * 3. Flushes any remaining logs.
325
+ * 4. Disables the transport.
326
+ *
327
+ * @returns {Promise<void>} A promise that resolves when the transport has been stopped.
328
+ */
329
+ stop(): Promise<void>;
330
+ /**
331
+ * Resets the transport by clearing handlers, emptying messages, and re-enabling the transport.
332
+ * If an interval is set, it will be cleared.
333
+ */
334
+ reset(): void;
335
+ /**
336
+ * Configure the transport options for the logger.
337
+ *
338
+ * @param {TransportOptions} options - The configuration options for the transport.
339
+ * @param {string} [options.label] - The label to be used by the logger.
340
+ * @param {boolean} [options.debug] - If true, sets the logger level to 'debug', otherwise sets it to 'info'.
341
+ * @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.
342
+ */
343
+ config(options: TransportOptions): void;
344
+ }
345
+ declare function getTransport(): Transport;
346
+ //#endregion
347
+ export { Color, type ExportedHandler, type FuncConfig, type FuncPluginConfig, type Level, LevelColor, type LoadEnvFileIfExistsOptions, Logger, type LoggerMessage, type NodeRuntime, Transport, type TransportHandler, type TransportOptions, colorfy, deepMerge, detectNodeRuntime, formatLogger, getTransport, loadConfig, loadEnvFileIfExists, loadFunc, loadPackage, resetRuntime, streamToObject, streamToString, streamToText };