@briangits/node-log 0.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,181 @@
1
+ # node-log
2
+
3
+ > Logging for Node.js with typed writers, log levels, and structured output.
4
+
5
+ ## Features
6
+
7
+ - **Sync & Async Writers** — Log to the console synchronously or to files asynchronously.
8
+ - **Log Levels** — `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `CRITICAL`.
9
+ - **Tags** — Attach contextual tags to every log record.
10
+ - **Structured Output** — Built-in JSON Lines writer with automatic serialization of `Error`, `Map`, `Set`, and `bigint`.
11
+ - **Customizable Formatting** — Console writer supports format strings with placeholders.
12
+ - **TypeScript First** — Fully typed with declaration maps.
13
+ - **Dual Format** — Ships both ESM and CJS builds.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ # pnpm
19
+ pnpm add @briangits/node-log
20
+
21
+ # npm
22
+ npm install @briangits/node-log
23
+
24
+ # yarn
25
+ yarn add @briangits/node-log
26
+ ```
27
+
28
+ ## Quick Start
29
+
30
+ ```typescript
31
+ import { Logger, ConsoleLogWriter, LogLevel } from '@briangits/node-log'
32
+
33
+ const logger = new Logger(new ConsoleLogWriter())
34
+
35
+ logger.info('Server started on port', 3000)
36
+ logger.warn('High memory usage', { used: '1.2GB' })
37
+ logger.error('Connection failed', new Error('timeout'))
38
+ ```
39
+
40
+ **Console output:**
41
+
42
+ ```
43
+ [2026-06-25T06:30:00.000Z] [INFO]: Server started on port 3000
44
+ [2026-06-25T06:30:00.001Z] [WARN]: High memory usage { used: '1.2GB' }
45
+ [2026-06-25T06:30:00.002Z] [ERROR]: Connection failed Error: timeout
46
+ ```
47
+
48
+ ## Writers
49
+
50
+ Writers are the target destination for log records. The library provides two built-in writers and a simple interface for creating your own.
51
+
52
+ ### ConsoleLogWriter
53
+
54
+ Outputs formatted log records to `stdout`.
55
+
56
+ ```typescript
57
+ import { Logger, ConsoleLogWriter } from '@briangits/node-log'
58
+
59
+ const logger = new Logger(new ConsoleLogWriter('[%t] %l — %msg'))
60
+
61
+ logger.info('Hello, world!')
62
+ // => [2026-06-25T06:30:00.000Z] INFO — Hello, world!
63
+ ```
64
+
65
+ **Message extraction:**
66
+
67
+ - If the **first** argument is a string, it is used as the message.
68
+ - Otherwise, if the **last** argument is a string, it is used as the message.
69
+ - Any remaining arguments are passed through as additional data.
70
+
71
+ **Format placeholders:**
72
+
73
+ | Placeholder | Description |
74
+ | ----------- | ----------------------------------------------- |
75
+ | `%t` | ISO timestamp |
76
+ | `%l` | Log level name (e.g., `INFO`) |
77
+ | `%tag` | Tags joined by `/` (omitted if no tags are set) |
78
+ | `%msg` | Log message |
79
+
80
+ Additional arguments are appended after the formatted message and passed directly to `console.log`.
81
+
82
+ ### JSONLFileLogWriter
83
+
84
+ Appends log records as JSON Lines to a file. Automatically normalizes special values so they remain serializable.
85
+
86
+ ```typescript
87
+ import { Logger, JSONLFileLogWriter } from '@briangits/node-log'
88
+
89
+ const logger = new Logger(new JSONLFileLogWriter('./app.log'))
90
+
91
+ await logger.info('User logged in', { userId: 42 })
92
+ ```
93
+
94
+ **Serialized output (`./app.log`):**
95
+
96
+ ```json
97
+ {
98
+ "level": 30,
99
+ "time": "2026-06-25T06:30:00.000Z",
100
+ "tags": [],
101
+ "message": "User logged in",
102
+ "args": [{ "userId": 42 }]
103
+ }
104
+ ```
105
+
106
+ **Normalization rules:**
107
+
108
+ | Type | Serialized as |
109
+ | -------- | ------------------------------------- |
110
+ | `Error` | `{ name, message, stack }` |
111
+ | `Map` | Plain object via `Object.fromEntries` |
112
+ | `Set` | Array via `[...set]` |
113
+ | `bigint` | String via `.toString()` |
114
+
115
+ ### Custom Writer
116
+
117
+ Implement `LogWriter` for synchronous output or `AsyncLogWriter` for asynchronous output.
118
+
119
+ ```typescript
120
+ import { LogWriter, LogRecord, Logger } from '@briangits/node-log'
121
+
122
+ class SyslogWriter implements LogWriter {
123
+ write(log: LogRecord): void {
124
+ // forward to syslog, etc.
125
+ }
126
+ }
127
+
128
+ const logger = new Logger(new SyslogWriter())
129
+ logger.info('Sent to syslog')
130
+ ```
131
+
132
+ ## API Reference
133
+
134
+ ### `Logger<Writer>`
135
+
136
+ The main entry point for creating log records.
137
+
138
+ ```typescript
139
+ new Logger(writer: Writer, tags?: string[])
140
+ ```
141
+
142
+ | Method | Description |
143
+ | --------------------- | --------------------------------------- |
144
+ | `log(level, ...args)` | Write a record at the given `LogLevel`. |
145
+ | `trace(...args)` | Write a `TRACE` record. |
146
+ | `debug(...args)` | Write a `DEBUG` record. |
147
+ | `info(...args)` | Write an `INFO` record. |
148
+ | `warn(...args)` | Write a `WARN` record. |
149
+ | `error(...args)` | Write an `ERROR` record. |
150
+ | `critical(...args)` | Write a `CRITICAL` record. |
151
+
152
+ When the writer is an `AsyncLogWriter`, all methods return `Promise<void>`; otherwise they return `void`.
153
+
154
+ ### `LogLevel`
155
+
156
+ ```typescript
157
+ enum LogLevel {
158
+ TRACE = 10,
159
+ DEBUG = 20,
160
+ INFO = 30,
161
+ WARN = 40,
162
+ ERROR = 50,
163
+ CRITICAL = 60
164
+ }
165
+ ```
166
+
167
+ ### `LogRecord`
168
+
169
+ ```typescript
170
+ interface LogRecord {
171
+ level: LogLevel
172
+ time: Date
173
+ tags: string[]
174
+ message: string | undefined
175
+ args: unknown[]
176
+ }
177
+ ```
178
+
179
+ ## License
180
+
181
+ Apache-2.0
package/dist/index.cjs ADDED
@@ -0,0 +1,217 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let node_fs_promises = require("node:fs/promises");
3
+ //#region src/LogLevel.ts
4
+ /**
5
+ * Defines the severity levels for log records.
6
+ *
7
+ * Levels are ordered by increasing severity:
8
+ * `TRACE` < `DEBUG` < `INFO` < `WARN` < `ERROR` < `CRITICAL`.
9
+ */
10
+ let LogLevel = /* @__PURE__ */ function(LogLevel) {
11
+ /** Fine-grained informational events useful for deep debugging. */
12
+ LogLevel[LogLevel["TRACE"] = 10] = "TRACE";
13
+ /** Informational events useful for debugging an application. */
14
+ LogLevel[LogLevel["DEBUG"] = 20] = "DEBUG";
15
+ /** Informational messages that highlight the progress of the application. */
16
+ LogLevel[LogLevel["INFO"] = 30] = "INFO";
17
+ /** Potentially harmful situations that do not prevent execution. */
18
+ LogLevel[LogLevel["WARN"] = 40] = "WARN";
19
+ /** Error events that might still allow the application to continue running. */
20
+ LogLevel[LogLevel["ERROR"] = 50] = "ERROR";
21
+ /** Very severe error events that will presumably lead the application to abort. */
22
+ LogLevel[LogLevel["CRITICAL"] = 60] = "CRITICAL";
23
+ return LogLevel;
24
+ }({});
25
+ //#endregion
26
+ //#region src/Logger.ts
27
+ /**
28
+ * A logger that accepts log records and forwards them to a {@link LogWriter}.
29
+ *
30
+ * The generic `Writer` type controls whether logging is synchronous or asynchronous.
31
+ */
32
+ var Logger = class {
33
+ writer;
34
+ tags;
35
+ /**
36
+ * Creates a new `Logger` instance.
37
+ * @param writer - The log writer to receive records.
38
+ * @param tags - Optional tags to attach to every record.
39
+ */
40
+ constructor(writer, tags = []) {
41
+ this.writer = writer;
42
+ this.tags = tags;
43
+ }
44
+ /**
45
+ * Extracts an optional message string from the argument list.
46
+ * If the first argument is a string it is treated as the message;
47
+ * otherwise, if the last argument is a string it is treated as the message.
48
+ * @param args - The raw arguments passed to a log method.
49
+ * @returns The message and remaining arguments.
50
+ */
51
+ parseArgs(...args) {
52
+ let msg = void 0;
53
+ let data = args;
54
+ if (typeof args[0] === "string") {
55
+ msg = args[0];
56
+ data = args.slice(1);
57
+ } else if (args.length > 0 && typeof args[args.length - 1] === "string") {
58
+ msg = args[args.length - 1];
59
+ data = args.slice(0, -1);
60
+ }
61
+ return {
62
+ msg,
63
+ args: data
64
+ };
65
+ }
66
+ /**
67
+ * Writes a log record at the specified level.
68
+ * @param level - The severity level.
69
+ * @param args - The log message and any additional data.
70
+ * @returns A `Promise<void>` when using an {@link AsyncLogWriter}, otherwise `void`.
71
+ */
72
+ log(level, ...args) {
73
+ const { msg, args: _args } = this.parseArgs(...args);
74
+ return this.writer.write({
75
+ level,
76
+ time: /* @__PURE__ */ new Date(),
77
+ tags: this.tags,
78
+ message: msg,
79
+ args: _args
80
+ });
81
+ }
82
+ /**
83
+ * Writes a `TRACE` level log record.
84
+ * @param args - The log message and any additional data.
85
+ */
86
+ trace(...args) {
87
+ return this.log(10, ...args);
88
+ }
89
+ /**
90
+ * Writes a `DEBUG` level log record.
91
+ * @param args - The log message and any additional data.
92
+ */
93
+ debug(...args) {
94
+ return this.log(20, ...args);
95
+ }
96
+ /**
97
+ * Writes an `INFO` level log record.
98
+ * @param args - The log message and any additional data.
99
+ */
100
+ info(...args) {
101
+ return this.log(30, ...args);
102
+ }
103
+ /**
104
+ * Writes a `WARN` level log record.
105
+ * @param args - The log message and any additional data.
106
+ */
107
+ warn(...args) {
108
+ return this.log(40, ...args);
109
+ }
110
+ /**
111
+ * Writes an `ERROR` level log record.
112
+ * @param args - The log message and any additional data.
113
+ */
114
+ error(...args) {
115
+ return this.log(50, ...args);
116
+ }
117
+ /**
118
+ * Writes a `CRITICAL` level log record.
119
+ * @param args - The log message and any additional data.
120
+ */
121
+ critical(...args) {
122
+ return this.log(60, ...args);
123
+ }
124
+ };
125
+ //#endregion
126
+ //#region src/writer/ConsoleLogWriter.ts
127
+ /**
128
+ * A synchronous log writer that outputs formatted log records
129
+ * to the console. Supports customizable format strings
130
+ * using placeholders: `%t` (timestamp), `%l` (level), `%tag` (tags), `%msg` (message).
131
+ */
132
+ var ConsoleLogWriter = class {
133
+ format;
134
+ /**
135
+ * Creates a new `ConsoleLogWriter` instance.
136
+ * @param format - The format string. Defaults to `[%t] [%l] [%tag]: %msg`.
137
+ */
138
+ constructor(format = "[%t] [%l] [%tag]: %msg") {
139
+ this.format = format;
140
+ }
141
+ /**
142
+ * Formats a `LogRecord` into an array suitable for `console.log`.
143
+ * @param log - The log record to format.
144
+ * @returns An array of formatted values and extras.
145
+ */
146
+ fmt(log) {
147
+ const tag = log.tags.length > 0 ? `[${log.tags.join("/")}]` : "";
148
+ return [this.format.replace("%t", log.time.toISOString()).replace("%l", LogLevel[log.level]).replace("%tag", tag).replace("%msg", log.message ?? "").trim(), ...log.args];
149
+ }
150
+ /**
151
+ * Writes a log record to the console.
152
+ * @param log - The log record to write.
153
+ */
154
+ write(log) {
155
+ console.log(...this.fmt(log));
156
+ }
157
+ };
158
+ //#endregion
159
+ //#region src/writer/JSONLFileLogWriter.ts
160
+ /**
161
+ * An asynchronous log writer that serializes log records as JSON Lines
162
+ * and appends them to a file. Special values like `Error`, `Map`, `Set`,
163
+ * and `bigint` are normalized before serialization.
164
+ */
165
+ var JSONLFileLogWriter = class {
166
+ path;
167
+ /**
168
+ * Creates a new `JSONLFileLogWriter` instance.
169
+ * @param path - The path to the JSON Lines file.
170
+ */
171
+ constructor(path) {
172
+ this.path = path;
173
+ }
174
+ /**
175
+ * Serializes a `LogRecord` into a plain object.
176
+ * @param log - The log record to serialize.
177
+ * @returns A plain object representation of the log record.
178
+ * @private
179
+ */
180
+ serialize(log) {
181
+ return {
182
+ ...log,
183
+ args: log.args.map((arg) => this.serializeValue(arg))
184
+ };
185
+ }
186
+ /**
187
+ * Serializes the `value` to a plain object
188
+ * @param value - The value to serialize.
189
+ * @return A plain object representation of the value.
190
+ * @private
191
+ */
192
+ serializeValue(value) {
193
+ if (value instanceof Error) return {
194
+ name: value.name,
195
+ message: value.message,
196
+ stack: value.stack
197
+ };
198
+ if (value instanceof Map) return Object.fromEntries(value);
199
+ if (value instanceof Set) return [...value];
200
+ if (typeof value === "bigint") return value.toString();
201
+ return value;
202
+ }
203
+ /**
204
+ * Writes a log record to the log file.
205
+ * @param log - The log record to write.
206
+ */
207
+ async write(log) {
208
+ await (0, node_fs_promises.appendFile)(this.path, JSON.stringify(this.serialize(log)) + "\n");
209
+ }
210
+ };
211
+ //#endregion
212
+ exports.ConsoleLogWriter = ConsoleLogWriter;
213
+ exports.JSONLFileLogWriter = JSONLFileLogWriter;
214
+ exports.LogLevel = LogLevel;
215
+ exports.Logger = Logger;
216
+
217
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../src/LogLevel.ts","../src/Logger.ts","../src/writer/ConsoleLogWriter.ts","../src/writer/JSONLFileLogWriter.ts"],"sourcesContent":["/**\n * Defines the severity levels for log records.\n *\n * Levels are ordered by increasing severity:\n * `TRACE` < `DEBUG` < `INFO` < `WARN` < `ERROR` < `CRITICAL`.\n */\nexport enum LogLevel {\n /** Fine-grained informational events useful for deep debugging. */\n TRACE = 10,\n\n /** Informational events useful for debugging an application. */\n DEBUG = 20,\n\n /** Informational messages that highlight the progress of the application. */\n INFO = 30,\n\n /** Potentially harmful situations that do not prevent execution. */\n WARN = 40,\n\n /** Error events that might still allow the application to continue running. */\n ERROR = 50,\n\n /** Very severe error events that will presumably lead the application to abort. */\n CRITICAL = 60\n}\n","import { LogLevel } from './LogLevel'\nimport { MaybePromise } from './MaybePromise'\nimport { AsyncLogWriter, LogWriter } from './writer'\n\n/**\n * A logger that accepts log records and forwards them to a {@link LogWriter}.\n *\n * The generic `Writer` type controls whether logging is synchronous or asynchronous.\n */\nexport class Logger<Writer extends LogWriter | AsyncLogWriter = LogWriter> {\n /**\n * Creates a new `Logger` instance.\n * @param writer - The log writer to receive records.\n * @param tags - Optional tags to attach to every record.\n */\n constructor(\n private readonly writer: Writer,\n private readonly tags: string[] = []\n ) {}\n\n /**\n * Extracts an optional message string from the argument list.\n * If the first argument is a string it is treated as the message;\n * otherwise, if the last argument is a string it is treated as the message.\n * @param args - The raw arguments passed to a log method.\n * @returns The message and remaining arguments.\n */\n private parseArgs(...args: unknown[]): {\n msg: string | undefined\n args: unknown[]\n } {\n let msg: string | undefined = undefined\n let data: unknown[] = args\n\n if (typeof args[0] === 'string') {\n msg = args[0]\n data = args.slice(1)\n } else if (args.length > 0 && typeof args[args.length - 1] === 'string') {\n msg = args[args.length - 1] as any\n data = args.slice(0, -1)\n }\n\n return { msg, args: data }\n }\n\n /**\n * Writes a log record at the specified level.\n * @param level - The severity level.\n * @param args - The log message and any additional data.\n * @returns A `Promise<void>` when using an {@link AsyncLogWriter}, otherwise `void`.\n */\n log(level: LogLevel, ...args: unknown[]): MaybePromise<Writer, void> {\n const { msg, args: _args } = this.parseArgs(...args)\n\n return this.writer.write({\n level,\n time: new Date(),\n tags: this.tags,\n message: msg,\n args: _args\n }) as MaybePromise<Writer, void>\n }\n\n /**\n * Writes a `TRACE` level log record.\n * @param args - The log message and any additional data.\n */\n trace(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.TRACE, ...args)\n }\n\n /**\n * Writes a `DEBUG` level log record.\n * @param args - The log message and any additional data.\n */\n debug(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.DEBUG, ...args)\n }\n\n /**\n * Writes an `INFO` level log record.\n * @param args - The log message and any additional data.\n */\n info(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.INFO, ...args)\n }\n\n /**\n * Writes a `WARN` level log record.\n * @param args - The log message and any additional data.\n */\n warn(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.WARN, ...args)\n }\n\n /**\n * Writes an `ERROR` level log record.\n * @param args - The log message and any additional data.\n */\n error(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.ERROR, ...args)\n }\n\n /**\n * Writes a `CRITICAL` level log record.\n * @param args - The log message and any additional data.\n */\n critical(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.CRITICAL, ...args)\n }\n}\n","import { LogLevel } from '../LogLevel'\nimport { LogRecord } from '../LogRecord'\nimport { LogWriter } from './LogWriter'\n\n/**\n * A synchronous log writer that outputs formatted log records\n * to the console. Supports customizable format strings\n * using placeholders: `%t` (timestamp), `%l` (level), `%tag` (tags), `%msg` (message).\n */\nexport class ConsoleLogWriter implements LogWriter {\n /**\n * Creates a new `ConsoleLogWriter` instance.\n * @param format - The format string. Defaults to `[%t] [%l] [%tag]: %msg`.\n */\n constructor(private readonly format: string = '[%t] [%l] [%tag]: %msg') {}\n\n /**\n * Formats a `LogRecord` into an array suitable for `console.log`.\n * @param log - The log record to format.\n * @returns An array of formatted values and extras.\n */\n private fmt(log: LogRecord): unknown[] {\n const tag = log.tags.length > 0 ? `[${log.tags.join('/')}]` : ''\n\n return [\n this.format\n .replace('%t', log.time.toISOString())\n .replace('%l', LogLevel[log.level])\n .replace('%tag', tag)\n .replace('%msg', log.message ?? '')\n .trim(),\n ...log.args\n ]\n }\n\n /**\n * Writes a log record to the console.\n * @param log - The log record to write.\n */\n write(log: LogRecord): void {\n console.log(...this.fmt(log))\n }\n}\n","import { appendFile } from 'node:fs/promises'\nimport { LogRecord } from '../LogRecord'\nimport { AsyncLogWriter } from './AsyncLogWriter'\n\n/**\n * An asynchronous log writer that serializes log records as JSON Lines\n * and appends them to a file. Special values like `Error`, `Map`, `Set`,\n * and `bigint` are normalized before serialization.\n */\nexport class JSONLFileLogWriter implements AsyncLogWriter {\n /**\n * Creates a new `JSONLFileLogWriter` instance.\n * @param path - The path to the JSON Lines file.\n */\n constructor(private readonly path: string) {}\n\n /**\n * Serializes a `LogRecord` into a plain object.\n * @param log - The log record to serialize.\n * @returns A plain object representation of the log record.\n * @private\n */\n private serialize(log: LogRecord): object {\n return {\n ...log,\n args: log.args.map(arg => this.serializeValue(arg))\n }\n }\n\n /**\n * Serializes the `value` to a plain object\n * @param value - The value to serialize.\n * @return A plain object representation of the value.\n * @private\n */\n private serializeValue(value: unknown): unknown {\n if (value instanceof Error) {\n return {\n name: value.name,\n message: value.message,\n stack: value.stack\n }\n }\n\n if (value instanceof Map) {\n return Object.fromEntries(value)\n }\n\n if (value instanceof Set) {\n return [...value]\n }\n\n if (typeof value === 'bigint') {\n return value.toString()\n }\n\n return value\n }\n\n /**\n * Writes a log record to the log file.\n * @param log - The log record to write.\n */\n async write(log: LogRecord): Promise<void> {\n await appendFile(this.path, JSON.stringify(this.serialize(log)) + '\\n')\n }\n}\n"],"mappings":";;;;;;;;;AAMA,IAAY,WAAL,yBAAA,UAAA;;CAEH,SAAA,SAAA,WAAA,MAAA;;CAGA,SAAA,SAAA,WAAA,MAAA;;CAGA,SAAA,SAAA,UAAA,MAAA;;CAGA,SAAA,SAAA,UAAA,MAAA;;CAGA,SAAA,SAAA,WAAA,MAAA;;CAGA,SAAA,SAAA,cAAA,MAAA;;AACJ,EAAA,CAAA,CAAA;;;;;;;;ACfA,IAAa,SAAb,MAA2E;CAOlD;CACA;;;;;;CAFrB,YACI,QACA,OAAkC,CAAC,GACrC;EAFmB,KAAA,SAAA;EACA,KAAA,OAAA;CAClB;;;;;;;;CASH,UAAkB,GAAG,MAGnB;EACE,IAAI,MAA0B,KAAA;EAC9B,IAAI,OAAkB;EAEtB,IAAI,OAAO,KAAK,OAAO,UAAU;GAC7B,MAAM,KAAK;GACX,OAAO,KAAK,MAAM,CAAC;EACvB,OAAO,IAAI,KAAK,SAAS,KAAK,OAAO,KAAK,KAAK,SAAS,OAAO,UAAU;GACrE,MAAM,KAAK,KAAK,SAAS;GACzB,OAAO,KAAK,MAAM,GAAG,EAAE;EAC3B;EAEA,OAAO;GAAE;GAAK,MAAM;EAAK;CAC7B;;;;;;;CAQA,IAAI,OAAiB,GAAG,MAA6C;EACjE,MAAM,EAAE,KAAK,MAAM,UAAU,KAAK,UAAU,GAAG,IAAI;EAEnD,OAAO,KAAK,OAAO,MAAM;GACrB;GACA,sBAAM,IAAI,KAAK;GACf,MAAM,KAAK;GACX,SAAS;GACT,MAAM;EACV,CAAC;CACL;;;;;CAMA,MAAM,GAAG,MAAyD;EAC9D,OAAO,KAAK,IAAA,IAAoB,GAAG,IAAI;CAC3C;;;;;CAMA,MAAM,GA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,MAAM;GACf,OAAO,MAAM;EACjB;EAGJ,IAAI,iBAAiB,KACjB,OAAO,OAAO,YAAY,KAAK;EAGnC,IAAI,iBAAiB,KACjB,OAAO,CAAC,GAAG,KAAK;EAGpB,IAAI,OAAO,UAAU,UACjB,OAAO,MAAM,SAAS;EAG1B,OAAO;CACX;;;;;CAMA,MAAM,MAAM,KAA+B;EACvC,OAAA,GAAA,iBAAA,WAAA,CAAiB,KAAK,MAAM,KAAK,UAAU,KAAK,UAAU,GAAG,CAAC,IAAI,IAAI;CAC1E;AACJ"}
@@ -0,0 +1,200 @@
1
+ //#region src/LogLevel.d.ts
2
+ /**
3
+ * Defines the severity levels for log records.
4
+ *
5
+ * Levels are ordered by increasing severity:
6
+ * `TRACE` < `DEBUG` < `INFO` < `WARN` < `ERROR` < `CRITICAL`.
7
+ */
8
+ declare enum LogLevel {
9
+ /** Fine-grained informational events useful for deep debugging. */
10
+ TRACE = 10,
11
+ /** Informational events useful for debugging an application. */
12
+ DEBUG = 20,
13
+ /** Informational messages that highlight the progress of the application. */
14
+ INFO = 30,
15
+ /** Potentially harmful situations that do not prevent execution. */
16
+ WARN = 40,
17
+ /** Error events that might still allow the application to continue running. */
18
+ ERROR = 50,
19
+ /** Very severe error events that will presumably lead the application to abort. */
20
+ CRITICAL = 60
21
+ }
22
+ //#endregion
23
+ //#region src/LogRecord.d.ts
24
+ /**
25
+ * Represents a single log record containing metadata, the message,
26
+ * and any additional arguments.
27
+ */
28
+ interface LogRecord {
29
+ /** The level of the log. */
30
+ level: LogLevel;
31
+ /** The timestamp when the log record was created. */
32
+ time: Date;
33
+ /** The tags associated with the log record. */
34
+ tags: string[];
35
+ /** The log message, if any. */
36
+ message: string | undefined;
37
+ /** Additional arguments passed to the log. */
38
+ args: unknown[];
39
+ }
40
+ //#endregion
41
+ //#region src/writer/AsyncLogWriter.d.ts
42
+ /**
43
+ * Defines an asynchronous log writer that accepts log records
44
+ * and writes them to a target output (console, file, etc.).
45
+ */
46
+ interface AsyncLogWriter {
47
+ /**
48
+ * Writes a single log record asynchronously.
49
+ * @param log - The log record to write.
50
+ */
51
+ write(log: LogRecord): Promise<void>;
52
+ }
53
+ //#endregion
54
+ //#region src/writer/LogWriter.d.ts
55
+ /**
56
+ * Defines a synchronous log writer that accepts log records
57
+ * and writes them to a target output (console, file, etc.).
58
+ */
59
+ interface LogWriter {
60
+ /**
61
+ * Writes a single log record synchronously.
62
+ * @param log - The log record to write.
63
+ */
64
+ write(log: LogRecord): void;
65
+ }
66
+ //#endregion
67
+ //#region src/writer/ConsoleLogWriter.d.ts
68
+ /**
69
+ * A synchronous log writer that outputs formatted log records
70
+ * to the console. Supports customizable format strings
71
+ * using placeholders: `%t` (timestamp), `%l` (level), `%tag` (tags), `%msg` (message).
72
+ */
73
+ declare class ConsoleLogWriter implements LogWriter {
74
+ private readonly format;
75
+ /**
76
+ * Creates a new `ConsoleLogWriter` instance.
77
+ * @param format - The format string. Defaults to `[%t] [%l] [%tag]: %msg`.
78
+ */
79
+ constructor(format?: string);
80
+ /**
81
+ * Formats a `LogRecord` into an array suitable for `console.log`.
82
+ * @param log - The log record to format.
83
+ * @returns An array of formatted values and extras.
84
+ */
85
+ private fmt;
86
+ /**
87
+ * Writes a log record to the console.
88
+ * @param log - The log record to write.
89
+ */
90
+ write(log: LogRecord): void;
91
+ }
92
+ //#endregion
93
+ //#region src/writer/JSONLFileLogWriter.d.ts
94
+ /**
95
+ * An asynchronous log writer that serializes log records as JSON Lines
96
+ * and appends them to a file. Special values like `Error`, `Map`, `Set`,
97
+ * and `bigint` are normalized before serialization.
98
+ */
99
+ declare class JSONLFileLogWriter implements AsyncLogWriter {
100
+ private readonly path;
101
+ /**
102
+ * Creates a new `JSONLFileLogWriter` instance.
103
+ * @param path - The path to the JSON Lines file.
104
+ */
105
+ constructor(path: string);
106
+ /**
107
+ * Serializes a `LogRecord` into a plain object.
108
+ * @param log - The log record to serialize.
109
+ * @returns A plain object representation of the log record.
110
+ * @private
111
+ */
112
+ private serialize;
113
+ /**
114
+ * Serializes the `value` to a plain object
115
+ * @param value - The value to serialize.
116
+ * @return A plain object representation of the value.
117
+ * @private
118
+ */
119
+ private serializeValue;
120
+ /**
121
+ * Writes a log record to the log file.
122
+ * @param log - The log record to write.
123
+ */
124
+ write(log: LogRecord): Promise<void>;
125
+ }
126
+ //#endregion
127
+ //#region src/MaybePromise.d.ts
128
+ /**
129
+ * A conditional type that resolves to `Promise<R>` when the writer is
130
+ * an {@link AsyncLogWriter}, otherwise `R`.
131
+ *
132
+ * @typeParam Writer - The writer type to check.
133
+ * @typeParam R - The return type of the operation.
134
+ */
135
+ type MaybePromise<Writer extends LogWriter | AsyncLogWriter, R> = Writer extends AsyncLogWriter ? Promise<R> : R;
136
+ //#endregion
137
+ //#region src/Logger.d.ts
138
+ /**
139
+ * A logger that accepts log records and forwards them to a {@link LogWriter}.
140
+ *
141
+ * The generic `Writer` type controls whether logging is synchronous or asynchronous.
142
+ */
143
+ declare class Logger<Writer extends LogWriter | AsyncLogWriter = LogWriter> {
144
+ private readonly writer;
145
+ private readonly tags;
146
+ /**
147
+ * Creates a new `Logger` instance.
148
+ * @param writer - The log writer to receive records.
149
+ * @param tags - Optional tags to attach to every record.
150
+ */
151
+ constructor(writer: Writer, tags?: string[]);
152
+ /**
153
+ * Extracts an optional message string from the argument list.
154
+ * If the first argument is a string it is treated as the message;
155
+ * otherwise, if the last argument is a string it is treated as the message.
156
+ * @param args - The raw arguments passed to a log method.
157
+ * @returns The message and remaining arguments.
158
+ */
159
+ private parseArgs;
160
+ /**
161
+ * Writes a log record at the specified level.
162
+ * @param level - The severity level.
163
+ * @param args - The log message and any additional data.
164
+ * @returns A `Promise<void>` when using an {@link AsyncLogWriter}, otherwise `void`.
165
+ */
166
+ log(level: LogLevel, ...args: unknown[]): MaybePromise<Writer, void>;
167
+ /**
168
+ * Writes a `TRACE` level log record.
169
+ * @param args - The log message and any additional data.
170
+ */
171
+ trace(...args: unknown[]): MaybePromise<typeof this.writer, void>;
172
+ /**
173
+ * Writes a `DEBUG` level log record.
174
+ * @param args - The log message and any additional data.
175
+ */
176
+ debug(...args: unknown[]): MaybePromise<typeof this.writer, void>;
177
+ /**
178
+ * Writes an `INFO` level log record.
179
+ * @param args - The log message and any additional data.
180
+ */
181
+ info(...args: unknown[]): MaybePromise<typeof this.writer, void>;
182
+ /**
183
+ * Writes a `WARN` level log record.
184
+ * @param args - The log message and any additional data.
185
+ */
186
+ warn(...args: unknown[]): MaybePromise<typeof this.writer, void>;
187
+ /**
188
+ * Writes an `ERROR` level log record.
189
+ * @param args - The log message and any additional data.
190
+ */
191
+ error(...args: unknown[]): MaybePromise<typeof this.writer, void>;
192
+ /**
193
+ * Writes a `CRITICAL` level log record.
194
+ * @param args - The log message and any additional data.
195
+ */
196
+ critical(...args: unknown[]): MaybePromise<typeof this.writer, void>;
197
+ }
198
+ //#endregion
199
+ export { AsyncLogWriter, ConsoleLogWriter, JSONLFileLogWriter, LogLevel, LogRecord, LogWriter, Logger, MaybePromise };
200
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/LogLevel.ts","../src/LogRecord.ts","../src/writer/AsyncLogWriter.ts","../src/writer/LogWriter.ts","../src/writer/ConsoleLogWriter.ts","../src/writer/JSONLFileLogWriter.ts","../src/MaybePromise.ts","../src/Logger.ts"],"mappings":";;AAMA;;;;;aAAY,QAAA;EAQR;EANA,KAAA;EAYA;EATA,KAAA;EAYQ;EATR,IAAA;;EAGA,IAAA;;EAGA,KAAA;ECdsB;EDiBtB,QAAA;AAAA;;;AAjBJ;;;;AAAA,UCAiB,SAAA;EDKb;ECHA,KAAA,EAAO,QAAA;EDSP;ECPA,IAAA,EAAM,IAAI;EDaV;ECXA,IAAA;EDWQ;ECTR,OAAA;;EAEA,IAAA;AAAA;;;ADVJ;;;;AAAA,UEAiB,cAAA;EFKb;;;;EEAA,KAAA,CAAM,GAAA,EAAK,SAAA,GAAY,OAAO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,aAAyB,MAAA;AAAA"}
@@ -0,0 +1,200 @@
1
+ //#region src/LogLevel.d.ts
2
+ /**
3
+ * Defines the severity levels for log records.
4
+ *
5
+ * Levels are ordered by increasing severity:
6
+ * `TRACE` < `DEBUG` < `INFO` < `WARN` < `ERROR` < `CRITICAL`.
7
+ */
8
+ declare enum LogLevel {
9
+ /** Fine-grained informational events useful for deep debugging. */
10
+ TRACE = 10,
11
+ /** Informational events useful for debugging an application. */
12
+ DEBUG = 20,
13
+ /** Informational messages that highlight the progress of the application. */
14
+ INFO = 30,
15
+ /** Potentially harmful situations that do not prevent execution. */
16
+ WARN = 40,
17
+ /** Error events that might still allow the application to continue running. */
18
+ ERROR = 50,
19
+ /** Very severe error events that will presumably lead the application to abort. */
20
+ CRITICAL = 60
21
+ }
22
+ //#endregion
23
+ //#region src/LogRecord.d.ts
24
+ /**
25
+ * Represents a single log record containing metadata, the message,
26
+ * and any additional arguments.
27
+ */
28
+ interface LogRecord {
29
+ /** The level of the log. */
30
+ level: LogLevel;
31
+ /** The timestamp when the log record was created. */
32
+ time: Date;
33
+ /** The tags associated with the log record. */
34
+ tags: string[];
35
+ /** The log message, if any. */
36
+ message: string | undefined;
37
+ /** Additional arguments passed to the log. */
38
+ args: unknown[];
39
+ }
40
+ //#endregion
41
+ //#region src/writer/AsyncLogWriter.d.ts
42
+ /**
43
+ * Defines an asynchronous log writer that accepts log records
44
+ * and writes them to a target output (console, file, etc.).
45
+ */
46
+ interface AsyncLogWriter {
47
+ /**
48
+ * Writes a single log record asynchronously.
49
+ * @param log - The log record to write.
50
+ */
51
+ write(log: LogRecord): Promise<void>;
52
+ }
53
+ //#endregion
54
+ //#region src/writer/LogWriter.d.ts
55
+ /**
56
+ * Defines a synchronous log writer that accepts log records
57
+ * and writes them to a target output (console, file, etc.).
58
+ */
59
+ interface LogWriter {
60
+ /**
61
+ * Writes a single log record synchronously.
62
+ * @param log - The log record to write.
63
+ */
64
+ write(log: LogRecord): void;
65
+ }
66
+ //#endregion
67
+ //#region src/writer/ConsoleLogWriter.d.ts
68
+ /**
69
+ * A synchronous log writer that outputs formatted log records
70
+ * to the console. Supports customizable format strings
71
+ * using placeholders: `%t` (timestamp), `%l` (level), `%tag` (tags), `%msg` (message).
72
+ */
73
+ declare class ConsoleLogWriter implements LogWriter {
74
+ private readonly format;
75
+ /**
76
+ * Creates a new `ConsoleLogWriter` instance.
77
+ * @param format - The format string. Defaults to `[%t] [%l] [%tag]: %msg`.
78
+ */
79
+ constructor(format?: string);
80
+ /**
81
+ * Formats a `LogRecord` into an array suitable for `console.log`.
82
+ * @param log - The log record to format.
83
+ * @returns An array of formatted values and extras.
84
+ */
85
+ private fmt;
86
+ /**
87
+ * Writes a log record to the console.
88
+ * @param log - The log record to write.
89
+ */
90
+ write(log: LogRecord): void;
91
+ }
92
+ //#endregion
93
+ //#region src/writer/JSONLFileLogWriter.d.ts
94
+ /**
95
+ * An asynchronous log writer that serializes log records as JSON Lines
96
+ * and appends them to a file. Special values like `Error`, `Map`, `Set`,
97
+ * and `bigint` are normalized before serialization.
98
+ */
99
+ declare class JSONLFileLogWriter implements AsyncLogWriter {
100
+ private readonly path;
101
+ /**
102
+ * Creates a new `JSONLFileLogWriter` instance.
103
+ * @param path - The path to the JSON Lines file.
104
+ */
105
+ constructor(path: string);
106
+ /**
107
+ * Serializes a `LogRecord` into a plain object.
108
+ * @param log - The log record to serialize.
109
+ * @returns A plain object representation of the log record.
110
+ * @private
111
+ */
112
+ private serialize;
113
+ /**
114
+ * Serializes the `value` to a plain object
115
+ * @param value - The value to serialize.
116
+ * @return A plain object representation of the value.
117
+ * @private
118
+ */
119
+ private serializeValue;
120
+ /**
121
+ * Writes a log record to the log file.
122
+ * @param log - The log record to write.
123
+ */
124
+ write(log: LogRecord): Promise<void>;
125
+ }
126
+ //#endregion
127
+ //#region src/MaybePromise.d.ts
128
+ /**
129
+ * A conditional type that resolves to `Promise<R>` when the writer is
130
+ * an {@link AsyncLogWriter}, otherwise `R`.
131
+ *
132
+ * @typeParam Writer - The writer type to check.
133
+ * @typeParam R - The return type of the operation.
134
+ */
135
+ type MaybePromise<Writer extends LogWriter | AsyncLogWriter, R> = Writer extends AsyncLogWriter ? Promise<R> : R;
136
+ //#endregion
137
+ //#region src/Logger.d.ts
138
+ /**
139
+ * A logger that accepts log records and forwards them to a {@link LogWriter}.
140
+ *
141
+ * The generic `Writer` type controls whether logging is synchronous or asynchronous.
142
+ */
143
+ declare class Logger<Writer extends LogWriter | AsyncLogWriter = LogWriter> {
144
+ private readonly writer;
145
+ private readonly tags;
146
+ /**
147
+ * Creates a new `Logger` instance.
148
+ * @param writer - The log writer to receive records.
149
+ * @param tags - Optional tags to attach to every record.
150
+ */
151
+ constructor(writer: Writer, tags?: string[]);
152
+ /**
153
+ * Extracts an optional message string from the argument list.
154
+ * If the first argument is a string it is treated as the message;
155
+ * otherwise, if the last argument is a string it is treated as the message.
156
+ * @param args - The raw arguments passed to a log method.
157
+ * @returns The message and remaining arguments.
158
+ */
159
+ private parseArgs;
160
+ /**
161
+ * Writes a log record at the specified level.
162
+ * @param level - The severity level.
163
+ * @param args - The log message and any additional data.
164
+ * @returns A `Promise<void>` when using an {@link AsyncLogWriter}, otherwise `void`.
165
+ */
166
+ log(level: LogLevel, ...args: unknown[]): MaybePromise<Writer, void>;
167
+ /**
168
+ * Writes a `TRACE` level log record.
169
+ * @param args - The log message and any additional data.
170
+ */
171
+ trace(...args: unknown[]): MaybePromise<typeof this.writer, void>;
172
+ /**
173
+ * Writes a `DEBUG` level log record.
174
+ * @param args - The log message and any additional data.
175
+ */
176
+ debug(...args: unknown[]): MaybePromise<typeof this.writer, void>;
177
+ /**
178
+ * Writes an `INFO` level log record.
179
+ * @param args - The log message and any additional data.
180
+ */
181
+ info(...args: unknown[]): MaybePromise<typeof this.writer, void>;
182
+ /**
183
+ * Writes a `WARN` level log record.
184
+ * @param args - The log message and any additional data.
185
+ */
186
+ warn(...args: unknown[]): MaybePromise<typeof this.writer, void>;
187
+ /**
188
+ * Writes an `ERROR` level log record.
189
+ * @param args - The log message and any additional data.
190
+ */
191
+ error(...args: unknown[]): MaybePromise<typeof this.writer, void>;
192
+ /**
193
+ * Writes a `CRITICAL` level log record.
194
+ * @param args - The log message and any additional data.
195
+ */
196
+ critical(...args: unknown[]): MaybePromise<typeof this.writer, void>;
197
+ }
198
+ //#endregion
199
+ export { AsyncLogWriter, ConsoleLogWriter, JSONLFileLogWriter, LogLevel, LogRecord, LogWriter, Logger, MaybePromise };
200
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/LogLevel.ts","../src/LogRecord.ts","../src/writer/AsyncLogWriter.ts","../src/writer/LogWriter.ts","../src/writer/ConsoleLogWriter.ts","../src/writer/JSONLFileLogWriter.ts","../src/MaybePromise.ts","../src/Logger.ts"],"mappings":";;AAMA;;;;;aAAY,QAAA;EAQR;EANA,KAAA;EAYA;EATA,KAAA;EAYQ;EATR,IAAA;;EAGA,IAAA;;EAGA,KAAA;ECdsB;EDiBtB,QAAA;AAAA;;;AAjBJ;;;;AAAA,UCAiB,SAAA;EDKb;ECHA,KAAA,EAAO,QAAA;EDSP;ECPA,IAAA,EAAM,IAAI;EDaV;ECXA,IAAA;EDWQ;ECTR,OAAA;;EAEA,IAAA;AAAA;;;ADVJ;;;;AAAA,UEAiB,cAAA;EFKb;;;;EEAA,KAAA,CAAM,GAAA,EAAK,SAAA,GAAY,OAAO;AAAA;;;AFLlC;;;;AAAA,UGAiB,SAAA;EHKb;;;;EGAA,KAAA,CAAM,GAAA,EAAK,SAAS;AAAA;;;;;;;;cCFX,gBAAA,YAA4B,SAAS;EAAA,iBAKjB,MAAA;EJM7B;;;AAGQ;cITqB,MAAA;;;AHRjC;;;UGeY,GAAA;EHbR;;;;EG+BA,KAAA,CAAM,GAAA,EAAK,SAAA;AAAA;;;;;;;;cC9BF,kBAAA,YAA8B,cAAA;EAAA,iBAKV,IAAA;ELM7B;;;AAGQ;cKTqB,IAAA;;;AJRjC;;;;UIgBY,SAAA;EJdD;;;;;;EAAA,QI2BC,cAAA;EJnBJ;;;;EI+CE,KAAA,CAAM,GAAA,EAAK,SAAA,GAAY,OAAA;AAAA;;;ALzDjC;;;;;;;AAAA,KMGY,YAAA,gBACO,SAAA,GAAY,cAAA,OAE3B,MAAA,SAAe,cAAA,GAAiB,OAAA,CAAQ,CAAA,IAAK,CAAA;;;;;;;;cCHpC,MAAA,gBAAsB,SAAA,GAAY,cAAA,GAAiB,SAAA;EAAA,iBAOvC,MAAA;EAAA,iBACA,IAAA;EPMb;AAAA;;;;cOPa,MAAA,EAAQ,MAAA,EACR,IAAA;ENXC;;;;;;;EAAA,QMqBd,SAAA;ENbR;;;AAEI;;;EMmCJ,GAAA,CAAI,KAAA,EAAO,QAAA,KAAa,IAAA,cAAkB,YAAA,CAAa,MAAA;EL7C1C;;;;EK6Db,KAAA,IAAS,IAAA,cAAkB,YAAA,aAAyB,MAAA;ELxDzC;;;;EKgEX,KAAA,IAAS,IAAA,cAAkB,YAAA,aAAyB,MAAA;;;;AJrExD;EI6EI,IAAA,IAAQ,IAAA,cAAkB,YAAA,aAAyB,MAAA;;;;;EAQnD,IAAA,IAAQ,IAAA,cAAkB,YAAA,aAAyB,MAAA;EJhF/B;AAAA;;;EIwFpB,KAAA,IAAS,IAAA,cAAkB,YAAA,aAAyB,MAAA;EH1F3C;;;;EGkGT,QAAA,IAAY,IAAA,cAAkB,YAAA,aAAyB,MAAA;AAAA"}
package/dist/index.mjs ADDED
@@ -0,0 +1,213 @@
1
+ import { appendFile } from "node:fs/promises";
2
+ //#region src/LogLevel.ts
3
+ /**
4
+ * Defines the severity levels for log records.
5
+ *
6
+ * Levels are ordered by increasing severity:
7
+ * `TRACE` < `DEBUG` < `INFO` < `WARN` < `ERROR` < `CRITICAL`.
8
+ */
9
+ let LogLevel = /* @__PURE__ */ function(LogLevel) {
10
+ /** Fine-grained informational events useful for deep debugging. */
11
+ LogLevel[LogLevel["TRACE"] = 10] = "TRACE";
12
+ /** Informational events useful for debugging an application. */
13
+ LogLevel[LogLevel["DEBUG"] = 20] = "DEBUG";
14
+ /** Informational messages that highlight the progress of the application. */
15
+ LogLevel[LogLevel["INFO"] = 30] = "INFO";
16
+ /** Potentially harmful situations that do not prevent execution. */
17
+ LogLevel[LogLevel["WARN"] = 40] = "WARN";
18
+ /** Error events that might still allow the application to continue running. */
19
+ LogLevel[LogLevel["ERROR"] = 50] = "ERROR";
20
+ /** Very severe error events that will presumably lead the application to abort. */
21
+ LogLevel[LogLevel["CRITICAL"] = 60] = "CRITICAL";
22
+ return LogLevel;
23
+ }({});
24
+ //#endregion
25
+ //#region src/Logger.ts
26
+ /**
27
+ * A logger that accepts log records and forwards them to a {@link LogWriter}.
28
+ *
29
+ * The generic `Writer` type controls whether logging is synchronous or asynchronous.
30
+ */
31
+ var Logger = class {
32
+ writer;
33
+ tags;
34
+ /**
35
+ * Creates a new `Logger` instance.
36
+ * @param writer - The log writer to receive records.
37
+ * @param tags - Optional tags to attach to every record.
38
+ */
39
+ constructor(writer, tags = []) {
40
+ this.writer = writer;
41
+ this.tags = tags;
42
+ }
43
+ /**
44
+ * Extracts an optional message string from the argument list.
45
+ * If the first argument is a string it is treated as the message;
46
+ * otherwise, if the last argument is a string it is treated as the message.
47
+ * @param args - The raw arguments passed to a log method.
48
+ * @returns The message and remaining arguments.
49
+ */
50
+ parseArgs(...args) {
51
+ let msg = void 0;
52
+ let data = args;
53
+ if (typeof args[0] === "string") {
54
+ msg = args[0];
55
+ data = args.slice(1);
56
+ } else if (args.length > 0 && typeof args[args.length - 1] === "string") {
57
+ msg = args[args.length - 1];
58
+ data = args.slice(0, -1);
59
+ }
60
+ return {
61
+ msg,
62
+ args: data
63
+ };
64
+ }
65
+ /**
66
+ * Writes a log record at the specified level.
67
+ * @param level - The severity level.
68
+ * @param args - The log message and any additional data.
69
+ * @returns A `Promise<void>` when using an {@link AsyncLogWriter}, otherwise `void`.
70
+ */
71
+ log(level, ...args) {
72
+ const { msg, args: _args } = this.parseArgs(...args);
73
+ return this.writer.write({
74
+ level,
75
+ time: /* @__PURE__ */ new Date(),
76
+ tags: this.tags,
77
+ message: msg,
78
+ args: _args
79
+ });
80
+ }
81
+ /**
82
+ * Writes a `TRACE` level log record.
83
+ * @param args - The log message and any additional data.
84
+ */
85
+ trace(...args) {
86
+ return this.log(10, ...args);
87
+ }
88
+ /**
89
+ * Writes a `DEBUG` level log record.
90
+ * @param args - The log message and any additional data.
91
+ */
92
+ debug(...args) {
93
+ return this.log(20, ...args);
94
+ }
95
+ /**
96
+ * Writes an `INFO` level log record.
97
+ * @param args - The log message and any additional data.
98
+ */
99
+ info(...args) {
100
+ return this.log(30, ...args);
101
+ }
102
+ /**
103
+ * Writes a `WARN` level log record.
104
+ * @param args - The log message and any additional data.
105
+ */
106
+ warn(...args) {
107
+ return this.log(40, ...args);
108
+ }
109
+ /**
110
+ * Writes an `ERROR` level log record.
111
+ * @param args - The log message and any additional data.
112
+ */
113
+ error(...args) {
114
+ return this.log(50, ...args);
115
+ }
116
+ /**
117
+ * Writes a `CRITICAL` level log record.
118
+ * @param args - The log message and any additional data.
119
+ */
120
+ critical(...args) {
121
+ return this.log(60, ...args);
122
+ }
123
+ };
124
+ //#endregion
125
+ //#region src/writer/ConsoleLogWriter.ts
126
+ /**
127
+ * A synchronous log writer that outputs formatted log records
128
+ * to the console. Supports customizable format strings
129
+ * using placeholders: `%t` (timestamp), `%l` (level), `%tag` (tags), `%msg` (message).
130
+ */
131
+ var ConsoleLogWriter = class {
132
+ format;
133
+ /**
134
+ * Creates a new `ConsoleLogWriter` instance.
135
+ * @param format - The format string. Defaults to `[%t] [%l] [%tag]: %msg`.
136
+ */
137
+ constructor(format = "[%t] [%l] [%tag]: %msg") {
138
+ this.format = format;
139
+ }
140
+ /**
141
+ * Formats a `LogRecord` into an array suitable for `console.log`.
142
+ * @param log - The log record to format.
143
+ * @returns An array of formatted values and extras.
144
+ */
145
+ fmt(log) {
146
+ const tag = log.tags.length > 0 ? `[${log.tags.join("/")}]` : "";
147
+ return [this.format.replace("%t", log.time.toISOString()).replace("%l", LogLevel[log.level]).replace("%tag", tag).replace("%msg", log.message ?? "").trim(), ...log.args];
148
+ }
149
+ /**
150
+ * Writes a log record to the console.
151
+ * @param log - The log record to write.
152
+ */
153
+ write(log) {
154
+ console.log(...this.fmt(log));
155
+ }
156
+ };
157
+ //#endregion
158
+ //#region src/writer/JSONLFileLogWriter.ts
159
+ /**
160
+ * An asynchronous log writer that serializes log records as JSON Lines
161
+ * and appends them to a file. Special values like `Error`, `Map`, `Set`,
162
+ * and `bigint` are normalized before serialization.
163
+ */
164
+ var JSONLFileLogWriter = class {
165
+ path;
166
+ /**
167
+ * Creates a new `JSONLFileLogWriter` instance.
168
+ * @param path - The path to the JSON Lines file.
169
+ */
170
+ constructor(path) {
171
+ this.path = path;
172
+ }
173
+ /**
174
+ * Serializes a `LogRecord` into a plain object.
175
+ * @param log - The log record to serialize.
176
+ * @returns A plain object representation of the log record.
177
+ * @private
178
+ */
179
+ serialize(log) {
180
+ return {
181
+ ...log,
182
+ args: log.args.map((arg) => this.serializeValue(arg))
183
+ };
184
+ }
185
+ /**
186
+ * Serializes the `value` to a plain object
187
+ * @param value - The value to serialize.
188
+ * @return A plain object representation of the value.
189
+ * @private
190
+ */
191
+ serializeValue(value) {
192
+ if (value instanceof Error) return {
193
+ name: value.name,
194
+ message: value.message,
195
+ stack: value.stack
196
+ };
197
+ if (value instanceof Map) return Object.fromEntries(value);
198
+ if (value instanceof Set) return [...value];
199
+ if (typeof value === "bigint") return value.toString();
200
+ return value;
201
+ }
202
+ /**
203
+ * Writes a log record to the log file.
204
+ * @param log - The log record to write.
205
+ */
206
+ async write(log) {
207
+ await appendFile(this.path, JSON.stringify(this.serialize(log)) + "\n");
208
+ }
209
+ };
210
+ //#endregion
211
+ export { ConsoleLogWriter, JSONLFileLogWriter, LogLevel, Logger };
212
+
213
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/LogLevel.ts","../src/Logger.ts","../src/writer/ConsoleLogWriter.ts","../src/writer/JSONLFileLogWriter.ts"],"sourcesContent":["/**\n * Defines the severity levels for log records.\n *\n * Levels are ordered by increasing severity:\n * `TRACE` < `DEBUG` < `INFO` < `WARN` < `ERROR` < `CRITICAL`.\n */\nexport enum LogLevel {\n /** Fine-grained informational events useful for deep debugging. */\n TRACE = 10,\n\n /** Informational events useful for debugging an application. */\n DEBUG = 20,\n\n /** Informational messages that highlight the progress of the application. */\n INFO = 30,\n\n /** Potentially harmful situations that do not prevent execution. */\n WARN = 40,\n\n /** Error events that might still allow the application to continue running. */\n ERROR = 50,\n\n /** Very severe error events that will presumably lead the application to abort. */\n CRITICAL = 60\n}\n","import { LogLevel } from './LogLevel'\nimport { MaybePromise } from './MaybePromise'\nimport { AsyncLogWriter, LogWriter } from './writer'\n\n/**\n * A logger that accepts log records and forwards them to a {@link LogWriter}.\n *\n * The generic `Writer` type controls whether logging is synchronous or asynchronous.\n */\nexport class Logger<Writer extends LogWriter | AsyncLogWriter = LogWriter> {\n /**\n * Creates a new `Logger` instance.\n * @param writer - The log writer to receive records.\n * @param tags - Optional tags to attach to every record.\n */\n constructor(\n private readonly writer: Writer,\n private readonly tags: string[] = []\n ) {}\n\n /**\n * Extracts an optional message string from the argument list.\n * If the first argument is a string it is treated as the message;\n * otherwise, if the last argument is a string it is treated as the message.\n * @param args - The raw arguments passed to a log method.\n * @returns The message and remaining arguments.\n */\n private parseArgs(...args: unknown[]): {\n msg: string | undefined\n args: unknown[]\n } {\n let msg: string | undefined = undefined\n let data: unknown[] = args\n\n if (typeof args[0] === 'string') {\n msg = args[0]\n data = args.slice(1)\n } else if (args.length > 0 && typeof args[args.length - 1] === 'string') {\n msg = args[args.length - 1] as any\n data = args.slice(0, -1)\n }\n\n return { msg, args: data }\n }\n\n /**\n * Writes a log record at the specified level.\n * @param level - The severity level.\n * @param args - The log message and any additional data.\n * @returns A `Promise<void>` when using an {@link AsyncLogWriter}, otherwise `void`.\n */\n log(level: LogLevel, ...args: unknown[]): MaybePromise<Writer, void> {\n const { msg, args: _args } = this.parseArgs(...args)\n\n return this.writer.write({\n level,\n time: new Date(),\n tags: this.tags,\n message: msg,\n args: _args\n }) as MaybePromise<Writer, void>\n }\n\n /**\n * Writes a `TRACE` level log record.\n * @param args - The log message and any additional data.\n */\n trace(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.TRACE, ...args)\n }\n\n /**\n * Writes a `DEBUG` level log record.\n * @param args - The log message and any additional data.\n */\n debug(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.DEBUG, ...args)\n }\n\n /**\n * Writes an `INFO` level log record.\n * @param args - The log message and any additional data.\n */\n info(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.INFO, ...args)\n }\n\n /**\n * Writes a `WARN` level log record.\n * @param args - The log message and any additional data.\n */\n warn(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.WARN, ...args)\n }\n\n /**\n * Writes an `ERROR` level log record.\n * @param args - The log message and any additional data.\n */\n error(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.ERROR, ...args)\n }\n\n /**\n * Writes a `CRITICAL` level log record.\n * @param args - The log message and any additional data.\n */\n critical(...args: unknown[]): MaybePromise<typeof this.writer, void> {\n return this.log(LogLevel.CRITICAL, ...args)\n }\n}\n","import { LogLevel } from '../LogLevel'\nimport { LogRecord } from '../LogRecord'\nimport { LogWriter } from './LogWriter'\n\n/**\n * A synchronous log writer that outputs formatted log records\n * to the console. Supports customizable format strings\n * using placeholders: `%t` (timestamp), `%l` (level), `%tag` (tags), `%msg` (message).\n */\nexport class ConsoleLogWriter implements LogWriter {\n /**\n * Creates a new `ConsoleLogWriter` instance.\n * @param format - The format string. Defaults to `[%t] [%l] [%tag]: %msg`.\n */\n constructor(private readonly format: string = '[%t] [%l] [%tag]: %msg') {}\n\n /**\n * Formats a `LogRecord` into an array suitable for `console.log`.\n * @param log - The log record to format.\n * @returns An array of formatted values and extras.\n */\n private fmt(log: LogRecord): unknown[] {\n const tag = log.tags.length > 0 ? `[${log.tags.join('/')}]` : ''\n\n return [\n this.format\n .replace('%t', log.time.toISOString())\n .replace('%l', LogLevel[log.level])\n .replace('%tag', tag)\n .replace('%msg', log.message ?? '')\n .trim(),\n ...log.args\n ]\n }\n\n /**\n * Writes a log record to the console.\n * @param log - The log record to write.\n */\n write(log: LogRecord): void {\n console.log(...this.fmt(log))\n }\n}\n","import { appendFile } from 'node:fs/promises'\nimport { LogRecord } from '../LogRecord'\nimport { AsyncLogWriter } from './AsyncLogWriter'\n\n/**\n * An asynchronous log writer that serializes log records as JSON Lines\n * and appends them to a file. Special values like `Error`, `Map`, `Set`,\n * and `bigint` are normalized before serialization.\n */\nexport class JSONLFileLogWriter implements AsyncLogWriter {\n /**\n * Creates a new `JSONLFileLogWriter` instance.\n * @param path - The path to the JSON Lines file.\n */\n constructor(private readonly path: string) {}\n\n /**\n * Serializes a `LogRecord` into a plain object.\n * @param log - The log record to serialize.\n * @returns A plain object representation of the log record.\n * @private\n */\n private serialize(log: LogRecord): object {\n return {\n ...log,\n args: log.args.map(arg => this.serializeValue(arg))\n }\n }\n\n /**\n * Serializes the `value` to a plain object\n * @param value - The value to serialize.\n * @return A plain object representation of the value.\n * @private\n */\n private serializeValue(value: unknown): unknown {\n if (value instanceof Error) {\n return {\n name: value.name,\n message: value.message,\n stack: value.stack\n }\n }\n\n if (value instanceof Map) {\n return Object.fromEntries(value)\n }\n\n if (value instanceof Set) {\n return [...value]\n }\n\n if (typeof value === 'bigint') {\n return value.toString()\n }\n\n return value\n }\n\n /**\n * Writes a log record to the log file.\n * @param log - The log record to write.\n */\n async write(log: LogRecord): Promise<void> {\n await appendFile(this.path, JSON.stringify(this.serialize(log)) + '\\n')\n }\n}\n"],"mappings":";;;;;;;;AA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AAO;CACX;;;;;CAMA,MAAM,MAAM,KAA+B;EACvC,MAAM,WAAW,KAAK,MAAM,KAAK,UAAU,KAAK,UAAU,GAAG,CAAC,IAAI,IAAI;CAC1E;AACJ"}
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@briangits/node-log",
3
+ "version": "0.0.1",
4
+ "description": "Logging for Node.js",
5
+ "author": "Gits (https://github.com/briangits)",
6
+ "license": "Apache-2.0",
7
+ "keywords": [
8
+ "log",
9
+ "logging",
10
+ "logger"
11
+ ],
12
+ "homepage": "https://github.com/briangits/node-log#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/briangits/node-log/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/briangits/node-log.git"
19
+ },
20
+ "type": "module",
21
+ "main": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "import": "./dist/index.js",
27
+ "require": "./dist/index.cjs"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "sideEffects": false,
34
+ "devEngines": {
35
+ "packageManager": {
36
+ "name": "pnpm",
37
+ "version": "^11.7.0",
38
+ "onFail": "download"
39
+ }
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^25.9.3",
43
+ "prettier": "^3.8.4",
44
+ "prettier-plugin-organize-imports": "^4.3.0",
45
+ "tsdown": "^0.22.3",
46
+ "vitest": "^4.1.9"
47
+ },
48
+ "prettier": {
49
+ "printWidth": 100,
50
+ "tabWidth": 4,
51
+ "useTabs": false,
52
+ "semi": false,
53
+ "singleQuote": true,
54
+ "trailingComma": "none",
55
+ "bracketSpacing": true,
56
+ "arrowParens": "avoid",
57
+ "endOfLine": "lf",
58
+ "plugins": [
59
+ "prettier-plugin-organize-imports"
60
+ ]
61
+ },
62
+ "scripts": {
63
+ "lint": "prettier --check '**/*' --ignore-path .gitignore --ignore-unknown",
64
+ "format": "prettier --write '**/*' --ignore-path .gitignore --ignore-unknown",
65
+ "test": "vitest run",
66
+ "build": "tsdown -c tsdown.config.ts"
67
+ }
68
+ }