@gusto/baerly-storage 0.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 +97 -0
- package/dist/API.md +850 -0
- package/dist/app-config-Cb5dO2s9.d.ts +480 -0
- package/dist/app-config.d.ts +2 -0
- package/dist/app-config.js +8 -0
- package/dist/app-config.js.map +1 -0
- package/dist/auth.d.ts +237 -0
- package/dist/auth.js +1335 -0
- package/dist/auth.js.map +1 -0
- package/dist/baerly.js +761 -0
- package/dist/baerly.js.map +1 -0
- package/dist/bucket-uri-BrDEYvzy.js +4922 -0
- package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
- package/dist/chunk-EAsCxrDo.js +14 -0
- package/dist/client-BLf3Ae5s.d.ts +233 -0
- package/dist/client-react.d.ts +131 -0
- package/dist/client-react.js +559 -0
- package/dist/client-react.js.map +1 -0
- package/dist/client.d.ts +4 -0
- package/dist/client.js +160 -0
- package/dist/client.js.map +1 -0
- package/dist/cloudflare-CINJPKCW.js +911 -0
- package/dist/cloudflare-CINJPKCW.js.map +1 -0
- package/dist/cloudflare.d.ts +211 -0
- package/dist/cloudflare.js +445 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/config-Bsg8wgwo.js +198 -0
- package/dist/config-Bsg8wgwo.js.map +1 -0
- package/dist/context-Oj7ffwD-.js +187 -0
- package/dist/context-Oj7ffwD-.js.map +1 -0
- package/dist/cost-B1WiZxlf.js +203 -0
- package/dist/cost-B1WiZxlf.js.map +1 -0
- package/dist/current-json-BkatBzF7.js +252 -0
- package/dist/current-json-BkatBzF7.js.map +1 -0
- package/dist/db-D62JguBc.d.ts +336 -0
- package/dist/deploy-BB-wqbhf.js +83 -0
- package/dist/deploy-BB-wqbhf.js.map +1 -0
- package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
- package/dist/dev-vite.d.ts +146 -0
- package/dist/dev-vite.js +223 -0
- package/dist/dev-vite.js.map +1 -0
- package/dist/dev.d.ts +3 -0
- package/dist/dev.js +2 -0
- package/dist/doctor-B8h9GCN9.js +331 -0
- package/dist/doctor-B8h9GCN9.js.map +1 -0
- package/dist/dump-BHo_sIMZ.js +116 -0
- package/dist/dump-BHo_sIMZ.js.map +1 -0
- package/dist/errors-DOdL95kK.js +58 -0
- package/dist/errors-DOdL95kK.js.map +1 -0
- package/dist/export-Dz2PZKSR.js +423 -0
- package/dist/export-Dz2PZKSR.js.map +1 -0
- package/dist/fsck-DEz9lyCy.js +293 -0
- package/dist/fsck-DEz9lyCy.js.map +1 -0
- package/dist/http-CjUO1Bec.js +1756 -0
- package/dist/http-CjUO1Bec.js.map +1 -0
- package/dist/http.d.ts +1619 -0
- package/dist/http.js +2 -0
- package/dist/index-BGC-ENnj.d.ts +1065 -0
- package/dist/index-BYv0hb8M.d.ts +1457 -0
- package/dist/index-BquQkhJi.d.ts +112 -0
- package/dist/index-COsQ-Mlz.d.ts +146 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/indexes-BXn7a06a.js +297 -0
- package/dist/indexes-BXn7a06a.js.map +1 -0
- package/dist/indexes-DwOXkn1Y.d.ts +22 -0
- package/dist/inspect-x02aFWnh.js +149 -0
- package/dist/inspect-x02aFWnh.js.map +1 -0
- package/dist/log-walk-DIru96UT.js +260 -0
- package/dist/log-walk-DIru96UT.js.map +1 -0
- package/dist/maintenance-Bn6ul9aV.js +758 -0
- package/dist/maintenance-Bn6ul9aV.js.map +1 -0
- package/dist/maintenance.d.ts +323 -0
- package/dist/maintenance.js +2 -0
- package/dist/node.d.ts +422 -0
- package/dist/node.js +2 -0
- package/dist/normalize-XWY25_sG.js +133 -0
- package/dist/normalize-XWY25_sG.js.map +1 -0
- package/dist/observability-2IDYRuZK.js +2333 -0
- package/dist/observability-2IDYRuZK.js.map +1 -0
- package/dist/observability.d.ts +3 -0
- package/dist/observability.js +3 -0
- package/dist/plan-Cs17VqjU.js +224 -0
- package/dist/plan-Cs17VqjU.js.map +1 -0
- package/dist/query-DcSbFLJt.js +1880 -0
- package/dist/query-DcSbFLJt.js.map +1 -0
- package/dist/rebuild-index-C5gTXryd.js +119 -0
- package/dist/rebuild-index-C5gTXryd.js.map +1 -0
- package/dist/rebuild-index-DwXM0WfA.js +104 -0
- package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
- package/dist/request-BEF_OvMh.js +72 -0
- package/dist/request-BEF_OvMh.js.map +1 -0
- package/dist/restore-CbKVMMpm.js +847 -0
- package/dist/restore-CbKVMMpm.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js +71 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -0
- package/dist/snapshot-D7C4_FSl.js +71 -0
- package/dist/snapshot-D7C4_FSl.js.map +1 -0
- package/dist/snapshot-z_N9hpTe.js +917 -0
- package/dist/snapshot-z_N9hpTe.js.map +1 -0
- package/dist/src-Chafbw8r.js +522 -0
- package/dist/src-Chafbw8r.js.map +1 -0
- package/dist/src-DyET_VPP.js +6199 -0
- package/dist/src-DyET_VPP.js.map +1 -0
- package/dist/src-n0Te1r98.js +352 -0
- package/dist/src-n0Te1r98.js.map +1 -0
- package/dist/subcommand-BWs6K7zb.js +110 -0
- package/dist/subcommand-BWs6K7zb.js.map +1 -0
- package/dist/usage-RVUQMLop.js +339 -0
- package/dist/usage-RVUQMLop.js.map +1 -0
- package/dist/validate-DhH1lO8I.js +377 -0
- package/dist/validate-DhH1lO8I.js.map +1 -0
- package/dist/wire-izfGZDvr.js +7 -0
- package/dist/wire-izfGZDvr.js.map +1 -0
- package/package.json +189 -0
|
@@ -0,0 +1,2333 @@
|
|
|
1
|
+
import { n as __exportAll } from "./chunk-EAsCxrDo.js";
|
|
2
|
+
import { t as BaerlyError } from "./errors-DOdL95kK.js";
|
|
3
|
+
import { i as noopMetricsRecorder, n as getCurrentContext, r as runWithContext, t as createObservabilityContext } from "./context-Oj7ffwD-.js";
|
|
4
|
+
//#region packages/server/src/contract.ts
|
|
5
|
+
/**
|
|
6
|
+
* Single drift surface for the {@link HttpErrorEnvelope} shape. The
|
|
7
|
+
* router and both adapters call this — adding or renaming a field on
|
|
8
|
+
* the wire is a one-edit change here.
|
|
9
|
+
*/
|
|
10
|
+
const errorEnvelope = (code, message, issues) => ({ error: {
|
|
11
|
+
code,
|
|
12
|
+
message,
|
|
13
|
+
...issues !== void 0 && issues.length > 0 ? { issues } : {}
|
|
14
|
+
} });
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region node_modules/.pnpm/@logtape+logtape@2.1.1/node_modules/@logtape/logtape/dist/filter.js
|
|
17
|
+
/**
|
|
18
|
+
* Converts a {@link FilterLike} value to an actual {@link Filter}.
|
|
19
|
+
*
|
|
20
|
+
* @param filter The filter-like value to convert.
|
|
21
|
+
* @returns The actual filter.
|
|
22
|
+
*/
|
|
23
|
+
function toFilter(filter) {
|
|
24
|
+
if (typeof filter === "function") return filter;
|
|
25
|
+
return getLevelFilter(filter);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Returns a filter that accepts log records with the specified level.
|
|
29
|
+
*
|
|
30
|
+
* @param level The level to filter by. If `null`, the filter will reject all
|
|
31
|
+
* records.
|
|
32
|
+
* @returns The filter.
|
|
33
|
+
*/
|
|
34
|
+
function getLevelFilter(level) {
|
|
35
|
+
if (level == null) return () => false;
|
|
36
|
+
if (level === "fatal") return (record) => record.level === "fatal";
|
|
37
|
+
else if (level === "error") return (record) => record.level === "fatal" || record.level === "error";
|
|
38
|
+
else if (level === "warning") return (record) => record.level === "fatal" || record.level === "error" || record.level === "warning";
|
|
39
|
+
else if (level === "info") return (record) => record.level === "fatal" || record.level === "error" || record.level === "warning" || record.level === "info";
|
|
40
|
+
else if (level === "debug") return (record) => record.level === "fatal" || record.level === "error" || record.level === "warning" || record.level === "info" || record.level === "debug";
|
|
41
|
+
else if (level === "trace") return () => true;
|
|
42
|
+
throw new TypeError(`Invalid log level: ${level}.`);
|
|
43
|
+
}
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region node_modules/.pnpm/@logtape+logtape@2.1.1/node_modules/@logtape/logtape/dist/level.js
|
|
46
|
+
const logLevels = [
|
|
47
|
+
"trace",
|
|
48
|
+
"debug",
|
|
49
|
+
"info",
|
|
50
|
+
"warning",
|
|
51
|
+
"error",
|
|
52
|
+
"fatal"
|
|
53
|
+
];
|
|
54
|
+
/**
|
|
55
|
+
* Compares two log levels.
|
|
56
|
+
* @param a The first log level.
|
|
57
|
+
* @param b The second log level.
|
|
58
|
+
* @returns A negative number if `a` is less than `b`, a positive number if `a`
|
|
59
|
+
* is greater than `b`, or zero if they are equal.
|
|
60
|
+
* @since 0.8.0
|
|
61
|
+
*/
|
|
62
|
+
function compareLogLevel(a, b) {
|
|
63
|
+
const aIndex = logLevels.indexOf(a);
|
|
64
|
+
if (aIndex < 0) throw new TypeError(`Invalid log level: ${JSON.stringify(a)}.`);
|
|
65
|
+
const bIndex = logLevels.indexOf(b);
|
|
66
|
+
if (bIndex < 0) throw new TypeError(`Invalid log level: ${JSON.stringify(b)}.`);
|
|
67
|
+
return aIndex - bIndex;
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
//#region node_modules/.pnpm/@logtape+logtape@2.1.1/node_modules/@logtape/logtape/dist/logger.js
|
|
71
|
+
/**
|
|
72
|
+
* Symbol to identify lazy values.
|
|
73
|
+
*/
|
|
74
|
+
const lazySymbol = Symbol.for("logtape.lazy");
|
|
75
|
+
const throttlingSummaryRecordSymbol = Symbol.for("LogTape.throttlingSummaryRecord");
|
|
76
|
+
/**
|
|
77
|
+
* Checks if a value is a lazy value.
|
|
78
|
+
*
|
|
79
|
+
* @param value The value to check.
|
|
80
|
+
* @returns `true` if the value is a lazy value, `false` otherwise.
|
|
81
|
+
* @since 2.0.0
|
|
82
|
+
*/
|
|
83
|
+
function isLazy(value) {
|
|
84
|
+
return value != null && typeof value === "object" && lazySymbol in value && value[lazySymbol] === true;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Resolves lazy values in a properties object.
|
|
88
|
+
*
|
|
89
|
+
* @param properties The properties object with potential lazy values.
|
|
90
|
+
* @returns A new object with all lazy values resolved.
|
|
91
|
+
*/
|
|
92
|
+
function resolveProperties(properties) {
|
|
93
|
+
const resolved = {};
|
|
94
|
+
for (const key in properties) {
|
|
95
|
+
const value = properties[key];
|
|
96
|
+
resolved[key] = isLazy(value) ? value.getter() : value;
|
|
97
|
+
}
|
|
98
|
+
const symbolProperties = properties;
|
|
99
|
+
const symbolResolved = resolved;
|
|
100
|
+
if (Object.prototype.propertyIsEnumerable.call(properties, throttlingSummaryRecordSymbol)) {
|
|
101
|
+
const value = symbolProperties[throttlingSummaryRecordSymbol];
|
|
102
|
+
symbolResolved[throttlingSummaryRecordSymbol] = isLazy(value) ? value.getter() : value;
|
|
103
|
+
}
|
|
104
|
+
return resolved;
|
|
105
|
+
}
|
|
106
|
+
function isPromiseObject(value) {
|
|
107
|
+
if (value instanceof Promise) return true;
|
|
108
|
+
return Object.prototype.toString.call(value) === "[object Promise]" && typeof value.then === "function";
|
|
109
|
+
}
|
|
110
|
+
function logStringMessage(logger, level, message, props) {
|
|
111
|
+
if (typeof props !== "function") {
|
|
112
|
+
const properties = props ?? {};
|
|
113
|
+
logger.log(level, message, properties);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (!logger.isEnabledFor(level)) return Promise.resolve();
|
|
117
|
+
const result = props();
|
|
118
|
+
if (isPromiseObject(result)) return Promise.resolve(result).then((resolvedProps) => {
|
|
119
|
+
logger.log(level, message, resolvedProps);
|
|
120
|
+
});
|
|
121
|
+
logger.log(level, message, result);
|
|
122
|
+
}
|
|
123
|
+
function snapshotLogRecordProperties(record) {
|
|
124
|
+
const properties = resolveProperties(record.properties);
|
|
125
|
+
const descriptors = Object.getOwnPropertyDescriptors(record);
|
|
126
|
+
descriptors.properties = {
|
|
127
|
+
value: properties,
|
|
128
|
+
enumerable: true,
|
|
129
|
+
configurable: true
|
|
130
|
+
};
|
|
131
|
+
return Object.defineProperties({}, descriptors);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Get a logger with the given category.
|
|
135
|
+
*
|
|
136
|
+
* ```typescript
|
|
137
|
+
* const logger = getLogger(["my-app"]);
|
|
138
|
+
* ```
|
|
139
|
+
*
|
|
140
|
+
* @param category The category of the logger. It can be a string or an array
|
|
141
|
+
* of strings. If it is a string, it is equivalent to an array
|
|
142
|
+
* with a single element.
|
|
143
|
+
* @returns The logger.
|
|
144
|
+
*/
|
|
145
|
+
function getLogger$1(category = []) {
|
|
146
|
+
return LoggerImpl.getLogger(category);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The symbol for the global root logger.
|
|
150
|
+
*/
|
|
151
|
+
const globalRootLoggerSymbol = Symbol.for("logtape.rootLogger");
|
|
152
|
+
function isMetaLoggerCategory(category) {
|
|
153
|
+
return category.length === 2 && category[0] === "logtape" && category[1] === "meta";
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* A logger implementation. Do not use this directly; use {@link getLogger}
|
|
157
|
+
* instead. This class is exported for testing purposes.
|
|
158
|
+
*/
|
|
159
|
+
var LoggerImpl = class LoggerImpl {
|
|
160
|
+
parent;
|
|
161
|
+
children;
|
|
162
|
+
category;
|
|
163
|
+
sinks;
|
|
164
|
+
parentSinks = "inherit";
|
|
165
|
+
filters;
|
|
166
|
+
lowestLevel = "trace";
|
|
167
|
+
contextLocalStorage;
|
|
168
|
+
static getLogger(category = []) {
|
|
169
|
+
let rootLogger = globalRootLoggerSymbol in globalThis ? globalThis[globalRootLoggerSymbol] ?? null : null;
|
|
170
|
+
if (rootLogger == null) {
|
|
171
|
+
rootLogger = new LoggerImpl(null, []);
|
|
172
|
+
globalThis[globalRootLoggerSymbol] = rootLogger;
|
|
173
|
+
}
|
|
174
|
+
if (typeof category === "string") return rootLogger.getChild(category);
|
|
175
|
+
if (category.length === 0) return rootLogger;
|
|
176
|
+
return rootLogger.getChild(category);
|
|
177
|
+
}
|
|
178
|
+
static getNearestExistingLogger(category) {
|
|
179
|
+
let logger = LoggerImpl.getLogger();
|
|
180
|
+
for (const name of category) {
|
|
181
|
+
const childRef = logger.children[name];
|
|
182
|
+
const child = childRef instanceof LoggerImpl ? childRef : childRef?.deref();
|
|
183
|
+
if (child == null) break;
|
|
184
|
+
logger = child;
|
|
185
|
+
}
|
|
186
|
+
return logger;
|
|
187
|
+
}
|
|
188
|
+
constructor(parent, category) {
|
|
189
|
+
this.parent = parent;
|
|
190
|
+
this.children = {};
|
|
191
|
+
this.category = category;
|
|
192
|
+
this.sinks = [];
|
|
193
|
+
this.filters = [];
|
|
194
|
+
}
|
|
195
|
+
getChild(subcategory) {
|
|
196
|
+
const name = typeof subcategory === "string" ? subcategory : subcategory[0];
|
|
197
|
+
const childRef = this.children[name];
|
|
198
|
+
let child = childRef instanceof LoggerImpl ? childRef : childRef?.deref();
|
|
199
|
+
if (child == null) {
|
|
200
|
+
child = new LoggerImpl(this, [...this.category, name]);
|
|
201
|
+
this.children[name] = "WeakRef" in globalThis ? new WeakRef(child) : child;
|
|
202
|
+
}
|
|
203
|
+
if (typeof subcategory === "string" || subcategory.length === 1) return child;
|
|
204
|
+
return child.getChild(subcategory.slice(1));
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Reset the logger. This removes all sinks and filters from the logger.
|
|
208
|
+
*/
|
|
209
|
+
reset() {
|
|
210
|
+
while (this.sinks.length > 0) this.sinks.shift();
|
|
211
|
+
this.parentSinks = "inherit";
|
|
212
|
+
while (this.filters.length > 0) this.filters.shift();
|
|
213
|
+
this.lowestLevel = "trace";
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Reset the logger and all its descendants. This removes all sinks and
|
|
217
|
+
* filters from the logger and all its descendants.
|
|
218
|
+
*/
|
|
219
|
+
resetDescendants() {
|
|
220
|
+
for (const child of Object.values(this.children)) {
|
|
221
|
+
const logger = child instanceof LoggerImpl ? child : child.deref();
|
|
222
|
+
if (logger != null) logger.resetDescendants();
|
|
223
|
+
}
|
|
224
|
+
this.reset();
|
|
225
|
+
}
|
|
226
|
+
with(properties) {
|
|
227
|
+
return new LoggerCtx(this, { ...properties });
|
|
228
|
+
}
|
|
229
|
+
filter(record) {
|
|
230
|
+
for (const filter of this.filters) if (!filter(record)) return false;
|
|
231
|
+
if (this.filters.length < 1) return this.parent?.filter(record) ?? true;
|
|
232
|
+
return true;
|
|
233
|
+
}
|
|
234
|
+
*getSinks(level) {
|
|
235
|
+
if (this.lowestLevel === null || compareLogLevel(level, this.lowestLevel) < 0) return;
|
|
236
|
+
if (this.parent != null && this.parentSinks === "inherit") for (const sink of this.parent.getSinks(level)) yield sink;
|
|
237
|
+
for (const sink of this.sinks) yield sink;
|
|
238
|
+
}
|
|
239
|
+
isEnabledFor(level) {
|
|
240
|
+
const categoryPrefix = isMetaLoggerCategory(this.category) ? [] : getCategoryPrefix();
|
|
241
|
+
return (categoryPrefix.length > 0 ? LoggerImpl.getNearestExistingLogger([...categoryPrefix, ...this.category]) : this).isEnabledForResolved(level);
|
|
242
|
+
}
|
|
243
|
+
isEnabledForResolved(level) {
|
|
244
|
+
if (this.lowestLevel === null || compareLogLevel(level, this.lowestLevel) < 0) return false;
|
|
245
|
+
for (const _ of this.getSinks(level)) return true;
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
emit(record, bypassSinks) {
|
|
249
|
+
const baseCategory = "category" in record ? record.category : this.category;
|
|
250
|
+
const categoryPrefix = isMetaLoggerCategory(baseCategory) ? [] : getCategoryPrefix();
|
|
251
|
+
const fullCategory = categoryPrefix.length > 0 ? [...categoryPrefix, ...baseCategory] : baseCategory;
|
|
252
|
+
const descriptors = Object.getOwnPropertyDescriptors(record);
|
|
253
|
+
descriptors.category = {
|
|
254
|
+
value: fullCategory,
|
|
255
|
+
enumerable: true,
|
|
256
|
+
configurable: true
|
|
257
|
+
};
|
|
258
|
+
const fullRecord = Object.defineProperties({}, descriptors);
|
|
259
|
+
(categoryPrefix.length > 0 ? LoggerImpl.getNearestExistingLogger(fullCategory) : this).emitResolved(fullRecord, bypassSinks);
|
|
260
|
+
}
|
|
261
|
+
emitResolved(record, bypassSinks) {
|
|
262
|
+
if (this.lowestLevel === null || compareLogLevel(record.level, this.lowestLevel) < 0 || !this.filter(record)) return;
|
|
263
|
+
const sinks = [...this.getSinks(record.level)];
|
|
264
|
+
if (sinks.length < 1) return;
|
|
265
|
+
let snapshot;
|
|
266
|
+
let snapshotFailed = false;
|
|
267
|
+
for (const sink of sinks) {
|
|
268
|
+
if (bypassSinks?.has(sink)) continue;
|
|
269
|
+
try {
|
|
270
|
+
if (snapshot == null && !snapshotFailed) try {
|
|
271
|
+
snapshot = snapshotLogRecordProperties(record);
|
|
272
|
+
} catch {
|
|
273
|
+
snapshotFailed = true;
|
|
274
|
+
snapshot = record;
|
|
275
|
+
}
|
|
276
|
+
sink(snapshot ?? record);
|
|
277
|
+
} catch (error) {
|
|
278
|
+
const bypassSinks2 = new Set(bypassSinks);
|
|
279
|
+
bypassSinks2.add(sink);
|
|
280
|
+
metaLogger.log("fatal", "Failed to emit a log record to sink {sink}: {error}", {
|
|
281
|
+
sink,
|
|
282
|
+
error,
|
|
283
|
+
record
|
|
284
|
+
}, bypassSinks2);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
log(level, rawMessage, properties, bypassSinks) {
|
|
289
|
+
const implicitContext = getImplicitContext();
|
|
290
|
+
let cachedProps = void 0;
|
|
291
|
+
let cachedMessage = void 0;
|
|
292
|
+
const record = typeof properties === "function" ? {
|
|
293
|
+
category: this.category,
|
|
294
|
+
level,
|
|
295
|
+
timestamp: Date.now(),
|
|
296
|
+
get message() {
|
|
297
|
+
if (cachedMessage == null) cachedMessage = parseMessageTemplate(rawMessage, this.properties);
|
|
298
|
+
return cachedMessage;
|
|
299
|
+
},
|
|
300
|
+
rawMessage,
|
|
301
|
+
get properties() {
|
|
302
|
+
if (cachedProps == null) cachedProps = resolveProperties({
|
|
303
|
+
...implicitContext,
|
|
304
|
+
...properties()
|
|
305
|
+
});
|
|
306
|
+
return cachedProps;
|
|
307
|
+
}
|
|
308
|
+
} : {
|
|
309
|
+
category: this.category,
|
|
310
|
+
level,
|
|
311
|
+
timestamp: Date.now(),
|
|
312
|
+
get message() {
|
|
313
|
+
if (cachedMessage == null) cachedMessage = parseMessageTemplate(rawMessage, this.properties);
|
|
314
|
+
return cachedMessage;
|
|
315
|
+
},
|
|
316
|
+
rawMessage,
|
|
317
|
+
get properties() {
|
|
318
|
+
if (cachedProps == null) cachedProps = resolveProperties({
|
|
319
|
+
...implicitContext,
|
|
320
|
+
...properties
|
|
321
|
+
});
|
|
322
|
+
return cachedProps;
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
this.emit(record, bypassSinks);
|
|
326
|
+
}
|
|
327
|
+
logLazily(level, callback, properties = {}) {
|
|
328
|
+
const implicitContext = getImplicitContext();
|
|
329
|
+
let rawMessage = void 0;
|
|
330
|
+
let msg = void 0;
|
|
331
|
+
function realizeMessage() {
|
|
332
|
+
if (msg == null || rawMessage == null) {
|
|
333
|
+
msg = callback((tpl, ...values) => {
|
|
334
|
+
rawMessage = tpl;
|
|
335
|
+
return renderMessage(tpl, values);
|
|
336
|
+
});
|
|
337
|
+
if (rawMessage == null) throw new TypeError("No log record was made.");
|
|
338
|
+
}
|
|
339
|
+
return [msg, rawMessage];
|
|
340
|
+
}
|
|
341
|
+
this.emit({
|
|
342
|
+
category: this.category,
|
|
343
|
+
level,
|
|
344
|
+
get message() {
|
|
345
|
+
return realizeMessage()[0];
|
|
346
|
+
},
|
|
347
|
+
get rawMessage() {
|
|
348
|
+
return realizeMessage()[1];
|
|
349
|
+
},
|
|
350
|
+
timestamp: Date.now(),
|
|
351
|
+
properties: {
|
|
352
|
+
...implicitContext,
|
|
353
|
+
...properties
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
logTemplate(level, messageTemplate, values, properties = {}) {
|
|
358
|
+
const implicitContext = getImplicitContext();
|
|
359
|
+
this.emit({
|
|
360
|
+
category: this.category,
|
|
361
|
+
level,
|
|
362
|
+
message: renderMessage(messageTemplate, values),
|
|
363
|
+
rawMessage: messageTemplate,
|
|
364
|
+
timestamp: Date.now(),
|
|
365
|
+
properties: {
|
|
366
|
+
...implicitContext,
|
|
367
|
+
...properties
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
trace(message, ...values) {
|
|
372
|
+
if (typeof message === "string") return logStringMessage(this, "trace", message, values[0]);
|
|
373
|
+
else if (typeof message === "function") this.logLazily("trace", message);
|
|
374
|
+
else if (!Array.isArray(message)) this.log("trace", "{*}", message);
|
|
375
|
+
else this.logTemplate("trace", message, values);
|
|
376
|
+
}
|
|
377
|
+
debug(message, ...values) {
|
|
378
|
+
if (typeof message === "string") return logStringMessage(this, "debug", message, values[0]);
|
|
379
|
+
else if (typeof message === "function") this.logLazily("debug", message);
|
|
380
|
+
else if (!Array.isArray(message)) this.log("debug", "{*}", message);
|
|
381
|
+
else this.logTemplate("debug", message, values);
|
|
382
|
+
}
|
|
383
|
+
info(message, ...values) {
|
|
384
|
+
if (typeof message === "string") return logStringMessage(this, "info", message, values[0]);
|
|
385
|
+
else if (typeof message === "function") this.logLazily("info", message);
|
|
386
|
+
else if (!Array.isArray(message)) this.log("info", "{*}", message);
|
|
387
|
+
else this.logTemplate("info", message, values);
|
|
388
|
+
}
|
|
389
|
+
logError(level, error, props) {
|
|
390
|
+
if (typeof props !== "function") {
|
|
391
|
+
this.log(level, "{error.message}", {
|
|
392
|
+
...props,
|
|
393
|
+
error
|
|
394
|
+
});
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (!this.isEnabledFor(level)) return Promise.resolve();
|
|
398
|
+
const result = props();
|
|
399
|
+
if (result instanceof Promise) return result.then((resolved) => {
|
|
400
|
+
this.log(level, "{error.message}", {
|
|
401
|
+
...resolved,
|
|
402
|
+
error
|
|
403
|
+
});
|
|
404
|
+
});
|
|
405
|
+
this.log(level, "{error.message}", {
|
|
406
|
+
...result,
|
|
407
|
+
error
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
warn(message, ...values) {
|
|
411
|
+
if (message instanceof Error) return this.logError("warning", message, values[0]);
|
|
412
|
+
else if (typeof message === "string" && values[0] instanceof Error) this.log("warning", message, { error: values[0] });
|
|
413
|
+
else if (typeof message === "string") return logStringMessage(this, "warning", message, values[0]);
|
|
414
|
+
else if (typeof message === "function") this.logLazily("warning", message);
|
|
415
|
+
else if (!Array.isArray(message)) this.log("warning", "{*}", message);
|
|
416
|
+
else this.logTemplate("warning", message, values);
|
|
417
|
+
}
|
|
418
|
+
warning(message, ...values) {
|
|
419
|
+
if (message instanceof Error) return this.logError("warning", message, values[0]);
|
|
420
|
+
else if (typeof message === "string" && values[0] instanceof Error) this.log("warning", message, { error: values[0] });
|
|
421
|
+
else if (typeof message === "string") return logStringMessage(this, "warning", message, values[0]);
|
|
422
|
+
else if (typeof message === "function") this.logLazily("warning", message);
|
|
423
|
+
else if (!Array.isArray(message)) this.log("warning", "{*}", message);
|
|
424
|
+
else this.logTemplate("warning", message, values);
|
|
425
|
+
}
|
|
426
|
+
error(message, ...values) {
|
|
427
|
+
if (message instanceof Error) return this.logError("error", message, values[0]);
|
|
428
|
+
else if (typeof message === "string" && values[0] instanceof Error) this.log("error", message, { error: values[0] });
|
|
429
|
+
else if (typeof message === "string") return logStringMessage(this, "error", message, values[0]);
|
|
430
|
+
else if (typeof message === "function") this.logLazily("error", message);
|
|
431
|
+
else if (!Array.isArray(message)) this.log("error", "{*}", message);
|
|
432
|
+
else this.logTemplate("error", message, values);
|
|
433
|
+
}
|
|
434
|
+
fatal(message, ...values) {
|
|
435
|
+
if (message instanceof Error) return this.logError("fatal", message, values[0]);
|
|
436
|
+
else if (typeof message === "string" && values[0] instanceof Error) this.log("fatal", message, { error: values[0] });
|
|
437
|
+
else if (typeof message === "string") return logStringMessage(this, "fatal", message, values[0]);
|
|
438
|
+
else if (typeof message === "function") this.logLazily("fatal", message);
|
|
439
|
+
else if (!Array.isArray(message)) this.log("fatal", "{*}", message);
|
|
440
|
+
else this.logTemplate("fatal", message, values);
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
/**
|
|
444
|
+
* A logger implementation with contextual properties. Do not use this
|
|
445
|
+
* directly; use {@link Logger.with} instead. This class is exported
|
|
446
|
+
* for testing purposes.
|
|
447
|
+
*/
|
|
448
|
+
var LoggerCtx = class LoggerCtx {
|
|
449
|
+
logger;
|
|
450
|
+
properties;
|
|
451
|
+
constructor(logger, properties) {
|
|
452
|
+
this.logger = logger;
|
|
453
|
+
this.properties = properties;
|
|
454
|
+
}
|
|
455
|
+
get category() {
|
|
456
|
+
return this.logger.category;
|
|
457
|
+
}
|
|
458
|
+
get parent() {
|
|
459
|
+
return this.logger.parent;
|
|
460
|
+
}
|
|
461
|
+
getChild(subcategory) {
|
|
462
|
+
return this.logger.getChild(subcategory).with(this.properties);
|
|
463
|
+
}
|
|
464
|
+
with(properties) {
|
|
465
|
+
return new LoggerCtx(this.logger, {
|
|
466
|
+
...this.properties,
|
|
467
|
+
...properties
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
log(level, message, properties, bypassSinks) {
|
|
471
|
+
const contextProps = this.properties;
|
|
472
|
+
this.logger.log(level, message, typeof properties === "function" ? () => resolveProperties({
|
|
473
|
+
...contextProps,
|
|
474
|
+
...properties()
|
|
475
|
+
}) : () => resolveProperties({
|
|
476
|
+
...contextProps,
|
|
477
|
+
...properties
|
|
478
|
+
}), bypassSinks);
|
|
479
|
+
}
|
|
480
|
+
logLazily(level, callback) {
|
|
481
|
+
this.logger.logLazily(level, callback, resolveProperties(this.properties));
|
|
482
|
+
}
|
|
483
|
+
logTemplate(level, messageTemplate, values) {
|
|
484
|
+
this.logger.logTemplate(level, messageTemplate, values, resolveProperties(this.properties));
|
|
485
|
+
}
|
|
486
|
+
emit(record) {
|
|
487
|
+
const recordWithContext = {
|
|
488
|
+
...record,
|
|
489
|
+
properties: resolveProperties({
|
|
490
|
+
...this.properties,
|
|
491
|
+
...record.properties
|
|
492
|
+
})
|
|
493
|
+
};
|
|
494
|
+
this.logger.emit(recordWithContext);
|
|
495
|
+
}
|
|
496
|
+
isEnabledFor(level) {
|
|
497
|
+
return this.logger.isEnabledFor(level);
|
|
498
|
+
}
|
|
499
|
+
trace(message, ...values) {
|
|
500
|
+
if (typeof message === "string") return logStringMessage(this, "trace", message, values[0]);
|
|
501
|
+
else if (typeof message === "function") this.logLazily("trace", message);
|
|
502
|
+
else if (!Array.isArray(message)) this.log("trace", "{*}", message);
|
|
503
|
+
else this.logTemplate("trace", message, values);
|
|
504
|
+
}
|
|
505
|
+
debug(message, ...values) {
|
|
506
|
+
if (typeof message === "string") return logStringMessage(this, "debug", message, values[0]);
|
|
507
|
+
else if (typeof message === "function") this.logLazily("debug", message);
|
|
508
|
+
else if (!Array.isArray(message)) this.log("debug", "{*}", message);
|
|
509
|
+
else this.logTemplate("debug", message, values);
|
|
510
|
+
}
|
|
511
|
+
info(message, ...values) {
|
|
512
|
+
if (typeof message === "string") return logStringMessage(this, "info", message, values[0]);
|
|
513
|
+
else if (typeof message === "function") this.logLazily("info", message);
|
|
514
|
+
else if (!Array.isArray(message)) this.log("info", "{*}", message);
|
|
515
|
+
else this.logTemplate("info", message, values);
|
|
516
|
+
}
|
|
517
|
+
logError(level, error, props) {
|
|
518
|
+
if (typeof props !== "function") {
|
|
519
|
+
this.log(level, "{error.message}", {
|
|
520
|
+
...props,
|
|
521
|
+
error
|
|
522
|
+
});
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
if (!this.isEnabledFor(level)) return Promise.resolve();
|
|
526
|
+
const result = props();
|
|
527
|
+
if (result instanceof Promise) return result.then((resolved) => {
|
|
528
|
+
this.log(level, "{error.message}", {
|
|
529
|
+
...resolved,
|
|
530
|
+
error
|
|
531
|
+
});
|
|
532
|
+
});
|
|
533
|
+
this.log(level, "{error.message}", {
|
|
534
|
+
...result,
|
|
535
|
+
error
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
warn(message, ...values) {
|
|
539
|
+
if (message instanceof Error) return this.logError("warning", message, values[0]);
|
|
540
|
+
else if (typeof message === "string" && values[0] instanceof Error) this.log("warning", message, { error: values[0] });
|
|
541
|
+
else if (typeof message === "string") return logStringMessage(this, "warning", message, values[0]);
|
|
542
|
+
else if (typeof message === "function") this.logLazily("warning", message);
|
|
543
|
+
else if (!Array.isArray(message)) this.log("warning", "{*}", message);
|
|
544
|
+
else this.logTemplate("warning", message, values);
|
|
545
|
+
}
|
|
546
|
+
warning(message, ...values) {
|
|
547
|
+
if (message instanceof Error) return this.logError("warning", message, values[0]);
|
|
548
|
+
else if (typeof message === "string" && values[0] instanceof Error) this.log("warning", message, { error: values[0] });
|
|
549
|
+
else if (typeof message === "string") return logStringMessage(this, "warning", message, values[0]);
|
|
550
|
+
else if (typeof message === "function") this.logLazily("warning", message);
|
|
551
|
+
else if (!Array.isArray(message)) this.log("warning", "{*}", message);
|
|
552
|
+
else this.logTemplate("warning", message, values);
|
|
553
|
+
}
|
|
554
|
+
error(message, ...values) {
|
|
555
|
+
if (message instanceof Error) return this.logError("error", message, values[0]);
|
|
556
|
+
else if (typeof message === "string" && values[0] instanceof Error) this.log("error", message, { error: values[0] });
|
|
557
|
+
else if (typeof message === "string") return logStringMessage(this, "error", message, values[0]);
|
|
558
|
+
else if (typeof message === "function") this.logLazily("error", message);
|
|
559
|
+
else if (!Array.isArray(message)) this.log("error", "{*}", message);
|
|
560
|
+
else this.logTemplate("error", message, values);
|
|
561
|
+
}
|
|
562
|
+
fatal(message, ...values) {
|
|
563
|
+
if (message instanceof Error) return this.logError("fatal", message, values[0]);
|
|
564
|
+
else if (typeof message === "string" && values[0] instanceof Error) this.log("fatal", message, { error: values[0] });
|
|
565
|
+
else if (typeof message === "string") return logStringMessage(this, "fatal", message, values[0]);
|
|
566
|
+
else if (typeof message === "function") this.logLazily("fatal", message);
|
|
567
|
+
else if (!Array.isArray(message)) this.log("fatal", "{*}", message);
|
|
568
|
+
else this.logTemplate("fatal", message, values);
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
/**
|
|
572
|
+
* The meta logger. It is a logger with the category `["logtape", "meta"]`.
|
|
573
|
+
*/
|
|
574
|
+
const metaLogger = LoggerImpl.getLogger(["logtape", "meta"]);
|
|
575
|
+
/**
|
|
576
|
+
* Check if a property access key contains nested access patterns.
|
|
577
|
+
* @param key The property key to check.
|
|
578
|
+
* @returns True if the key contains nested access patterns.
|
|
579
|
+
*/
|
|
580
|
+
function isNestedAccess(key) {
|
|
581
|
+
return key.includes(".") || key.includes("[") || key.includes("?.");
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Safely access an own property from an object, blocking prototype pollution.
|
|
585
|
+
*
|
|
586
|
+
* @param obj The object to access the property from.
|
|
587
|
+
* @param key The property key to access.
|
|
588
|
+
* @returns The property value or undefined if not accessible.
|
|
589
|
+
*/
|
|
590
|
+
function getOwnProperty(obj, key) {
|
|
591
|
+
if (key === "__proto__" || key === "prototype" || key === "constructor") return void 0;
|
|
592
|
+
if ((typeof obj === "object" || typeof obj === "function") && obj !== null) return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : void 0;
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* Parse the next segment from a property path string.
|
|
596
|
+
*
|
|
597
|
+
* @param path The full property path string.
|
|
598
|
+
* @param fromIndex The index to start parsing from.
|
|
599
|
+
* @returns The parsed segment and next index, or null if parsing fails.
|
|
600
|
+
*/
|
|
601
|
+
function parseNextSegment(path, fromIndex) {
|
|
602
|
+
const len = path.length;
|
|
603
|
+
let i = fromIndex;
|
|
604
|
+
if (i >= len) return null;
|
|
605
|
+
let segment;
|
|
606
|
+
if (path[i] === "[") {
|
|
607
|
+
i++;
|
|
608
|
+
if (i >= len) return null;
|
|
609
|
+
if (path[i] === "\"" || path[i] === "'") {
|
|
610
|
+
const quote = path[i];
|
|
611
|
+
i++;
|
|
612
|
+
let segmentStr = "";
|
|
613
|
+
while (i < len && path[i] !== quote) if (path[i] === "\\") {
|
|
614
|
+
i++;
|
|
615
|
+
if (i < len) {
|
|
616
|
+
const escapeChar = path[i];
|
|
617
|
+
switch (escapeChar) {
|
|
618
|
+
case "n":
|
|
619
|
+
segmentStr += "\n";
|
|
620
|
+
break;
|
|
621
|
+
case "t":
|
|
622
|
+
segmentStr += " ";
|
|
623
|
+
break;
|
|
624
|
+
case "r":
|
|
625
|
+
segmentStr += "\r";
|
|
626
|
+
break;
|
|
627
|
+
case "b":
|
|
628
|
+
segmentStr += "\b";
|
|
629
|
+
break;
|
|
630
|
+
case "f":
|
|
631
|
+
segmentStr += "\f";
|
|
632
|
+
break;
|
|
633
|
+
case "v":
|
|
634
|
+
segmentStr += "\v";
|
|
635
|
+
break;
|
|
636
|
+
case "0":
|
|
637
|
+
segmentStr += "\0";
|
|
638
|
+
break;
|
|
639
|
+
case "\\":
|
|
640
|
+
segmentStr += "\\";
|
|
641
|
+
break;
|
|
642
|
+
case "\"":
|
|
643
|
+
segmentStr += "\"";
|
|
644
|
+
break;
|
|
645
|
+
case "'":
|
|
646
|
+
segmentStr += "'";
|
|
647
|
+
break;
|
|
648
|
+
case "u":
|
|
649
|
+
if (i + 4 < len) {
|
|
650
|
+
const hex = path.slice(i + 1, i + 5);
|
|
651
|
+
const codePoint = Number.parseInt(hex, 16);
|
|
652
|
+
if (!Number.isNaN(codePoint)) {
|
|
653
|
+
segmentStr += String.fromCharCode(codePoint);
|
|
654
|
+
i += 4;
|
|
655
|
+
} else segmentStr += escapeChar;
|
|
656
|
+
} else segmentStr += escapeChar;
|
|
657
|
+
break;
|
|
658
|
+
default: segmentStr += escapeChar;
|
|
659
|
+
}
|
|
660
|
+
i++;
|
|
661
|
+
}
|
|
662
|
+
} else {
|
|
663
|
+
segmentStr += path[i];
|
|
664
|
+
i++;
|
|
665
|
+
}
|
|
666
|
+
if (i >= len) return null;
|
|
667
|
+
segment = segmentStr;
|
|
668
|
+
i++;
|
|
669
|
+
} else {
|
|
670
|
+
const startIndex = i;
|
|
671
|
+
while (i < len && path[i] !== "]" && path[i] !== "'" && path[i] !== "\"") i++;
|
|
672
|
+
if (i >= len) return null;
|
|
673
|
+
const indexStr = path.slice(startIndex, i);
|
|
674
|
+
if (indexStr.length === 0) return null;
|
|
675
|
+
const indexNum = Number(indexStr);
|
|
676
|
+
segment = Number.isNaN(indexNum) ? indexStr : indexNum;
|
|
677
|
+
}
|
|
678
|
+
while (i < len && path[i] !== "]") i++;
|
|
679
|
+
if (i < len) i++;
|
|
680
|
+
} else {
|
|
681
|
+
const startIndex = i;
|
|
682
|
+
while (i < len && path[i] !== "." && path[i] !== "[" && path[i] !== "?" && path[i] !== "]") i++;
|
|
683
|
+
segment = path.slice(startIndex, i);
|
|
684
|
+
if (segment.length === 0) return null;
|
|
685
|
+
}
|
|
686
|
+
if (i < len && path[i] === ".") i++;
|
|
687
|
+
return {
|
|
688
|
+
segment,
|
|
689
|
+
nextIndex: i
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Access a property or index on an object or array.
|
|
694
|
+
*
|
|
695
|
+
* @param obj The object or array to access.
|
|
696
|
+
* @param segment The property key or array index.
|
|
697
|
+
* @returns The accessed value or undefined if not accessible.
|
|
698
|
+
*/
|
|
699
|
+
function accessProperty(obj, segment) {
|
|
700
|
+
if (typeof segment === "string") return getOwnProperty(obj, segment);
|
|
701
|
+
if (Array.isArray(obj) && segment >= 0 && segment < obj.length) return obj[segment];
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Resolve a nested property path from an object.
|
|
705
|
+
*
|
|
706
|
+
* There are two types of property access patterns:
|
|
707
|
+
* 1. Array/index access: [0] or ["prop"]
|
|
708
|
+
* 2. Property access: prop or prop?.next
|
|
709
|
+
*
|
|
710
|
+
* @param obj The object to traverse.
|
|
711
|
+
* @param path The property path (e.g., "user.name", "users[0].email", "user['full-name']").
|
|
712
|
+
* @returns The resolved value or undefined if path doesn't exist.
|
|
713
|
+
*/
|
|
714
|
+
function resolvePropertyPath(obj, path) {
|
|
715
|
+
if (obj == null) return void 0;
|
|
716
|
+
if (path.length === 0 || path.endsWith(".")) return void 0;
|
|
717
|
+
let current = obj;
|
|
718
|
+
let i = 0;
|
|
719
|
+
const len = path.length;
|
|
720
|
+
while (i < len) {
|
|
721
|
+
if (path.slice(i, i + 2) === "?.") {
|
|
722
|
+
i += 2;
|
|
723
|
+
if (current == null) return void 0;
|
|
724
|
+
} else if (current == null) return void 0;
|
|
725
|
+
const result = parseNextSegment(path, i);
|
|
726
|
+
if (result === null) return void 0;
|
|
727
|
+
const { segment, nextIndex } = result;
|
|
728
|
+
i = nextIndex;
|
|
729
|
+
current = accessProperty(current, segment);
|
|
730
|
+
if (current === void 0) return void 0;
|
|
731
|
+
}
|
|
732
|
+
return current;
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* Parse a message template into a message template array and a values array.
|
|
736
|
+
*
|
|
737
|
+
* Placeholders to be replaced with `values` are indicated by keys in curly braces
|
|
738
|
+
* (e.g., `{value}`). The system supports both simple property access and nested
|
|
739
|
+
* property access patterns:
|
|
740
|
+
*
|
|
741
|
+
* **Simple property access:**
|
|
742
|
+
* ```ts
|
|
743
|
+
* parseMessageTemplate("Hello, {user}!", { user: "foo" })
|
|
744
|
+
* // Returns: ["Hello, ", "foo", "!"]
|
|
745
|
+
* ```
|
|
746
|
+
*
|
|
747
|
+
* **Nested property access (dot notation):**
|
|
748
|
+
* ```ts
|
|
749
|
+
* parseMessageTemplate("Hello, {user.name}!", {
|
|
750
|
+
* user: { name: "foo", email: "foo@example.com" }
|
|
751
|
+
* })
|
|
752
|
+
* // Returns: ["Hello, ", "foo", "!"]
|
|
753
|
+
* ```
|
|
754
|
+
*
|
|
755
|
+
* **Array indexing:**
|
|
756
|
+
* ```ts
|
|
757
|
+
* parseMessageTemplate("First: {users[0]}", {
|
|
758
|
+
* users: ["foo", "bar", "baz"]
|
|
759
|
+
* })
|
|
760
|
+
* // Returns: ["First: ", "foo", ""]
|
|
761
|
+
* ```
|
|
762
|
+
*
|
|
763
|
+
* **Bracket notation for special property names:**
|
|
764
|
+
* ```ts
|
|
765
|
+
* parseMessageTemplate("Name: {user[\"full-name\"]}", {
|
|
766
|
+
* user: { "full-name": "foo bar" }
|
|
767
|
+
* })
|
|
768
|
+
* // Returns: ["Name: ", "foo bar", ""]
|
|
769
|
+
* ```
|
|
770
|
+
*
|
|
771
|
+
* **Optional chaining for safe navigation:**
|
|
772
|
+
* ```ts
|
|
773
|
+
* parseMessageTemplate("Email: {user?.profile?.email}", {
|
|
774
|
+
* user: { name: "foo" }
|
|
775
|
+
* })
|
|
776
|
+
* // Returns: ["Email: ", undefined, ""]
|
|
777
|
+
* ```
|
|
778
|
+
*
|
|
779
|
+
* **Wildcard patterns:**
|
|
780
|
+
* - `{*}` - Replaced with the entire properties object
|
|
781
|
+
* - `{ key-with-whitespace }` - Whitespace is trimmed when looking up keys
|
|
782
|
+
*
|
|
783
|
+
* **Escaping:**
|
|
784
|
+
* - `{{` and `}}` are escaped literal braces
|
|
785
|
+
*
|
|
786
|
+
* **Error handling:**
|
|
787
|
+
* - Non-existent paths return `undefined`
|
|
788
|
+
* - Malformed expressions resolve to `undefined` without throwing errors
|
|
789
|
+
* - Out of bounds array access returns `undefined`
|
|
790
|
+
*
|
|
791
|
+
* @param template The message template string containing placeholders.
|
|
792
|
+
* @param properties The values to replace placeholders with.
|
|
793
|
+
* @returns The message template array with values interleaved between text segments.
|
|
794
|
+
*/
|
|
795
|
+
function parseMessageTemplate(template, properties) {
|
|
796
|
+
const length = template.length;
|
|
797
|
+
if (length === 0) return [""];
|
|
798
|
+
if (!template.includes("{")) return [template];
|
|
799
|
+
const message = [];
|
|
800
|
+
let startIndex = 0;
|
|
801
|
+
for (let i = 0; i < length; i++) {
|
|
802
|
+
const char = template[i];
|
|
803
|
+
if (char === "{") {
|
|
804
|
+
if ((i + 1 < length ? template[i + 1] : "") === "{") {
|
|
805
|
+
i++;
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
const closeIndex = template.indexOf("}", i + 1);
|
|
809
|
+
if (closeIndex === -1) continue;
|
|
810
|
+
const beforeText = template.slice(startIndex, i);
|
|
811
|
+
message.push(beforeText.replace(/{{/g, "{").replace(/}}/g, "}"));
|
|
812
|
+
const key = template.slice(i + 1, closeIndex);
|
|
813
|
+
let prop;
|
|
814
|
+
const trimmedKey = key.trim();
|
|
815
|
+
if (trimmedKey === "*") prop = key in properties ? properties[key] : "*" in properties ? properties["*"] : properties;
|
|
816
|
+
else {
|
|
817
|
+
if (key !== trimmedKey) prop = key in properties ? properties[key] : properties[trimmedKey];
|
|
818
|
+
else prop = properties[key];
|
|
819
|
+
if (prop === void 0 && isNestedAccess(trimmedKey)) prop = resolvePropertyPath(properties, trimmedKey);
|
|
820
|
+
}
|
|
821
|
+
message.push(prop);
|
|
822
|
+
i = closeIndex;
|
|
823
|
+
startIndex = i + 1;
|
|
824
|
+
} else if (char === "}" && i + 1 < length && template[i + 1] === "}") i++;
|
|
825
|
+
}
|
|
826
|
+
const remainingText = template.slice(startIndex);
|
|
827
|
+
message.push(remainingText.replace(/{{/g, "{").replace(/}}/g, "}"));
|
|
828
|
+
return message;
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Render a message template with values.
|
|
832
|
+
* @param template The message template.
|
|
833
|
+
* @param values The message template values.
|
|
834
|
+
* @returns The message template values interleaved between the substitution
|
|
835
|
+
* values.
|
|
836
|
+
*/
|
|
837
|
+
function renderMessage(template, values) {
|
|
838
|
+
const args = [];
|
|
839
|
+
for (let i = 0; i < template.length; i++) {
|
|
840
|
+
args.push(template[i]);
|
|
841
|
+
if (i < values.length) args.push(values[i]);
|
|
842
|
+
}
|
|
843
|
+
return args;
|
|
844
|
+
}
|
|
845
|
+
//#endregion
|
|
846
|
+
//#region node_modules/.pnpm/@logtape+logtape@2.1.1/node_modules/@logtape/logtape/dist/context.js
|
|
847
|
+
/**
|
|
848
|
+
* Internal symbol for storing category prefix in context.
|
|
849
|
+
*/
|
|
850
|
+
const categoryPrefixSymbol = Symbol.for("logtape.categoryPrefix");
|
|
851
|
+
/**
|
|
852
|
+
* Gets the current category prefix from context local storage.
|
|
853
|
+
* @returns The current category prefix, or an empty array if not set.
|
|
854
|
+
* @since 1.3.0
|
|
855
|
+
*/
|
|
856
|
+
function getCategoryPrefix() {
|
|
857
|
+
const store = LoggerImpl.getLogger().contextLocalStorage?.getStore();
|
|
858
|
+
if (store == null) return [];
|
|
859
|
+
const prefix = store[categoryPrefixSymbol];
|
|
860
|
+
return Array.isArray(prefix) ? prefix : [];
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Gets the current implicit context from context local storage, excluding
|
|
864
|
+
* internal symbol keys (like category prefix).
|
|
865
|
+
* @returns The current implicit context without internal symbol keys.
|
|
866
|
+
* @since 1.3.0
|
|
867
|
+
*/
|
|
868
|
+
function getImplicitContext() {
|
|
869
|
+
const store = LoggerImpl.getLogger().contextLocalStorage?.getStore();
|
|
870
|
+
if (store == null) return {};
|
|
871
|
+
const result = {};
|
|
872
|
+
for (const key of Object.keys(store)) result[key] = store[key];
|
|
873
|
+
return result;
|
|
874
|
+
}
|
|
875
|
+
//#endregion
|
|
876
|
+
//#region node_modules/.pnpm/@logtape+logtape@2.1.1/node_modules/@logtape/logtape/dist/util.js
|
|
877
|
+
var util_exports = /* @__PURE__ */ __exportAll({ inspect: () => inspect$1 });
|
|
878
|
+
function inspect$1(obj, options) {
|
|
879
|
+
const indent = options?.compact === true ? void 0 : 2;
|
|
880
|
+
return JSON.stringify(obj, null, indent);
|
|
881
|
+
}
|
|
882
|
+
//#endregion
|
|
883
|
+
//#region node_modules/.pnpm/@logtape+logtape@2.1.1/node_modules/@logtape/logtape/dist/formatter.js
|
|
884
|
+
/**
|
|
885
|
+
* The severity level abbreviations.
|
|
886
|
+
*/
|
|
887
|
+
const levelAbbreviations = {
|
|
888
|
+
"trace": "TRC",
|
|
889
|
+
"debug": "DBG",
|
|
890
|
+
"info": "INF",
|
|
891
|
+
"warning": "WRN",
|
|
892
|
+
"error": "ERR",
|
|
893
|
+
"fatal": "FTL"
|
|
894
|
+
};
|
|
895
|
+
/**
|
|
896
|
+
* A platform-specific inspect function. In Deno, this is {@link Deno.inspect},
|
|
897
|
+
* and in Node.js/Bun it is `util.inspect()`. If neither is available, it
|
|
898
|
+
* falls back to {@link JSON.stringify}.
|
|
899
|
+
*
|
|
900
|
+
* @param value The value to inspect.
|
|
901
|
+
* @param options The options for inspecting the value.
|
|
902
|
+
* If `colors` is `true`, the output will be ANSI-colored.
|
|
903
|
+
* @returns The string representation of the value.
|
|
904
|
+
*/
|
|
905
|
+
const platformInspect = typeof document !== "undefined" || typeof navigator !== "undefined" && navigator.product === "ReactNative" ? (v) => JSON.stringify(v) : "Deno" in globalThis && "inspect" in globalThis.Deno && typeof globalThis.Deno.inspect === "function" ? (v, opts) => globalThis.Deno.inspect(v, {
|
|
906
|
+
strAbbreviateSize: Infinity,
|
|
907
|
+
iterableLimit: Infinity,
|
|
908
|
+
...opts
|
|
909
|
+
}) : util_exports != null && "inspect" in util_exports && typeof inspect$1 === "function" ? (v, opts) => inspect$1(v, {
|
|
910
|
+
maxArrayLength: Infinity,
|
|
911
|
+
maxStringLength: Infinity,
|
|
912
|
+
...opts
|
|
913
|
+
}) : (v) => JSON.stringify(v);
|
|
914
|
+
const inspect = (value, options) => String(platformInspect(value, options));
|
|
915
|
+
const utf8Encoder = new TextEncoder();
|
|
916
|
+
function renderMessageParts(msgParts, valueRenderer) {
|
|
917
|
+
const msgLen = msgParts.length;
|
|
918
|
+
if (msgLen === 1) return msgParts[0];
|
|
919
|
+
if (msgLen <= 6) {
|
|
920
|
+
let message = "";
|
|
921
|
+
for (let i = 0; i < msgLen; i++) message += i % 2 === 0 ? msgParts[i] : valueRenderer(msgParts[i]);
|
|
922
|
+
return message;
|
|
923
|
+
}
|
|
924
|
+
const parts = new Array(msgLen);
|
|
925
|
+
for (let i = 0; i < msgLen; i++) parts[i] = i % 2 === 0 ? msgParts[i] : valueRenderer(msgParts[i]);
|
|
926
|
+
return parts.join("");
|
|
927
|
+
}
|
|
928
|
+
function padZero(num) {
|
|
929
|
+
return num < 10 ? `0${num}` : `${num}`;
|
|
930
|
+
}
|
|
931
|
+
function padThree(num) {
|
|
932
|
+
return num < 10 ? `00${num}` : num < 100 ? `0${num}` : `${num}`;
|
|
933
|
+
}
|
|
934
|
+
const fixedOffsetPattern = /^([+-])(0\d|1\d|2[0-3]):([0-5]\d)$/;
|
|
935
|
+
function formatOffset(minutes, full) {
|
|
936
|
+
const sign = minutes < 0 ? "-" : "+";
|
|
937
|
+
const absolute = Math.abs(minutes);
|
|
938
|
+
const hour = padZero(Math.floor(absolute / 60));
|
|
939
|
+
const minute = padZero(absolute % 60);
|
|
940
|
+
if (!full && minute === "00") return `${sign}${hour}`;
|
|
941
|
+
return `${sign}${hour}:${minute}`;
|
|
942
|
+
}
|
|
943
|
+
function readPartsFromFormatter(formatter, ts) {
|
|
944
|
+
const parts = formatter.formatToParts(new Date(ts));
|
|
945
|
+
let year = "";
|
|
946
|
+
let month = "";
|
|
947
|
+
let day = "";
|
|
948
|
+
let hour = "";
|
|
949
|
+
let minute = "";
|
|
950
|
+
let second = "";
|
|
951
|
+
for (const part of parts) if (part.type === "year") year = part.value;
|
|
952
|
+
else if (part.type === "month") month = part.value;
|
|
953
|
+
else if (part.type === "day") day = part.value;
|
|
954
|
+
else if (part.type === "hour") hour = part.value;
|
|
955
|
+
else if (part.type === "minute") minute = part.value;
|
|
956
|
+
else if (part.type === "second") second = part.value;
|
|
957
|
+
return {
|
|
958
|
+
year,
|
|
959
|
+
month,
|
|
960
|
+
day,
|
|
961
|
+
hour,
|
|
962
|
+
minute,
|
|
963
|
+
second
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
function getDateParts(ts, config) {
|
|
967
|
+
const d = new Date(ts);
|
|
968
|
+
const ms = padThree(d.getUTCMilliseconds());
|
|
969
|
+
if (config.kind === "utc") return {
|
|
970
|
+
year: `${d.getUTCFullYear()}`,
|
|
971
|
+
month: padZero(d.getUTCMonth() + 1),
|
|
972
|
+
day: padZero(d.getUTCDate()),
|
|
973
|
+
hour: padZero(d.getUTCHours()),
|
|
974
|
+
minute: padZero(d.getUTCMinutes()),
|
|
975
|
+
second: padZero(d.getUTCSeconds()),
|
|
976
|
+
ms,
|
|
977
|
+
offsetMinutes: 0
|
|
978
|
+
};
|
|
979
|
+
if (config.kind === "local") return {
|
|
980
|
+
year: `${d.getFullYear()}`,
|
|
981
|
+
month: padZero(d.getMonth() + 1),
|
|
982
|
+
day: padZero(d.getDate()),
|
|
983
|
+
hour: padZero(d.getHours()),
|
|
984
|
+
minute: padZero(d.getMinutes()),
|
|
985
|
+
second: padZero(d.getSeconds()),
|
|
986
|
+
ms,
|
|
987
|
+
offsetMinutes: -d.getTimezoneOffset()
|
|
988
|
+
};
|
|
989
|
+
if (config.kind === "offset") {
|
|
990
|
+
const shifted = new Date(ts + config.minutes * 6e4);
|
|
991
|
+
return {
|
|
992
|
+
year: `${shifted.getUTCFullYear()}`,
|
|
993
|
+
month: padZero(shifted.getUTCMonth() + 1),
|
|
994
|
+
day: padZero(shifted.getUTCDate()),
|
|
995
|
+
hour: padZero(shifted.getUTCHours()),
|
|
996
|
+
minute: padZero(shifted.getUTCMinutes()),
|
|
997
|
+
second: padZero(shifted.getUTCSeconds()),
|
|
998
|
+
ms,
|
|
999
|
+
offsetMinutes: config.minutes
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
const parts = readPartsFromFormatter(config.formatter, ts);
|
|
1003
|
+
const asUtc = Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), Number(parts.hour), Number(parts.minute), Number(parts.second), d.getUTCMilliseconds());
|
|
1004
|
+
const offsetMinutes = Math.round((asUtc - ts) / 6e4);
|
|
1005
|
+
return {
|
|
1006
|
+
...parts,
|
|
1007
|
+
ms,
|
|
1008
|
+
offsetMinutes
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
function resolveTimeZone(timeZone) {
|
|
1012
|
+
if (typeof timeZone === "undefined") return { kind: "utc" };
|
|
1013
|
+
if (timeZone === null) return { kind: "local" };
|
|
1014
|
+
const offsetMatch = fixedOffsetPattern.exec(timeZone);
|
|
1015
|
+
if (offsetMatch != null) {
|
|
1016
|
+
const sign = offsetMatch[1] === "-" ? -1 : 1;
|
|
1017
|
+
const hours = Number(offsetMatch[2]);
|
|
1018
|
+
const minutes = Number(offsetMatch[3]);
|
|
1019
|
+
return {
|
|
1020
|
+
kind: "offset",
|
|
1021
|
+
minutes: sign * (hours * 60 + minutes)
|
|
1022
|
+
};
|
|
1023
|
+
}
|
|
1024
|
+
if (typeof Intl === "undefined" || typeof Intl.DateTimeFormat !== "function") throw new TypeError(`Invalid timeZone option: ${JSON.stringify(timeZone)}. This environment does not support IANA time zones.`);
|
|
1025
|
+
try {
|
|
1026
|
+
return {
|
|
1027
|
+
kind: "iana",
|
|
1028
|
+
formatter: new Intl.DateTimeFormat("en-CA", {
|
|
1029
|
+
timeZone,
|
|
1030
|
+
hour12: false,
|
|
1031
|
+
hourCycle: "h23",
|
|
1032
|
+
year: "numeric",
|
|
1033
|
+
month: "2-digit",
|
|
1034
|
+
day: "2-digit",
|
|
1035
|
+
hour: "2-digit",
|
|
1036
|
+
minute: "2-digit",
|
|
1037
|
+
second: "2-digit"
|
|
1038
|
+
})
|
|
1039
|
+
};
|
|
1040
|
+
} catch {
|
|
1041
|
+
throw new TypeError(`Invalid timeZone option: ${JSON.stringify(timeZone)}. Expected an IANA time zone name (e.g., "Asia/Seoul") or a fixed UTC offset string (e.g., "+09:00").`);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
function createTimestampFormatter(pattern, timeZone) {
|
|
1045
|
+
if (pattern === "none") return () => null;
|
|
1046
|
+
if (pattern === "rfc3339" && timeZone.kind === "utc") return (ts) => new Date(ts).toISOString();
|
|
1047
|
+
return (ts) => {
|
|
1048
|
+
const parts = getDateParts(ts, timeZone);
|
|
1049
|
+
const date = `${parts.year}-${parts.month}-${parts.day}`;
|
|
1050
|
+
const time = `${parts.hour}:${parts.minute}:${parts.second}.${parts.ms}`;
|
|
1051
|
+
const tzLong = formatOffset(parts.offsetMinutes, true);
|
|
1052
|
+
const tzShort = formatOffset(parts.offsetMinutes, false);
|
|
1053
|
+
if (pattern === "date-time-timezone") return `${date} ${time} ${tzLong}`;
|
|
1054
|
+
if (pattern === "date-time-tz") return `${date} ${time} ${tzShort}`;
|
|
1055
|
+
if (pattern === "date-time") return `${date} ${time}`;
|
|
1056
|
+
if (pattern === "time-timezone") return `${time} ${tzLong}`;
|
|
1057
|
+
if (pattern === "time-tz") return `${time} ${tzShort}`;
|
|
1058
|
+
if (pattern === "time") return time;
|
|
1059
|
+
if (pattern === "date") return date;
|
|
1060
|
+
return `${date}T${time}${tzLong}`;
|
|
1061
|
+
};
|
|
1062
|
+
}
|
|
1063
|
+
const levelRenderersCache = {
|
|
1064
|
+
ABBR: levelAbbreviations,
|
|
1065
|
+
abbr: {
|
|
1066
|
+
trace: "trc",
|
|
1067
|
+
debug: "dbg",
|
|
1068
|
+
info: "inf",
|
|
1069
|
+
warning: "wrn",
|
|
1070
|
+
error: "err",
|
|
1071
|
+
fatal: "ftl"
|
|
1072
|
+
},
|
|
1073
|
+
FULL: {
|
|
1074
|
+
trace: "TRACE",
|
|
1075
|
+
debug: "DEBUG",
|
|
1076
|
+
info: "INFO",
|
|
1077
|
+
warning: "WARNING",
|
|
1078
|
+
error: "ERROR",
|
|
1079
|
+
fatal: "FATAL"
|
|
1080
|
+
},
|
|
1081
|
+
full: {
|
|
1082
|
+
trace: "trace",
|
|
1083
|
+
debug: "debug",
|
|
1084
|
+
info: "info",
|
|
1085
|
+
warning: "warning",
|
|
1086
|
+
error: "error",
|
|
1087
|
+
fatal: "fatal"
|
|
1088
|
+
},
|
|
1089
|
+
L: {
|
|
1090
|
+
trace: "T",
|
|
1091
|
+
debug: "D",
|
|
1092
|
+
info: "I",
|
|
1093
|
+
warning: "W",
|
|
1094
|
+
error: "E",
|
|
1095
|
+
fatal: "F"
|
|
1096
|
+
},
|
|
1097
|
+
l: {
|
|
1098
|
+
trace: "t",
|
|
1099
|
+
debug: "d",
|
|
1100
|
+
info: "i",
|
|
1101
|
+
warning: "w",
|
|
1102
|
+
error: "e",
|
|
1103
|
+
fatal: "f"
|
|
1104
|
+
}
|
|
1105
|
+
};
|
|
1106
|
+
/**
|
|
1107
|
+
* Helper function to get the line ending value based on the option.
|
|
1108
|
+
* @param lineEnding The line ending option.
|
|
1109
|
+
* @returns The line ending string.
|
|
1110
|
+
*/
|
|
1111
|
+
function getLineEndingValue(lineEnding) {
|
|
1112
|
+
return lineEnding === "crlf" ? "\r\n" : "\n";
|
|
1113
|
+
}
|
|
1114
|
+
function jsonReplacer(_key, value) {
|
|
1115
|
+
if (!(value instanceof Error)) return value;
|
|
1116
|
+
const serialized = {
|
|
1117
|
+
name: value.name,
|
|
1118
|
+
message: value.message
|
|
1119
|
+
};
|
|
1120
|
+
if (typeof value.stack === "string") serialized.stack = value.stack;
|
|
1121
|
+
const cause = value.cause;
|
|
1122
|
+
if (cause !== void 0) serialized.cause = cause;
|
|
1123
|
+
if (typeof AggregateError !== "undefined" && value instanceof AggregateError) serialized.errors = value.errors;
|
|
1124
|
+
for (const key of Object.keys(value)) if (!(key in serialized)) serialized[key] = value[key];
|
|
1125
|
+
return serialized;
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Get a text formatter with the specified options. Although it's flexible
|
|
1129
|
+
* enough to create a custom formatter, if you want more control, you can
|
|
1130
|
+
* create a custom formatter that satisfies the {@link TextFormatter} type
|
|
1131
|
+
* instead.
|
|
1132
|
+
*
|
|
1133
|
+
* For more information on the options, see {@link TextFormatterOptions}.
|
|
1134
|
+
*
|
|
1135
|
+
* By default, the formatter formats log records as follows:
|
|
1136
|
+
*
|
|
1137
|
+
* ```
|
|
1138
|
+
* 2023-11-14 22:13:20.000 +00:00 [INF] category·subcategory: Hello, world!
|
|
1139
|
+
* ```
|
|
1140
|
+
* @param options The options for the text formatter.
|
|
1141
|
+
* @returns The text formatter.
|
|
1142
|
+
* @since 0.6.0
|
|
1143
|
+
*/
|
|
1144
|
+
function getTextFormatter(options = {}) {
|
|
1145
|
+
const timestampRenderer = (() => {
|
|
1146
|
+
const tsOption = options.timestamp;
|
|
1147
|
+
const timeZone = resolveTimeZone(options.timeZone);
|
|
1148
|
+
if (tsOption == null) return createTimestampFormatter("date-time-timezone", timeZone);
|
|
1149
|
+
else if (tsOption === "disabled") return createTimestampFormatter("none", timeZone);
|
|
1150
|
+
else if (typeof tsOption === "string" && (tsOption === "date-time-timezone" || tsOption === "date-time-tz" || tsOption === "date-time" || tsOption === "time-timezone" || tsOption === "time-tz" || tsOption === "time" || tsOption === "date" || tsOption === "rfc3339" || tsOption === "none")) return createTimestampFormatter(tsOption, timeZone);
|
|
1151
|
+
else return tsOption;
|
|
1152
|
+
})();
|
|
1153
|
+
const categorySeparator = options.category ?? "·";
|
|
1154
|
+
const valueRenderer = options.value ? (v) => options.value(v, inspect) : inspect;
|
|
1155
|
+
const levelRenderer = (() => {
|
|
1156
|
+
const levelOption = options.level;
|
|
1157
|
+
if (levelOption == null || levelOption === "ABBR") return (level) => levelRenderersCache.ABBR[level];
|
|
1158
|
+
else if (levelOption === "abbr") return (level) => levelRenderersCache.abbr[level];
|
|
1159
|
+
else if (levelOption === "FULL") return (level) => levelRenderersCache.FULL[level];
|
|
1160
|
+
else if (levelOption === "full") return (level) => levelRenderersCache.full[level];
|
|
1161
|
+
else if (levelOption === "L") return (level) => levelRenderersCache.L[level];
|
|
1162
|
+
else if (levelOption === "l") return (level) => levelRenderersCache.l[level];
|
|
1163
|
+
else return levelOption;
|
|
1164
|
+
})();
|
|
1165
|
+
const lineEnding = getLineEndingValue(options.lineEnding);
|
|
1166
|
+
const formatter = options.format ?? (({ timestamp, level, category, message }) => `${timestamp ? `${timestamp} ` : ""}[${level}] ${category}: ${message}`);
|
|
1167
|
+
return (record) => {
|
|
1168
|
+
const message = renderMessageParts(record.message, valueRenderer);
|
|
1169
|
+
return `${formatter({
|
|
1170
|
+
timestamp: timestampRenderer(record.timestamp),
|
|
1171
|
+
level: levelRenderer(record.level),
|
|
1172
|
+
category: typeof categorySeparator === "function" ? categorySeparator(record.category) : record.category.join(categorySeparator),
|
|
1173
|
+
message,
|
|
1174
|
+
record
|
|
1175
|
+
})}${lineEnding}`;
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
getTextFormatter();
|
|
1179
|
+
const RESET = "\x1B[0m";
|
|
1180
|
+
const ansiColors = {
|
|
1181
|
+
black: "\x1B[30m",
|
|
1182
|
+
red: "\x1B[31m",
|
|
1183
|
+
green: "\x1B[32m",
|
|
1184
|
+
yellow: "\x1B[33m",
|
|
1185
|
+
blue: "\x1B[34m",
|
|
1186
|
+
magenta: "\x1B[35m",
|
|
1187
|
+
cyan: "\x1B[36m",
|
|
1188
|
+
white: "\x1B[37m"
|
|
1189
|
+
};
|
|
1190
|
+
const ansiStyles = {
|
|
1191
|
+
bold: "\x1B[1m",
|
|
1192
|
+
dim: "\x1B[2m",
|
|
1193
|
+
italic: "\x1B[3m",
|
|
1194
|
+
underline: "\x1B[4m",
|
|
1195
|
+
strikethrough: "\x1B[9m"
|
|
1196
|
+
};
|
|
1197
|
+
const defaultLevelColors = {
|
|
1198
|
+
trace: null,
|
|
1199
|
+
debug: "blue",
|
|
1200
|
+
info: "green",
|
|
1201
|
+
warning: "yellow",
|
|
1202
|
+
error: "red",
|
|
1203
|
+
fatal: "magenta"
|
|
1204
|
+
};
|
|
1205
|
+
/**
|
|
1206
|
+
* Get an ANSI color formatter with the specified options.
|
|
1207
|
+
*
|
|
1208
|
+
* 
|
|
1209
|
+
* @param option The options for the ANSI color formatter.
|
|
1210
|
+
* @returns The ANSI color formatter.
|
|
1211
|
+
* @since 0.6.0
|
|
1212
|
+
*/
|
|
1213
|
+
function getAnsiColorFormatter(options = {}) {
|
|
1214
|
+
const format = options.format;
|
|
1215
|
+
const timestampStyle = typeof options.timestampStyle === "undefined" ? "dim" : options.timestampStyle;
|
|
1216
|
+
const timestampColor = options.timestampColor ?? null;
|
|
1217
|
+
const timestampPrefix = `${timestampStyle == null ? "" : ansiStyles[timestampStyle]}${timestampColor == null ? "" : ansiColors[timestampColor]}`;
|
|
1218
|
+
const timestampSuffix = timestampStyle == null && timestampColor == null ? "" : RESET;
|
|
1219
|
+
const levelStyle = typeof options.levelStyle === "undefined" ? "bold" : options.levelStyle;
|
|
1220
|
+
const levelColors = options.levelColors ?? defaultLevelColors;
|
|
1221
|
+
const categoryStyle = typeof options.categoryStyle === "undefined" ? "dim" : options.categoryStyle;
|
|
1222
|
+
const categoryColor = options.categoryColor ?? null;
|
|
1223
|
+
const categoryPrefix = `${categoryStyle == null ? "" : ansiStyles[categoryStyle]}${categoryColor == null ? "" : ansiColors[categoryColor]}`;
|
|
1224
|
+
const categorySuffix = categoryStyle == null && categoryColor == null ? "" : RESET;
|
|
1225
|
+
return getTextFormatter({
|
|
1226
|
+
timestamp: "date-time-tz",
|
|
1227
|
+
value(value, fallbackInspect) {
|
|
1228
|
+
return fallbackInspect(value, { colors: true });
|
|
1229
|
+
},
|
|
1230
|
+
...options,
|
|
1231
|
+
format({ timestamp, level, category, message, record }) {
|
|
1232
|
+
const levelColor = levelColors[record.level];
|
|
1233
|
+
timestamp = timestamp == null ? null : `${timestampPrefix}${timestamp}${timestampSuffix}`;
|
|
1234
|
+
level = `${levelStyle == null ? "" : ansiStyles[levelStyle]}${levelColor == null ? "" : ansiColors[levelColor]}${level}${levelStyle == null && levelColor == null ? "" : RESET}`;
|
|
1235
|
+
return format == null ? `${timestamp == null ? "" : `${timestamp} `}${level} ${categoryPrefix}${category}:${categorySuffix} ${message}` : format({
|
|
1236
|
+
timestamp,
|
|
1237
|
+
level,
|
|
1238
|
+
category: `${categoryPrefix}${category}${categorySuffix}`,
|
|
1239
|
+
message,
|
|
1240
|
+
record
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1245
|
+
getAnsiColorFormatter();
|
|
1246
|
+
/**
|
|
1247
|
+
* Get a [JSON Lines] formatter with the specified options. The log records
|
|
1248
|
+
* will be rendered as JSON objects, one per line, which is a common format
|
|
1249
|
+
* for log files. This format is also known as Newline-Delimited JSON (NDJSON).
|
|
1250
|
+
* It looks like this:
|
|
1251
|
+
*
|
|
1252
|
+
* ```json
|
|
1253
|
+
* {"@timestamp":"2023-11-14T22:13:20.000Z","level":"INFO","message":"Hello, world!","logger":"my.logger","properties":{"key":"value"}}
|
|
1254
|
+
* ```
|
|
1255
|
+
*
|
|
1256
|
+
* [JSON Lines]: https://jsonlines.org/
|
|
1257
|
+
* @param options The options for the JSON Lines formatter.
|
|
1258
|
+
* @returns The JSON Lines formatter.
|
|
1259
|
+
* @since 0.11.0
|
|
1260
|
+
*/
|
|
1261
|
+
function getJsonLinesFormatter(options = {}) {
|
|
1262
|
+
const lineEnding = getLineEndingValue(options.lineEnding);
|
|
1263
|
+
if (!options.categorySeparator && !options.message && !options.properties) return (record) => {
|
|
1264
|
+
if (record.message.length === 3) return JSON.stringify({
|
|
1265
|
+
"@timestamp": new Date(record.timestamp).toISOString(),
|
|
1266
|
+
level: record.level === "warning" ? "WARN" : record.level.toUpperCase(),
|
|
1267
|
+
message: record.message[0] + JSON.stringify(record.message[1]) + record.message[2],
|
|
1268
|
+
logger: record.category.join("."),
|
|
1269
|
+
properties: record.properties
|
|
1270
|
+
}, jsonReplacer) + lineEnding;
|
|
1271
|
+
if (record.message.length === 1) return JSON.stringify({
|
|
1272
|
+
"@timestamp": new Date(record.timestamp).toISOString(),
|
|
1273
|
+
level: record.level === "warning" ? "WARN" : record.level.toUpperCase(),
|
|
1274
|
+
message: record.message[0],
|
|
1275
|
+
logger: record.category.join("."),
|
|
1276
|
+
properties: record.properties
|
|
1277
|
+
}, jsonReplacer) + lineEnding;
|
|
1278
|
+
let msg = record.message[0];
|
|
1279
|
+
for (let i = 1; i < record.message.length; i++) msg += i & 1 ? JSON.stringify(record.message[i]) : record.message[i];
|
|
1280
|
+
return JSON.stringify({
|
|
1281
|
+
"@timestamp": new Date(record.timestamp).toISOString(),
|
|
1282
|
+
level: record.level === "warning" ? "WARN" : record.level.toUpperCase(),
|
|
1283
|
+
message: msg,
|
|
1284
|
+
logger: record.category.join("."),
|
|
1285
|
+
properties: record.properties
|
|
1286
|
+
}, jsonReplacer) + lineEnding;
|
|
1287
|
+
};
|
|
1288
|
+
const isTemplateMessage = options.message === "template";
|
|
1289
|
+
const propertiesOption = options.properties ?? "nest:properties";
|
|
1290
|
+
let joinCategory;
|
|
1291
|
+
if (typeof options.categorySeparator === "function") joinCategory = options.categorySeparator;
|
|
1292
|
+
else {
|
|
1293
|
+
const separator = options.categorySeparator ?? ".";
|
|
1294
|
+
joinCategory = (category) => category.join(separator);
|
|
1295
|
+
}
|
|
1296
|
+
let getProperties;
|
|
1297
|
+
if (propertiesOption === "flatten") getProperties = (properties) => properties;
|
|
1298
|
+
else if (propertiesOption.startsWith("prepend:")) {
|
|
1299
|
+
const prefix = propertiesOption.substring(8);
|
|
1300
|
+
if (prefix === "") throw new TypeError(`Invalid properties option: ${JSON.stringify(propertiesOption)}. It must be of the form "prepend:<prefix>" where <prefix> is a non-empty string.`);
|
|
1301
|
+
getProperties = (properties) => {
|
|
1302
|
+
const result = {};
|
|
1303
|
+
for (const key in properties) result[`${prefix}${key}`] = properties[key];
|
|
1304
|
+
return result;
|
|
1305
|
+
};
|
|
1306
|
+
} else if (propertiesOption.startsWith("nest:")) {
|
|
1307
|
+
const key = propertiesOption.substring(5);
|
|
1308
|
+
getProperties = (properties) => ({ [key]: properties });
|
|
1309
|
+
} else throw new TypeError(`Invalid properties option: ${JSON.stringify(propertiesOption)}. It must be "flatten", "prepend:<prefix>", or "nest:<key>".`);
|
|
1310
|
+
let getMessage;
|
|
1311
|
+
if (isTemplateMessage) getMessage = (record) => {
|
|
1312
|
+
if (typeof record.rawMessage === "string") return record.rawMessage;
|
|
1313
|
+
let msg = "";
|
|
1314
|
+
for (let i = 0; i < record.rawMessage.length; i++) {
|
|
1315
|
+
if (i > 0) msg += "{}";
|
|
1316
|
+
msg += record.rawMessage[i];
|
|
1317
|
+
}
|
|
1318
|
+
return msg;
|
|
1319
|
+
};
|
|
1320
|
+
else getMessage = (record) => {
|
|
1321
|
+
const msgLen = record.message.length;
|
|
1322
|
+
if (msgLen === 1) return record.message[0];
|
|
1323
|
+
let msg = "";
|
|
1324
|
+
for (let i = 0; i < msgLen; i++) msg += i % 2 < 1 ? record.message[i] : JSON.stringify(record.message[i]);
|
|
1325
|
+
return msg;
|
|
1326
|
+
};
|
|
1327
|
+
return (record) => {
|
|
1328
|
+
return JSON.stringify({
|
|
1329
|
+
"@timestamp": new Date(record.timestamp).toISOString(),
|
|
1330
|
+
level: record.level === "warning" ? "WARN" : record.level.toUpperCase(),
|
|
1331
|
+
message: getMessage(record),
|
|
1332
|
+
logger: joinCategory(record.category),
|
|
1333
|
+
...getProperties(record.properties)
|
|
1334
|
+
}, jsonReplacer) + lineEnding;
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
getJsonLinesFormatter();
|
|
1338
|
+
function renderStructuredMessage(record, template) {
|
|
1339
|
+
if (template) {
|
|
1340
|
+
if (typeof record.rawMessage === "string") return record.rawMessage;
|
|
1341
|
+
return record.rawMessage.join("{}");
|
|
1342
|
+
}
|
|
1343
|
+
return renderMessageParts(record.message, stringifyLogfmtValue);
|
|
1344
|
+
}
|
|
1345
|
+
function filterLogfmtKey(key) {
|
|
1346
|
+
if (key === "") return null;
|
|
1347
|
+
let needsEscape = false;
|
|
1348
|
+
for (const char of key) if (shouldEscapeLogfmtKeyChar(char, char.codePointAt(0))) {
|
|
1349
|
+
needsEscape = true;
|
|
1350
|
+
break;
|
|
1351
|
+
}
|
|
1352
|
+
if (!needsEscape) return key;
|
|
1353
|
+
let result = "";
|
|
1354
|
+
for (const char of key) if (shouldEscapeLogfmtKeyChar(char, char.codePointAt(0))) result += encodeLogfmtKeyChar(char);
|
|
1355
|
+
else result += char;
|
|
1356
|
+
return result;
|
|
1357
|
+
}
|
|
1358
|
+
function shouldEscapeLogfmtKeyChar(char, code) {
|
|
1359
|
+
return code <= 32 || code === 127 || code === 65533 || char === "=" || char === "\"" || char === "%";
|
|
1360
|
+
}
|
|
1361
|
+
function encodeLogfmtKeyChar(char) {
|
|
1362
|
+
let result = "";
|
|
1363
|
+
for (const byte of utf8Encoder.encode(char)) result += `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
1364
|
+
return result;
|
|
1365
|
+
}
|
|
1366
|
+
function stringifyLogfmtValue(value) {
|
|
1367
|
+
if (typeof value === "string") return value;
|
|
1368
|
+
if (value === null) return "null";
|
|
1369
|
+
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || typeof value === "undefined" || typeof value === "symbol" || typeof value === "function") return String(value);
|
|
1370
|
+
try {
|
|
1371
|
+
const json = JSON.stringify(value, jsonReplacer);
|
|
1372
|
+
if (typeof json === "string") return unwrapJsonStringLiteral(json);
|
|
1373
|
+
} catch {}
|
|
1374
|
+
return inspect(value, { colors: false });
|
|
1375
|
+
}
|
|
1376
|
+
function unwrapJsonStringLiteral(json) {
|
|
1377
|
+
if (json.startsWith("\"") && json.endsWith("\"")) return JSON.parse(json);
|
|
1378
|
+
return json;
|
|
1379
|
+
}
|
|
1380
|
+
function quoteLogfmtValue(value, isString) {
|
|
1381
|
+
let needsQuote = value === "" || isString && shouldQuoteStringLiteral(value);
|
|
1382
|
+
for (const char of value) if (shouldQuoteLogfmtValueChar(char, char.codePointAt(0))) {
|
|
1383
|
+
needsQuote = true;
|
|
1384
|
+
break;
|
|
1385
|
+
}
|
|
1386
|
+
if (!needsQuote) return value;
|
|
1387
|
+
let quoted = "";
|
|
1388
|
+
for (const char of value) {
|
|
1389
|
+
const code = char.codePointAt(0);
|
|
1390
|
+
quoted += escapeLogfmtValueChar(char, code);
|
|
1391
|
+
}
|
|
1392
|
+
return `"${quoted}"`;
|
|
1393
|
+
}
|
|
1394
|
+
function shouldQuoteStringLiteral(value) {
|
|
1395
|
+
return value === "null" || value === "undefined" || value === "true" || value === "false";
|
|
1396
|
+
}
|
|
1397
|
+
function shouldQuoteLogfmtValueChar(char, code) {
|
|
1398
|
+
return code <= 32 || code === 127 || code === 65533 || char === "=" || char === "\"" || char === "\\";
|
|
1399
|
+
}
|
|
1400
|
+
function escapeLogfmtValueChar(char, code) {
|
|
1401
|
+
switch (char) {
|
|
1402
|
+
case " ": return "\\t";
|
|
1403
|
+
case "\n": return "\\n";
|
|
1404
|
+
case "\r": return "\\r";
|
|
1405
|
+
case "\"": return "\\\"";
|
|
1406
|
+
case "\\": return "\\\\";
|
|
1407
|
+
default: return code <= 31 || code === 127 ? `\\u${code.toString(16).padStart(4, "0")}` : char;
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
function formatLogfmtValue(value) {
|
|
1411
|
+
return quoteLogfmtValue(stringifyLogfmtValue(value), typeof value === "string");
|
|
1412
|
+
}
|
|
1413
|
+
function pushLogfmtPair(pairs, key, value) {
|
|
1414
|
+
const filteredKey = filterLogfmtKey(key);
|
|
1415
|
+
if (filteredKey == null) return;
|
|
1416
|
+
pairs.push(`${filteredKey}=${formatLogfmtValue(value)}`);
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* Get a [logfmt] formatter with the specified options. The log records
|
|
1420
|
+
* will be rendered as space-delimited key-value pairs, one record per line.
|
|
1421
|
+
* It looks like this:
|
|
1422
|
+
*
|
|
1423
|
+
* ```text
|
|
1424
|
+
* time=2023-11-14T22:13:20.000Z level=info logger=my.logger msg="Hello, world!" key=value
|
|
1425
|
+
* ```
|
|
1426
|
+
*
|
|
1427
|
+
* [logfmt]: https://brandur.org/logfmt
|
|
1428
|
+
* @param options The options for the logfmt formatter.
|
|
1429
|
+
* @returns The logfmt formatter.
|
|
1430
|
+
* @since 2.1.0
|
|
1431
|
+
*/
|
|
1432
|
+
function getLogfmtFormatter(options = {}) {
|
|
1433
|
+
const prependPrefix = "prepend:";
|
|
1434
|
+
const lineEnding = getLineEndingValue(options.lineEnding);
|
|
1435
|
+
const timestampRenderer = createTimestampFormatter("rfc3339", resolveTimeZone(options.timeZone));
|
|
1436
|
+
const isTemplateMessage = options.message === "template";
|
|
1437
|
+
const propertiesOption = options.properties ?? "flatten";
|
|
1438
|
+
let joinCategory;
|
|
1439
|
+
if (typeof options.categorySeparator === "function") joinCategory = options.categorySeparator;
|
|
1440
|
+
else {
|
|
1441
|
+
const separator = options.categorySeparator ?? ".";
|
|
1442
|
+
joinCategory = (category) => category.join(separator);
|
|
1443
|
+
}
|
|
1444
|
+
let propertyPrefix = "";
|
|
1445
|
+
if (propertiesOption === "flatten") propertyPrefix = "";
|
|
1446
|
+
else if (propertiesOption.startsWith(prependPrefix)) {
|
|
1447
|
+
propertyPrefix = propertiesOption.substring(8);
|
|
1448
|
+
if (propertyPrefix === "") throw new TypeError("Invalid properties option: " + JSON.stringify(propertiesOption) + ". It must be of the form \"prepend:<prefix>\" where <prefix> is a non-empty string.");
|
|
1449
|
+
} else throw new TypeError(`Invalid properties option: ${JSON.stringify(propertiesOption)}. It must be "flatten" or "prepend:<prefix>".`);
|
|
1450
|
+
return (record) => {
|
|
1451
|
+
const pairs = [];
|
|
1452
|
+
pushLogfmtPair(pairs, "time", timestampRenderer(record.timestamp));
|
|
1453
|
+
pushLogfmtPair(pairs, "level", record.level);
|
|
1454
|
+
pushLogfmtPair(pairs, "logger", joinCategory(record.category));
|
|
1455
|
+
pushLogfmtPair(pairs, "msg", renderStructuredMessage(record, isTemplateMessage));
|
|
1456
|
+
for (const key in record.properties) if (Object.prototype.hasOwnProperty.call(record.properties, key)) pushLogfmtPair(pairs, `${propertyPrefix}${key}`, record.properties[key]);
|
|
1457
|
+
return `${pairs.join(" ")}${lineEnding}`;
|
|
1458
|
+
};
|
|
1459
|
+
}
|
|
1460
|
+
getLogfmtFormatter();
|
|
1461
|
+
/**
|
|
1462
|
+
* The styles for the log level in the console.
|
|
1463
|
+
*/
|
|
1464
|
+
const logLevelStyles = {
|
|
1465
|
+
"trace": "background-color: gray; color: white;",
|
|
1466
|
+
"debug": "background-color: gray; color: white;",
|
|
1467
|
+
"info": "background-color: white; color: black;",
|
|
1468
|
+
"warning": "background-color: orange; color: black;",
|
|
1469
|
+
"error": "background-color: red; color: white;",
|
|
1470
|
+
"fatal": "background-color: maroon; color: white;"
|
|
1471
|
+
};
|
|
1472
|
+
/**
|
|
1473
|
+
* The default console formatter.
|
|
1474
|
+
*
|
|
1475
|
+
* @param record The log record to format.
|
|
1476
|
+
* @returns The formatted log record, as an array of arguments for
|
|
1477
|
+
* {@link console.log}.
|
|
1478
|
+
*/
|
|
1479
|
+
function defaultConsoleFormatter(record) {
|
|
1480
|
+
let msg = "";
|
|
1481
|
+
const values = [];
|
|
1482
|
+
for (let i = 0; i < record.message.length; i++) if (i % 2 === 0) msg += record.message[i];
|
|
1483
|
+
else {
|
|
1484
|
+
msg += "%o";
|
|
1485
|
+
values.push(record.message[i]);
|
|
1486
|
+
}
|
|
1487
|
+
const date = new Date(record.timestamp);
|
|
1488
|
+
return [
|
|
1489
|
+
`%c${`${date.getUTCHours().toString().padStart(2, "0")}:${date.getUTCMinutes().toString().padStart(2, "0")}:${date.getUTCSeconds().toString().padStart(2, "0")}.${date.getUTCMilliseconds().toString().padStart(3, "0")}`} %c${levelAbbreviations[record.level]}%c %c${record.category.join("·")} %c${msg}`,
|
|
1490
|
+
"color: gray;",
|
|
1491
|
+
logLevelStyles[record.level],
|
|
1492
|
+
"background-color: default;",
|
|
1493
|
+
"color: gray;",
|
|
1494
|
+
"color: default;",
|
|
1495
|
+
...values
|
|
1496
|
+
];
|
|
1497
|
+
}
|
|
1498
|
+
//#endregion
|
|
1499
|
+
//#region node_modules/.pnpm/@logtape+logtape@2.1.1/node_modules/@logtape/logtape/dist/sink.js
|
|
1500
|
+
/**
|
|
1501
|
+
* A console sink factory that returns a sink that logs to the console.
|
|
1502
|
+
*
|
|
1503
|
+
* @param options The options for the sink.
|
|
1504
|
+
* @returns A sink that logs to the console. If `nonBlocking` is enabled,
|
|
1505
|
+
* returns a sink that also implements {@link Disposable}.
|
|
1506
|
+
*/
|
|
1507
|
+
function getConsoleSink(options = {}) {
|
|
1508
|
+
const formatter = options.formatter ?? defaultConsoleFormatter;
|
|
1509
|
+
const levelMap = {
|
|
1510
|
+
trace: "debug",
|
|
1511
|
+
debug: "debug",
|
|
1512
|
+
info: "info",
|
|
1513
|
+
warning: "warn",
|
|
1514
|
+
error: "error",
|
|
1515
|
+
fatal: "error",
|
|
1516
|
+
...options.levelMap ?? {}
|
|
1517
|
+
};
|
|
1518
|
+
const console = options.console ?? globalThis.console;
|
|
1519
|
+
const baseSink = (record) => {
|
|
1520
|
+
const args = formatter(record);
|
|
1521
|
+
const method = levelMap[record.level];
|
|
1522
|
+
if (method === void 0) throw new TypeError(`Invalid log level: ${record.level}.`);
|
|
1523
|
+
if (typeof args === "string") {
|
|
1524
|
+
const msg = args.replace(/\r?\n$/, "");
|
|
1525
|
+
console[method](msg);
|
|
1526
|
+
} else console[method](...args);
|
|
1527
|
+
};
|
|
1528
|
+
if (!options.nonBlocking) return baseSink;
|
|
1529
|
+
const nonBlockingConfig = options.nonBlocking === true ? {} : options.nonBlocking;
|
|
1530
|
+
const bufferSize = nonBlockingConfig.bufferSize ?? 100;
|
|
1531
|
+
const flushInterval = nonBlockingConfig.flushInterval ?? 100;
|
|
1532
|
+
const buffer = [];
|
|
1533
|
+
let flushTimer = null;
|
|
1534
|
+
let disposed = false;
|
|
1535
|
+
let flushScheduled = false;
|
|
1536
|
+
const maxBufferSize = bufferSize * 2;
|
|
1537
|
+
function flush() {
|
|
1538
|
+
if (buffer.length === 0) return;
|
|
1539
|
+
const records = buffer.splice(0);
|
|
1540
|
+
for (const record of records) try {
|
|
1541
|
+
baseSink(record);
|
|
1542
|
+
} catch {}
|
|
1543
|
+
}
|
|
1544
|
+
function scheduleFlush() {
|
|
1545
|
+
if (flushScheduled) return;
|
|
1546
|
+
flushScheduled = true;
|
|
1547
|
+
setTimeout(() => {
|
|
1548
|
+
flushScheduled = false;
|
|
1549
|
+
flush();
|
|
1550
|
+
}, 0);
|
|
1551
|
+
}
|
|
1552
|
+
function startFlushTimer() {
|
|
1553
|
+
if (flushTimer !== null || disposed) return;
|
|
1554
|
+
flushTimer = setInterval(() => {
|
|
1555
|
+
flush();
|
|
1556
|
+
}, flushInterval);
|
|
1557
|
+
}
|
|
1558
|
+
const nonBlockingSink = (record) => {
|
|
1559
|
+
if (disposed) return;
|
|
1560
|
+
if (buffer.length >= maxBufferSize) buffer.shift();
|
|
1561
|
+
buffer.push(record);
|
|
1562
|
+
if (buffer.length >= bufferSize) scheduleFlush();
|
|
1563
|
+
else if (flushTimer === null) startFlushTimer();
|
|
1564
|
+
};
|
|
1565
|
+
nonBlockingSink[Symbol.dispose] = () => {
|
|
1566
|
+
disposed = true;
|
|
1567
|
+
if (flushTimer !== null) {
|
|
1568
|
+
clearInterval(flushTimer);
|
|
1569
|
+
flushTimer = null;
|
|
1570
|
+
}
|
|
1571
|
+
flush();
|
|
1572
|
+
};
|
|
1573
|
+
return nonBlockingSink;
|
|
1574
|
+
}
|
|
1575
|
+
//#endregion
|
|
1576
|
+
//#region node_modules/.pnpm/@logtape+logtape@2.1.1/node_modules/@logtape/logtape/dist/config.js
|
|
1577
|
+
/**
|
|
1578
|
+
* The current configuration, if any. Otherwise, `null`.
|
|
1579
|
+
*/
|
|
1580
|
+
let currentConfig = null;
|
|
1581
|
+
/**
|
|
1582
|
+
* Strong references to the loggers.
|
|
1583
|
+
* This is to prevent the loggers from being garbage collected so that their
|
|
1584
|
+
* sinks and filters are not removed.
|
|
1585
|
+
*/
|
|
1586
|
+
const strongRefs = /* @__PURE__ */ new Set();
|
|
1587
|
+
/**
|
|
1588
|
+
* Sync filter disposables to dispose when resetting the configuration.
|
|
1589
|
+
*/
|
|
1590
|
+
const filterDisposables = /* @__PURE__ */ new Set();
|
|
1591
|
+
/**
|
|
1592
|
+
* Sync sink disposables to dispose when resetting the configuration.
|
|
1593
|
+
*/
|
|
1594
|
+
const sinkDisposables = /* @__PURE__ */ new Set();
|
|
1595
|
+
/**
|
|
1596
|
+
* Async filter disposables to dispose when resetting the configuration.
|
|
1597
|
+
*/
|
|
1598
|
+
const asyncFilterDisposables = /* @__PURE__ */ new Set();
|
|
1599
|
+
/**
|
|
1600
|
+
* Async sink disposables to dispose when resetting the configuration.
|
|
1601
|
+
*/
|
|
1602
|
+
const asyncSinkDisposables = /* @__PURE__ */ new Set();
|
|
1603
|
+
/**
|
|
1604
|
+
* Check if a config is for the meta logger.
|
|
1605
|
+
*/
|
|
1606
|
+
function isLoggerConfigMeta(cfg) {
|
|
1607
|
+
return cfg.category.length === 0 || cfg.category.length === 1 && cfg.category[0] === "logtape" || cfg.category.length === 2 && cfg.category[0] === "logtape" && cfg.category[1] === "meta";
|
|
1608
|
+
}
|
|
1609
|
+
function registerDisposeHook(allowAsync) {
|
|
1610
|
+
const handler = allowAsync ? dispose : disposeSync;
|
|
1611
|
+
if (typeof globalThis.EdgeRuntime !== "string" && "process" in globalThis && !("Deno" in globalThis)) {
|
|
1612
|
+
const proc = globalThis.process;
|
|
1613
|
+
const onMethod = proc?.["on"];
|
|
1614
|
+
if (typeof onMethod === "function") {
|
|
1615
|
+
onMethod.call(proc, "exit", handler);
|
|
1616
|
+
return;
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
const addEventListenerMethod = globalThis.addEventListener;
|
|
1620
|
+
if (typeof addEventListenerMethod !== "function") return;
|
|
1621
|
+
if ("Deno" in globalThis) addEventListenerMethod.call(globalThis, "unload", handler);
|
|
1622
|
+
else addEventListenerMethod.call(globalThis, "pagehide", handler);
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* Configure the loggers with the specified configuration.
|
|
1626
|
+
*
|
|
1627
|
+
* Note that if the given sinks or filters are disposable, they will be
|
|
1628
|
+
* disposed when the configuration is reset, or when the process exits.
|
|
1629
|
+
*
|
|
1630
|
+
* @example
|
|
1631
|
+
* ```typescript
|
|
1632
|
+
* await configure({
|
|
1633
|
+
* sinks: {
|
|
1634
|
+
* console: getConsoleSink(),
|
|
1635
|
+
* },
|
|
1636
|
+
* filters: {
|
|
1637
|
+
* slow: (log) =>
|
|
1638
|
+
* "duration" in log.properties &&
|
|
1639
|
+
* log.properties.duration as number > 1000,
|
|
1640
|
+
* },
|
|
1641
|
+
* loggers: [
|
|
1642
|
+
* {
|
|
1643
|
+
* category: "my-app",
|
|
1644
|
+
* sinks: ["console"],
|
|
1645
|
+
* lowestLevel: "info",
|
|
1646
|
+
* },
|
|
1647
|
+
* {
|
|
1648
|
+
* category: ["my-app", "sql"],
|
|
1649
|
+
* filters: ["slow"],
|
|
1650
|
+
* lowestLevel: "debug",
|
|
1651
|
+
* },
|
|
1652
|
+
* {
|
|
1653
|
+
* category: "logtape",
|
|
1654
|
+
* sinks: ["console"],
|
|
1655
|
+
* lowestLevel: "error",
|
|
1656
|
+
* },
|
|
1657
|
+
* ],
|
|
1658
|
+
* });
|
|
1659
|
+
* ```
|
|
1660
|
+
*
|
|
1661
|
+
* @param config The configuration.
|
|
1662
|
+
*/
|
|
1663
|
+
async function configure(config) {
|
|
1664
|
+
if (currentConfig != null && !config.reset) throw new ConfigError("Already configured; if you want to reset, turn on the reset flag.");
|
|
1665
|
+
await reset();
|
|
1666
|
+
try {
|
|
1667
|
+
configureInternal(config, true);
|
|
1668
|
+
} catch (e) {
|
|
1669
|
+
if (e instanceof ConfigError) await reset();
|
|
1670
|
+
throw e;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
function configureInternal(config, allowAsync) {
|
|
1674
|
+
currentConfig = config;
|
|
1675
|
+
let metaConfigured = false;
|
|
1676
|
+
const configuredCategories = /* @__PURE__ */ new Set();
|
|
1677
|
+
for (const cfg of config.loggers) {
|
|
1678
|
+
if (isLoggerConfigMeta(cfg)) metaConfigured = true;
|
|
1679
|
+
const categoryKey = Array.isArray(cfg.category) ? JSON.stringify(cfg.category) : JSON.stringify([cfg.category]);
|
|
1680
|
+
if (configuredCategories.has(categoryKey)) throw new ConfigError(`Duplicate logger configuration for category: ${categoryKey}. Each category can only be configured once.`);
|
|
1681
|
+
configuredCategories.add(categoryKey);
|
|
1682
|
+
const logger = LoggerImpl.getLogger(cfg.category);
|
|
1683
|
+
for (const sinkId of cfg.sinks ?? []) {
|
|
1684
|
+
const sink = config.sinks[sinkId];
|
|
1685
|
+
if (!sink) throw new ConfigError(`Sink not found: ${sinkId}.`);
|
|
1686
|
+
logger.sinks.push(sink);
|
|
1687
|
+
}
|
|
1688
|
+
logger.parentSinks = cfg.parentSinks ?? "inherit";
|
|
1689
|
+
if (cfg.lowestLevel !== void 0) logger.lowestLevel = cfg.lowestLevel;
|
|
1690
|
+
for (const filterId of cfg.filters ?? []) {
|
|
1691
|
+
const filter = config.filters?.[filterId];
|
|
1692
|
+
if (filter === void 0) throw new ConfigError(`Filter not found: ${filterId}.`);
|
|
1693
|
+
logger.filters.push(toFilter(filter));
|
|
1694
|
+
}
|
|
1695
|
+
strongRefs.add(logger);
|
|
1696
|
+
}
|
|
1697
|
+
LoggerImpl.getLogger().contextLocalStorage = config.contextLocalStorage;
|
|
1698
|
+
for (const sink of Object.values(config.sinks)) {
|
|
1699
|
+
if (Symbol.asyncDispose in sink) if (allowAsync) asyncSinkDisposables.add(sink);
|
|
1700
|
+
else throw new ConfigError("Async disposables cannot be used with configureSync().");
|
|
1701
|
+
if (Symbol.dispose in sink) sinkDisposables.add(sink);
|
|
1702
|
+
}
|
|
1703
|
+
for (const filter of Object.values(config.filters ?? {})) {
|
|
1704
|
+
if (filter == null || typeof filter === "string") continue;
|
|
1705
|
+
if (Symbol.asyncDispose in filter) {
|
|
1706
|
+
if (allowAsync) asyncFilterDisposables.add(filter);
|
|
1707
|
+
else throw new ConfigError("Async disposables cannot be used with configureSync().");
|
|
1708
|
+
asyncSinkDisposables.delete(filter);
|
|
1709
|
+
}
|
|
1710
|
+
if (Symbol.dispose in filter) {
|
|
1711
|
+
filterDisposables.add(filter);
|
|
1712
|
+
sinkDisposables.delete(filter);
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
registerDisposeHook(allowAsync);
|
|
1716
|
+
const meta = LoggerImpl.getLogger(["logtape", "meta"]);
|
|
1717
|
+
if (!metaConfigured) meta.sinks.push(getConsoleSink());
|
|
1718
|
+
meta.info("LogTape loggers are configured. Note that LogTape itself uses the meta logger, which has category {metaLoggerCategory}. The meta logger is used to log internal diagnostics such as sink exceptions. It's recommended to configure the meta logger with a separate sink so that you can easily notice if logging itself fails or is misconfigured. To turn off this message, configure the meta logger with higher log levels than {dismissLevel}. See also <https://logtape.org/manual/categories#meta-logger>.", {
|
|
1719
|
+
metaLoggerCategory: ["logtape", "meta"],
|
|
1720
|
+
dismissLevel: "info"
|
|
1721
|
+
});
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* Reset the configuration. Mostly for testing purposes.
|
|
1725
|
+
*/
|
|
1726
|
+
async function reset() {
|
|
1727
|
+
await dispose();
|
|
1728
|
+
resetInternal();
|
|
1729
|
+
}
|
|
1730
|
+
function resetInternal() {
|
|
1731
|
+
const rootLogger = LoggerImpl.getLogger([]);
|
|
1732
|
+
rootLogger.resetDescendants();
|
|
1733
|
+
delete rootLogger.contextLocalStorage;
|
|
1734
|
+
strongRefs.clear();
|
|
1735
|
+
currentConfig = null;
|
|
1736
|
+
}
|
|
1737
|
+
/**
|
|
1738
|
+
* Dispose of the disposables.
|
|
1739
|
+
*/
|
|
1740
|
+
async function dispose() {
|
|
1741
|
+
const errors = [];
|
|
1742
|
+
try {
|
|
1743
|
+
disposeSyncFilters();
|
|
1744
|
+
} catch (error) {
|
|
1745
|
+
errors.push(error);
|
|
1746
|
+
}
|
|
1747
|
+
try {
|
|
1748
|
+
await disposeAsyncFilters();
|
|
1749
|
+
} catch (error) {
|
|
1750
|
+
errors.push(error);
|
|
1751
|
+
}
|
|
1752
|
+
try {
|
|
1753
|
+
disposeSyncSinks();
|
|
1754
|
+
} catch (error) {
|
|
1755
|
+
errors.push(error);
|
|
1756
|
+
}
|
|
1757
|
+
try {
|
|
1758
|
+
await disposeAsyncSinks();
|
|
1759
|
+
} catch (error) {
|
|
1760
|
+
errors.push(error);
|
|
1761
|
+
}
|
|
1762
|
+
throwDisposeErrors(errors);
|
|
1763
|
+
}
|
|
1764
|
+
/**
|
|
1765
|
+
* Dispose of the sync disposables. Async disposables will be untouched,
|
|
1766
|
+
* use {@link dispose} if you have async sinks.
|
|
1767
|
+
* @since 0.9.0
|
|
1768
|
+
*/
|
|
1769
|
+
function disposeSync() {
|
|
1770
|
+
const errors = [];
|
|
1771
|
+
try {
|
|
1772
|
+
disposeSyncFilters();
|
|
1773
|
+
} catch (error) {
|
|
1774
|
+
errors.push(error);
|
|
1775
|
+
}
|
|
1776
|
+
try {
|
|
1777
|
+
disposeSyncSinks();
|
|
1778
|
+
} catch (error) {
|
|
1779
|
+
errors.push(error);
|
|
1780
|
+
}
|
|
1781
|
+
throwDisposeErrors(errors);
|
|
1782
|
+
}
|
|
1783
|
+
function disposeSyncFilters() {
|
|
1784
|
+
disposeSyncDisposables(filterDisposables);
|
|
1785
|
+
}
|
|
1786
|
+
function disposeSyncSinks() {
|
|
1787
|
+
disposeSyncDisposables(sinkDisposables);
|
|
1788
|
+
}
|
|
1789
|
+
function disposeSyncDisposables(disposables) {
|
|
1790
|
+
const errors = [];
|
|
1791
|
+
try {
|
|
1792
|
+
for (const disposable of disposables) try {
|
|
1793
|
+
disposable[Symbol.dispose]();
|
|
1794
|
+
} catch (error) {
|
|
1795
|
+
errors.push(error);
|
|
1796
|
+
} finally {
|
|
1797
|
+
disposables.delete(disposable);
|
|
1798
|
+
}
|
|
1799
|
+
} finally {
|
|
1800
|
+
disposables.clear();
|
|
1801
|
+
}
|
|
1802
|
+
throwDisposeErrors(errors);
|
|
1803
|
+
}
|
|
1804
|
+
async function disposeAsyncFilters() {
|
|
1805
|
+
await disposeAsyncDisposables(asyncFilterDisposables);
|
|
1806
|
+
}
|
|
1807
|
+
async function disposeAsyncSinks() {
|
|
1808
|
+
await disposeAsyncDisposables(asyncSinkDisposables);
|
|
1809
|
+
}
|
|
1810
|
+
async function disposeAsyncDisposables(disposables) {
|
|
1811
|
+
const promises = [];
|
|
1812
|
+
try {
|
|
1813
|
+
for (const disposable of disposables) try {
|
|
1814
|
+
promises.push(Promise.resolve(disposable[Symbol.asyncDispose]()));
|
|
1815
|
+
} catch (error) {
|
|
1816
|
+
promises.push(Promise.reject(error));
|
|
1817
|
+
} finally {
|
|
1818
|
+
disposables.delete(disposable);
|
|
1819
|
+
}
|
|
1820
|
+
} finally {
|
|
1821
|
+
disposables.clear();
|
|
1822
|
+
}
|
|
1823
|
+
await settleDisposePromises(promises);
|
|
1824
|
+
}
|
|
1825
|
+
async function settleDisposePromises(promises) {
|
|
1826
|
+
throwDisposeErrors((await Promise.allSettled(promises)).filter((result) => result.status === "rejected").map((result) => result.reason));
|
|
1827
|
+
}
|
|
1828
|
+
function throwDisposeErrors(errors) {
|
|
1829
|
+
if (errors.length < 1) return;
|
|
1830
|
+
if (errors.length === 1) throw errors[0];
|
|
1831
|
+
throw new AggregateError(errors, "Multiple errors occurred while disposing LogTape resources.");
|
|
1832
|
+
}
|
|
1833
|
+
/**
|
|
1834
|
+
* A configuration error.
|
|
1835
|
+
*/
|
|
1836
|
+
var ConfigError = class extends Error {
|
|
1837
|
+
/**
|
|
1838
|
+
* Constructs a new configuration error.
|
|
1839
|
+
* @param message The error message.
|
|
1840
|
+
*/
|
|
1841
|
+
constructor(message) {
|
|
1842
|
+
super(message);
|
|
1843
|
+
this.name = "ConfigureError";
|
|
1844
|
+
}
|
|
1845
|
+
};
|
|
1846
|
+
//#endregion
|
|
1847
|
+
//#region packages/server/src/observability/logger.ts
|
|
1848
|
+
/**
|
|
1849
|
+
* LogTape configuration entry point.
|
|
1850
|
+
*
|
|
1851
|
+
* `@logtape/logtape` ships a tiny library-first API: a global
|
|
1852
|
+
* `configure({ sinks, loggers })` and a `getLogger(category)` that
|
|
1853
|
+
* routes to the configured sinks. We expose a small wrapper so the
|
|
1854
|
+
* boot path can hand LogTape the built-in `"console-json"` shortcut
|
|
1855
|
+
* (or any custom `Sink` function — pretty rendering lives in
|
|
1856
|
+
* `@baerly/adapter-node` so picocolors stays off the kernel) and
|
|
1857
|
+
* an env-driven level override.
|
|
1858
|
+
*
|
|
1859
|
+
* The wrapper is intentionally thin: anything LogTape can do
|
|
1860
|
+
* (custom sinks, filters, child loggers via `getChild`) the caller
|
|
1861
|
+
* can do by importing LogTape directly. We add value only on the
|
|
1862
|
+
* defaults + env-shorthand surface.
|
|
1863
|
+
*
|
|
1864
|
+
* ## Categories
|
|
1865
|
+
*
|
|
1866
|
+
* Canonical category names live as constants ({@link CATEGORY}) so
|
|
1867
|
+
* downstream modules in this dispatch (and Dispatch 3+ wiring code)
|
|
1868
|
+
* type-check the string at the call site instead of fat-fingering
|
|
1869
|
+
* `"baerly.htttp"` and silently producing an unrouteable logger.
|
|
1870
|
+
*
|
|
1871
|
+
* ## Levels
|
|
1872
|
+
*
|
|
1873
|
+
* LogTape's canonical name for the warn level is `"warning"`. Our
|
|
1874
|
+
* config surface accepts the shorter `"warn"` because it matches
|
|
1875
|
+
* the rest of the project's vocabulary; we translate at the
|
|
1876
|
+
* configure boundary.
|
|
1877
|
+
*
|
|
1878
|
+
* ## Idempotency
|
|
1879
|
+
*
|
|
1880
|
+
* `configureObservability` is safe to call multiple times. LogTape's
|
|
1881
|
+
* own `configure` will reject re-configuration without `reset: true`;
|
|
1882
|
+
* we always pass `reset: true` so the last call wins and operators
|
|
1883
|
+
* can hot-swap config in dev without restarting.
|
|
1884
|
+
*/
|
|
1885
|
+
/**
|
|
1886
|
+
* Canonical category names. Use these instead of bare strings.
|
|
1887
|
+
*
|
|
1888
|
+
* Each entry is a two-segment array (`["baerly", "<unit>"]`) so
|
|
1889
|
+
* LogTape's hierarchical routing — categories descend by element,
|
|
1890
|
+
* not by string-split — picks up the parent `"baerly"` config we
|
|
1891
|
+
* register in {@link configureObservability}. Passing the dotted
|
|
1892
|
+
* string `"baerly.http"` would create a single-element sibling
|
|
1893
|
+
* category and miss the parent's sink wiring.
|
|
1894
|
+
*/
|
|
1895
|
+
const CATEGORY = {
|
|
1896
|
+
http: ["baerly", "http"],
|
|
1897
|
+
storage: ["baerly", "storage"]
|
|
1898
|
+
};
|
|
1899
|
+
/**
|
|
1900
|
+
* Wire LogTape's global config.
|
|
1901
|
+
*
|
|
1902
|
+
* Idempotent — call as many times as you like. The adapter boot
|
|
1903
|
+
* path calls it once at init; tests call it once per
|
|
1904
|
+
* `beforeEach`.
|
|
1905
|
+
*/
|
|
1906
|
+
const configureObservability = async (config = {}) => {
|
|
1907
|
+
const level = resolveLevel(config.level);
|
|
1908
|
+
await configure({
|
|
1909
|
+
reset: true,
|
|
1910
|
+
sinks: { primary: resolveSink(config.sink) },
|
|
1911
|
+
loggers: [{
|
|
1912
|
+
category: "baerly",
|
|
1913
|
+
sinks: ["primary"],
|
|
1914
|
+
lowestLevel: level
|
|
1915
|
+
}, {
|
|
1916
|
+
category: ["logtape", "meta"],
|
|
1917
|
+
sinks: ["primary"],
|
|
1918
|
+
lowestLevel: "error"
|
|
1919
|
+
}]
|
|
1920
|
+
});
|
|
1921
|
+
};
|
|
1922
|
+
/**
|
|
1923
|
+
* Thin re-export. Identical shape to `@logtape/logtape`'s `getLogger`.
|
|
1924
|
+
* Constants in {@link CATEGORY} are the canonical inputs; bare
|
|
1925
|
+
* strings still work for ad-hoc instrumentation.
|
|
1926
|
+
*/
|
|
1927
|
+
const getLogger = (category) => getLogger$1(category);
|
|
1928
|
+
/** Map our friendly `"warn"` onto LogTape's canonical `"warning"`. */
|
|
1929
|
+
const toLogTapeLevel = (l) => l === "warn" ? "warning" : l;
|
|
1930
|
+
const resolveLevel = (configLevel) => {
|
|
1931
|
+
if (configLevel !== void 0) return toLogTapeLevel(configLevel);
|
|
1932
|
+
const env = readEnv("LOG_LEVEL")?.toLowerCase();
|
|
1933
|
+
if (env === "debug" || env === "info" || env === "error") return env;
|
|
1934
|
+
if (env === "warn" || env === "warning") return "warning";
|
|
1935
|
+
return "info";
|
|
1936
|
+
};
|
|
1937
|
+
const resolveSink = (configSink) => {
|
|
1938
|
+
if (typeof configSink === "function") return configSink;
|
|
1939
|
+
return jsonConsoleSink();
|
|
1940
|
+
};
|
|
1941
|
+
const readEnv = (name) => {
|
|
1942
|
+
return (globalThis.process?.env)?.[name];
|
|
1943
|
+
};
|
|
1944
|
+
/**
|
|
1945
|
+
* Built-in JSON-line sink. Each record becomes one `console.log`
|
|
1946
|
+
* call with a flat object containing `timestamp`, `level`,
|
|
1947
|
+
* `category`, `message`, and the record's `properties`.
|
|
1948
|
+
*/
|
|
1949
|
+
const jsonConsoleSink = () => (record) => {
|
|
1950
|
+
const payload = {
|
|
1951
|
+
timestamp: record.timestamp,
|
|
1952
|
+
level: record.level,
|
|
1953
|
+
category: record.category.join("."),
|
|
1954
|
+
message: record.message.map((m) => typeof m === "string" ? m : JSON.stringify(m)).join(""),
|
|
1955
|
+
...record.properties
|
|
1956
|
+
};
|
|
1957
|
+
console.log(JSON.stringify(payload));
|
|
1958
|
+
};
|
|
1959
|
+
//#endregion
|
|
1960
|
+
//#region packages/server/src/observability/derive-outcome.ts
|
|
1961
|
+
const deriveOutcome = (method, status, error) => {
|
|
1962
|
+
if (error !== void 0 && status >= 500) return "error";
|
|
1963
|
+
if (status < 400) return method === "GET" ? "read" : "committed";
|
|
1964
|
+
if (status === 409) return "conflict";
|
|
1965
|
+
return "error";
|
|
1966
|
+
};
|
|
1967
|
+
//#endregion
|
|
1968
|
+
//#region packages/server/src/observability/canonical.ts
|
|
1969
|
+
/**
|
|
1970
|
+
* Canonical-log-line flusher.
|
|
1971
|
+
*
|
|
1972
|
+
* One HTTP request emits exactly one canonical line at its end. The
|
|
1973
|
+
* line carries: the request id, the duration, the outcome string,
|
|
1974
|
+
* the HTTP status, every entry the per-request
|
|
1975
|
+
* {@link RequestScopedMetricsRecorder} accumulated, every entry the
|
|
1976
|
+
* {@link ObservabilityContext.fields} bag picked up along the way,
|
|
1977
|
+
* and a redacted error structure on the failure path.
|
|
1978
|
+
*
|
|
1979
|
+
* Every HTTP request emits a line; level is computed from
|
|
1980
|
+
* status/error.
|
|
1981
|
+
*
|
|
1982
|
+
* Level mapping at emit time:
|
|
1983
|
+
*
|
|
1984
|
+
* - `error` present → `error`
|
|
1985
|
+
* - `status >= 500` → `error`
|
|
1986
|
+
* - `status >= 400` → `warn`
|
|
1987
|
+
* - otherwise → `info`
|
|
1988
|
+
*/
|
|
1989
|
+
/**
|
|
1990
|
+
* Emit (or suppress) the canonical line for this unit-of-work.
|
|
1991
|
+
*
|
|
1992
|
+
* Idempotent in the sense that the caller is expected to call it
|
|
1993
|
+
* exactly once per unit-of-work. Calling it twice will produce two
|
|
1994
|
+
* lines — there is no internal latch.
|
|
1995
|
+
*/
|
|
1996
|
+
const flushCanonicalLine = (ctx, recorder, opts) => {
|
|
1997
|
+
const level = pickLevel(opts);
|
|
1998
|
+
const properties = buildProperties(ctx, recorder, opts, level);
|
|
1999
|
+
const logger = getLogger(CATEGORY.http);
|
|
2000
|
+
switch (level) {
|
|
2001
|
+
case "error":
|
|
2002
|
+
logger.error("canonical", properties);
|
|
2003
|
+
return;
|
|
2004
|
+
case "warn":
|
|
2005
|
+
logger.warn("canonical", properties);
|
|
2006
|
+
return;
|
|
2007
|
+
case "info":
|
|
2008
|
+
logger.info("canonical", properties);
|
|
2009
|
+
return;
|
|
2010
|
+
}
|
|
2011
|
+
};
|
|
2012
|
+
/**
|
|
2013
|
+
* HTTP unit-of-work scope. Opens an {@link ObservabilityContext} from the
|
|
2014
|
+
* inbound `Request` (request id from `x-request-id` header or generated),
|
|
2015
|
+
* runs `fetch(req)` under {@link runWithContext}, and flushes the canonical
|
|
2016
|
+
* line in finally with `unit: "http"`.
|
|
2017
|
+
*
|
|
2018
|
+
* Production adapters open their own context BEFORE calling
|
|
2019
|
+
* `createRouter().fetch`; this helper is for standalone callers (tests,
|
|
2020
|
+
* one-off harnesses) that want one canonical line per request without
|
|
2021
|
+
* managing the bracket themselves.
|
|
2022
|
+
*
|
|
2023
|
+
* Behaviour mirrors what the legacy `app.use("*", ...)` middleware
|
|
2024
|
+
* did in Mode B (no ambient context): canonical line on every
|
|
2025
|
+
* request in `finally`. Because this wrapper sits OUTSIDE
|
|
2026
|
+
* `app.fetch`, errors absorbed by `app.onError` reach the caller as
|
|
2027
|
+
* a non-2xx `Response` whose body is the {@link HttpErrorEnvelope};
|
|
2028
|
+
* the helper reconstructs a `BaerlyError` from that envelope so the
|
|
2029
|
+
* canonical line carries the same `{ code, message }` shape it would
|
|
2030
|
+
* have under the in-Hono middleware.
|
|
2031
|
+
*/
|
|
2032
|
+
const withHttpObservability = async (req, fetch) => {
|
|
2033
|
+
const ctx = createObservabilityContext({ request_id: req.headers.get("x-request-id") ?? crypto.randomUUID() });
|
|
2034
|
+
const path = new URL(req.url).pathname;
|
|
2035
|
+
return runWithContext(ctx, async () => {
|
|
2036
|
+
let response;
|
|
2037
|
+
let caughtError;
|
|
2038
|
+
try {
|
|
2039
|
+
response = await fetch(req);
|
|
2040
|
+
return response;
|
|
2041
|
+
} catch (error) {
|
|
2042
|
+
caughtError = error;
|
|
2043
|
+
throw error;
|
|
2044
|
+
} finally {
|
|
2045
|
+
const status = response !== void 0 ? response.status : 500;
|
|
2046
|
+
let effectiveError = caughtError;
|
|
2047
|
+
if (effectiveError === void 0 && response !== void 0 && status >= 400) effectiveError = await reconstructErrorFromEnvelope(response);
|
|
2048
|
+
flushCanonicalLine(ctx, ctx.recorder, {
|
|
2049
|
+
unit: "http",
|
|
2050
|
+
status,
|
|
2051
|
+
outcome: deriveOutcome(req.method, status, effectiveError),
|
|
2052
|
+
...effectiveError !== void 0 && { error: effectiveError },
|
|
2053
|
+
extra: {
|
|
2054
|
+
method: req.method,
|
|
2055
|
+
path
|
|
2056
|
+
}
|
|
2057
|
+
});
|
|
2058
|
+
}
|
|
2059
|
+
});
|
|
2060
|
+
};
|
|
2061
|
+
/**
|
|
2062
|
+
* Best-effort BaerlyError reconstruction from a non-2xx
|
|
2063
|
+
* {@link HttpErrorEnvelope}. Used by {@link withHttpObservability} to
|
|
2064
|
+
* preserve the canonical-line `error` shape across `app.onError`
|
|
2065
|
+
* (which swallows the original throw).
|
|
2066
|
+
*
|
|
2067
|
+
* Failures (non-JSON body, missing fields, already-consumed stream)
|
|
2068
|
+
* fall through to `undefined` — the canonical line then surfaces only
|
|
2069
|
+
* the wire status, which is the worst-case behaviour the legacy
|
|
2070
|
+
* middleware would have produced on an unrecognised throw shape.
|
|
2071
|
+
*/
|
|
2072
|
+
const reconstructErrorFromEnvelope = async (response) => {
|
|
2073
|
+
try {
|
|
2074
|
+
const body = await response.clone().json();
|
|
2075
|
+
const code = body.error?.code;
|
|
2076
|
+
const message = body.error?.message;
|
|
2077
|
+
if (typeof code !== "string" || typeof message !== "string") return;
|
|
2078
|
+
return new BaerlyError(code, message);
|
|
2079
|
+
} catch {
|
|
2080
|
+
return;
|
|
2081
|
+
}
|
|
2082
|
+
};
|
|
2083
|
+
/**
|
|
2084
|
+
* Verifier rejected the request — log the warn, flush the canonical
|
|
2085
|
+
* line, and return the 401 envelope Response. Adapters call this
|
|
2086
|
+
* inside `runWithContext(obsCtx, ...)` so the canonical line lands on
|
|
2087
|
+
* the same context the rest of the request would have used.
|
|
2088
|
+
*
|
|
2089
|
+
* Both adapters share this so the 401 wire shape AND the
|
|
2090
|
+
* observability record are byte-identical across runtimes.
|
|
2091
|
+
*/
|
|
2092
|
+
const flushUnauthorizedAndRespond = (obsCtx, req) => {
|
|
2093
|
+
getLogger(CATEGORY.http).warn("verifier_rejected", { reason: "null" });
|
|
2094
|
+
const path = new URL(req.url).pathname;
|
|
2095
|
+
flushCanonicalLine(obsCtx, obsCtx.recorder, {
|
|
2096
|
+
unit: "http",
|
|
2097
|
+
status: 401,
|
|
2098
|
+
outcome: "error",
|
|
2099
|
+
extra: {
|
|
2100
|
+
method: req.method,
|
|
2101
|
+
path
|
|
2102
|
+
}
|
|
2103
|
+
});
|
|
2104
|
+
return new Response(JSON.stringify(errorEnvelope("Unauthorized", "Missing or invalid Authorization header")), {
|
|
2105
|
+
status: 401,
|
|
2106
|
+
headers: { "content-type": "application/json" }
|
|
2107
|
+
});
|
|
2108
|
+
};
|
|
2109
|
+
const pickLevel = (opts) => {
|
|
2110
|
+
if (opts.error !== void 0) return "error";
|
|
2111
|
+
if (opts.status !== void 0) {
|
|
2112
|
+
if (opts.status >= 500) return "error";
|
|
2113
|
+
if (opts.status >= 400) return "warn";
|
|
2114
|
+
}
|
|
2115
|
+
return "info";
|
|
2116
|
+
};
|
|
2117
|
+
const buildProperties = (ctx, recorder, opts, level) => {
|
|
2118
|
+
const duration_ms = Math.max(0, performance.now() - ctx.started_at);
|
|
2119
|
+
const props = {
|
|
2120
|
+
...recorder.summarize(),
|
|
2121
|
+
request_id: ctx.request_id,
|
|
2122
|
+
duration_ms,
|
|
2123
|
+
outcome: opts.outcome
|
|
2124
|
+
};
|
|
2125
|
+
if (opts.status !== void 0) props["status"] = opts.status;
|
|
2126
|
+
for (const [k, v] of ctx.fields) props[k] = v;
|
|
2127
|
+
if (opts.extra !== void 0) Object.assign(props, opts.extra);
|
|
2128
|
+
if (opts.error !== void 0) props["error"] = serializeError(opts.error, level === "error");
|
|
2129
|
+
return props;
|
|
2130
|
+
};
|
|
2131
|
+
/**
|
|
2132
|
+
* Convert an unknown thrown value into a {@link SerializedError}.
|
|
2133
|
+
*
|
|
2134
|
+
* Two rules:
|
|
2135
|
+
*
|
|
2136
|
+
* 1. `BaerlyError` — preserve its `code` discriminant verbatim.
|
|
2137
|
+
* 2. Any other error or non-error value — collapse to
|
|
2138
|
+
* `{ code: "Internal", message: <stringified> }`.
|
|
2139
|
+
*
|
|
2140
|
+
* Stacks are included when `includeStack` is `true`. Callers pass
|
|
2141
|
+
* `level === "error"` to honor the "stacks only at error level" rule.
|
|
2142
|
+
*
|
|
2143
|
+
* @param err The thrown value (anything `try { ... } catch (e)` can yield).
|
|
2144
|
+
* @param includeStack If `true`, include the stack trace when `err` is
|
|
2145
|
+
* an `Error` (or `BaerlyError`) with a `stack` property. Defaults to `false`.
|
|
2146
|
+
*/
|
|
2147
|
+
const serializeError = (err, includeStack = false) => {
|
|
2148
|
+
if (err instanceof BaerlyError) {
|
|
2149
|
+
const base = {
|
|
2150
|
+
code: err.code,
|
|
2151
|
+
message: err.message
|
|
2152
|
+
};
|
|
2153
|
+
return includeStack && err.stack !== void 0 ? {
|
|
2154
|
+
...base,
|
|
2155
|
+
stack: err.stack
|
|
2156
|
+
} : base;
|
|
2157
|
+
}
|
|
2158
|
+
if (err instanceof Error) {
|
|
2159
|
+
const base = {
|
|
2160
|
+
code: "Internal",
|
|
2161
|
+
message: err.message
|
|
2162
|
+
};
|
|
2163
|
+
return includeStack && err.stack !== void 0 ? {
|
|
2164
|
+
...base,
|
|
2165
|
+
stack: err.stack
|
|
2166
|
+
} : base;
|
|
2167
|
+
}
|
|
2168
|
+
if (typeof err === "object" && err !== null) try {
|
|
2169
|
+
return {
|
|
2170
|
+
code: "Internal",
|
|
2171
|
+
message: JSON.stringify(err)
|
|
2172
|
+
};
|
|
2173
|
+
} catch {
|
|
2174
|
+
return {
|
|
2175
|
+
code: "Internal",
|
|
2176
|
+
message: "[unserializable object]"
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
2179
|
+
return {
|
|
2180
|
+
code: "Internal",
|
|
2181
|
+
message: String(err)
|
|
2182
|
+
};
|
|
2183
|
+
};
|
|
2184
|
+
//#endregion
|
|
2185
|
+
//#region packages/server/src/observability/storage.ts
|
|
2186
|
+
/**
|
|
2187
|
+
* `Storage` decorator that emits per-op observability:
|
|
2188
|
+
*
|
|
2189
|
+
* - One histogram observation per call: `db.storage.<op>.duration_ms`.
|
|
2190
|
+
* - One counter increment per call: `db.storage.<op>.calls_total`.
|
|
2191
|
+
* - One counter increment per class A / class B classification:
|
|
2192
|
+
* `db.storage.class_a_ops_total` / `db.storage.class_b_ops_total`.
|
|
2193
|
+
* We follow S3 pricing: PUT / DELETE / LIST count as class A;
|
|
2194
|
+
* GET counts as class B. (S3 charges Class A for PUT/POST/COPY/
|
|
2195
|
+
* LIST and Class B for GET/HEAD; DELETE is free under S3 but
|
|
2196
|
+
* we still count it as class A internally because it triggers
|
|
2197
|
+
* write-side traffic in the kernel's accounting.)
|
|
2198
|
+
* - On error: counter increment `db.storage.<op>.errors_total` and
|
|
2199
|
+
* re-throw the original value verbatim.
|
|
2200
|
+
*
|
|
2201
|
+
* Read paths are NOT decorated by default; consumers pass a
|
|
2202
|
+
* recorder when they want observation. The default no-op recorder
|
|
2203
|
+
* still works — every emission is a single function call.
|
|
2204
|
+
*
|
|
2205
|
+
* The decorator preserves the `Storage` contract exactly: same
|
|
2206
|
+
* input types, same output types, same `null`-on-not-found
|
|
2207
|
+
* convention, same `AsyncIterable` for `list`.
|
|
2208
|
+
*
|
|
2209
|
+
* The debug-level per-call log line is gated on
|
|
2210
|
+
* `getLogger(CATEGORY.storage).isEnabledFor("debug")` so we don't
|
|
2211
|
+
* pay the formatting cost in production where the level is
|
|
2212
|
+
* `info` or higher. (LogTape provides `isEnabledFor` since 2.0.0.)
|
|
2213
|
+
*/
|
|
2214
|
+
const CLASS_A_OPS = new Set([
|
|
2215
|
+
"put",
|
|
2216
|
+
"delete",
|
|
2217
|
+
"list"
|
|
2218
|
+
]);
|
|
2219
|
+
const ctxMetrics = () => getCurrentContext()?.recorder ?? noopMetricsRecorder;
|
|
2220
|
+
/**
|
|
2221
|
+
* Wrap `inner` with metric emission. The returned object is itself
|
|
2222
|
+
* a `Storage` impl and passes the `Storage` conformance suite
|
|
2223
|
+
* (round-trip semantics, ETag preservation, `list` ordering — none
|
|
2224
|
+
* of which the decorator touches).
|
|
2225
|
+
*
|
|
2226
|
+
* Per-op counters and per-op duration histograms flow into the
|
|
2227
|
+
* active {@link ObservabilityContext}'s recorder (`ctxMetrics()`);
|
|
2228
|
+
* outside any context they fall through to {@link noopMetricsRecorder}.
|
|
2229
|
+
*/
|
|
2230
|
+
const observableStorage = (inner) => {
|
|
2231
|
+
const logger = getLogger(CATEGORY.storage);
|
|
2232
|
+
const debug = (op, key, durationMs, outcome, bytes) => {
|
|
2233
|
+
if (!logger.isEnabledFor("debug")) return;
|
|
2234
|
+
const props = {
|
|
2235
|
+
op,
|
|
2236
|
+
key,
|
|
2237
|
+
duration_ms: durationMs,
|
|
2238
|
+
outcome
|
|
2239
|
+
};
|
|
2240
|
+
if (bytes !== void 0) props["bytes"] = bytes;
|
|
2241
|
+
logger.debug("storage", props);
|
|
2242
|
+
};
|
|
2243
|
+
const recordCall = (op) => {
|
|
2244
|
+
const recorder = ctxMetrics();
|
|
2245
|
+
recorder.counter(`db.storage.${op}.calls_total`, 1);
|
|
2246
|
+
recorder.counter(CLASS_A_OPS.has(op) ? "db.storage.class_a_ops_total" : "db.storage.class_b_ops_total", 1);
|
|
2247
|
+
};
|
|
2248
|
+
const recordError = (op) => {
|
|
2249
|
+
ctxMetrics().counter(`db.storage.${op}.errors_total`, 1);
|
|
2250
|
+
};
|
|
2251
|
+
const recordDuration = (op, durationMs) => {
|
|
2252
|
+
ctxMetrics().histogram(`db.storage.${op}.duration_ms`, durationMs);
|
|
2253
|
+
};
|
|
2254
|
+
return {
|
|
2255
|
+
async get(key, opts) {
|
|
2256
|
+
const op = "get";
|
|
2257
|
+
recordCall(op);
|
|
2258
|
+
const start = performance.now();
|
|
2259
|
+
try {
|
|
2260
|
+
const result = await inner.get(key, opts);
|
|
2261
|
+
const dt = performance.now() - start;
|
|
2262
|
+
recordDuration(op, dt);
|
|
2263
|
+
debug(op, key, dt, result === null ? "miss" : "hit", result?.body.byteLength);
|
|
2264
|
+
return result;
|
|
2265
|
+
} catch (error) {
|
|
2266
|
+
const dt = performance.now() - start;
|
|
2267
|
+
recordDuration(op, dt);
|
|
2268
|
+
recordError(op);
|
|
2269
|
+
debug(op, key, dt, "error");
|
|
2270
|
+
throw error;
|
|
2271
|
+
}
|
|
2272
|
+
},
|
|
2273
|
+
async put(key, body, opts) {
|
|
2274
|
+
const op = "put";
|
|
2275
|
+
recordCall(op);
|
|
2276
|
+
const start = performance.now();
|
|
2277
|
+
try {
|
|
2278
|
+
const result = await inner.put(key, body, opts);
|
|
2279
|
+
const dt = performance.now() - start;
|
|
2280
|
+
recordDuration(op, dt);
|
|
2281
|
+
debug(op, key, dt, "ok", body.byteLength);
|
|
2282
|
+
return result;
|
|
2283
|
+
} catch (error) {
|
|
2284
|
+
const dt = performance.now() - start;
|
|
2285
|
+
recordDuration(op, dt);
|
|
2286
|
+
recordError(op);
|
|
2287
|
+
debug(op, key, dt, "error", body.byteLength);
|
|
2288
|
+
throw error;
|
|
2289
|
+
}
|
|
2290
|
+
},
|
|
2291
|
+
async delete(key, opts) {
|
|
2292
|
+
const op = "delete";
|
|
2293
|
+
recordCall(op);
|
|
2294
|
+
const start = performance.now();
|
|
2295
|
+
try {
|
|
2296
|
+
await inner.delete(key, opts);
|
|
2297
|
+
const dt = performance.now() - start;
|
|
2298
|
+
recordDuration(op, dt);
|
|
2299
|
+
debug(op, key, dt, "ok");
|
|
2300
|
+
} catch (error) {
|
|
2301
|
+
const dt = performance.now() - start;
|
|
2302
|
+
recordDuration(op, dt);
|
|
2303
|
+
recordError(op);
|
|
2304
|
+
debug(op, key, dt, "error");
|
|
2305
|
+
throw error;
|
|
2306
|
+
}
|
|
2307
|
+
},
|
|
2308
|
+
list(prefix, opts) {
|
|
2309
|
+
const op = "list";
|
|
2310
|
+
recordCall(op);
|
|
2311
|
+
const start = performance.now();
|
|
2312
|
+
const innerIter = inner.list(prefix, opts);
|
|
2313
|
+
return { async *[Symbol.asyncIterator]() {
|
|
2314
|
+
try {
|
|
2315
|
+
for await (const entry of innerIter) yield entry;
|
|
2316
|
+
const dt = performance.now() - start;
|
|
2317
|
+
recordDuration(op, dt);
|
|
2318
|
+
debug(op, prefix, dt, "ok");
|
|
2319
|
+
} catch (error) {
|
|
2320
|
+
const dt = performance.now() - start;
|
|
2321
|
+
recordDuration(op, dt);
|
|
2322
|
+
recordError(op);
|
|
2323
|
+
debug(op, prefix, dt, "error");
|
|
2324
|
+
throw error;
|
|
2325
|
+
}
|
|
2326
|
+
} };
|
|
2327
|
+
}
|
|
2328
|
+
};
|
|
2329
|
+
};
|
|
2330
|
+
//#endregion
|
|
2331
|
+
export { withHttpObservability as a, configureObservability as c, serializeError as i, getLogger as l, flushCanonicalLine as n, deriveOutcome as o, flushUnauthorizedAndRespond as r, CATEGORY as s, observableStorage as t, errorEnvelope as u };
|
|
2332
|
+
|
|
2333
|
+
//# sourceMappingURL=observability-2IDYRuZK.js.map
|