@murky-web/simplelog 2.0.1 → 3.1.0
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/README.md +151 -16
- package/dist/browser_console.js +91 -0
- package/dist/browser_console.js.map +1 -0
- package/dist/{deno_logger.d.ts → browser_logger.d.ts} +1 -3
- package/dist/browser_logger.d.ts.map +1 -0
- package/dist/browser_logger.js +17 -0
- package/dist/browser_logger.js.map +1 -0
- package/dist/bun_logger.d.ts +0 -2
- package/dist/bun_logger.d.ts.map +1 -1
- package/dist/bun_logger.js +1 -2
- package/dist/bun_logger.js.map +1 -1
- package/dist/console_defaults.js +45 -0
- package/dist/console_defaults.js.map +1 -0
- package/dist/console_text.d.ts +25 -0
- package/dist/console_text.d.ts.map +1 -0
- package/dist/console_text.js +168 -0
- package/dist/console_text.js.map +1 -0
- package/dist/console_timestamp.d.ts +4 -0
- package/dist/console_timestamp.d.ts.map +1 -0
- package/dist/console_timestamp.js +22 -0
- package/dist/console_timestamp.js.map +1 -0
- package/dist/hono_middleware.d.ts +14 -4
- package/dist/hono_middleware.d.ts.map +1 -1
- package/dist/hono_middleware.js +45 -20
- package/dist/hono_middleware.js.map +1 -1
- package/dist/log_file.d.ts +9 -0
- package/dist/log_file.d.ts.map +1 -0
- package/dist/log_file.js +52 -0
- package/dist/log_file.js.map +1 -0
- package/dist/logger.d.ts +0 -2
- package/dist/logger.d.ts.map +1 -1
- package/dist/logger.js +1 -2
- package/dist/logger.js.map +1 -1
- package/dist/logger_factory.d.ts +45 -11
- package/dist/logger_factory.d.ts.map +1 -1
- package/dist/logger_factory.js +38 -217
- package/dist/logger_factory.js.map +1 -1
- package/dist/node_runtime.js +17 -6
- package/dist/node_runtime.js.map +1 -1
- package/dist/otel.d.ts +0 -2
- package/dist/otel.d.ts.map +1 -1
- package/dist/otel.js +2 -3
- package/dist/serialize_value.d.ts +44 -0
- package/dist/serialize_value.d.ts.map +1 -0
- package/dist/serialize_value.js +313 -0
- package/dist/serialize_value.js.map +1 -0
- package/dist/web_logger.d.ts +0 -2
- package/dist/web_logger.d.ts.map +1 -1
- package/dist/web_logger.js +3 -3
- package/dist/web_logger.js.map +1 -1
- package/oxlint/prefer-runtime-entry.mjs +1 -1
- package/package.json +19 -13
- package/dist/deno_logger.d.ts.map +0 -1
- package/dist/deno_logger.js +0 -39
- package/dist/deno_logger.js.map +0 -1
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Escapes what would let a value end or fake a line in a log file: control
|
|
3
|
+
* characters (line breaks above all), the Unicode line separators and the
|
|
4
|
+
* bidirectional controls.
|
|
5
|
+
*
|
|
6
|
+
* @param {string} text - Text that is about to be written to a log file.
|
|
7
|
+
* @returns {string} The text with those characters written as `\n`, `\r` or
|
|
8
|
+
* `\uXXXX`. Tab and backslash stay as they are.
|
|
9
|
+
*/
|
|
10
|
+
declare function escapeFileCharacters(text: string): string;
|
|
11
|
+
declare function formatFunctionLabel(functionName: string): string;
|
|
12
|
+
/**
|
|
13
|
+
* Recognises Errors, including those from other realms (another `vm` context,
|
|
14
|
+
* an iframe), which fail `instanceof Error`. `Error.isError` is a brand check
|
|
15
|
+
* and is used where the runtime has it; elsewhere `instanceof` or the `[object
|
|
16
|
+
* Error]` tag decide.
|
|
17
|
+
*
|
|
18
|
+
* @param {Readonly<object>} value - Any object.
|
|
19
|
+
* @returns {boolean} Whether it is an Error.
|
|
20
|
+
*/
|
|
21
|
+
declare function isError(value: Readonly<object>): boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Turns a value into something `JSON.stringify` can print without losing or
|
|
24
|
+
* throwing on it, and without printing without limit.
|
|
25
|
+
*
|
|
26
|
+
* - Cycles become `"[Circular]"`, nesting deeper than 8 levels `"[MaxDepth]"`
|
|
27
|
+
* - At most 1000 values in total, and 50 keys or items per object or array; what
|
|
28
|
+
* is left out becomes `"[Truncated]"`
|
|
29
|
+
* - BigInt and symbols become strings, functions become their label, boxed
|
|
30
|
+
* primitives their primitive value, typed arrays, `DataView` and
|
|
31
|
+
* `ArrayBuffer` a label with their byte length
|
|
32
|
+
* - `Error` becomes `{ name, message, stack, cause?, code?, errors? }`, where
|
|
33
|
+
* `cause` and `errors` elements that are not Errors print as `"[Object]"`;
|
|
34
|
+
* `Map` becomes `{ Map: [[key, value]] }` and `Set` `{ Set: [value] }`
|
|
35
|
+
*
|
|
36
|
+
* Only the objects on the way down count as a cycle, so an object that appears
|
|
37
|
+
* twice side by side prints twice (and counts twice against the budget).
|
|
38
|
+
*
|
|
39
|
+
* @param {unknown} value - The value to convert.
|
|
40
|
+
* @returns {unknown} A JSON-safe value.
|
|
41
|
+
*/
|
|
42
|
+
declare function toJsonSafeValue(value: unknown): unknown;
|
|
43
|
+
export { escapeFileCharacters, formatFunctionLabel, isError, toJsonSafeValue };
|
|
44
|
+
//# sourceMappingURL=serialize_value.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serialize_value.d.ts","names":[],"sources":["../src/serialize_value.ts"],"mappings":";;;;;;;;;iBAgES,qBAAqB;iBAkBrB,oBAAoB;;;;;;;;;;iBA8GpB,QAAQ,OAAO;;;;;;;;;;;;;;;;;;;;;iBAkVf,gBAAgB"}
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// src/serialize_value.ts
|
|
2
|
+
const ANONYMOUS_FUNCTION_LABEL = "[Function anonymous]";
|
|
3
|
+
const BINARY_BUFFER_TAGS = /* @__PURE__ */ new Set(["[object ArrayBuffer]", "[object SharedArrayBuffer]"]);
|
|
4
|
+
const BOXED_PRIMITIVE_TAGS = /* @__PURE__ */ new Set([
|
|
5
|
+
"[object Boolean]",
|
|
6
|
+
"[object Number]",
|
|
7
|
+
"[object String]"
|
|
8
|
+
]);
|
|
9
|
+
const CIRCULAR_REFERENCE_LABEL = "[Circular]";
|
|
10
|
+
const EMPTY_FUNCTION_NAME_LENGTH = 0;
|
|
11
|
+
const ERROR_TAG = "[object Error]";
|
|
12
|
+
const FIRST_CHARACTER_INDEX = 0;
|
|
13
|
+
const FUNCTION_LABEL_PREFIX = "[Function ";
|
|
14
|
+
const FUNCTION_LABEL_SUFFIX = "]";
|
|
15
|
+
const HEX_RADIX = 16;
|
|
16
|
+
const MAX_COLLECTION_ITEMS = 50;
|
|
17
|
+
const MAX_DEPTH_LABEL = "[MaxDepth]";
|
|
18
|
+
const MAX_SERIALIZATION_DEPTH = 8;
|
|
19
|
+
const MAX_SERIALIZED_NODES = 1e3;
|
|
20
|
+
const MISSING_CODE_POINT = 0;
|
|
21
|
+
const NOTHING = 0;
|
|
22
|
+
const OBJECT_LABEL = "[Object]";
|
|
23
|
+
const ONE = 1;
|
|
24
|
+
const TAG_PREFIX_LENGTH = 8;
|
|
25
|
+
const TRUNCATED_LABEL = "[Truncated]";
|
|
26
|
+
const UNICODE_ESCAPE_WIDTH = 4;
|
|
27
|
+
/**
|
|
28
|
+
* Control characters except tab, the Unicode line and paragraph separators, and
|
|
29
|
+
* the bidirectional controls (U+200E, U+200F, U+061C, U+202A to U+202E and
|
|
30
|
+
* U+2066 to U+2069) plus the byte order mark (U+FEFF). They can make a log line
|
|
31
|
+
* read differently from how it is stored, or end it. Anything in this set never
|
|
32
|
+
* reaches a file raw. Backslashes are not escaped: that would mangle Windows
|
|
33
|
+
* paths.
|
|
34
|
+
*/
|
|
35
|
+
const FILE_UNSAFE_CHARACTER_PATTERN = /(?!\t)[\p{Cc}\p{Zl}\p{Zp}\u{061C}\u{200E}\u{200F}\u{202A}-\u{202E}\u{2066}-\u{2069}\u{FEFF}]/gu;
|
|
36
|
+
const FILE_CHARACTER_ESCAPES = {
|
|
37
|
+
"\n": String.raw`\n`,
|
|
38
|
+
"\r": String.raw`\r`
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Escapes what would let a value end or fake a line in a log file: control
|
|
42
|
+
* characters (line breaks above all), the Unicode line separators and the
|
|
43
|
+
* bidirectional controls.
|
|
44
|
+
*
|
|
45
|
+
* @param {string} text - Text that is about to be written to a log file.
|
|
46
|
+
* @returns {string} The text with those characters written as `\n`, `\r` or
|
|
47
|
+
* `\uXXXX`. Tab and backslash stay as they are.
|
|
48
|
+
*/
|
|
49
|
+
function escapeFileCharacters(text) {
|
|
50
|
+
return text.replaceAll(FILE_UNSAFE_CHARACTER_PATTERN, (character) => {
|
|
51
|
+
const knownEscape = FILE_CHARACTER_ESCAPES[character];
|
|
52
|
+
if (typeof knownEscape === "string") return knownEscape;
|
|
53
|
+
return `\\u${(character.codePointAt(FIRST_CHARACTER_INDEX) ?? MISSING_CODE_POINT).toString(HEX_RADIX).padStart(UNICODE_ESCAPE_WIDTH, "0")}`;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
function formatFunctionLabel(functionName) {
|
|
57
|
+
if (functionName.length === EMPTY_FUNCTION_NAME_LENGTH) return ANONYMOUS_FUNCTION_LABEL;
|
|
58
|
+
return `${FUNCTION_LABEL_PREFIX}${functionName}${FUNCTION_LABEL_SUFFIX}`;
|
|
59
|
+
}
|
|
60
|
+
function createBudget() {
|
|
61
|
+
let remaining = MAX_SERIALIZED_NODES;
|
|
62
|
+
return { take() {
|
|
63
|
+
if (remaining <= NOTHING) return false;
|
|
64
|
+
remaining -= ONE;
|
|
65
|
+
return true;
|
|
66
|
+
} };
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Reads the first `MAX_COLLECTION_ITEMS` entries of an array by index. The rest
|
|
70
|
+
* is never visited: the omitted count comes from `length`, so a sparse array of
|
|
71
|
+
* length 2^32 - 1 costs as much as one of length 50.
|
|
72
|
+
*
|
|
73
|
+
* @param {readonly unknown[]} array - The array.
|
|
74
|
+
* @returns {TakenItems<unknown>} The kept items and how many were left out.
|
|
75
|
+
*/
|
|
76
|
+
function takeArrayItems(array) {
|
|
77
|
+
const count = Math.min(array.length, MAX_COLLECTION_ITEMS);
|
|
78
|
+
return {
|
|
79
|
+
items: Array.from({ length: count }, (_unused, index) => {
|
|
80
|
+
return array[index];
|
|
81
|
+
}),
|
|
82
|
+
omitted: array.length - count
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Reads the first `MAX_COLLECTION_ITEMS` entries of a Map or Set and stops
|
|
87
|
+
* there. The omitted count comes from `size`.
|
|
88
|
+
*
|
|
89
|
+
* @param {Readonly<Iterable<Item>>} source - The Map or Set.
|
|
90
|
+
* @param {number} size - Its `size`.
|
|
91
|
+
* @returns {TakenItems<Item>} The kept items and how many were left out.
|
|
92
|
+
*/
|
|
93
|
+
function takeFirstItems(source, size) {
|
|
94
|
+
const items = [];
|
|
95
|
+
for (const item of source) {
|
|
96
|
+
if (items.length >= MAX_COLLECTION_ITEMS) break;
|
|
97
|
+
items.push(item);
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
items,
|
|
101
|
+
omitted: Math.max(size - items.length, NOTHING)
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function withTruncationMarker(items, omitted) {
|
|
105
|
+
if (omitted > NOTHING) return [...items, TRUNCATED_LABEL];
|
|
106
|
+
return items;
|
|
107
|
+
}
|
|
108
|
+
function readProperty(value, key) {
|
|
109
|
+
return Reflect.get(value, key);
|
|
110
|
+
}
|
|
111
|
+
function readString(value, key, fallback) {
|
|
112
|
+
const property = readProperty(value, key);
|
|
113
|
+
if (typeof property === "string") return property;
|
|
114
|
+
return fallback;
|
|
115
|
+
}
|
|
116
|
+
function readTag(value) {
|
|
117
|
+
return Object.prototype.toString.call(value);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Recognises Errors, including those from other realms (another `vm` context,
|
|
121
|
+
* an iframe), which fail `instanceof Error`. `Error.isError` is a brand check
|
|
122
|
+
* and is used where the runtime has it; elsewhere `instanceof` or the `[object
|
|
123
|
+
* Error]` tag decide.
|
|
124
|
+
*
|
|
125
|
+
* @param {Readonly<object>} value - Any object.
|
|
126
|
+
* @returns {boolean} Whether it is an Error.
|
|
127
|
+
*/
|
|
128
|
+
function isError(value) {
|
|
129
|
+
const nativeIsError = Reflect.get(Error, "isError");
|
|
130
|
+
if (typeof nativeIsError === "function") return Reflect.apply(nativeIsError, Error, [value]) === true;
|
|
131
|
+
return value instanceof Error || readTag(value) === ERROR_TAG;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Reads the primitive out of a `String`, `Number` or `Boolean` object. The
|
|
135
|
+
* built-in `valueOf` of each is brand-checked and throws for anything else, so
|
|
136
|
+
* a plain object that only claims one of these tags is not unboxed.
|
|
137
|
+
*
|
|
138
|
+
* @param {Readonly<object>} value - Any object.
|
|
139
|
+
* @returns {readonly [unknown] | undefined} The primitive in a one-item tuple,
|
|
140
|
+
* or `undefined` when `value` is not a boxed primitive.
|
|
141
|
+
*/
|
|
142
|
+
function unboxPrimitive(value) {
|
|
143
|
+
if (!BOXED_PRIMITIVE_TAGS.has(readTag(value))) return;
|
|
144
|
+
for (const prototype of [
|
|
145
|
+
Number.prototype,
|
|
146
|
+
String.prototype,
|
|
147
|
+
Boolean.prototype
|
|
148
|
+
]) try {
|
|
149
|
+
const valueOf = Reflect.get(prototype, "valueOf");
|
|
150
|
+
if (typeof valueOf !== "function") continue;
|
|
151
|
+
return [Reflect.apply(valueOf, value, [])];
|
|
152
|
+
} catch {}
|
|
153
|
+
}
|
|
154
|
+
function readByteLength(value) {
|
|
155
|
+
const byteLength = readProperty(value, "byteLength");
|
|
156
|
+
if (typeof byteLength === "number") return byteLength;
|
|
157
|
+
return NOTHING;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Typed arrays, `DataView` and `ArrayBuffer` print as a label with their byte
|
|
161
|
+
* length. Their contents are not read: they can be megabytes, and Node's
|
|
162
|
+
* `Buffer` has a `toJSON` that would copy every byte into an array.
|
|
163
|
+
*
|
|
164
|
+
* @param {Readonly<object>} value - Any object.
|
|
165
|
+
* @returns {string | undefined} The label, or `undefined` for other objects.
|
|
166
|
+
*/
|
|
167
|
+
function binaryLabel(value) {
|
|
168
|
+
const tag = readTag(value);
|
|
169
|
+
if (!ArrayBuffer.isView(value) && !BINARY_BUFFER_TAGS.has(tag)) return;
|
|
170
|
+
return `[${tag.slice(TAG_PREFIX_LENGTH, -1)} ${readByteLength(value)} bytes]`;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Inside an Error, a nested value prints in full only when it is an Error
|
|
174
|
+
* itself. Any other object becomes a label: `cause` is often an HTTP response
|
|
175
|
+
* or request object that carries credentials, and the Error allow-list would
|
|
176
|
+
* mean nothing if those printed through the `cause` slot.
|
|
177
|
+
*
|
|
178
|
+
* @param {unknown} value - A `cause` or one element of `errors`.
|
|
179
|
+
* @param {Serialize} serialize - Serializes a value under the normal rules.
|
|
180
|
+
* @returns {unknown} The label, or the serialized primitive or Error.
|
|
181
|
+
*/
|
|
182
|
+
function serializeErrorChild(value, serialize) {
|
|
183
|
+
if (typeof value === "object" && value !== null && !isError(value)) return OBJECT_LABEL;
|
|
184
|
+
return serialize(value);
|
|
185
|
+
}
|
|
186
|
+
function serializeAggregatedErrors(errors, serialize) {
|
|
187
|
+
const { items, omitted } = takeArrayItems(errors);
|
|
188
|
+
return withTruncationMarker(items.map((entry) => {
|
|
189
|
+
return serializeErrorChild(entry, serialize);
|
|
190
|
+
}), omitted);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Serializes an Error from an allow-list only: `name`, `message`, `stack`,
|
|
194
|
+
* `cause`, `code` (when it is a string or a number) and, for an
|
|
195
|
+
* `AggregateError`, `errors`. Other own properties are left out on purpose:
|
|
196
|
+
* HTTP client errors (axios, got) carry the request, its headers and its body
|
|
197
|
+
* there, which means credentials. `cause` and the elements of `errors` follow
|
|
198
|
+
* the rule in `serializeErrorChild`.
|
|
199
|
+
*
|
|
200
|
+
* @param {Readonly<object>} error - The Error.
|
|
201
|
+
* @param {Serialize} serialize - Serializes a nested value under the same
|
|
202
|
+
* rules.
|
|
203
|
+
* @returns {unknown} A plain object.
|
|
204
|
+
*/
|
|
205
|
+
function serializeError(error, serialize) {
|
|
206
|
+
const name = readString(error, "name", "Error");
|
|
207
|
+
const entries = [
|
|
208
|
+
["name", name],
|
|
209
|
+
["message", readString(error, "message", "")],
|
|
210
|
+
["stack", readString(error, "stack", "")]
|
|
211
|
+
];
|
|
212
|
+
const cause = readProperty(error, "cause");
|
|
213
|
+
const code = readProperty(error, "code");
|
|
214
|
+
const errors = readProperty(error, "errors");
|
|
215
|
+
if (typeof cause !== "undefined") entries.push(["cause", serializeErrorChild(cause, serialize)]);
|
|
216
|
+
if (typeof code === "string" || typeof code === "number") entries.push(["code", code]);
|
|
217
|
+
if ((error instanceof AggregateError || name === "AggregateError") && Array.isArray(errors)) entries.push(["errors", serializeAggregatedErrors(errors, serialize)]);
|
|
218
|
+
return Object.fromEntries(entries);
|
|
219
|
+
}
|
|
220
|
+
function serializeMap(map, serialize) {
|
|
221
|
+
const { items, omitted } = takeFirstItems(map, map.size);
|
|
222
|
+
return { Map: withTruncationMarker(items.map(([key, entry]) => {
|
|
223
|
+
return [serialize(key), serialize(entry)];
|
|
224
|
+
}), omitted) };
|
|
225
|
+
}
|
|
226
|
+
function serializeSet(set, serialize) {
|
|
227
|
+
const { items, omitted } = takeFirstItems(set, set.size);
|
|
228
|
+
return { Set: withTruncationMarker(items.map((entry) => {
|
|
229
|
+
return serialize(entry);
|
|
230
|
+
}), omitted) };
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Serializes the own enumerable keys of an object, at most
|
|
234
|
+
* `MAX_COLLECTION_ITEMS` of them. Only the values of the kept keys are visited,
|
|
235
|
+
* but the key list is built in full: `Object.keys` is a single native pass, and
|
|
236
|
+
* `for...in` with an early exit does not avoid it (V8 collects the keys before
|
|
237
|
+
* the first iteration; measured at the same cost). An object with millions of
|
|
238
|
+
* keys therefore costs one linear key listing, not millions of serializations.
|
|
239
|
+
*
|
|
240
|
+
* @param {Readonly<object>} value - The object.
|
|
241
|
+
* @param {Serialize} serialize - Serializes a nested value.
|
|
242
|
+
* @returns {unknown} A plain object, with a `[Truncated]` key when keys were
|
|
243
|
+
* left out.
|
|
244
|
+
*/
|
|
245
|
+
function serializePlainObject(value, serialize) {
|
|
246
|
+
const allKeys = Object.keys(value);
|
|
247
|
+
const entries = allKeys.slice(NOTHING, MAX_COLLECTION_ITEMS).map((key) => {
|
|
248
|
+
return [key, serialize(readProperty(value, key))];
|
|
249
|
+
});
|
|
250
|
+
if (allKeys.length > MAX_COLLECTION_ITEMS) entries.push([TRUNCATED_LABEL, allKeys.length - MAX_COLLECTION_ITEMS]);
|
|
251
|
+
return Object.fromEntries(entries);
|
|
252
|
+
}
|
|
253
|
+
function serializeCollection(value, serialize) {
|
|
254
|
+
if (value instanceof Map) return serializeMap(value, serialize);
|
|
255
|
+
if (value instanceof Set) return serializeSet(value, serialize);
|
|
256
|
+
if (Array.isArray(value)) {
|
|
257
|
+
const { items, omitted } = takeArrayItems(value);
|
|
258
|
+
return withTruncationMarker(items.map((entry) => {
|
|
259
|
+
return serialize(entry);
|
|
260
|
+
}), omitted);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function serializeObject(value, serialize) {
|
|
264
|
+
if (isError(value)) return serializeError(value, serialize);
|
|
265
|
+
const boxed = unboxPrimitive(value);
|
|
266
|
+
if (typeof boxed !== "undefined") return serialize(boxed[FIRST_CHARACTER_INDEX]);
|
|
267
|
+
const label = binaryLabel(value);
|
|
268
|
+
if (typeof label === "string") return label;
|
|
269
|
+
const collection = serializeCollection(value, serialize);
|
|
270
|
+
if (typeof collection !== "undefined") return collection;
|
|
271
|
+
const toJson = readProperty(value, "toJSON");
|
|
272
|
+
if (typeof toJson === "function") return serialize(Reflect.apply(toJson, value, []));
|
|
273
|
+
return serializePlainObject(value, serialize);
|
|
274
|
+
}
|
|
275
|
+
function serializeAtPath(value, path, budget) {
|
|
276
|
+
if (!budget.take()) return TRUNCATED_LABEL;
|
|
277
|
+
if (typeof value === "bigint") return `${value}n`;
|
|
278
|
+
if (typeof value === "symbol") return value.toString();
|
|
279
|
+
if (typeof value === "function") return formatFunctionLabel(value.name);
|
|
280
|
+
if (typeof value !== "object" || value === null) return value;
|
|
281
|
+
if (path.includes(value)) return CIRCULAR_REFERENCE_LABEL;
|
|
282
|
+
if (path.length >= MAX_SERIALIZATION_DEPTH) return MAX_DEPTH_LABEL;
|
|
283
|
+
const childPath = [...path, value];
|
|
284
|
+
return serializeObject(value, (child) => {
|
|
285
|
+
return serializeAtPath(child, childPath, budget);
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Turns a value into something `JSON.stringify` can print without losing or
|
|
290
|
+
* throwing on it, and without printing without limit.
|
|
291
|
+
*
|
|
292
|
+
* - Cycles become `"[Circular]"`, nesting deeper than 8 levels `"[MaxDepth]"`
|
|
293
|
+
* - At most 1000 values in total, and 50 keys or items per object or array; what
|
|
294
|
+
* is left out becomes `"[Truncated]"`
|
|
295
|
+
* - BigInt and symbols become strings, functions become their label, boxed
|
|
296
|
+
* primitives their primitive value, typed arrays, `DataView` and
|
|
297
|
+
* `ArrayBuffer` a label with their byte length
|
|
298
|
+
* - `Error` becomes `{ name, message, stack, cause?, code?, errors? }`, where
|
|
299
|
+
* `cause` and `errors` elements that are not Errors print as `"[Object]"`;
|
|
300
|
+
* `Map` becomes `{ Map: [[key, value]] }` and `Set` `{ Set: [value] }`
|
|
301
|
+
*
|
|
302
|
+
* Only the objects on the way down count as a cycle, so an object that appears
|
|
303
|
+
* twice side by side prints twice (and counts twice against the budget).
|
|
304
|
+
*
|
|
305
|
+
* @param {unknown} value - The value to convert.
|
|
306
|
+
* @returns {unknown} A JSON-safe value.
|
|
307
|
+
*/
|
|
308
|
+
function toJsonSafeValue(value) {
|
|
309
|
+
return serializeAtPath(value, [], createBudget());
|
|
310
|
+
}
|
|
311
|
+
export { escapeFileCharacters, formatFunctionLabel, isError, toJsonSafeValue };
|
|
312
|
+
|
|
313
|
+
//# sourceMappingURL=serialize_value.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serialize_value.js","names":[],"sources":["../src/serialize_value.ts"],"sourcesContent":["const ANONYMOUS_FUNCTION_LABEL = \"[Function anonymous]\";\nconst BINARY_BUFFER_TAGS: ReadonlySet<string> = new Set([\n \"[object ArrayBuffer]\",\n \"[object SharedArrayBuffer]\",\n]);\nconst BOXED_PRIMITIVE_TAGS: ReadonlySet<string> = new Set([\n \"[object Boolean]\",\n \"[object Number]\",\n \"[object String]\",\n]);\nconst CIRCULAR_REFERENCE_LABEL = \"[Circular]\";\nconst EMPTY_FUNCTION_NAME_LENGTH = 0;\nconst ERROR_TAG = \"[object Error]\";\nconst FIRST_CHARACTER_INDEX = 0;\nconst FUNCTION_LABEL_PREFIX = \"[Function \";\nconst FUNCTION_LABEL_SUFFIX = \"]\";\nconst HEX_RADIX = 16;\nconst MAX_COLLECTION_ITEMS = 50;\nconst MAX_DEPTH_LABEL = \"[MaxDepth]\";\nconst MAX_SERIALIZATION_DEPTH = 8;\nconst MAX_SERIALIZED_NODES = 1000;\nconst MISSING_CODE_POINT = 0;\nconst NOTHING = 0;\nconst OBJECT_LABEL = \"[Object]\";\nconst ONE = 1;\nconst TAG_PREFIX_LENGTH = \"[object \".length;\nconst TAG_SUFFIX_LENGTH = \"]\".length;\nconst TRUNCATED_LABEL = \"[Truncated]\";\nconst UNICODE_ESCAPE_WIDTH = 4;\n/**\n * Control characters except tab, the Unicode line and paragraph separators, and\n * the bidirectional controls (U+200E, U+200F, U+061C, U+202A to U+202E and\n * U+2066 to U+2069) plus the byte order mark (U+FEFF). They can make a log line\n * read differently from how it is stored, or end it. Anything in this set never\n * reaches a file raw. Backslashes are not escaped: that would mangle Windows\n * paths.\n */\nconst FILE_UNSAFE_CHARACTER_PATTERN =\n /(?!\\t)[\\p{Cc}\\p{Zl}\\p{Zp}\\u{061C}\\u{200E}\\u{200F}\\u{202A}-\\u{202E}\\u{2066}-\\u{2069}\\u{FEFF}]/gu;\nconst FILE_CHARACTER_ESCAPES: Readonly<Record<string, string>> = {\n \"\\n\": String.raw`\\n`,\n \"\\r\": String.raw`\\r`,\n};\n\ntype Serialize = (value: unknown) => unknown;\n\ntype Budget = Readonly<{\n take: () => boolean;\n}>;\n\ntype TakenItems<Item> = Readonly<{\n items: readonly Item[];\n omitted: number;\n}>;\n\n/**\n * Escapes what would let a value end or fake a line in a log file: control\n * characters (line breaks above all), the Unicode line separators and the\n * bidirectional controls.\n *\n * @param {string} text - Text that is about to be written to a log file.\n * @returns {string} The text with those characters written as `\\n`, `\\r` or\n * `\\uXXXX`. Tab and backslash stay as they are.\n */\nfunction escapeFileCharacters(text: string): string {\n return text.replaceAll(FILE_UNSAFE_CHARACTER_PATTERN, (character) => {\n const knownEscape = FILE_CHARACTER_ESCAPES[character];\n\n if (typeof knownEscape === \"string\") {\n return knownEscape;\n }\n\n const hexCode = (\n character.codePointAt(FIRST_CHARACTER_INDEX) ?? MISSING_CODE_POINT\n )\n .toString(HEX_RADIX)\n .padStart(UNICODE_ESCAPE_WIDTH, \"0\");\n\n return `\\\\u${hexCode}`;\n });\n}\n\nfunction formatFunctionLabel(functionName: string): string {\n if (functionName.length === EMPTY_FUNCTION_NAME_LENGTH) {\n return ANONYMOUS_FUNCTION_LABEL;\n }\n\n return `${FUNCTION_LABEL_PREFIX}${functionName}${FUNCTION_LABEL_SUFFIX}`;\n}\n\nfunction createBudget(): Budget {\n let remaining = MAX_SERIALIZED_NODES;\n\n return {\n take(): boolean {\n if (remaining <= NOTHING) {\n return false;\n }\n\n remaining -= ONE;\n\n return true;\n },\n };\n}\n\n/**\n * Reads the first `MAX_COLLECTION_ITEMS` entries of an array by index. The rest\n * is never visited: the omitted count comes from `length`, so a sparse array of\n * length 2^32 - 1 costs as much as one of length 50.\n *\n * @param {readonly unknown[]} array - The array.\n * @returns {TakenItems<unknown>} The kept items and how many were left out.\n */\nfunction takeArrayItems(array: readonly unknown[]): TakenItems<unknown> {\n const count = Math.min(array.length, MAX_COLLECTION_ITEMS);\n\n return {\n items: Array.from({ length: count }, (_unused, index) => {\n return array[index];\n }),\n omitted: array.length - count,\n };\n}\n\n/**\n * Reads the first `MAX_COLLECTION_ITEMS` entries of a Map or Set and stops\n * there. The omitted count comes from `size`.\n *\n * @param {Readonly<Iterable<Item>>} source - The Map or Set.\n * @param {number} size - Its `size`.\n * @returns {TakenItems<Item>} The kept items and how many were left out.\n */\nfunction takeFirstItems<Item>(\n source: Readonly<Iterable<Item>>,\n size: number,\n): TakenItems<Item> {\n const items: Item[] = [];\n\n for (const item of source) {\n if (items.length >= MAX_COLLECTION_ITEMS) {\n break;\n }\n\n items.push(item);\n }\n\n return { items, omitted: Math.max(size - items.length, NOTHING) };\n}\n\nfunction withTruncationMarker(\n items: readonly unknown[],\n omitted: number,\n): readonly unknown[] {\n if (omitted > NOTHING) {\n return [...items, TRUNCATED_LABEL];\n }\n\n return items;\n}\n\nfunction readProperty(value: Readonly<object>, key: string): unknown {\n return Reflect.get(value, key);\n}\n\nfunction readString(\n value: Readonly<object>,\n key: string,\n fallback: string,\n): string {\n const property = readProperty(value, key);\n\n if (typeof property === \"string\") {\n return property;\n }\n\n return fallback;\n}\n\nfunction readTag(value: Readonly<object>): string {\n return Object.prototype.toString.call(value);\n}\n\n/**\n * Recognises Errors, including those from other realms (another `vm` context,\n * an iframe), which fail `instanceof Error`. `Error.isError` is a brand check\n * and is used where the runtime has it; elsewhere `instanceof` or the `[object\n * Error]` tag decide.\n *\n * @param {Readonly<object>} value - Any object.\n * @returns {boolean} Whether it is an Error.\n */\nfunction isError(value: Readonly<object>): boolean {\n const nativeIsError: unknown = Reflect.get(Error, \"isError\");\n\n if (typeof nativeIsError === \"function\") {\n return Reflect.apply(nativeIsError, Error, [value]) === true;\n }\n\n return value instanceof Error || readTag(value) === ERROR_TAG;\n}\n\n/**\n * Reads the primitive out of a `String`, `Number` or `Boolean` object. The\n * built-in `valueOf` of each is brand-checked and throws for anything else, so\n * a plain object that only claims one of these tags is not unboxed.\n *\n * @param {Readonly<object>} value - Any object.\n * @returns {readonly [unknown] | undefined} The primitive in a one-item tuple,\n * or `undefined` when `value` is not a boxed primitive.\n */\nfunction unboxPrimitive(\n value: Readonly<object>,\n): readonly [unknown] | undefined {\n if (!BOXED_PRIMITIVE_TAGS.has(readTag(value))) {\n return undefined;\n }\n\n for (const prototype of [\n Number.prototype,\n String.prototype,\n Boolean.prototype,\n ]) {\n try {\n const valueOf: unknown = Reflect.get(prototype, \"valueOf\");\n\n if (typeof valueOf !== \"function\") {\n continue;\n }\n\n return [Reflect.apply(valueOf, value, [])];\n } catch {\n // Not this kind of box; try the next one.\n }\n }\n\n return undefined;\n}\n\nfunction readByteLength(value: Readonly<object>): number {\n const byteLength = readProperty(value, \"byteLength\");\n\n if (typeof byteLength === \"number\") {\n return byteLength;\n }\n\n return NOTHING;\n}\n\n/**\n * Typed arrays, `DataView` and `ArrayBuffer` print as a label with their byte\n * length. Their contents are not read: they can be megabytes, and Node's\n * `Buffer` has a `toJSON` that would copy every byte into an array.\n *\n * @param {Readonly<object>} value - Any object.\n * @returns {string | undefined} The label, or `undefined` for other objects.\n */\nfunction binaryLabel(value: Readonly<object>): string | undefined {\n const tag = readTag(value);\n\n if (!ArrayBuffer.isView(value) && !BINARY_BUFFER_TAGS.has(tag)) {\n return undefined;\n }\n\n const typeName = tag.slice(TAG_PREFIX_LENGTH, -TAG_SUFFIX_LENGTH);\n\n return `[${typeName} ${readByteLength(value)} bytes]`;\n}\n\n/**\n * Inside an Error, a nested value prints in full only when it is an Error\n * itself. Any other object becomes a label: `cause` is often an HTTP response\n * or request object that carries credentials, and the Error allow-list would\n * mean nothing if those printed through the `cause` slot.\n *\n * @param {unknown} value - A `cause` or one element of `errors`.\n * @param {Serialize} serialize - Serializes a value under the normal rules.\n * @returns {unknown} The label, or the serialized primitive or Error.\n */\nfunction serializeErrorChild(value: unknown, serialize: Serialize): unknown {\n if (typeof value === \"object\" && value !== null && !isError(value)) {\n return OBJECT_LABEL;\n }\n\n return serialize(value);\n}\n\nfunction serializeAggregatedErrors(\n errors: readonly unknown[],\n serialize: Serialize,\n): readonly unknown[] {\n const { items, omitted } = takeArrayItems(errors);\n\n return withTruncationMarker(\n items.map((entry) => {\n return serializeErrorChild(entry, serialize);\n }),\n omitted,\n );\n}\n\n/**\n * Serializes an Error from an allow-list only: `name`, `message`, `stack`,\n * `cause`, `code` (when it is a string or a number) and, for an\n * `AggregateError`, `errors`. Other own properties are left out on purpose:\n * HTTP client errors (axios, got) carry the request, its headers and its body\n * there, which means credentials. `cause` and the elements of `errors` follow\n * the rule in `serializeErrorChild`.\n *\n * @param {Readonly<object>} error - The Error.\n * @param {Serialize} serialize - Serializes a nested value under the same\n * rules.\n * @returns {unknown} A plain object.\n */\nfunction serializeError(\n error: Readonly<object>,\n serialize: Serialize,\n): unknown {\n const name = readString(error, \"name\", \"Error\");\n const entries: [string, unknown][] = [\n [\"name\", name],\n [\"message\", readString(error, \"message\", \"\")],\n [\"stack\", readString(error, \"stack\", \"\")],\n ];\n const cause = readProperty(error, \"cause\");\n const code = readProperty(error, \"code\");\n const errors = readProperty(error, \"errors\");\n\n if (typeof cause !== \"undefined\") {\n entries.push([\"cause\", serializeErrorChild(cause, serialize)]);\n }\n\n if (typeof code === \"string\" || typeof code === \"number\") {\n entries.push([\"code\", code]);\n }\n\n if (\n (error instanceof AggregateError || name === \"AggregateError\") &&\n Array.isArray(errors)\n ) {\n entries.push([\"errors\", serializeAggregatedErrors(errors, serialize)]);\n }\n\n return Object.fromEntries(entries);\n}\n\nfunction serializeMap(\n map: Readonly<ReadonlyMap<unknown, unknown>>,\n serialize: Serialize,\n): unknown {\n const { items, omitted } = takeFirstItems(map, map.size);\n\n return {\n Map: withTruncationMarker(\n items.map(([key, entry]: readonly [unknown, unknown]) => {\n return [serialize(key), serialize(entry)];\n }),\n omitted,\n ),\n };\n}\n\nfunction serializeSet(\n set: Readonly<ReadonlySet<unknown>>,\n serialize: Serialize,\n): unknown {\n const { items, omitted } = takeFirstItems(set, set.size);\n\n return {\n Set: withTruncationMarker(\n items.map((entry: unknown) => {\n return serialize(entry);\n }),\n omitted,\n ),\n };\n}\n\n/**\n * Serializes the own enumerable keys of an object, at most\n * `MAX_COLLECTION_ITEMS` of them. Only the values of the kept keys are visited,\n * but the key list is built in full: `Object.keys` is a single native pass, and\n * `for...in` with an early exit does not avoid it (V8 collects the keys before\n * the first iteration; measured at the same cost). An object with millions of\n * keys therefore costs one linear key listing, not millions of serializations.\n *\n * @param {Readonly<object>} value - The object.\n * @param {Serialize} serialize - Serializes a nested value.\n * @returns {unknown} A plain object, with a `[Truncated]` key when keys were\n * left out.\n */\nfunction serializePlainObject(\n value: Readonly<object>,\n serialize: Serialize,\n): unknown {\n const allKeys = Object.keys(value);\n const entries: [string, unknown][] = allKeys\n .slice(NOTHING, MAX_COLLECTION_ITEMS)\n .map((key) => {\n return [key, serialize(readProperty(value, key))];\n });\n\n if (allKeys.length > MAX_COLLECTION_ITEMS) {\n entries.push([TRUNCATED_LABEL, allKeys.length - MAX_COLLECTION_ITEMS]);\n }\n\n return Object.fromEntries(entries);\n}\n\nfunction serializeCollection(\n value: Readonly<object>,\n serialize: Serialize,\n): unknown {\n if (value instanceof Map) {\n return serializeMap(value, serialize);\n }\n\n if (value instanceof Set) {\n return serializeSet(value, serialize);\n }\n\n if (Array.isArray(value)) {\n const { items, omitted } = takeArrayItems(value);\n\n return withTruncationMarker(\n items.map((entry) => {\n return serialize(entry);\n }),\n omitted,\n );\n }\n\n return undefined;\n}\n\nfunction serializeObject(\n value: Readonly<object>,\n serialize: Serialize,\n): unknown {\n if (isError(value)) {\n return serializeError(value, serialize);\n }\n\n const boxed = unboxPrimitive(value);\n\n if (typeof boxed !== \"undefined\") {\n return serialize(boxed[FIRST_CHARACTER_INDEX]);\n }\n\n const label = binaryLabel(value);\n\n if (typeof label === \"string\") {\n return label;\n }\n\n const collection = serializeCollection(value, serialize);\n\n if (typeof collection !== \"undefined\") {\n return collection;\n }\n\n const toJson = readProperty(value, \"toJSON\");\n\n if (typeof toJson === \"function\") {\n return serialize(Reflect.apply(toJson, value, []));\n }\n\n return serializePlainObject(value, serialize);\n}\n\nfunction serializeAtPath(\n value: unknown,\n path: readonly Readonly<object>[],\n budget: Budget,\n): unknown {\n if (!budget.take()) {\n return TRUNCATED_LABEL;\n }\n\n if (typeof value === \"bigint\") {\n return `${value}n`;\n }\n\n if (typeof value === \"symbol\") {\n return value.toString();\n }\n\n if (typeof value === \"function\") {\n return formatFunctionLabel(value.name);\n }\n\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n\n if (path.includes(value)) {\n return CIRCULAR_REFERENCE_LABEL;\n }\n\n if (path.length >= MAX_SERIALIZATION_DEPTH) {\n return MAX_DEPTH_LABEL;\n }\n\n const childPath = [...path, value];\n\n return serializeObject(value, (child) => {\n return serializeAtPath(child, childPath, budget);\n });\n}\n\n/**\n * Turns a value into something `JSON.stringify` can print without losing or\n * throwing on it, and without printing without limit.\n *\n * - Cycles become `\"[Circular]\"`, nesting deeper than 8 levels `\"[MaxDepth]\"`\n * - At most 1000 values in total, and 50 keys or items per object or array; what\n * is left out becomes `\"[Truncated]\"`\n * - BigInt and symbols become strings, functions become their label, boxed\n * primitives their primitive value, typed arrays, `DataView` and\n * `ArrayBuffer` a label with their byte length\n * - `Error` becomes `{ name, message, stack, cause?, code?, errors? }`, where\n * `cause` and `errors` elements that are not Errors print as `\"[Object]\"`;\n * `Map` becomes `{ Map: [[key, value]] }` and `Set` `{ Set: [value] }`\n *\n * Only the objects on the way down count as a cycle, so an object that appears\n * twice side by side prints twice (and counts twice against the budget).\n *\n * @param {unknown} value - The value to convert.\n * @returns {unknown} A JSON-safe value.\n */\nfunction toJsonSafeValue(value: unknown): unknown {\n return serializeAtPath(value, [], createBudget());\n}\n\nexport { escapeFileCharacters, formatFunctionLabel, isError, toJsonSafeValue };\n"],"mappings":";AAAA,MAAM,2BAA2B;AACjC,MAAM,qCAA0C,IAAI,IAAI,C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GACb,OAAO,eAAe,OAAO,SAAS;CAG1C,MAAM,QAAQ,eAAe,KAAK;CAElC,IAAI,OAAO,UAAU,aACjB,OAAO,UAAU,MAAM,sBAAsB;CAGjD,MAAM,QAAQ,YAAY,KAAK;CAE/B,IAAI,OAAO,UAAU,UACjB,OAAO;CAGX,MAAM,aAAa,oBAAoB,OAAO,SAAS;CAEvD,IAAI,OAAO,eAAe,aACtB,OAAO;CAGX,MAAM,SAAS,aAAa,OAAO,QAAQ;CAE3C,IAAI,OAAO,WAAW,YAClB,OAAO,UAAU,QAAQ,MAAM,QAAQ,OAAO,CAAC,CAAC,CAAC;CAGrD,OAAO,qBAAqB,OAAO,SAAS;AAChD;AAEA,SAAS,gBACL,OACA,MACA,QACO;CACP,IAAI,CAAC,OAAO,KAAK,GACb,OAAO;CAGX,IAAI,OAAO,UAAU,UACjB,OAAO,GAAG,MAAM;CAGpB,IAAI,OAAO,UAAU,UACjB,OAAO,MAAM,SAAS;CAG1B,IAAI,OAAO,UAAU,YACjB,OAAO,oBAAoB,MAAM,IAAI;CAGzC,IAAI,OAAO,UAAU,YAAY,UAAU,MACvC,OAAO;CAGX,IAAI,KAAK,SAAS,KAAK,GACnB,OAAO;CAGX,IAAI,KAAK,UAAU,yBACf,OAAO;CAGX,MAAM,YAAY,CAAC,GAAG,MAAM,KAAK;CAEjC,OAAO,gBAAgB,QAAQ,UAAU;EACrC,OAAO,gBAAgB,OAAO,WAAW,MAAM;CACnD,CAAC;AACL;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAS,gBAAgB,OAAyB;CAC9C,OAAO,gBAAgB,OAAO,CAAC,GAAG,aAAa,CAAC;AACpD"}
|
package/dist/web_logger.d.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { LogLevel, LoggerBase, LoggerOptions, LoggerParent } from "./logger_factory.js";
|
|
2
|
-
//#region src/web_logger.d.ts
|
|
3
2
|
declare class Logger extends LoggerBase {
|
|
4
3
|
constructor(name: string, parent?: LoggerParent, options?: LoggerOptions);
|
|
5
4
|
}
|
|
6
|
-
//#endregion
|
|
7
5
|
export { type LogLevel, Logger, type LoggerOptions };
|
|
8
6
|
//# sourceMappingURL=web_logger.d.ts.map
|
package/dist/web_logger.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web_logger.d.ts","names":[],"sources":["../src/web_logger.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"web_logger.d.ts","names":[],"sources":["../src/web_logger.ts"],"mappings":";cAeM,eAAe;EACjB,YACI,cACA,SAAS,cACT,UAAS"}
|
package/dist/web_logger.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
+
import { createTextLogWriter } from "./console_text.js";
|
|
1
2
|
import { LoggerBase, createLoggerConsole } from "./logger_factory.js";
|
|
2
|
-
|
|
3
|
-
const webRuntime = {
|
|
3
|
+
// src/web_logger.ts
|
|
4
|
+
const webRuntime = { write: createTextLogWriter(createLoggerConsole()) };
|
|
4
5
|
var Logger = class Logger extends LoggerBase {
|
|
5
6
|
constructor(name, parent, options = {}) {
|
|
6
7
|
super(Logger, webRuntime, name, parent, options);
|
|
7
8
|
}
|
|
8
9
|
};
|
|
9
|
-
//#endregion
|
|
10
10
|
export { Logger };
|
|
11
11
|
|
|
12
12
|
//# sourceMappingURL=web_logger.js.map
|
package/dist/web_logger.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web_logger.js","names":[],"sources":["../src/web_logger.ts"],"sourcesContent":["import { LoggerBase, createLoggerConsole } from \"./logger_factory\";\nimport type {\n
|
|
1
|
+
{"version":3,"file":"web_logger.js","names":[],"sources":["../src/web_logger.ts"],"sourcesContent":["import { createTextLogWriter } from \"./console_text\";\nimport { LoggerBase, createLoggerConsole } from \"./logger_factory\";\nimport type {\n LoggerOptions,\n LoggerParent,\n LoggerRuntime,\n LogLevel,\n} from \"./logger_factory\";\n\n// Servers and edge runtimes (Cloudflare, Netlify, Deno): text output with the\n// serializer's safety rules. Browsers resolve `browser_logger` instead.\nconst webRuntime = {\n write: createTextLogWriter(createLoggerConsole()),\n} satisfies LoggerRuntime;\n\nclass Logger extends LoggerBase {\n constructor(\n name: string,\n parent?: LoggerParent,\n options: LoggerOptions = {},\n ) {\n super(Logger, webRuntime, name, parent, options);\n }\n}\n\nexport { Logger };\n\nexport type { LoggerOptions, LogLevel };\n"],"mappings":";;;AAWA,MAAM,aAAa,EACf,OAAO,oBAAoB,oBAAoB,CAAC,EACpD;AAEA,IAAM,SAAN,MAAM,eAAe,WAAW;CAC5B,YACI,MACA,QACA,UAAyB,CAAC,GAC5B;EACE,MAAM,QAAQ,YAAY,MAAM,QAAQ,OAAO;CACnD;AACJ"}
|
|
@@ -9,7 +9,7 @@ export const preferRuntimeEntryRule = {
|
|
|
9
9
|
},
|
|
10
10
|
schema: [],
|
|
11
11
|
messages: {
|
|
12
|
-
preferRuntimeEntry: `Prefer an explicit runtime entry over "${SIMPLELOG_PACKAGE}". Use a runtime-specific import like "@murky-web/simplelog/node", "@murky-web/simplelog/web", "@murky-web/simplelog/bun",
|
|
12
|
+
preferRuntimeEntry: `Prefer an explicit runtime entry over "${SIMPLELOG_PACKAGE}". Use a runtime-specific import like "@murky-web/simplelog/node", "@murky-web/simplelog/web", "@murky-web/simplelog/bun", or "@murky-web/simplelog/hono".`,
|
|
13
13
|
},
|
|
14
14
|
},
|
|
15
15
|
create(context) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@murky-web/simplelog",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.1.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "A simple wrapper around console to make logging enjoyable again",
|
|
6
6
|
"homepage": "https://github.com/MurkyTheMurloc/web_dev_tools/tree/main/packages/simplelog",
|
|
@@ -35,10 +35,6 @@
|
|
|
35
35
|
"import": "./dist/bun_logger.js",
|
|
36
36
|
"types": "./dist/bun_logger.d.ts"
|
|
37
37
|
},
|
|
38
|
-
"./deno": {
|
|
39
|
-
"import": "./dist/deno_logger.js",
|
|
40
|
-
"types": "./dist/deno_logger.d.ts"
|
|
41
|
-
},
|
|
42
38
|
"./hono": {
|
|
43
39
|
"import": "./dist/hono_middleware.js",
|
|
44
40
|
"types": "./dist/hono_middleware.d.ts"
|
|
@@ -52,8 +48,15 @@
|
|
|
52
48
|
"types": "./dist/otel.d.ts"
|
|
53
49
|
},
|
|
54
50
|
"./web": {
|
|
55
|
-
"
|
|
56
|
-
"
|
|
51
|
+
"types": "./dist/web_logger.d.ts",
|
|
52
|
+
"workerd": "./dist/web_logger.js",
|
|
53
|
+
"worker": "./dist/web_logger.js",
|
|
54
|
+
"edge-light": "./dist/web_logger.js",
|
|
55
|
+
"deno": "./dist/web_logger.js",
|
|
56
|
+
"bun": "./dist/web_logger.js",
|
|
57
|
+
"node": "./dist/web_logger.js",
|
|
58
|
+
"browser": "./dist/browser_logger.js",
|
|
59
|
+
"import": "./dist/web_logger.js"
|
|
57
60
|
},
|
|
58
61
|
"./package.json": "./package.json"
|
|
59
62
|
},
|
|
@@ -66,18 +69,18 @@
|
|
|
66
69
|
"clean": "rm -rf dist",
|
|
67
70
|
"lint": "oxlint -c ./.oxlintrc.jsonc --tsconfig ./tsconfig.json --type-aware src tsdown.config.ts",
|
|
68
71
|
"lint:fix": "oxlint -c ./.oxlintrc.jsonc --tsconfig ./tsconfig.json --type-aware --fix src tsdown.config.ts",
|
|
69
|
-
"format": "oxfmt -c
|
|
70
|
-
"format:check": "oxfmt -c
|
|
72
|
+
"format": "oxfmt -c ../../config/oxc/.oxfmtrc.jsonc src oxlint smoke tsdown.config.ts",
|
|
73
|
+
"format:check": "oxfmt -c ../../config/oxc/.oxfmtrc.jsonc --check src oxlint smoke tsdown.config.ts",
|
|
71
74
|
"smoke:oxlint": "bun ./smoke/oxlint/run-smoke.ts",
|
|
72
75
|
"smoke:entries": "bun run build && bun ./smoke/entries/run.ts",
|
|
76
|
+
"smoke:treeshake": "bun run build && bun ./smoke/treeshake/run.ts",
|
|
73
77
|
"test": "vitest run",
|
|
74
78
|
"typecheck": "tsc --project ./tsconfig.json --noEmit"
|
|
75
79
|
},
|
|
76
80
|
"devDependencies": {
|
|
77
|
-
"@
|
|
78
|
-
"@
|
|
79
|
-
"
|
|
80
|
-
"hono": "^4.12.8"
|
|
81
|
+
"@opentelemetry/api": "^1.10.0",
|
|
82
|
+
"@types/node": "^24.19.2",
|
|
83
|
+
"hono": "^4.13.19"
|
|
81
84
|
},
|
|
82
85
|
"peerDependencies": {
|
|
83
86
|
"@opentelemetry/api": "^1.9.0",
|
|
@@ -86,6 +89,9 @@
|
|
|
86
89
|
"peerDependenciesMeta": {
|
|
87
90
|
"@opentelemetry/api": {
|
|
88
91
|
"optional": true
|
|
92
|
+
},
|
|
93
|
+
"hono": {
|
|
94
|
+
"optional": true
|
|
89
95
|
}
|
|
90
96
|
}
|
|
91
97
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"deno_logger.d.ts","names":[],"sources":["../src/deno_logger.ts"],"mappings":";;cAkFM,eAAe;EACnB,YACE,cACA,SAAS,cACT,UAAS"}
|
package/dist/deno_logger.js
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import { LoggerBase, createLoggerConsole } from "./logger_factory.js";
|
|
2
|
-
//#region src/deno_logger.ts
|
|
3
|
-
const ROOT_DIRECTORY_INDEX = 0;
|
|
4
|
-
function getDirectoryPath(filePath) {
|
|
5
|
-
const lastSlashIndex = Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\"));
|
|
6
|
-
if (lastSlashIndex <= ROOT_DIRECTORY_INDEX) return ".";
|
|
7
|
-
return filePath.slice(ROOT_DIRECTORY_INDEX, lastSlashIndex);
|
|
8
|
-
}
|
|
9
|
-
function isDenoApi(runtime) {
|
|
10
|
-
if (typeof runtime !== "object" || runtime === null) return false;
|
|
11
|
-
return "mkdirSync" in runtime && typeof Reflect.get(runtime, "mkdirSync") === "function" && "writeTextFileSync" in runtime && typeof Reflect.get(runtime, "writeTextFileSync") === "function";
|
|
12
|
-
}
|
|
13
|
-
function getDenoRuntime() {
|
|
14
|
-
const denoCandidate = Reflect.get(globalThis, "Deno");
|
|
15
|
-
if (!isDenoApi(denoCandidate)) throw new Error("The Deno logger requires the Deno runtime.");
|
|
16
|
-
return denoCandidate;
|
|
17
|
-
}
|
|
18
|
-
function appendWithDeno(filePath, content) {
|
|
19
|
-
const denoRuntime = getDenoRuntime();
|
|
20
|
-
denoRuntime.mkdirSync(getDirectoryPath(filePath), { recursive: true });
|
|
21
|
-
denoRuntime.writeTextFileSync(filePath, content, {
|
|
22
|
-
append: true,
|
|
23
|
-
create: true,
|
|
24
|
-
write: true
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
const denoRuntime = {
|
|
28
|
-
appendTextFileSync: appendWithDeno,
|
|
29
|
-
console: createLoggerConsole()
|
|
30
|
-
};
|
|
31
|
-
var Logger = class Logger extends LoggerBase {
|
|
32
|
-
constructor(name, parent, options = {}) {
|
|
33
|
-
super(Logger, denoRuntime, name, parent, options);
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
-
//#endregion
|
|
37
|
-
export { Logger };
|
|
38
|
-
|
|
39
|
-
//# sourceMappingURL=deno_logger.js.map
|
package/dist/deno_logger.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"deno_logger.js","names":[],"sources":["../src/deno_logger.ts"],"sourcesContent":["import { LoggerBase, createLoggerConsole } from \"./logger_factory\";\nimport type {\n LoggerOptions,\n LoggerParent,\n LoggerRuntime,\n LogLevel,\n} from \"./logger_factory\";\n\ntype DenoOpenOptions = Readonly<{\n append?: boolean;\n create?: boolean;\n write?: boolean;\n}>;\n\ntype DenoApi = Readonly<{\n mkdirSync: (\n path: string,\n options: Readonly<{\n recursive?: boolean;\n }>,\n ) => void;\n writeTextFileSync: (\n path: string,\n data: string,\n options: DenoOpenOptions,\n ) => void;\n}>;\n\nconst ROOT_DIRECTORY_INDEX = 0;\n\nfunction getDirectoryPath(filePath: string): string {\n const lastSlashIndex = Math.max(\n filePath.lastIndexOf(\"/\"),\n filePath.lastIndexOf(\"\\\\\"),\n );\n\n if (lastSlashIndex <= ROOT_DIRECTORY_INDEX) {\n return \".\";\n }\n\n return filePath.slice(ROOT_DIRECTORY_INDEX, lastSlashIndex);\n}\n\nfunction isDenoApi(runtime: unknown): runtime is DenoApi {\n if (typeof runtime !== \"object\" || runtime === null) {\n return false;\n }\n\n return (\n \"mkdirSync\" in runtime &&\n typeof Reflect.get(runtime, \"mkdirSync\") === \"function\" &&\n \"writeTextFileSync\" in runtime &&\n typeof Reflect.get(runtime, \"writeTextFileSync\") === \"function\"\n );\n}\n\nfunction getDenoRuntime(): DenoApi {\n const denoCandidate: unknown = Reflect.get(globalThis, \"Deno\");\n\n if (!isDenoApi(denoCandidate)) {\n throw new Error(\"The Deno logger requires the Deno runtime.\");\n }\n\n return denoCandidate;\n}\n\nfunction appendWithDeno(filePath: string, content: string): void {\n const denoRuntime = getDenoRuntime();\n\n denoRuntime.mkdirSync(getDirectoryPath(filePath), { recursive: true });\n denoRuntime.writeTextFileSync(filePath, content, {\n append: true,\n create: true,\n write: true,\n });\n}\n\nconst denoRuntime = {\n appendTextFileSync: appendWithDeno,\n console: createLoggerConsole(),\n} satisfies LoggerRuntime;\n\nclass Logger extends LoggerBase {\n constructor(\n name: string,\n parent?: LoggerParent,\n options: LoggerOptions = {},\n ) {\n super(Logger, denoRuntime, name, parent, options);\n }\n}\n\nexport { Logger };\n\nexport type { LoggerOptions, LogLevel };\n"],"mappings":";;AA4BA,MAAM,uBAAuB;AAE7B,SAAS,iBAAiB,UAA0B;CAClD,MAAM,iBAAiB,KAAK,IAC1B,SAAS,YAAY,GAAG,GACxB,SAAS,YAAY,IAAI,CAC3B;CAEA,IAAI,kBAAkB,sBACpB,OAAO;CAGT,OAAO,SAAS,MAAM,sBAAsB,cAAc;AAC5D;AAEA,SAAS,UAAU,SAAsC;CACvD,IAAI,OAAO,YAAY,YAAY,YAAY,MAC7C,OAAO;CAGT,OACE,eAAe,WACf,OAAO,QAAQ,IAAI,SAAS,WAAW,MAAM,cAC7C,uBAAuB,WACvB,OAAO,QAAQ,IAAI,SAAS,mBAAmB,MAAM;AAEzD;AAEA,SAAS,iBAA0B;CACjC,MAAM,gBAAyB,QAAQ,IAAI,YAAY,MAAM;CAE7D,IAAI,CAAC,UAAU,aAAa,GAC1B,MAAM,IAAI,MAAM,4CAA4C;CAG9D,OAAO;AACT;AAEA,SAAS,eAAe,UAAkB,SAAuB;CAC/D,MAAM,cAAc,eAAe;CAEnC,YAAY,UAAU,iBAAiB,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;CACrE,YAAY,kBAAkB,UAAU,SAAS;EAC/C,QAAQ;EACR,QAAQ;EACR,OAAO;CACT,CAAC;AACH;AAEA,MAAM,cAAc;CAClB,oBAAoB;CACpB,SAAS,oBAAoB;AAC/B;AAEA,IAAM,SAAN,MAAM,eAAe,WAAW;CAC9B,YACE,MACA,QACA,UAAyB,CAAC,GAC1B;EACA,MAAM,QAAQ,aAAa,MAAM,QAAQ,OAAO;CAClD;AACF"}
|