@logtape/redaction 2.0.30-dev.1027 → 2.0.30-dev.1038
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/field.cjs +47 -36
- package/dist/field.d.cts.map +1 -1
- package/dist/field.d.ts.map +1 -1
- package/dist/field.js +48 -36
- package/dist/field.js.map +1 -1
- package/dist/pattern.cjs +13 -3
- package/dist/pattern.d.cts.map +1 -1
- package/dist/pattern.d.ts.map +1 -1
- package/dist/pattern.js +14 -3
- package/dist/pattern.js.map +1 -1
- package/dist/structured.cjs +82 -0
- package/dist/structured.js +80 -0
- package/dist/structured.js.map +1 -0
- package/package.json +2 -2
package/dist/field.cjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const require_structured = require('./structured.cjs');
|
|
1
2
|
|
|
2
3
|
//#region src/field.ts
|
|
3
4
|
const disposeSymbol = Symbol.dispose ?? Symbol.for("Symbol.dispose");
|
|
@@ -52,15 +53,17 @@ const DEFAULT_REDACT_FIELDS = [
|
|
|
52
53
|
function redactByField(sink, options = DEFAULT_REDACT_FIELDS) {
|
|
53
54
|
const opts = Array.isArray(options) ? { fieldPatterns: options } : options;
|
|
54
55
|
const wrapped = (record) => {
|
|
55
|
-
const
|
|
56
|
+
const visited = /* @__PURE__ */ new Map();
|
|
57
|
+
const redactedProperties = redactProperties(record.properties, opts, visited);
|
|
58
|
+
const redactArgument = (value) => redactValue(value, opts, visited);
|
|
56
59
|
let redactedMessage = record.message;
|
|
57
60
|
if (typeof record.rawMessage === "string") {
|
|
58
61
|
const placeholders = extractPlaceholderNames(record.rawMessage);
|
|
59
62
|
const { redactedIndices, wildcardIndices } = getRedactedPlaceholderIndices(placeholders, opts.fieldPatterns);
|
|
60
|
-
redactedMessage = redactMessageArray(record.message, placeholders, redactedIndices, wildcardIndices, redactedProperties, opts.action);
|
|
63
|
+
redactedMessage = redactMessageArray(record.message, placeholders, redactedIndices, wildcardIndices, redactedProperties, opts.action, redactArgument);
|
|
61
64
|
} else {
|
|
62
65
|
const redactedValues = getRedactedValues(record.properties, redactedProperties);
|
|
63
|
-
|
|
66
|
+
redactedMessage = redactMessageByValues(record.message, redactedValues, redactArgument);
|
|
64
67
|
}
|
|
65
68
|
sink({
|
|
66
69
|
...record,
|
|
@@ -94,33 +97,37 @@ function redactProperties(properties, options, visited = /* @__PURE__ */ new Map
|
|
|
94
97
|
visited.set(properties, copy);
|
|
95
98
|
for (const field in properties) {
|
|
96
99
|
if (shouldFieldRedacted(field, options.fieldPatterns)) {
|
|
97
|
-
if (typeof options.action === "function") copy
|
|
100
|
+
if (typeof options.action === "function") require_structured.defineField(copy, field, options.action(properties[field]));
|
|
98
101
|
continue;
|
|
99
102
|
}
|
|
100
|
-
|
|
101
|
-
if (Array.isArray(value)) copy[field] = redactArray(value, options, visited);
|
|
102
|
-
else if (typeof value === "object" && value !== null) if (isBuiltInObject(value)) copy[field] = value;
|
|
103
|
-
else copy[field] = redactProperties(value, options, visited);
|
|
104
|
-
else copy[field] = value;
|
|
103
|
+
require_structured.defineField(copy, field, redactValue(properties[field], options, visited));
|
|
105
104
|
}
|
|
106
105
|
return copy;
|
|
107
106
|
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
107
|
+
function redactValue(value, options, visited) {
|
|
108
|
+
if (typeof value !== "object" || value == null) return value;
|
|
109
|
+
if (visited.has(value)) return visited.get(value);
|
|
110
|
+
const transform = (item) => redactValue(item, options, visited);
|
|
111
|
+
if (Array.isArray(value)) {
|
|
112
|
+
const copy = new Array(value.length);
|
|
113
|
+
visited.set(value, copy);
|
|
114
|
+
Array.prototype.forEach.call(value, (item, index) => {
|
|
115
|
+
copy[index] = transform(item);
|
|
116
|
+
});
|
|
117
|
+
return copy;
|
|
118
|
+
}
|
|
119
|
+
const structured = require_structured.copyStructured(value, visited, transform, (key, item) => {
|
|
120
|
+
if (!shouldFieldRedacted(key, options.fieldPatterns)) return transform(item);
|
|
121
|
+
if (typeof options.action !== "function") return require_structured.omit;
|
|
122
|
+
try {
|
|
123
|
+
return options.action(item);
|
|
124
|
+
} catch {
|
|
125
|
+
return require_structured.omit;
|
|
121
126
|
}
|
|
122
|
-
|
|
123
|
-
|
|
127
|
+
}, false);
|
|
128
|
+
if (structured != null) return structured;
|
|
129
|
+
if (isBuiltInObject(value)) return value;
|
|
130
|
+
return redactProperties(value, options, visited);
|
|
124
131
|
}
|
|
125
132
|
/**
|
|
126
133
|
* Checks if a value is a built-in object that should not be recursively
|
|
@@ -129,7 +136,7 @@ function redactArray(array, options, visited) {
|
|
|
129
136
|
* @returns `true` if the value is a built-in object, `false` otherwise.
|
|
130
137
|
*/
|
|
131
138
|
function isBuiltInObject(value) {
|
|
132
|
-
return value instanceof
|
|
139
|
+
return value instanceof Date || value instanceof RegExp || value instanceof WeakMap || value instanceof WeakSet || value instanceof Promise || value instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer || ArrayBuffer.isView(value);
|
|
133
140
|
}
|
|
134
141
|
/**
|
|
135
142
|
* Checks if a field should be redacted based on the provided field patterns.
|
|
@@ -219,9 +226,10 @@ function getRedactedPlaceholderIndices(placeholders, fieldPatterns) {
|
|
|
219
226
|
* @param wildcardIndices Set of wildcard placeholder indices.
|
|
220
227
|
* @param redactedProperties The redacted properties object.
|
|
221
228
|
* @param action The redaction action.
|
|
229
|
+
* @param redactArgument Transforms an argument without a matching field.
|
|
222
230
|
* @returns New message array with redacted values.
|
|
223
231
|
*/
|
|
224
|
-
function redactMessageArray(message, placeholders, redactedIndices, wildcardIndices, redactedProperties, action) {
|
|
232
|
+
function redactMessageArray(message, placeholders, redactedIndices, wildcardIndices, redactedProperties, action, redactArgument) {
|
|
225
233
|
const result = [];
|
|
226
234
|
let placeholderIndex = 0;
|
|
227
235
|
for (let i = 0; i < message.length; i++) if (i % 2 === 0) result.push(message[i]);
|
|
@@ -230,10 +238,10 @@ function redactMessageArray(message, placeholders, redactedIndices, wildcardIndi
|
|
|
230
238
|
else if (redactedIndices.has(placeholderIndex)) if (action == null || action === "delete") result.push("");
|
|
231
239
|
else result.push(action(message[i]));
|
|
232
240
|
else {
|
|
233
|
-
const placeholderName = placeholders[placeholderIndex];
|
|
241
|
+
const placeholderName = placeholders[placeholderIndex] ?? "";
|
|
234
242
|
const rootKey = parsePathSegments(placeholderName)[0];
|
|
235
|
-
if (rootKey
|
|
236
|
-
else result.push(message[i]);
|
|
243
|
+
if (Object.hasOwn(redactedProperties, rootKey)) result.push(redactedProperties[rootKey]);
|
|
244
|
+
else result.push(redactArgument(message[i]));
|
|
237
245
|
}
|
|
238
246
|
placeholderIndex++;
|
|
239
247
|
}
|
|
@@ -245,13 +253,16 @@ function redactMessageArray(message, placeholders, redactedIndices, wildcardIndi
|
|
|
245
253
|
* @param redacted The redacted properties.
|
|
246
254
|
* @param map The map to populate with original -> redacted value pairs.
|
|
247
255
|
*/
|
|
248
|
-
function collectRedactedValues(original, redacted, map) {
|
|
256
|
+
function collectRedactedValues(original, redacted, map, ancestors) {
|
|
257
|
+
if (ancestors.has(original)) return;
|
|
258
|
+
ancestors.add(original);
|
|
249
259
|
for (const key in original) {
|
|
250
260
|
const origVal = original[key];
|
|
251
|
-
const redVal = redacted[key];
|
|
261
|
+
const redVal = Object.hasOwn(redacted, key) ? redacted[key] : void 0;
|
|
252
262
|
if (origVal !== redVal) map.set(origVal, redVal);
|
|
253
|
-
if (typeof origVal === "object" && origVal !== null && typeof redVal === "object" && redVal !== null && !Array.isArray(origVal)) collectRedactedValues(origVal, redVal, map);
|
|
263
|
+
if (typeof origVal === "object" && origVal !== null && typeof redVal === "object" && redVal !== null && !Array.isArray(origVal) && Object.getPrototypeOf(redVal) === Object.prototype) collectRedactedValues(origVal, redVal, map, ancestors);
|
|
254
264
|
}
|
|
265
|
+
ancestors.delete(original);
|
|
255
266
|
}
|
|
256
267
|
/**
|
|
257
268
|
* Gets a map of original values to their redacted replacements.
|
|
@@ -261,7 +272,7 @@ function collectRedactedValues(original, redacted, map) {
|
|
|
261
272
|
*/
|
|
262
273
|
function getRedactedValues(original, redacted) {
|
|
263
274
|
const map = /* @__PURE__ */ new Map();
|
|
264
|
-
collectRedactedValues(original, redacted, map);
|
|
275
|
+
collectRedactedValues(original, redacted, map, /* @__PURE__ */ new Set());
|
|
265
276
|
return map;
|
|
266
277
|
}
|
|
267
278
|
/**
|
|
@@ -269,16 +280,16 @@ function getRedactedValues(original, redacted) {
|
|
|
269
280
|
* Used for tagged template literals where placeholder names are not available.
|
|
270
281
|
* @param message The original message array.
|
|
271
282
|
* @param redactedValues Map of original -> redacted values.
|
|
283
|
+
* @param redactArgument Transforms an argument without a matching field.
|
|
272
284
|
* @returns New message array with redacted values.
|
|
273
285
|
*/
|
|
274
|
-
function redactMessageByValues(message, redactedValues) {
|
|
275
|
-
if (redactedValues.size === 0) return message;
|
|
286
|
+
function redactMessageByValues(message, redactedValues, redactArgument) {
|
|
276
287
|
const result = [];
|
|
277
288
|
for (let i = 0; i < message.length; i++) if (i % 2 === 0) result.push(message[i]);
|
|
278
289
|
else {
|
|
279
290
|
const val = message[i];
|
|
280
291
|
if (redactedValues.has(val)) result.push(redactedValues.get(val));
|
|
281
|
-
else result.push(val);
|
|
292
|
+
else result.push(redactArgument(val));
|
|
282
293
|
}
|
|
283
294
|
return result;
|
|
284
295
|
}
|
package/dist/field.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"field.d.cts","names":[],"sources":["../src/field.ts"],"sourcesContent":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"field.d.cts","names":[],"sources":["../src/field.ts"],"sourcesContent":[],"mappings":";;;;;;AAcA;AAOA;AAQA;AAqBiB,KApCL,YAAA,GAoCK,MAAqB,GApCF,MA2CV;AAyC1B;;;;;AACmC,KA9EvB,aAAA,GAAgB,YA8EO,EAAA;;;;;;;AAEL,cAxEjB,qBAwEiB,EAxEM,aAwEN;;AAAsB;;;;UAnDnC,qBAAA;;;;;;;0BAOS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyCV,aAAA,OACR,OAAO,OAAO,aAAa,OAAO,2BAC/B,wBAAwB,gBAChC,OAAO,OAAO,aAAa,OAAO"}
|
package/dist/field.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"field.d.ts","names":[],"sources":["../src/field.ts"],"sourcesContent":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"field.d.ts","names":[],"sources":["../src/field.ts"],"sourcesContent":[],"mappings":";;;;;;AAcA;AAOA;AAQA;AAqBiB,KApCL,YAAA,GAoCK,MAAqB,GApCF,MA2CV;AAyC1B;;;;;AACmC,KA9EvB,aAAA,GAAgB,YA8EO,EAAA;;;;;;;AAEL,cAxEjB,qBAwEiB,EAxEM,aAwEN;;AAAsB;;;;UAnDnC,qBAAA;;;;;;;0BAOS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyCV,aAAA,OACR,OAAO,OAAO,aAAa,OAAO,2BAC/B,wBAAwB,gBAChC,OAAO,OAAO,aAAa,OAAO"}
|
package/dist/field.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { copyStructured, defineField, omit } from "./structured.js";
|
|
2
|
+
|
|
1
3
|
//#region src/field.ts
|
|
2
4
|
const disposeSymbol = Symbol.dispose ?? Symbol.for("Symbol.dispose");
|
|
3
5
|
const asyncDisposeSymbol = Symbol.asyncDispose ?? Symbol.for("Symbol.asyncDispose");
|
|
@@ -51,15 +53,17 @@ const DEFAULT_REDACT_FIELDS = [
|
|
|
51
53
|
function redactByField(sink, options = DEFAULT_REDACT_FIELDS) {
|
|
52
54
|
const opts = Array.isArray(options) ? { fieldPatterns: options } : options;
|
|
53
55
|
const wrapped = (record) => {
|
|
54
|
-
const
|
|
56
|
+
const visited = /* @__PURE__ */ new Map();
|
|
57
|
+
const redactedProperties = redactProperties(record.properties, opts, visited);
|
|
58
|
+
const redactArgument = (value) => redactValue(value, opts, visited);
|
|
55
59
|
let redactedMessage = record.message;
|
|
56
60
|
if (typeof record.rawMessage === "string") {
|
|
57
61
|
const placeholders = extractPlaceholderNames(record.rawMessage);
|
|
58
62
|
const { redactedIndices, wildcardIndices } = getRedactedPlaceholderIndices(placeholders, opts.fieldPatterns);
|
|
59
|
-
redactedMessage = redactMessageArray(record.message, placeholders, redactedIndices, wildcardIndices, redactedProperties, opts.action);
|
|
63
|
+
redactedMessage = redactMessageArray(record.message, placeholders, redactedIndices, wildcardIndices, redactedProperties, opts.action, redactArgument);
|
|
60
64
|
} else {
|
|
61
65
|
const redactedValues = getRedactedValues(record.properties, redactedProperties);
|
|
62
|
-
|
|
66
|
+
redactedMessage = redactMessageByValues(record.message, redactedValues, redactArgument);
|
|
63
67
|
}
|
|
64
68
|
sink({
|
|
65
69
|
...record,
|
|
@@ -93,33 +97,37 @@ function redactProperties(properties, options, visited = /* @__PURE__ */ new Map
|
|
|
93
97
|
visited.set(properties, copy);
|
|
94
98
|
for (const field in properties) {
|
|
95
99
|
if (shouldFieldRedacted(field, options.fieldPatterns)) {
|
|
96
|
-
if (typeof options.action === "function") copy
|
|
100
|
+
if (typeof options.action === "function") defineField(copy, field, options.action(properties[field]));
|
|
97
101
|
continue;
|
|
98
102
|
}
|
|
99
|
-
|
|
100
|
-
if (Array.isArray(value)) copy[field] = redactArray(value, options, visited);
|
|
101
|
-
else if (typeof value === "object" && value !== null) if (isBuiltInObject(value)) copy[field] = value;
|
|
102
|
-
else copy[field] = redactProperties(value, options, visited);
|
|
103
|
-
else copy[field] = value;
|
|
103
|
+
defineField(copy, field, redactValue(properties[field], options, visited));
|
|
104
104
|
}
|
|
105
105
|
return copy;
|
|
106
106
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
107
|
+
function redactValue(value, options, visited) {
|
|
108
|
+
if (typeof value !== "object" || value == null) return value;
|
|
109
|
+
if (visited.has(value)) return visited.get(value);
|
|
110
|
+
const transform = (item) => redactValue(item, options, visited);
|
|
111
|
+
if (Array.isArray(value)) {
|
|
112
|
+
const copy = new Array(value.length);
|
|
113
|
+
visited.set(value, copy);
|
|
114
|
+
Array.prototype.forEach.call(value, (item, index) => {
|
|
115
|
+
copy[index] = transform(item);
|
|
116
|
+
});
|
|
117
|
+
return copy;
|
|
118
|
+
}
|
|
119
|
+
const structured = copyStructured(value, visited, transform, (key, item) => {
|
|
120
|
+
if (!shouldFieldRedacted(key, options.fieldPatterns)) return transform(item);
|
|
121
|
+
if (typeof options.action !== "function") return omit;
|
|
122
|
+
try {
|
|
123
|
+
return options.action(item);
|
|
124
|
+
} catch {
|
|
125
|
+
return omit;
|
|
120
126
|
}
|
|
121
|
-
|
|
122
|
-
|
|
127
|
+
}, false);
|
|
128
|
+
if (structured != null) return structured;
|
|
129
|
+
if (isBuiltInObject(value)) return value;
|
|
130
|
+
return redactProperties(value, options, visited);
|
|
123
131
|
}
|
|
124
132
|
/**
|
|
125
133
|
* Checks if a value is a built-in object that should not be recursively
|
|
@@ -128,7 +136,7 @@ function redactArray(array, options, visited) {
|
|
|
128
136
|
* @returns `true` if the value is a built-in object, `false` otherwise.
|
|
129
137
|
*/
|
|
130
138
|
function isBuiltInObject(value) {
|
|
131
|
-
return value instanceof
|
|
139
|
+
return value instanceof Date || value instanceof RegExp || value instanceof WeakMap || value instanceof WeakSet || value instanceof Promise || value instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer || ArrayBuffer.isView(value);
|
|
132
140
|
}
|
|
133
141
|
/**
|
|
134
142
|
* Checks if a field should be redacted based on the provided field patterns.
|
|
@@ -218,9 +226,10 @@ function getRedactedPlaceholderIndices(placeholders, fieldPatterns) {
|
|
|
218
226
|
* @param wildcardIndices Set of wildcard placeholder indices.
|
|
219
227
|
* @param redactedProperties The redacted properties object.
|
|
220
228
|
* @param action The redaction action.
|
|
229
|
+
* @param redactArgument Transforms an argument without a matching field.
|
|
221
230
|
* @returns New message array with redacted values.
|
|
222
231
|
*/
|
|
223
|
-
function redactMessageArray(message, placeholders, redactedIndices, wildcardIndices, redactedProperties, action) {
|
|
232
|
+
function redactMessageArray(message, placeholders, redactedIndices, wildcardIndices, redactedProperties, action, redactArgument) {
|
|
224
233
|
const result = [];
|
|
225
234
|
let placeholderIndex = 0;
|
|
226
235
|
for (let i = 0; i < message.length; i++) if (i % 2 === 0) result.push(message[i]);
|
|
@@ -229,10 +238,10 @@ function redactMessageArray(message, placeholders, redactedIndices, wildcardIndi
|
|
|
229
238
|
else if (redactedIndices.has(placeholderIndex)) if (action == null || action === "delete") result.push("");
|
|
230
239
|
else result.push(action(message[i]));
|
|
231
240
|
else {
|
|
232
|
-
const placeholderName = placeholders[placeholderIndex];
|
|
241
|
+
const placeholderName = placeholders[placeholderIndex] ?? "";
|
|
233
242
|
const rootKey = parsePathSegments(placeholderName)[0];
|
|
234
|
-
if (rootKey
|
|
235
|
-
else result.push(message[i]);
|
|
243
|
+
if (Object.hasOwn(redactedProperties, rootKey)) result.push(redactedProperties[rootKey]);
|
|
244
|
+
else result.push(redactArgument(message[i]));
|
|
236
245
|
}
|
|
237
246
|
placeholderIndex++;
|
|
238
247
|
}
|
|
@@ -244,13 +253,16 @@ function redactMessageArray(message, placeholders, redactedIndices, wildcardIndi
|
|
|
244
253
|
* @param redacted The redacted properties.
|
|
245
254
|
* @param map The map to populate with original -> redacted value pairs.
|
|
246
255
|
*/
|
|
247
|
-
function collectRedactedValues(original, redacted, map) {
|
|
256
|
+
function collectRedactedValues(original, redacted, map, ancestors) {
|
|
257
|
+
if (ancestors.has(original)) return;
|
|
258
|
+
ancestors.add(original);
|
|
248
259
|
for (const key in original) {
|
|
249
260
|
const origVal = original[key];
|
|
250
|
-
const redVal = redacted[key];
|
|
261
|
+
const redVal = Object.hasOwn(redacted, key) ? redacted[key] : void 0;
|
|
251
262
|
if (origVal !== redVal) map.set(origVal, redVal);
|
|
252
|
-
if (typeof origVal === "object" && origVal !== null && typeof redVal === "object" && redVal !== null && !Array.isArray(origVal)) collectRedactedValues(origVal, redVal, map);
|
|
263
|
+
if (typeof origVal === "object" && origVal !== null && typeof redVal === "object" && redVal !== null && !Array.isArray(origVal) && Object.getPrototypeOf(redVal) === Object.prototype) collectRedactedValues(origVal, redVal, map, ancestors);
|
|
253
264
|
}
|
|
265
|
+
ancestors.delete(original);
|
|
254
266
|
}
|
|
255
267
|
/**
|
|
256
268
|
* Gets a map of original values to their redacted replacements.
|
|
@@ -260,7 +272,7 @@ function collectRedactedValues(original, redacted, map) {
|
|
|
260
272
|
*/
|
|
261
273
|
function getRedactedValues(original, redacted) {
|
|
262
274
|
const map = /* @__PURE__ */ new Map();
|
|
263
|
-
collectRedactedValues(original, redacted, map);
|
|
275
|
+
collectRedactedValues(original, redacted, map, /* @__PURE__ */ new Set());
|
|
264
276
|
return map;
|
|
265
277
|
}
|
|
266
278
|
/**
|
|
@@ -268,16 +280,16 @@ function getRedactedValues(original, redacted) {
|
|
|
268
280
|
* Used for tagged template literals where placeholder names are not available.
|
|
269
281
|
* @param message The original message array.
|
|
270
282
|
* @param redactedValues Map of original -> redacted values.
|
|
283
|
+
* @param redactArgument Transforms an argument without a matching field.
|
|
271
284
|
* @returns New message array with redacted values.
|
|
272
285
|
*/
|
|
273
|
-
function redactMessageByValues(message, redactedValues) {
|
|
274
|
-
if (redactedValues.size === 0) return message;
|
|
286
|
+
function redactMessageByValues(message, redactedValues, redactArgument) {
|
|
275
287
|
const result = [];
|
|
276
288
|
for (let i = 0; i < message.length; i++) if (i % 2 === 0) result.push(message[i]);
|
|
277
289
|
else {
|
|
278
290
|
const val = message[i];
|
|
279
291
|
if (redactedValues.has(val)) result.push(redactedValues.get(val));
|
|
280
|
-
else result.push(val);
|
|
292
|
+
else result.push(redactArgument(val));
|
|
281
293
|
}
|
|
282
294
|
return result;
|
|
283
295
|
}
|
package/dist/field.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"field.js","names":["disposeSymbol: typeof Symbol.dispose","asyncDisposeSymbol: typeof Symbol.asyncDispose","DEFAULT_REDACT_FIELDS: FieldPatterns","sink: Sink | Sink & Disposable | Sink & AsyncDisposable","options: FieldRedactionOptions | FieldPatterns","record: LogRecord","properties: Record<string, unknown>","options: FieldRedactionOptions","copy: Record<string, unknown>","array: unknown[]","visited: Map<object, object>","value: object","field: string","fieldPatterns: FieldPatterns","template: string","placeholders: string[]","path: string","segments: string[]","message: readonly unknown[]","redactedIndices: Set<number>","wildcardIndices: Set<number>","redactedProperties: Record<string, unknown>","action: \"delete\" | ((value: unknown) => unknown) | undefined","result: unknown[]","original: Record<string, unknown>","redacted: Record<string, unknown>","map: Map<unknown, unknown>","redactedValues: Map<unknown, unknown>"],"sources":["../src/field.ts"],"sourcesContent":["import type { LogRecord, Sink } from \"@logtape/logtape\";\n\n// Match transpiled resource management without changing the global Symbol.\nconst disposeSymbol: typeof Symbol.dispose = Symbol.dispose ??\n Symbol.for(\"Symbol.dispose\");\nconst asyncDisposeSymbol: typeof Symbol.asyncDispose = Symbol.asyncDispose ??\n Symbol.for(\"Symbol.asyncDispose\");\n\n/**\n * The type for a field pattern used in redaction. A string or a regular\n * expression that matches field names.\n * @since 0.10.0\n */\nexport type FieldPattern = string | RegExp;\n\n/**\n * An array of field patterns used for redaction. Each pattern can be\n * a string or a regular expression that matches field names.\n * @since 0.10.0\n */\nexport type FieldPatterns = FieldPattern[];\n\n/**\n * Default field patterns for redaction. These patterns will match\n * common sensitive fields such as passwords, tokens, and personal\n * information.\n * @since 0.10.0\n */\nexport const DEFAULT_REDACT_FIELDS: FieldPatterns = [\n /pass(?:code|phrase|word)/i,\n /secret/i,\n /token/i,\n /key/i,\n /credential/i,\n /auth/i,\n /signature/i,\n /sensitive/i,\n /private/i,\n /ssn/i,\n /email/i,\n /phone/i,\n /address/i,\n];\n\n/**\n * Options for redacting fields in a {@link LogRecord}. Used by\n * the {@link redactByField} function.\n * @since 0.10.0\n */\nexport interface FieldRedactionOptions {\n /**\n * The field patterns to match against. This can be an array of\n * strings or regular expressions. If a field matches any of the\n * patterns, it will be redacted.\n * @defaultValue {@link DEFAULT_REDACT_FIELDS}\n */\n readonly fieldPatterns: FieldPatterns;\n\n /**\n * The action to perform on the matched fields. If not provided,\n * the default action is to delete the field from the properties.\n * If a function is provided, it will be called with the\n * value of the field, and the return value will be used to replace\n * the field in the properties.\n * If the action is `\"delete\"`, the field will be removed from the\n * properties.\n * @default `\"delete\"`\n */\n readonly action?: \"delete\" | ((value: unknown) => unknown);\n}\n\n/**\n * Redacts properties and message values in a {@link LogRecord} based on the\n * provided field patterns and action.\n *\n * Note that it is a decorator which wraps the sink and redacts properties\n * and message values before passing them to the sink.\n *\n * For string templates (e.g., `\"Hello, {name}!\"`), placeholder names are\n * matched against the field patterns to determine which values to redact.\n *\n * For tagged template literals (e.g., `` `Hello, ${name}!` ``), redaction\n * is performed by comparing message values with redacted property values.\n *\n * @example\n * ```ts\n * import { getConsoleSink } from \"@logtape/logtape\";\n * import { redactByField } from \"@logtape/redaction\";\n *\n * const sink = redactByField(getConsoleSink());\n * ```\n *\n * @param sink The sink to wrap.\n * @param options The redaction options.\n * @returns The wrapped sink.\n * @since 0.10.0\n */\nexport function redactByField(\n sink: Sink | Sink & Disposable | Sink & AsyncDisposable,\n options: FieldRedactionOptions | FieldPatterns = DEFAULT_REDACT_FIELDS,\n): Sink | Sink & Disposable | Sink & AsyncDisposable {\n const opts = Array.isArray(options) ? { fieldPatterns: options } : options;\n const wrapped = (record: LogRecord) => {\n const redactedProperties = redactProperties(record.properties, opts);\n let redactedMessage = record.message;\n\n if (typeof record.rawMessage === \"string\") {\n // String template: redact by placeholder names\n const placeholders = extractPlaceholderNames(record.rawMessage);\n const { redactedIndices, wildcardIndices } =\n getRedactedPlaceholderIndices(\n placeholders,\n opts.fieldPatterns,\n );\n redactedMessage = redactMessageArray(\n record.message,\n placeholders,\n redactedIndices,\n wildcardIndices,\n redactedProperties,\n opts.action,\n );\n } else {\n // Tagged template: redact by comparing values\n const redactedValues = getRedactedValues(\n record.properties,\n redactedProperties,\n );\n if (redactedValues.size > 0) {\n redactedMessage = redactMessageByValues(record.message, redactedValues);\n }\n }\n\n sink({\n ...record,\n message: redactedMessage,\n properties: redactedProperties,\n });\n };\n if (disposeSymbol in sink) wrapped[disposeSymbol] = sink[disposeSymbol];\n if (asyncDisposeSymbol in sink) {\n wrapped[asyncDisposeSymbol] = sink[asyncDisposeSymbol];\n }\n return wrapped;\n}\n\n/**\n * Redacts properties from an object based on specified field patterns.\n *\n * This function creates a shallow copy of the input object and applies\n * redaction rules to its properties. For properties that match the redaction\n * patterns, the function either removes them or transforms their values based\n * on the provided action.\n *\n * The redaction process is recursive and will be applied to nested objects\n * as well, allowing for deep redaction of sensitive data in complex object\n * structures.\n * @param properties The properties to redact.\n * @param options The redaction options.\n * @returns The redacted properties.\n * @since 0.10.0\n */\nexport function redactProperties(\n properties: Record<string, unknown>,\n options: FieldRedactionOptions,\n visited = new Map<object, object>(),\n): Record<string, unknown> {\n if (visited.has(properties)) {\n return visited.get(properties) as Record<string, unknown>;\n }\n\n const copy: Record<string, unknown> = {};\n visited.set(properties, copy);\n\n for (const field in properties) {\n if (shouldFieldRedacted(field, options.fieldPatterns)) {\n if (typeof options.action === \"function\") {\n copy[field] = options.action(properties[field]);\n }\n continue;\n }\n\n const value = properties[field];\n if (Array.isArray(value)) {\n copy[field] = redactArray(value, options, visited);\n } else if (typeof value === \"object\" && value !== null) {\n if (isBuiltInObject(value)) {\n copy[field] = value;\n } else {\n copy[field] = redactProperties(\n value as Record<string, unknown>,\n options,\n visited,\n );\n }\n } else {\n copy[field] = value;\n }\n }\n return copy;\n}\n\n/**\n * Redacts sensitive fields in an array recursively.\n * @param array The array to process.\n * @param options The redaction options.\n * @param visited Map of visited objects to prevent circular reference issues.\n * @returns A new array with redacted values.\n */\nfunction redactArray(\n array: unknown[],\n options: FieldRedactionOptions,\n visited: Map<object, object>,\n): unknown[] {\n return array.map((item) => {\n if (Array.isArray(item)) {\n return redactArray(item, options, visited);\n }\n if (typeof item === \"object\" && item !== null) {\n if (isBuiltInObject(item)) {\n return item;\n }\n return redactProperties(\n item as Record<string, unknown>,\n options,\n visited,\n );\n }\n return item;\n });\n}\n\n/**\n * Checks if a value is a built-in object that should not be recursively\n * processed (e.g., Error, Date, RegExp, Map, Set, etc.).\n * @param value The value to check.\n * @returns `true` if the value is a built-in object, `false` otherwise.\n */\nfunction isBuiltInObject(value: object): boolean {\n return value instanceof Error ||\n value instanceof Date ||\n value instanceof RegExp ||\n value instanceof Map ||\n value instanceof Set ||\n value instanceof WeakMap ||\n value instanceof WeakSet ||\n value instanceof Promise ||\n value instanceof ArrayBuffer ||\n (typeof SharedArrayBuffer !== \"undefined\" &&\n value instanceof SharedArrayBuffer) ||\n ArrayBuffer.isView(value);\n}\n\n/**\n * Checks if a field should be redacted based on the provided field patterns.\n * @param field The field name to check.\n * @param fieldPatterns The field patterns to match against.\n * @returns `true` if the field should be redacted, `false` otherwise.\n * @since 0.10.0\n */\nexport function shouldFieldRedacted(\n field: string,\n fieldPatterns: FieldPatterns,\n): boolean {\n for (const fieldPattern of fieldPatterns) {\n if (typeof fieldPattern === \"string\") {\n if (fieldPattern === field) return true;\n } else {\n if (fieldPattern.test(field)) return true;\n }\n }\n return false;\n}\n\n/**\n * Extracts placeholder names from a message template string in order.\n * @param template The message template string.\n * @returns An array of placeholder names in the order they appear.\n */\nfunction extractPlaceholderNames(template: string): string[] {\n const placeholders: string[] = [];\n for (let i = 0; i < template.length; i++) {\n if (template[i] === \"{\") {\n // Check for escaped brace\n if (i + 1 < template.length && template[i + 1] === \"{\") {\n i++;\n continue;\n }\n const closeIndex = template.indexOf(\"}\", i + 1);\n if (closeIndex === -1) continue;\n const key = template.slice(i + 1, closeIndex).trim();\n placeholders.push(key);\n i = closeIndex;\n }\n }\n return placeholders;\n}\n\n/**\n * Parses a property path into its segments.\n * @param path The property path (e.g., \"user.password\" or \"users[0].email\").\n * @returns An array of path segments.\n */\nfunction parsePathSegments(path: string): string[] {\n const segments: string[] = [];\n let current = \"\";\n for (const char of path) {\n if (char === \".\" || char === \"[\") {\n if (current) segments.push(current);\n current = \"\";\n } else if (char === \"]\" || char === \"?\") {\n // Skip these characters\n } else {\n current += char;\n }\n }\n if (current) segments.push(current);\n return segments;\n}\n\n/**\n * Determines which placeholder indices should be redacted based on field\n * patterns, and which are wildcard placeholders.\n * @param placeholders Array of placeholder names from the template.\n * @param fieldPatterns Field patterns to match against.\n * @returns Object with redactedIndices and wildcardIndices.\n */\nfunction getRedactedPlaceholderIndices(\n placeholders: string[],\n fieldPatterns: FieldPatterns,\n): { redactedIndices: Set<number>; wildcardIndices: Set<number> } {\n const redactedIndices = new Set<number>();\n const wildcardIndices = new Set<number>();\n\n for (let i = 0; i < placeholders.length; i++) {\n const placeholder = placeholders[i];\n\n // Track wildcard {*} separately\n if (placeholder === \"*\") {\n wildcardIndices.add(i);\n continue;\n }\n\n // Check the full placeholder name\n if (shouldFieldRedacted(placeholder, fieldPatterns)) {\n redactedIndices.add(i);\n continue;\n }\n // For nested paths, check each segment\n const segments = parsePathSegments(placeholder);\n for (const segment of segments) {\n if (shouldFieldRedacted(segment, fieldPatterns)) {\n redactedIndices.add(i);\n break;\n }\n }\n }\n return { redactedIndices, wildcardIndices };\n}\n\n/**\n * Redacts values in the message array based on the redacted placeholder\n * indices and wildcard indices.\n * @param message The original message array.\n * @param placeholders Array of placeholder names from the template.\n * @param redactedIndices Set of placeholder indices to redact.\n * @param wildcardIndices Set of wildcard placeholder indices.\n * @param redactedProperties The redacted properties object.\n * @param action The redaction action.\n * @returns New message array with redacted values.\n */\nfunction redactMessageArray(\n message: readonly unknown[],\n placeholders: string[],\n redactedIndices: Set<number>,\n wildcardIndices: Set<number>,\n redactedProperties: Record<string, unknown>,\n action: \"delete\" | ((value: unknown) => unknown) | undefined,\n): readonly unknown[] {\n const result: unknown[] = [];\n let placeholderIndex = 0;\n\n for (let i = 0; i < message.length; i++) {\n if (i % 2 === 0) {\n // Even index: text segment\n result.push(message[i]);\n } else {\n // Odd index: value/placeholder\n if (wildcardIndices.has(placeholderIndex)) {\n // Wildcard {*}: replace with redacted properties\n result.push(redactedProperties);\n } else if (redactedIndices.has(placeholderIndex)) {\n if (action == null || action === \"delete\") {\n result.push(\"\");\n } else {\n result.push(action(message[i]));\n }\n } else {\n // For non-redacted placeholders, use value from redactedProperties\n // to ensure nested sensitive fields are redacted\n const placeholderName = placeholders[placeholderIndex];\n const rootKey = parsePathSegments(placeholderName)[0];\n if (rootKey in redactedProperties) {\n result.push(redactedProperties[rootKey]);\n } else {\n result.push(message[i]);\n }\n }\n placeholderIndex++;\n }\n }\n return result;\n}\n\n/**\n * Collects redacted value mappings from original to redacted properties.\n * @param original The original properties.\n * @param redacted The redacted properties.\n * @param map The map to populate with original -> redacted value pairs.\n */\nfunction collectRedactedValues(\n original: Record<string, unknown>,\n redacted: Record<string, unknown>,\n map: Map<unknown, unknown>,\n): void {\n for (const key in original) {\n const origVal = original[key];\n const redVal = redacted[key];\n\n if (origVal !== redVal) {\n map.set(origVal, redVal);\n }\n\n // Recurse into nested objects\n if (\n typeof origVal === \"object\" && origVal !== null &&\n typeof redVal === \"object\" && redVal !== null &&\n !Array.isArray(origVal)\n ) {\n collectRedactedValues(\n origVal as Record<string, unknown>,\n redVal as Record<string, unknown>,\n map,\n );\n }\n }\n}\n\n/**\n * Gets a map of original values to their redacted replacements.\n * @param original The original properties.\n * @param redacted The redacted properties.\n * @returns A map of original -> redacted values.\n */\nfunction getRedactedValues(\n original: Record<string, unknown>,\n redacted: Record<string, unknown>,\n): Map<unknown, unknown> {\n const map = new Map<unknown, unknown>();\n collectRedactedValues(original, redacted, map);\n return map;\n}\n\n/**\n * Redacts message array values by comparing with redacted property values.\n * Used for tagged template literals where placeholder names are not available.\n * @param message The original message array.\n * @param redactedValues Map of original -> redacted values.\n * @returns New message array with redacted values.\n */\nfunction redactMessageByValues(\n message: readonly unknown[],\n redactedValues: Map<unknown, unknown>,\n): readonly unknown[] {\n if (redactedValues.size === 0) return message;\n\n const result: unknown[] = [];\n for (let i = 0; i < message.length; i++) {\n if (i % 2 === 0) {\n result.push(message[i]);\n } else {\n const val = message[i];\n if (redactedValues.has(val)) {\n result.push(redactedValues.get(val));\n } else {\n result.push(val);\n }\n }\n }\n return result;\n}\n"],"mappings":";AAGA,MAAMA,gBAAuC,OAAO,WAClD,OAAO,IAAI,iBAAiB;AAC9B,MAAMC,qBAAiD,OAAO,gBAC5D,OAAO,IAAI,sBAAsB;;;;;;;AAsBnC,MAAaC,wBAAuC;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDD,SAAgB,cACdC,MACAC,UAAiD,uBACE;CACnD,MAAM,OAAO,MAAM,QAAQ,QAAQ,GAAG,EAAE,eAAe,QAAS,IAAG;CACnE,MAAM,UAAU,CAACC,WAAsB;EACrC,MAAM,qBAAqB,iBAAiB,OAAO,YAAY,KAAK;EACpE,IAAI,kBAAkB,OAAO;AAE7B,aAAW,OAAO,eAAe,UAAU;GAEzC,MAAM,eAAe,wBAAwB,OAAO,WAAW;GAC/D,MAAM,EAAE,iBAAiB,iBAAiB,GACxC,8BACE,cACA,KAAK,cACN;AACH,qBAAkB,mBAChB,OAAO,SACP,cACA,iBACA,iBACA,oBACA,KAAK,OACN;EACF,OAAM;GAEL,MAAM,iBAAiB,kBACrB,OAAO,YACP,mBACD;AACD,OAAI,eAAe,OAAO,EACxB,mBAAkB,sBAAsB,OAAO,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C9C,QAAO;AACR;;;;;;;;AASD,SAAS,sBACPP,SACAS,gBACoB;AACpB,KAAI,eAAe,SAAS,EAAG,QAAO;CAEtC,MAAMJ,SAAoB,CAAE;AAC5B,MAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,IAClC,KAAI,IAAI,MAAM,EACZ,QAAO,KAAK,QAAQ,GAAG;MAClB;EACL,MAAM,MAAM,QAAQ;AACpB,MAAI,eAAe,IAAI,IAAI,CACzB,QAAO,KAAK,eAAe,IAAI,IAAI,CAAC;MAEpC,QAAO,KAAK,IAAI;CAEnB;AAEH,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"field.js","names":["disposeSymbol: typeof Symbol.dispose","asyncDisposeSymbol: typeof Symbol.asyncDispose","DEFAULT_REDACT_FIELDS: FieldPatterns","sink: Sink | Sink & Disposable | Sink & AsyncDisposable","options: FieldRedactionOptions | FieldPatterns","record: LogRecord","value: unknown","properties: Record<string, unknown>","options: FieldRedactionOptions","copy: Record<string, unknown>","visited: Map<object, object>","item: unknown","copy: unknown[]","index: number","value: object","field: string","fieldPatterns: FieldPatterns","template: string","placeholders: string[]","path: string","segments: string[]","message: readonly unknown[]","redactedIndices: Set<number>","wildcardIndices: Set<number>","redactedProperties: Record<string, unknown>","action: \"delete\" | ((value: unknown) => unknown) | undefined","redactArgument: (value: unknown) => unknown","result: unknown[]","original: Record<string, unknown>","redacted: Record<string, unknown>","map: Map<unknown, unknown>","ancestors: Set<object>","redactedValues: Map<unknown, unknown>"],"sources":["../src/field.ts"],"sourcesContent":["import type { LogRecord, Sink } from \"@logtape/logtape\";\nimport { copyStructured, defineField, omit } from \"./structured.ts\";\n\n// Match transpiled resource management without changing the global Symbol.\nconst disposeSymbol: typeof Symbol.dispose = Symbol.dispose ??\n Symbol.for(\"Symbol.dispose\");\nconst asyncDisposeSymbol: typeof Symbol.asyncDispose = Symbol.asyncDispose ??\n Symbol.for(\"Symbol.asyncDispose\");\n\n/**\n * The type for a field pattern used in redaction. A string or a regular\n * expression that matches field names.\n * @since 0.10.0\n */\nexport type FieldPattern = string | RegExp;\n\n/**\n * An array of field patterns used for redaction. Each pattern can be\n * a string or a regular expression that matches field names.\n * @since 0.10.0\n */\nexport type FieldPatterns = FieldPattern[];\n\n/**\n * Default field patterns for redaction. These patterns will match\n * common sensitive fields such as passwords, tokens, and personal\n * information.\n * @since 0.10.0\n */\nexport const DEFAULT_REDACT_FIELDS: FieldPatterns = [\n /pass(?:code|phrase|word)/i,\n /secret/i,\n /token/i,\n /key/i,\n /credential/i,\n /auth/i,\n /signature/i,\n /sensitive/i,\n /private/i,\n /ssn/i,\n /email/i,\n /phone/i,\n /address/i,\n];\n\n/**\n * Options for redacting fields in a {@link LogRecord}. Used by\n * the {@link redactByField} function.\n * @since 0.10.0\n */\nexport interface FieldRedactionOptions {\n /**\n * The field patterns to match against. This can be an array of\n * strings or regular expressions. If a field matches any of the\n * patterns, it will be redacted.\n * @defaultValue {@link DEFAULT_REDACT_FIELDS}\n */\n readonly fieldPatterns: FieldPatterns;\n\n /**\n * The action to perform on the matched fields. If not provided,\n * the default action is to delete the field from the properties.\n * If a function is provided, it will be called with the\n * value of the field, and the return value will be used to replace\n * the field in the properties.\n * If the action is `\"delete\"`, the field will be removed from the\n * properties.\n * @default `\"delete\"`\n */\n readonly action?: \"delete\" | ((value: unknown) => unknown);\n}\n\n/**\n * Redacts properties and message values in a {@link LogRecord} based on the\n * provided field patterns and action.\n *\n * Note that it is a decorator which wraps the sink and redacts properties\n * and message values before passing them to the sink.\n *\n * For string templates (e.g., `\"Hello, {name}!\"`), placeholder names are\n * matched against the field patterns to determine which values to redact.\n *\n * For tagged template literals (e.g., `` `Hello, ${name}!` ``), redaction\n * is performed by comparing message values with redacted property values.\n *\n * @example\n * ```ts\n * import { getConsoleSink } from \"@logtape/logtape\";\n * import { redactByField } from \"@logtape/redaction\";\n *\n * const sink = redactByField(getConsoleSink());\n * ```\n *\n * @param sink The sink to wrap.\n * @param options The redaction options.\n * @returns The wrapped sink.\n * @since 0.10.0\n */\nexport function redactByField(\n sink: Sink | Sink & Disposable | Sink & AsyncDisposable,\n options: FieldRedactionOptions | FieldPatterns = DEFAULT_REDACT_FIELDS,\n): Sink | Sink & Disposable | Sink & AsyncDisposable {\n const opts = Array.isArray(options) ? { fieldPatterns: options } : options;\n const wrapped = (record: LogRecord) => {\n const visited = new Map<object, object>();\n const redactedProperties = redactProperties(\n record.properties,\n opts,\n visited,\n );\n const redactArgument = (value: unknown): unknown =>\n redactValue(value, opts, visited);\n let redactedMessage = record.message;\n\n if (typeof record.rawMessage === \"string\") {\n // String template: redact by placeholder names\n const placeholders = extractPlaceholderNames(record.rawMessage);\n const { redactedIndices, wildcardIndices } =\n getRedactedPlaceholderIndices(\n placeholders,\n opts.fieldPatterns,\n );\n redactedMessage = redactMessageArray(\n record.message,\n placeholders,\n redactedIndices,\n wildcardIndices,\n redactedProperties,\n opts.action,\n redactArgument,\n );\n } else {\n // Tagged template: redact by comparing values\n const redactedValues = getRedactedValues(\n record.properties,\n redactedProperties,\n );\n redactedMessage = redactMessageByValues(\n record.message,\n redactedValues,\n redactArgument,\n );\n }\n\n sink({\n ...record,\n message: redactedMessage,\n properties: redactedProperties,\n });\n };\n if (disposeSymbol in sink) wrapped[disposeSymbol] = sink[disposeSymbol];\n if (asyncDisposeSymbol in sink) {\n wrapped[asyncDisposeSymbol] = sink[asyncDisposeSymbol];\n }\n return wrapped;\n}\n\n/**\n * Redacts properties from an object based on specified field patterns.\n *\n * This function creates a shallow copy of the input object and applies\n * redaction rules to its properties. For properties that match the redaction\n * patterns, the function either removes them or transforms their values based\n * on the provided action.\n *\n * The redaction process is recursive and will be applied to nested objects\n * as well, allowing for deep redaction of sensitive data in complex object\n * structures.\n * @param properties The properties to redact.\n * @param options The redaction options.\n * @returns The redacted properties.\n * @since 0.10.0\n */\nexport function redactProperties(\n properties: Record<string, unknown>,\n options: FieldRedactionOptions,\n visited = new Map<object, object>(),\n): Record<string, unknown> {\n if (visited.has(properties)) {\n return visited.get(properties) as Record<string, unknown>;\n }\n\n const copy: Record<string, unknown> = {};\n visited.set(properties, copy);\n\n for (const field in properties) {\n if (shouldFieldRedacted(field, options.fieldPatterns)) {\n if (typeof options.action === \"function\") {\n defineField(copy, field, options.action(properties[field]));\n }\n continue;\n }\n\n defineField(copy, field, redactValue(properties[field], options, visited));\n }\n return copy;\n}\n\nfunction redactValue(\n value: unknown,\n options: FieldRedactionOptions,\n visited: Map<object, object>,\n): unknown {\n if (typeof value !== \"object\" || value == null) return value;\n if (visited.has(value)) return visited.get(value);\n const transform = (item: unknown): unknown =>\n redactValue(item, options, visited);\n if (Array.isArray(value)) {\n const copy: unknown[] = new Array(value.length);\n visited.set(value, copy);\n Array.prototype.forEach.call(value, (item, index: number) => {\n copy[index] = transform(item);\n });\n return copy;\n }\n const structured = copyStructured(\n value,\n visited,\n transform,\n (key, item) => {\n if (!shouldFieldRedacted(key, options.fieldPatterns)) {\n return transform(item);\n }\n if (typeof options.action !== \"function\") return omit;\n try {\n return options.action(item);\n } catch {\n return omit;\n }\n },\n false,\n );\n if (structured != null) return structured;\n if (isBuiltInObject(value)) return value;\n return redactProperties(value as Record<string, unknown>, options, visited);\n}\n\n/**\n * Checks if a value is a built-in object that should not be recursively\n * processed (e.g., Error, Date, RegExp, Map, Set, etc.).\n * @param value The value to check.\n * @returns `true` if the value is a built-in object, `false` otherwise.\n */\nfunction isBuiltInObject(value: object): boolean {\n return value instanceof Date ||\n value instanceof RegExp ||\n value instanceof WeakMap ||\n value instanceof WeakSet ||\n value instanceof Promise ||\n value instanceof ArrayBuffer ||\n (typeof SharedArrayBuffer !== \"undefined\" &&\n value instanceof SharedArrayBuffer) ||\n ArrayBuffer.isView(value);\n}\n\n/**\n * Checks if a field should be redacted based on the provided field patterns.\n * @param field The field name to check.\n * @param fieldPatterns The field patterns to match against.\n * @returns `true` if the field should be redacted, `false` otherwise.\n * @since 0.10.0\n */\nexport function shouldFieldRedacted(\n field: string,\n fieldPatterns: FieldPatterns,\n): boolean {\n for (const fieldPattern of fieldPatterns) {\n if (typeof fieldPattern === \"string\") {\n if (fieldPattern === field) return true;\n } else {\n if (fieldPattern.test(field)) return true;\n }\n }\n return false;\n}\n\n/**\n * Extracts placeholder names from a message template string in order.\n * @param template The message template string.\n * @returns An array of placeholder names in the order they appear.\n */\nfunction extractPlaceholderNames(template: string): string[] {\n const placeholders: string[] = [];\n for (let i = 0; i < template.length; i++) {\n if (template[i] === \"{\") {\n // Check for escaped brace\n if (i + 1 < template.length && template[i + 1] === \"{\") {\n i++;\n continue;\n }\n const closeIndex = template.indexOf(\"}\", i + 1);\n if (closeIndex === -1) continue;\n const key = template.slice(i + 1, closeIndex).trim();\n placeholders.push(key);\n i = closeIndex;\n }\n }\n return placeholders;\n}\n\n/**\n * Parses a property path into its segments.\n * @param path The property path (e.g., \"user.password\" or \"users[0].email\").\n * @returns An array of path segments.\n */\nfunction parsePathSegments(path: string): string[] {\n const segments: string[] = [];\n let current = \"\";\n for (const char of path) {\n if (char === \".\" || char === \"[\") {\n if (current) segments.push(current);\n current = \"\";\n } else if (char === \"]\" || char === \"?\") {\n // Skip these characters\n } else {\n current += char;\n }\n }\n if (current) segments.push(current);\n return segments;\n}\n\n/**\n * Determines which placeholder indices should be redacted based on field\n * patterns, and which are wildcard placeholders.\n * @param placeholders Array of placeholder names from the template.\n * @param fieldPatterns Field patterns to match against.\n * @returns Object with redactedIndices and wildcardIndices.\n */\nfunction getRedactedPlaceholderIndices(\n placeholders: string[],\n fieldPatterns: FieldPatterns,\n): { redactedIndices: Set<number>; wildcardIndices: Set<number> } {\n const redactedIndices = new Set<number>();\n const wildcardIndices = new Set<number>();\n\n for (let i = 0; i < placeholders.length; i++) {\n const placeholder = placeholders[i];\n\n // Track wildcard {*} separately\n if (placeholder === \"*\") {\n wildcardIndices.add(i);\n continue;\n }\n\n // Check the full placeholder name\n if (shouldFieldRedacted(placeholder, fieldPatterns)) {\n redactedIndices.add(i);\n continue;\n }\n // For nested paths, check each segment\n const segments = parsePathSegments(placeholder);\n for (const segment of segments) {\n if (shouldFieldRedacted(segment, fieldPatterns)) {\n redactedIndices.add(i);\n break;\n }\n }\n }\n return { redactedIndices, wildcardIndices };\n}\n\n/**\n * Redacts values in the message array based on the redacted placeholder\n * indices and wildcard indices.\n * @param message The original message array.\n * @param placeholders Array of placeholder names from the template.\n * @param redactedIndices Set of placeholder indices to redact.\n * @param wildcardIndices Set of wildcard placeholder indices.\n * @param redactedProperties The redacted properties object.\n * @param action The redaction action.\n * @param redactArgument Transforms an argument without a matching field.\n * @returns New message array with redacted values.\n */\nfunction redactMessageArray(\n message: readonly unknown[],\n placeholders: string[],\n redactedIndices: Set<number>,\n wildcardIndices: Set<number>,\n redactedProperties: Record<string, unknown>,\n action: \"delete\" | ((value: unknown) => unknown) | undefined,\n redactArgument: (value: unknown) => unknown,\n): readonly unknown[] {\n const result: unknown[] = [];\n let placeholderIndex = 0;\n\n for (let i = 0; i < message.length; i++) {\n if (i % 2 === 0) {\n // Even index: text segment\n result.push(message[i]);\n } else {\n // Odd index: value/placeholder\n if (wildcardIndices.has(placeholderIndex)) {\n // Wildcard {*}: replace with redacted properties\n result.push(redactedProperties);\n } else if (redactedIndices.has(placeholderIndex)) {\n if (action == null || action === \"delete\") {\n result.push(\"\");\n } else {\n result.push(action(message[i]));\n }\n } else {\n // For non-redacted placeholders, use value from redactedProperties\n // to ensure nested sensitive fields are redacted\n const placeholderName = placeholders[placeholderIndex] ?? \"\";\n const rootKey = parsePathSegments(placeholderName)[0];\n if (Object.hasOwn(redactedProperties, rootKey)) {\n result.push(redactedProperties[rootKey]);\n } else {\n result.push(redactArgument(message[i]));\n }\n }\n placeholderIndex++;\n }\n }\n return result;\n}\n\n/**\n * Collects redacted value mappings from original to redacted properties.\n * @param original The original properties.\n * @param redacted The redacted properties.\n * @param map The map to populate with original -> redacted value pairs.\n */\nfunction collectRedactedValues(\n original: Record<string, unknown>,\n redacted: Record<string, unknown>,\n map: Map<unknown, unknown>,\n ancestors: Set<object>,\n): void {\n if (ancestors.has(original)) return;\n ancestors.add(original);\n for (const key in original) {\n const origVal = original[key];\n const redVal = Object.hasOwn(redacted, key) ? redacted[key] : undefined;\n\n if (origVal !== redVal) {\n map.set(origVal, redVal);\n }\n\n // Recurse into nested objects\n if (\n typeof origVal === \"object\" && origVal !== null &&\n typeof redVal === \"object\" && redVal !== null &&\n !Array.isArray(origVal) &&\n Object.getPrototypeOf(redVal) === Object.prototype\n ) {\n collectRedactedValues(\n origVal as Record<string, unknown>,\n redVal as Record<string, unknown>,\n map,\n ancestors,\n );\n }\n }\n ancestors.delete(original);\n}\n\n/**\n * Gets a map of original values to their redacted replacements.\n * @param original The original properties.\n * @param redacted The redacted properties.\n * @returns A map of original -> redacted values.\n */\nfunction getRedactedValues(\n original: Record<string, unknown>,\n redacted: Record<string, unknown>,\n): Map<unknown, unknown> {\n const map = new Map<unknown, unknown>();\n collectRedactedValues(original, redacted, map, new Set());\n return map;\n}\n\n/**\n * Redacts message array values by comparing with redacted property values.\n * Used for tagged template literals where placeholder names are not available.\n * @param message The original message array.\n * @param redactedValues Map of original -> redacted values.\n * @param redactArgument Transforms an argument without a matching field.\n * @returns New message array with redacted values.\n */\nfunction redactMessageByValues(\n message: readonly unknown[],\n redactedValues: Map<unknown, unknown>,\n redactArgument: (value: unknown) => unknown,\n): readonly unknown[] {\n const result: unknown[] = [];\n for (let i = 0; i < message.length; i++) {\n if (i % 2 === 0) {\n result.push(message[i]);\n } else {\n const val = message[i];\n if (redactedValues.has(val)) {\n result.push(redactedValues.get(val));\n } else {\n result.push(redactArgument(val));\n }\n }\n }\n return result;\n}\n"],"mappings":";;;AAIA,MAAMA,gBAAuC,OAAO,WAClD,OAAO,IAAI,iBAAiB;AAC9B,MAAMC,qBAAiD,OAAO,gBAC5D,OAAO,IAAI,sBAAsB;;;;;;;AAsBnC,MAAaC,wBAAuC;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAC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oB,CAAE;AAC5B,MAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,IAClC,KAAI,IAAI,MAAM,EACZ,QAAO,KAAK,QAAQ,GAAG;MAClB;EACL,MAAM,MAAM,QAAQ;AACpB,MAAI,eAAe,IAAI,IAAI,CACzB,QAAO,KAAK,eAAe,IAAI,IAAI,CAAC;MAEpC,QAAO,KAAK,eAAe,IAAI,CAAC;CAEnC;AAEH,QAAO;AACR"}
|
package/dist/pattern.cjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const require_structured = require('./structured.cjs');
|
|
1
2
|
|
|
2
3
|
//#region src/pattern.ts
|
|
3
4
|
/**
|
|
@@ -121,7 +122,7 @@ const JWT_PATTERN = {
|
|
|
121
122
|
* @returns `true` if the value is a built-in object, `false` otherwise.
|
|
122
123
|
*/
|
|
123
124
|
function isBuiltInObject(value) {
|
|
124
|
-
return value instanceof
|
|
125
|
+
return value instanceof Date || value instanceof RegExp || value instanceof WeakMap || value instanceof WeakSet || value instanceof Promise || value instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer || ArrayBuffer.isView(value);
|
|
125
126
|
}
|
|
126
127
|
function redactByPattern(formatter, patterns) {
|
|
127
128
|
for (const { pattern } of patterns) if (!pattern.global) throw new TypeError(`Pattern ${pattern} does not have the global flag set.`);
|
|
@@ -141,10 +142,12 @@ function redactByPattern(formatter, patterns) {
|
|
|
141
142
|
return copy;
|
|
142
143
|
}
|
|
143
144
|
if (typeof object === "object" && object !== null) {
|
|
145
|
+
const structured = require_structured.copyStructured(object, visited, (value) => replaceObject(value, visited), (_key, value) => replaceObject(value, visited), true);
|
|
146
|
+
if (structured != null) return structured;
|
|
144
147
|
if (isBuiltInObject(object)) return object;
|
|
145
148
|
const redacted = {};
|
|
146
149
|
visited.set(object, redacted);
|
|
147
|
-
for (const key in object) if (Object.prototype.hasOwnProperty.call(object, key)) redacted
|
|
150
|
+
for (const key in object) if (Object.prototype.hasOwnProperty.call(object, key)) require_structured.defineField(redacted, key, replaceObject(object[key], visited));
|
|
148
151
|
return redacted;
|
|
149
152
|
}
|
|
150
153
|
return object;
|
|
@@ -152,7 +155,14 @@ function redactByPattern(formatter, patterns) {
|
|
|
152
155
|
return (record) => {
|
|
153
156
|
const output = formatter(record);
|
|
154
157
|
if (typeof output === "string") return replaceString(output);
|
|
155
|
-
|
|
158
|
+
const visited = /* @__PURE__ */ new Map();
|
|
159
|
+
return output.map((obj) => {
|
|
160
|
+
try {
|
|
161
|
+
return replaceObject(obj, visited);
|
|
162
|
+
} catch {
|
|
163
|
+
return "[Redaction failed]";
|
|
164
|
+
}
|
|
165
|
+
});
|
|
156
166
|
};
|
|
157
167
|
}
|
|
158
168
|
|
package/dist/pattern.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pattern.d.cts","names":[],"sources":["../src/pattern.ts"],"sourcesContent":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"pattern.d.cts","names":[],"sources":["../src/pattern.ts"],"sourcesContent":[],"mappings":";;;;;;AAYA;AAsBA;AAiJA;AASa,UAhLI,gBAAA,CAgLY;EAUhB;AASb;AASA;AAsDA;EAA+B,SAAA,OAAA,EA7PX,MA6PW;EAAA;;;AAGf;AAmChB;EAA+B,SAAA,WAAA,EAAA,MAAA,GAAA,CAAA,CAAA,KAAA,EAAA,MAAA,EAAA,GAAA,IAAA,EAAA,SAAA,GAAA,EAAA,EAAA,GAAA,MAAA,CAAA;;;;AAGZ;;cArRN,uBAAuB;;;;;;cAiJvB,4BAA4B;;;;;cAS5B,gBAAgB;;;;;;cAUhB,gBAAgB;;;;;cAShB,aAAa;;;;;KASd,iBAAA,YAA6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsDzB,eAAA,YACH,yBACD,oBACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmCa,eAAA,YACH,4BACD,oBACT"}
|
package/dist/pattern.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pattern.d.ts","names":[],"sources":["../src/pattern.ts"],"sourcesContent":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"pattern.d.ts","names":[],"sources":["../src/pattern.ts"],"sourcesContent":[],"mappings":";;;;;;AAYA;AAsBA;AAiJA;AASa,UAhLI,gBAAA,CAgLY;EAUhB;AASb;AASA;AAsDA;EAA+B,SAAA,OAAA,EA7PX,MA6PW;EAAA;;;AAGf;AAmChB;EAA+B,SAAA,WAAA,EAAA,MAAA,GAAA,CAAA,CAAA,KAAA,EAAA,MAAA,EAAA,GAAA,IAAA,EAAA,SAAA,GAAA,EAAA,EAAA,GAAA,MAAA,CAAA;;;;AAGZ;;cArRN,uBAAuB;;;;;;cAiJvB,4BAA4B;;;;;cAS5B,gBAAgB;;;;;;cAUhB,gBAAgB;;;;;cAShB,aAAa;;;;;KASd,iBAAA,YAA6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsDzB,eAAA,YACH,yBACD,oBACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmCa,eAAA,YACH,4BACD,oBACT"}
|
package/dist/pattern.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { copyStructured, defineField } from "./structured.js";
|
|
2
|
+
|
|
1
3
|
//#region src/pattern.ts
|
|
2
4
|
/**
|
|
3
5
|
* A redaction pattern for email addresses.
|
|
@@ -120,7 +122,7 @@ const JWT_PATTERN = {
|
|
|
120
122
|
* @returns `true` if the value is a built-in object, `false` otherwise.
|
|
121
123
|
*/
|
|
122
124
|
function isBuiltInObject(value) {
|
|
123
|
-
return value instanceof
|
|
125
|
+
return value instanceof Date || value instanceof RegExp || value instanceof WeakMap || value instanceof WeakSet || value instanceof Promise || value instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer || ArrayBuffer.isView(value);
|
|
124
126
|
}
|
|
125
127
|
function redactByPattern(formatter, patterns) {
|
|
126
128
|
for (const { pattern } of patterns) if (!pattern.global) throw new TypeError(`Pattern ${pattern} does not have the global flag set.`);
|
|
@@ -140,10 +142,12 @@ function redactByPattern(formatter, patterns) {
|
|
|
140
142
|
return copy;
|
|
141
143
|
}
|
|
142
144
|
if (typeof object === "object" && object !== null) {
|
|
145
|
+
const structured = copyStructured(object, visited, (value) => replaceObject(value, visited), (_key, value) => replaceObject(value, visited), true);
|
|
146
|
+
if (structured != null) return structured;
|
|
143
147
|
if (isBuiltInObject(object)) return object;
|
|
144
148
|
const redacted = {};
|
|
145
149
|
visited.set(object, redacted);
|
|
146
|
-
for (const key in object) if (Object.prototype.hasOwnProperty.call(object, key)) redacted
|
|
150
|
+
for (const key in object) if (Object.prototype.hasOwnProperty.call(object, key)) defineField(redacted, key, replaceObject(object[key], visited));
|
|
147
151
|
return redacted;
|
|
148
152
|
}
|
|
149
153
|
return object;
|
|
@@ -151,7 +155,14 @@ function redactByPattern(formatter, patterns) {
|
|
|
151
155
|
return (record) => {
|
|
152
156
|
const output = formatter(record);
|
|
153
157
|
if (typeof output === "string") return replaceString(output);
|
|
154
|
-
|
|
158
|
+
const visited = /* @__PURE__ */ new Map();
|
|
159
|
+
return output.map((obj) => {
|
|
160
|
+
try {
|
|
161
|
+
return replaceObject(obj, visited);
|
|
162
|
+
} catch {
|
|
163
|
+
return "[Redaction failed]";
|
|
164
|
+
}
|
|
165
|
+
});
|
|
155
166
|
};
|
|
156
167
|
}
|
|
157
168
|
|
package/dist/pattern.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pattern.js","names":["EMAIL_ADDRESS_PATTERN: RedactionPattern","digits: string","groups: readonly string[]","match: string","candidates: CreditCardCandidate[]","candidatesByStart: CreditCardCandidate[][]","candidate","completeCovers: (CreditCardCover | null | undefined)[]","redacted: string[]","CREDIT_CARD_NUMBER_PATTERN: RedactionPattern","US_SSN_PATTERN: RedactionPattern","KR_RRN_PATTERN: RedactionPattern","JWT_PATTERN: RedactionPattern","value: object","formatter: TextFormatter | ConsoleFormatter","patterns: RedactionPatterns","str: string","object: unknown","visited: Map<object, object>","copy: unknown[]","redacted: Record<string, unknown>","record: LogRecord"],"sources":["../src/pattern.ts"],"sourcesContent":["import type {\n ConsoleFormatter,\n LogRecord,\n TextFormatter,\n} from \"@logtape/logtape\";\n\n/**\n * A redaction pattern, which is a pair of regular expression and replacement\n * string or function.\n * @since 0.10.0\n */\nexport interface RedactionPattern {\n /**\n * The regular expression to match against. Note that it must have the\n * `g` (global) flag set, otherwise it will throw a `TypeError`.\n */\n readonly pattern: RegExp;\n\n /**\n * The replacement string or function. If the replacement is a function,\n * it will be called with the matched string and any capture groups (the same\n * signature as `String.prototype.replaceAll()`).\n */\n readonly replacement:\n | string\n // deno-lint-ignore no-explicit-any\n | ((match: string, ...rest: readonly any[]) => string);\n}\n\n/**\n * A redaction pattern for email addresses.\n * @since 0.10.0\n */\nexport const EMAIL_ADDRESS_PATTERN: RedactionPattern = {\n pattern:\n /[\\p{L}0-9.!#$%&'*+/=?^_`{|}~-]+@[\\p{L}0-9](?:[\\p{L}0-9-]{0,61}[\\p{L}0-9])?(?:\\.[\\p{L}0-9](?:[\\p{L}0-9-]{0,61}[\\p{L}0-9])?)+/gu,\n replacement: \"REDACTED@EMAIL.ADDRESS\",\n};\n\nfunction hasValidLuhnChecksum(digits: string): boolean {\n let checksum = 0;\n let shouldDouble = false;\n\n for (let i = digits.length - 1; i >= 0; i--, shouldDouble = !shouldDouble) {\n let digit = digits.charCodeAt(i) - 48;\n if (shouldDouble) {\n digit *= 2;\n if (digit > 9) digit -= 9;\n }\n checksum += digit;\n }\n\n return checksum % 10 === 0;\n}\n\nfunction hasCommonCreditCardGrouping(groups: readonly string[]): boolean {\n if (groups.length === 1) {\n return groups[0].length >= 13 && groups[0].length <= 19;\n }\n if (groups.length === 3) {\n return groups[0].length === 4 &&\n ((groups[1].length === 6 && groups[2].length >= 4 &&\n groups[2].length <= 5) ||\n ((groups[1].length === 4 || groups[1].length === 5) &&\n groups[2].length === 6));\n }\n if (groups.length === 4) {\n return groups[0].length === 4 && groups[1].length === 4 &&\n groups[2].length === 4 && groups[3].length >= 1 &&\n groups[3].length <= 4;\n }\n if (groups.length === 5) {\n return groups[0].length === 4 && groups[1].length === 4 &&\n groups[2].length === 4 && groups[3].length === 4 &&\n groups[4].length >= 1 && groups[4].length <= 3;\n }\n return false;\n}\n\nconst creditCardNumberReplacement = \"XXXX-XXXX-XXXX-XXXX\";\n\ntype CreditCardCandidate = {\n start: number;\n end: number;\n endGroup: number;\n};\n\ntype CreditCardCover = {\n readonly candidate: CreditCardCandidate;\n readonly next: CreditCardCover | null;\n};\n\nfunction redactCreditCardNumber(match: string): string {\n const groups = [...match.matchAll(/\\d+/g)];\n const candidates: CreditCardCandidate[] = [];\n const candidatesByStart: CreditCardCandidate[][] = Array.from(\n { length: groups.length },\n () => [],\n );\n\n for (let start = 0; start < groups.length; start++) {\n let digits = \"\";\n for (let end = start; end < groups.length; end++) {\n digits += groups[end][0];\n if (digits.length > 19) break;\n if (\n digits.length >= 13 &&\n hasCommonCreditCardGrouping(\n groups.slice(start, end + 1).map((group) => group[0]),\n ) &&\n hasValidLuhnChecksum(digits)\n ) {\n const candidate = {\n start: groups[start].index,\n end: groups[end].index + groups[end][0].length,\n endGroup: end,\n };\n candidates.push(candidate);\n candidatesByStart[start].push(candidate);\n }\n }\n }\n\n if (candidates.length === 0) return match;\n\n // Keep adjacent card numbers as separate redactions when their candidates\n // cover the complete group sequence without overlapping.\n const completeCovers: (CreditCardCover | null | undefined)[] = [];\n completeCovers[groups.length] = null;\n for (let start = groups.length - 1; start >= 0; start--) {\n for (const candidate of candidatesByStart[start]) {\n const tail = completeCovers[candidate.endGroup + 1];\n if (tail !== undefined) {\n completeCovers[start] = { candidate, next: tail };\n break;\n }\n }\n }\n\n const completeCover = completeCovers[0];\n const intervals = completeCover === undefined ? candidates : [];\n for (\n let cover = completeCover;\n cover != null;\n cover = cover.next\n ) {\n intervals.push(cover.candidate);\n }\n const redacted: string[] = [];\n let candidate = { ...intervals[0] };\n let offset = 0;\n for (let i = 1; i < intervals.length; i++) {\n const next = intervals[i];\n // Merge ambiguous overlaps so no portion of a possible PAN remains visible.\n if (next.start < candidate.end) {\n candidate.end = Math.max(candidate.end, next.end);\n } else {\n redacted.push(\n match.slice(offset, candidate.start),\n creditCardNumberReplacement,\n );\n offset = candidate.end;\n candidate = next;\n }\n }\n redacted.push(\n match.slice(offset, candidate.start),\n creditCardNumberReplacement,\n match.slice(candidate.end),\n );\n return redacted.join(\"\");\n}\n\n/**\n * A redaction pattern for Luhn-valid credit card numbers with 13–19 digits,\n * including numbers separated into common groups with spaces or hyphens.\n * @since 0.10.0\n */\nexport const CREDIT_CARD_NUMBER_PATTERN: RedactionPattern = {\n pattern: /(?<!\\d)(?:\\d{13,19}|\\d{4}(?:(?: +|-)\\d{1,6})+)(?!\\d)/g,\n replacement: redactCreditCardNumber,\n};\n\n/**\n * A redaction pattern for U.S. Social Security numbers.\n * @since 0.10.0\n */\nexport const US_SSN_PATTERN: RedactionPattern = {\n pattern: /(?<!\\d)\\d{3}-\\d{2}-\\d{4}(?!\\d)/g,\n replacement: \"XXX-XX-XXXX\",\n};\n\n/**\n * A redaction pattern for South Korean resident registration numbers\n * (住民登錄番號).\n * @since 0.10.0\n */\nexport const KR_RRN_PATTERN: RedactionPattern = {\n pattern: /(?<!\\d)\\d{6}-\\d{7}(?!\\d)/g,\n replacement: \"XXXXXX-XXXXXXX\",\n};\n\n/**\n * A redaction pattern for JSON Web Tokens (JWT).\n * @since 0.10.0\n */\nexport const JWT_PATTERN: RedactionPattern = {\n pattern: /eyJ[a-zA-Z0-9_-]*\\.[a-zA-Z0-9_-]*\\.[a-zA-Z0-9_-]*/g,\n replacement: \"[JWT REDACTED]\",\n};\n\n/**\n * A list of {@link RedactionPattern}s.\n * @since 0.10.0\n */\nexport type RedactionPatterns = readonly RedactionPattern[];\n\n/**\n * Checks if a value is a built-in object that should not be recursively\n * processed (e.g., Error, Date, RegExp, Map, Set, etc.).\n * @param value The value to check.\n * @returns `true` if the value is a built-in object, `false` otherwise.\n */\nfunction isBuiltInObject(value: object): boolean {\n return value instanceof Error ||\n value instanceof Date ||\n value instanceof RegExp ||\n value instanceof Map ||\n value instanceof Set ||\n value instanceof WeakMap ||\n value instanceof WeakSet ||\n value instanceof Promise ||\n value instanceof ArrayBuffer ||\n (typeof SharedArrayBuffer !== \"undefined\" &&\n value instanceof SharedArrayBuffer) ||\n ArrayBuffer.isView(value);\n}\n\n/**\n * Applies data redaction to a {@link TextFormatter}.\n *\n * Note that there are some built-in redaction patterns:\n *\n * - {@link CREDIT_CARD_NUMBER_PATTERN}\n * - {@link EMAIL_ADDRESS_PATTERN}\n * - {@link JWT_PATTERN}\n * - {@link KR_RRN_PATTERN}\n * - {@link US_SSN_PATTERN}\n *\n * @example\n * ```ts\n * import { getFileSink } from \"@logtape/file\";\n * import { getAnsiColorFormatter } from \"@logtape/logtape\";\n * import {\n * CREDIT_CARD_NUMBER_PATTERN,\n * EMAIL_ADDRESS_PATTERN,\n * JWT_PATTERN,\n * redactByPattern,\n * } from \"@logtape/redaction\";\n *\n * const formatter = redactByPattern(getAnsiConsoleFormatter(), [\n * CREDIT_CARD_NUMBER_PATTERN,\n * EMAIL_ADDRESS_PATTERN,\n * JWT_PATTERN,\n * ]);\n * const sink = getFileSink(\"my-app.log\", { formatter });\n * ```\n * @param formatter The text formatter to apply redaction to.\n * @param patterns The redaction patterns to apply.\n * @returns The redacted text formatter.\n * @since 0.10.0\n */\nexport function redactByPattern(\n formatter: TextFormatter,\n patterns: RedactionPatterns,\n): TextFormatter;\n\n/**\n * Applies data redaction to a {@link ConsoleFormatter}.\n *\n * Note that there are some built-in redaction patterns:\n *\n * - {@link CREDIT_CARD_NUMBER_PATTERN}\n * - {@link EMAIL_ADDRESS_PATTERN}\n * - {@link JWT_PATTERN}\n * - {@link KR_RRN_PATTERN}\n * - {@link US_SSN_PATTERN}\n *\n * @example\n * ```ts\n * import { defaultConsoleFormatter, getConsoleSink } from \"@logtape/logtape\";\n * import {\n * CREDIT_CARD_NUMBER_PATTERN,\n * EMAIL_ADDRESS_PATTERN,\n * JWT_PATTERN,\n * redactByPattern,\n * } from \"@logtape/redaction\";\n *\n * const formatter = redactByPattern(defaultConsoleFormatter, [\n * CREDIT_CARD_NUMBER_PATTERN,\n * EMAIL_ADDRESS_PATTERN,\n * JWT_PATTERN,\n * ]);\n * const sink = getConsoleSink({ formatter });\n * ```\n * @param formatter The console formatter to apply redaction to.\n * @param patterns The redaction patterns to apply.\n * @returns The redacted console formatter.\n * @since 0.10.0\n */\nexport function redactByPattern(\n formatter: ConsoleFormatter,\n patterns: RedactionPatterns,\n): ConsoleFormatter;\n\nexport function redactByPattern(\n formatter: TextFormatter | ConsoleFormatter,\n patterns: RedactionPatterns,\n): (record: LogRecord) => string | readonly unknown[] {\n for (const { pattern } of patterns) {\n if (!pattern.global) {\n throw new TypeError(\n `Pattern ${pattern} does not have the global flag set.`,\n );\n }\n }\n\n function replaceString(str: string): string {\n for (const p of patterns) {\n // The following ternary operator may seem strange, but it's for\n // making TypeScript happy:\n str = typeof p.replacement === \"string\"\n ? str.replaceAll(p.pattern, p.replacement)\n : str.replaceAll(p.pattern, p.replacement);\n }\n return str;\n }\n\n function replaceObject(\n object: unknown,\n visited: Map<object, object>,\n ): unknown {\n if (typeof object === \"object\" && object !== null) {\n if (visited.has(object)) {\n return visited.get(object)!; // Circular reference detected\n }\n }\n\n if (typeof object === \"string\") return replaceString(object);\n if (Array.isArray(object)) {\n const copy: unknown[] = [];\n visited.set(object, copy);\n object.forEach((item) => copy.push(replaceObject(item, visited)));\n return copy;\n }\n if (typeof object === \"object\" && object !== null) {\n if (isBuiltInObject(object)) {\n return object;\n }\n const redacted: Record<string, unknown> = {};\n visited.set(object, redacted);\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n redacted[key] = replaceObject(\n (object as Record<string, unknown>)[key],\n visited,\n );\n }\n }\n return redacted;\n }\n return object;\n }\n\n return (record: LogRecord) => {\n const output = formatter(record);\n if (typeof output === \"string\") return replaceString(output);\n return output.map((obj) => replaceObject(obj, new Map()));\n };\n}\n"],"mappings":";;;;;AAiCA,MAAaA,wBAA0C;CACrD,SACE;CACF,aAAa;AACd;AAED,SAAS,qBAAqBC,QAAyB;CACrD,IAAI,WAAW;CACf,IAAI,eAAe;AAEnB,MAAK,IAAI,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KAAK,gBAAgB,cAAc;EACzE,IAAI,QAAQ,OAAO,WAAW,EAAE,GAAG;AACnC,MAAI,cAAc;AAChB,YAAS;AACT,OAAI,QAAQ,EAAG,UAAS;EACzB;AACD,cAAY;CACb;AAED,QAAO,WAAW,OAAO;AAC1B;AAED,SAAS,4BAA4BC,QAAoC;AACvE,KAAI,OAAO,WAAW,EACpB,QAAO,OAAO,GAAG,UAAU,MAAM,OAAO,GAAG,UAAU;AAEvD,KAAI,OAAO,WAAW,EACpB,QAAO,OAAO,GAAG,WAAW,MACxB,OAAO,GAAG,WAAW,KAAK,OAAO,GAAG,UAAU,KAC9C,OAAO,GAAG,UAAU,MAClB,OAAO,GAAG,WAAW,KAAK,OAAO,GAAG,WAAW,MAC/C,OAAO,GAAG,WAAW;AAE7B,KAAI,OAAO,WAAW,EACpB,QAAO,OAAO,GAAG,WAAW,KAAK,OAAO,GAAG,WAAW,KACpD,OAAO,GAAG,WAAW,KAAK,OAAO,GAAG,UAAU,KAC9C,OAAO,GAAG,UAAU;AAExB,KAAI,OAAO,WAAW,EACpB,QAAO,OAAO,GAAG,WAAW,KAAK,OAAO,GAAG,WAAW,KACpD,OAAO,GAAG,WAAW,KAAK,OAAO,GAAG,WAAW,KAC/C,OAAO,GAAG,UAAU,KAAK,OAAO,GAAG,UAAU;AAEjD,QAAO;AACR;AAED,MAAM,8BAA8B;AAapC,SAAS,uBAAuBC,OAAu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QAAO,QAAQ,IAAI,OAAO;EAC3B;AAGH,aAAW,WAAW,SAAU,QAAO,cAAc,OAAO;AAC5D,MAAI,MAAM,QAAQ,OAAO,EAAE;GACzB,MAAMC,OAAkB,CAAE;AAC1B,WAAQ,IAAI,QAAQ,KAAK;AACzB,UAAO,QAAQ,CAAC,SAAS,KAAK,KAAK,cAAc,MAAM,QAAQ,CAAC,CAAC;AACjE,UAAO;EACR;AACD,aAAW,WAAW,YAAY,WAAW,MAAM;AACjD,OAAI,gBAAgB,OAAO,CACzB,QAAO;GAET,MAAMC,WAAoC,CAAE;AAC5C,WAAQ,IAAI,QAAQ,SAAS;AAC7B,QAAK,MAAM,OAAO,OAChB,KAAI,OAAO,UAAU,eAAe,KAAK,QAAQ,IAAI,CACnD,UAAS,OAAO,cACb,OAAmC,MACpC,QACD;AAGL,UAAO;EACR;AACD,SAAO;CACR;AAED,QAAO,CAACC,WAAsB;EAC5B,MAAM,SAAS,UAAU,OAAO;AAChC,aAAW,WAAW,SAAU,QAAO,cAAc,OAAO;AAC5D,SAAO,OAAO,IAAI,CAAC,QAAQ,cAAc,qBAAK,IAAI,MAAM,CAAC;CAC1D;AACF"}
|
|
1
|
+
{"version":3,"file":"pattern.js","names":["EMAIL_ADDRESS_PATTERN: RedactionPattern","digits: string","groups: readonly string[]","match: string","candidates: CreditCardCandidate[]","candidatesByStart: CreditCardCandidate[][]","candidate","completeCovers: (CreditCardCover | null | undefined)[]","redacted: string[]","CREDIT_CARD_NUMBER_PATTERN: RedactionPattern","US_SSN_PATTERN: RedactionPattern","KR_RRN_PATTERN: RedactionPattern","JWT_PATTERN: RedactionPattern","value: object","formatter: TextFormatter | ConsoleFormatter","patterns: RedactionPatterns","str: string","object: unknown","visited: Map<object, object>","copy: unknown[]","redacted: Record<string, unknown>","record: LogRecord"],"sources":["../src/pattern.ts"],"sourcesContent":["import type {\n ConsoleFormatter,\n LogRecord,\n TextFormatter,\n} from \"@logtape/logtape\";\nimport { copyStructured, defineField } from \"./structured.ts\";\n\n/**\n * A redaction pattern, which is a pair of regular expression and replacement\n * string or function.\n * @since 0.10.0\n */\nexport interface RedactionPattern {\n /**\n * The regular expression to match against. Note that it must have the\n * `g` (global) flag set, otherwise it will throw a `TypeError`.\n */\n readonly pattern: RegExp;\n\n /**\n * The replacement string or function. If the replacement is a function,\n * it will be called with the matched string and any capture groups (the same\n * signature as `String.prototype.replaceAll()`).\n */\n readonly replacement:\n | string\n // deno-lint-ignore no-explicit-any\n | ((match: string, ...rest: readonly any[]) => string);\n}\n\n/**\n * A redaction pattern for email addresses.\n * @since 0.10.0\n */\nexport const EMAIL_ADDRESS_PATTERN: RedactionPattern = {\n pattern:\n /[\\p{L}0-9.!#$%&'*+/=?^_`{|}~-]+@[\\p{L}0-9](?:[\\p{L}0-9-]{0,61}[\\p{L}0-9])?(?:\\.[\\p{L}0-9](?:[\\p{L}0-9-]{0,61}[\\p{L}0-9])?)+/gu,\n replacement: \"REDACTED@EMAIL.ADDRESS\",\n};\n\nfunction hasValidLuhnChecksum(digits: string): boolean {\n let checksum = 0;\n let shouldDouble = false;\n\n for (let i = digits.length - 1; i >= 0; i--, shouldDouble = !shouldDouble) {\n let digit = digits.charCodeAt(i) - 48;\n if (shouldDouble) {\n digit *= 2;\n if (digit > 9) digit -= 9;\n }\n checksum += digit;\n }\n\n return checksum % 10 === 0;\n}\n\nfunction hasCommonCreditCardGrouping(groups: readonly string[]): boolean {\n if (groups.length === 1) {\n return groups[0].length >= 13 && groups[0].length <= 19;\n }\n if (groups.length === 3) {\n return groups[0].length === 4 &&\n ((groups[1].length === 6 && groups[2].length >= 4 &&\n groups[2].length <= 5) ||\n ((groups[1].length === 4 || groups[1].length === 5) &&\n groups[2].length === 6));\n }\n if (groups.length === 4) {\n return groups[0].length === 4 && groups[1].length === 4 &&\n groups[2].length === 4 && groups[3].length >= 1 &&\n groups[3].length <= 4;\n }\n if (groups.length === 5) {\n return groups[0].length === 4 && groups[1].length === 4 &&\n groups[2].length === 4 && groups[3].length === 4 &&\n groups[4].length >= 1 && groups[4].length <= 3;\n }\n return false;\n}\n\nconst creditCardNumberReplacement = \"XXXX-XXXX-XXXX-XXXX\";\n\ntype CreditCardCandidate = {\n start: number;\n end: number;\n endGroup: number;\n};\n\ntype CreditCardCover = {\n readonly candidate: CreditCardCandidate;\n readonly next: CreditCardCover | null;\n};\n\nfunction redactCreditCardNumber(match: string): string {\n const groups = [...match.matchAll(/\\d+/g)];\n const candidates: CreditCardCandidate[] = [];\n const candidatesByStart: CreditCardCandidate[][] = Array.from(\n { length: groups.length },\n () => [],\n );\n\n for (let start = 0; start < groups.length; start++) {\n let digits = \"\";\n for (let end = start; end < groups.length; end++) {\n digits += groups[end][0];\n if (digits.length > 19) break;\n if (\n digits.length >= 13 &&\n hasCommonCreditCardGrouping(\n groups.slice(start, end + 1).map((group) => group[0]),\n ) &&\n hasValidLuhnChecksum(digits)\n ) {\n const candidate = {\n start: groups[start].index,\n end: groups[end].index + groups[end][0].length,\n endGroup: end,\n };\n candidates.push(candidate);\n candidatesByStart[start].push(candidate);\n }\n }\n }\n\n if (candidates.length === 0) return match;\n\n // Keep adjacent card numbers as separate redactions when their candidates\n // cover the complete group sequence without overlapping.\n const completeCovers: (CreditCardCover | null | undefined)[] = [];\n completeCovers[groups.length] = null;\n for (let start = groups.length - 1; start >= 0; start--) {\n for (const candidate of candidatesByStart[start]) {\n const tail = completeCovers[candidate.endGroup + 1];\n if (tail !== undefined) {\n completeCovers[start] = { candidate, next: tail };\n break;\n }\n }\n }\n\n const completeCover = completeCovers[0];\n const intervals = completeCover === undefined ? candidates : [];\n for (\n let cover = completeCover;\n cover != null;\n cover = cover.next\n ) {\n intervals.push(cover.candidate);\n }\n const redacted: string[] = [];\n let candidate = { ...intervals[0] };\n let offset = 0;\n for (let i = 1; i < intervals.length; i++) {\n const next = intervals[i];\n // Merge ambiguous overlaps so no portion of a possible PAN remains visible.\n if (next.start < candidate.end) {\n candidate.end = Math.max(candidate.end, next.end);\n } else {\n redacted.push(\n match.slice(offset, candidate.start),\n creditCardNumberReplacement,\n );\n offset = candidate.end;\n candidate = next;\n }\n }\n redacted.push(\n match.slice(offset, candidate.start),\n creditCardNumberReplacement,\n match.slice(candidate.end),\n );\n return redacted.join(\"\");\n}\n\n/**\n * A redaction pattern for Luhn-valid credit card numbers with 13–19 digits,\n * including numbers separated into common groups with spaces or hyphens.\n * @since 0.10.0\n */\nexport const CREDIT_CARD_NUMBER_PATTERN: RedactionPattern = {\n pattern: /(?<!\\d)(?:\\d{13,19}|\\d{4}(?:(?: +|-)\\d{1,6})+)(?!\\d)/g,\n replacement: redactCreditCardNumber,\n};\n\n/**\n * A redaction pattern for U.S. Social Security numbers.\n * @since 0.10.0\n */\nexport const US_SSN_PATTERN: RedactionPattern = {\n pattern: /(?<!\\d)\\d{3}-\\d{2}-\\d{4}(?!\\d)/g,\n replacement: \"XXX-XX-XXXX\",\n};\n\n/**\n * A redaction pattern for South Korean resident registration numbers\n * (住民登錄番號).\n * @since 0.10.0\n */\nexport const KR_RRN_PATTERN: RedactionPattern = {\n pattern: /(?<!\\d)\\d{6}-\\d{7}(?!\\d)/g,\n replacement: \"XXXXXX-XXXXXXX\",\n};\n\n/**\n * A redaction pattern for JSON Web Tokens (JWT).\n * @since 0.10.0\n */\nexport const JWT_PATTERN: RedactionPattern = {\n pattern: /eyJ[a-zA-Z0-9_-]*\\.[a-zA-Z0-9_-]*\\.[a-zA-Z0-9_-]*/g,\n replacement: \"[JWT REDACTED]\",\n};\n\n/**\n * A list of {@link RedactionPattern}s.\n * @since 0.10.0\n */\nexport type RedactionPatterns = readonly RedactionPattern[];\n\n/**\n * Checks if a value is a built-in object that should not be recursively\n * processed (e.g., Error, Date, RegExp, Map, Set, etc.).\n * @param value The value to check.\n * @returns `true` if the value is a built-in object, `false` otherwise.\n */\nfunction isBuiltInObject(value: object): boolean {\n return value instanceof Date ||\n value instanceof RegExp ||\n value instanceof WeakMap ||\n value instanceof WeakSet ||\n value instanceof Promise ||\n value instanceof ArrayBuffer ||\n (typeof SharedArrayBuffer !== \"undefined\" &&\n value instanceof SharedArrayBuffer) ||\n ArrayBuffer.isView(value);\n}\n\n/**\n * Applies data redaction to a {@link TextFormatter}.\n *\n * Note that there are some built-in redaction patterns:\n *\n * - {@link CREDIT_CARD_NUMBER_PATTERN}\n * - {@link EMAIL_ADDRESS_PATTERN}\n * - {@link JWT_PATTERN}\n * - {@link KR_RRN_PATTERN}\n * - {@link US_SSN_PATTERN}\n *\n * @example\n * ```ts\n * import { getFileSink } from \"@logtape/file\";\n * import { getAnsiColorFormatter } from \"@logtape/logtape\";\n * import {\n * CREDIT_CARD_NUMBER_PATTERN,\n * EMAIL_ADDRESS_PATTERN,\n * JWT_PATTERN,\n * redactByPattern,\n * } from \"@logtape/redaction\";\n *\n * const formatter = redactByPattern(getAnsiConsoleFormatter(), [\n * CREDIT_CARD_NUMBER_PATTERN,\n * EMAIL_ADDRESS_PATTERN,\n * JWT_PATTERN,\n * ]);\n * const sink = getFileSink(\"my-app.log\", { formatter });\n * ```\n * @param formatter The text formatter to apply redaction to.\n * @param patterns The redaction patterns to apply.\n * @returns The redacted text formatter.\n * @since 0.10.0\n */\nexport function redactByPattern(\n formatter: TextFormatter,\n patterns: RedactionPatterns,\n): TextFormatter;\n\n/**\n * Applies data redaction to a {@link ConsoleFormatter}.\n *\n * Note that there are some built-in redaction patterns:\n *\n * - {@link CREDIT_CARD_NUMBER_PATTERN}\n * - {@link EMAIL_ADDRESS_PATTERN}\n * - {@link JWT_PATTERN}\n * - {@link KR_RRN_PATTERN}\n * - {@link US_SSN_PATTERN}\n *\n * @example\n * ```ts\n * import { defaultConsoleFormatter, getConsoleSink } from \"@logtape/logtape\";\n * import {\n * CREDIT_CARD_NUMBER_PATTERN,\n * EMAIL_ADDRESS_PATTERN,\n * JWT_PATTERN,\n * redactByPattern,\n * } from \"@logtape/redaction\";\n *\n * const formatter = redactByPattern(defaultConsoleFormatter, [\n * CREDIT_CARD_NUMBER_PATTERN,\n * EMAIL_ADDRESS_PATTERN,\n * JWT_PATTERN,\n * ]);\n * const sink = getConsoleSink({ formatter });\n * ```\n * @param formatter The console formatter to apply redaction to.\n * @param patterns The redaction patterns to apply.\n * @returns The redacted console formatter.\n * @since 0.10.0\n */\nexport function redactByPattern(\n formatter: ConsoleFormatter,\n patterns: RedactionPatterns,\n): ConsoleFormatter;\n\nexport function redactByPattern(\n formatter: TextFormatter | ConsoleFormatter,\n patterns: RedactionPatterns,\n): (record: LogRecord) => string | readonly unknown[] {\n for (const { pattern } of patterns) {\n if (!pattern.global) {\n throw new TypeError(\n `Pattern ${pattern} does not have the global flag set.`,\n );\n }\n }\n\n function replaceString(str: string): string {\n for (const p of patterns) {\n // The following ternary operator may seem strange, but it's for\n // making TypeScript happy:\n str = typeof p.replacement === \"string\"\n ? str.replaceAll(p.pattern, p.replacement)\n : str.replaceAll(p.pattern, p.replacement);\n }\n return str;\n }\n\n function replaceObject(\n object: unknown,\n visited: Map<object, object>,\n ): unknown {\n if (typeof object === \"object\" && object !== null) {\n if (visited.has(object)) {\n return visited.get(object)!; // Circular reference detected\n }\n }\n\n if (typeof object === \"string\") return replaceString(object);\n if (Array.isArray(object)) {\n const copy: unknown[] = [];\n visited.set(object, copy);\n object.forEach((item) => copy.push(replaceObject(item, visited)));\n return copy;\n }\n if (typeof object === \"object\" && object !== null) {\n const structured = copyStructured(\n object,\n visited,\n (value) => replaceObject(value, visited),\n (_key, value) => replaceObject(value, visited),\n true,\n );\n if (structured != null) return structured;\n if (isBuiltInObject(object)) {\n return object;\n }\n const redacted: Record<string, unknown> = {};\n visited.set(object, redacted);\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n defineField(\n redacted,\n key,\n replaceObject((object as Record<string, unknown>)[key], visited),\n );\n }\n }\n return redacted;\n }\n return object;\n }\n\n return (record: LogRecord) => {\n const output = formatter(record);\n if (typeof output === \"string\") return replaceString(output);\n const visited = new Map<object, object>();\n return output.map((obj) => {\n try {\n return repla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AAQ,KAAK;AACzB,UAAO,QAAQ,CAAC,SAAS,KAAK,KAAK,cAAc,MAAM,QAAQ,CAAC,CAAC;AACjE,UAAO;EACR;AACD,aAAW,WAAW,YAAY,WAAW,MAAM;GACjD,MAAM,aAAa,eACjB,QACA,SACA,CAAC,UAAU,cAAc,OAAO,QAAQ,EACxC,CAAC,MAAM,UAAU,cAAc,OAAO,QAAQ,EAC9C,KACD;AACD,OAAI,cAAc,KAAM,QAAO;AAC/B,OAAI,gBAAgB,OAAO,CACzB,QAAO;GAET,MAAMC,WAAoC,CAAE;AAC5C,WAAQ,IAAI,QAAQ,SAAS;AAC7B,QAAK,MAAM,OAAO,OAChB,KAAI,OAAO,UAAU,eAAe,KAAK,QAAQ,IAAI,CACnD,aACE,UACA,KACA,cAAe,OAAmC,MAAM,QAAQ,CACjE;AAGL,UAAO;EACR;AACD,SAAO;CACR;AAED,QAAO,CAACC,WAAsB;EAC5B,MAAM,SAAS,UAAU,OAAO;AAChC,aAAW,WAAW,SAAU,QAAO,cAAc,OAAO;EAC5D,MAAM,0BAAU,IAAI;AACpB,SAAO,OAAO,IAAI,CAAC,QAAQ;AACzB,OAAI;AACF,WAAO,cAAc,KAAK,QAAQ;GACnC,QAAO;AACN,WAAO;GACR;EACF,EAAC;CACH;AACF"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/structured.ts
|
|
3
|
+
const mapForEach = Map.prototype.forEach;
|
|
4
|
+
const setForEach = Set.prototype.forEach;
|
|
5
|
+
const errorIsError = Error.isError;
|
|
6
|
+
const errorCopies = /* @__PURE__ */ new WeakSet();
|
|
7
|
+
const errorPrototypes = [
|
|
8
|
+
AggregateError.prototype,
|
|
9
|
+
EvalError.prototype,
|
|
10
|
+
RangeError.prototype,
|
|
11
|
+
ReferenceError.prototype,
|
|
12
|
+
SyntaxError.prototype,
|
|
13
|
+
TypeError.prototype,
|
|
14
|
+
URIError.prototype,
|
|
15
|
+
Error.prototype
|
|
16
|
+
];
|
|
17
|
+
const omit = Symbol();
|
|
18
|
+
function defineField(target, key, value, enumerable = true) {
|
|
19
|
+
Object.defineProperty(target, key, {
|
|
20
|
+
value,
|
|
21
|
+
enumerable,
|
|
22
|
+
configurable: true,
|
|
23
|
+
writable: true
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
function errorPrototype(value) {
|
|
27
|
+
if (errorIsError != null && !errorIsError(value) && !errorCopies.has(value)) return void 0;
|
|
28
|
+
return errorPrototypes.find((p) => Object.prototype.isPrototypeOf.call(p, value)) ?? (errorIsError == null ? void 0 : Error.prototype);
|
|
29
|
+
}
|
|
30
|
+
function copyStructured(value, visited, transform, transformField, transformMapKey) {
|
|
31
|
+
const prototype = errorPrototype(value);
|
|
32
|
+
if (prototype != null) {
|
|
33
|
+
const copy = Object.create(prototype);
|
|
34
|
+
errorCopies.add(copy);
|
|
35
|
+
visited.set(value, copy);
|
|
36
|
+
const diagnostics = [
|
|
37
|
+
"name",
|
|
38
|
+
"message",
|
|
39
|
+
"cause",
|
|
40
|
+
"errors"
|
|
41
|
+
];
|
|
42
|
+
for (const key of new Set([...diagnostics, ...Object.keys(value)])) {
|
|
43
|
+
if (key === "stack" || key === "toJSON" || key === "toString" || key === "valueOf") continue;
|
|
44
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
45
|
+
if (descriptor == null || !("value" in descriptor) || typeof descriptor.value === "function") continue;
|
|
46
|
+
let result;
|
|
47
|
+
try {
|
|
48
|
+
result = transformField(key, descriptor.value);
|
|
49
|
+
} catch {
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (result === omit) continue;
|
|
53
|
+
if ((key === "name" || key === "message") && typeof result !== "string") continue;
|
|
54
|
+
defineField(copy, key, result, !diagnostics.includes(key));
|
|
55
|
+
}
|
|
56
|
+
return copy;
|
|
57
|
+
}
|
|
58
|
+
if (value instanceof Map) {
|
|
59
|
+
const copy = /* @__PURE__ */ new Map();
|
|
60
|
+
visited.set(value, copy);
|
|
61
|
+
mapForEach.call(value, (member, key) => {
|
|
62
|
+
const result = typeof key === "string" ? transformField(key, member) : transform(member);
|
|
63
|
+
if (result !== omit) {
|
|
64
|
+
const outputKey = !transformMapKey && typeof key === "string" ? key : transform(key);
|
|
65
|
+
copy.set(outputKey, result);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
return copy;
|
|
69
|
+
}
|
|
70
|
+
if (value instanceof Set) {
|
|
71
|
+
const copy = /* @__PURE__ */ new Set();
|
|
72
|
+
visited.set(value, copy);
|
|
73
|
+
setForEach.call(value, (member) => copy.add(transform(member)));
|
|
74
|
+
return copy;
|
|
75
|
+
}
|
|
76
|
+
return void 0;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
//#endregion
|
|
80
|
+
exports.copyStructured = copyStructured;
|
|
81
|
+
exports.defineField = defineField;
|
|
82
|
+
exports.omit = omit;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
//#region src/structured.ts
|
|
2
|
+
const mapForEach = Map.prototype.forEach;
|
|
3
|
+
const setForEach = Set.prototype.forEach;
|
|
4
|
+
const errorIsError = Error.isError;
|
|
5
|
+
const errorCopies = /* @__PURE__ */ new WeakSet();
|
|
6
|
+
const errorPrototypes = [
|
|
7
|
+
AggregateError.prototype,
|
|
8
|
+
EvalError.prototype,
|
|
9
|
+
RangeError.prototype,
|
|
10
|
+
ReferenceError.prototype,
|
|
11
|
+
SyntaxError.prototype,
|
|
12
|
+
TypeError.prototype,
|
|
13
|
+
URIError.prototype,
|
|
14
|
+
Error.prototype
|
|
15
|
+
];
|
|
16
|
+
const omit = Symbol();
|
|
17
|
+
function defineField(target, key, value, enumerable = true) {
|
|
18
|
+
Object.defineProperty(target, key, {
|
|
19
|
+
value,
|
|
20
|
+
enumerable,
|
|
21
|
+
configurable: true,
|
|
22
|
+
writable: true
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
function errorPrototype(value) {
|
|
26
|
+
if (errorIsError != null && !errorIsError(value) && !errorCopies.has(value)) return void 0;
|
|
27
|
+
return errorPrototypes.find((p) => Object.prototype.isPrototypeOf.call(p, value)) ?? (errorIsError == null ? void 0 : Error.prototype);
|
|
28
|
+
}
|
|
29
|
+
function copyStructured(value, visited, transform, transformField, transformMapKey) {
|
|
30
|
+
const prototype = errorPrototype(value);
|
|
31
|
+
if (prototype != null) {
|
|
32
|
+
const copy = Object.create(prototype);
|
|
33
|
+
errorCopies.add(copy);
|
|
34
|
+
visited.set(value, copy);
|
|
35
|
+
const diagnostics = [
|
|
36
|
+
"name",
|
|
37
|
+
"message",
|
|
38
|
+
"cause",
|
|
39
|
+
"errors"
|
|
40
|
+
];
|
|
41
|
+
for (const key of new Set([...diagnostics, ...Object.keys(value)])) {
|
|
42
|
+
if (key === "stack" || key === "toJSON" || key === "toString" || key === "valueOf") continue;
|
|
43
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
44
|
+
if (descriptor == null || !("value" in descriptor) || typeof descriptor.value === "function") continue;
|
|
45
|
+
let result;
|
|
46
|
+
try {
|
|
47
|
+
result = transformField(key, descriptor.value);
|
|
48
|
+
} catch {
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (result === omit) continue;
|
|
52
|
+
if ((key === "name" || key === "message") && typeof result !== "string") continue;
|
|
53
|
+
defineField(copy, key, result, !diagnostics.includes(key));
|
|
54
|
+
}
|
|
55
|
+
return copy;
|
|
56
|
+
}
|
|
57
|
+
if (value instanceof Map) {
|
|
58
|
+
const copy = /* @__PURE__ */ new Map();
|
|
59
|
+
visited.set(value, copy);
|
|
60
|
+
mapForEach.call(value, (member, key) => {
|
|
61
|
+
const result = typeof key === "string" ? transformField(key, member) : transform(member);
|
|
62
|
+
if (result !== omit) {
|
|
63
|
+
const outputKey = !transformMapKey && typeof key === "string" ? key : transform(key);
|
|
64
|
+
copy.set(outputKey, result);
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
return copy;
|
|
68
|
+
}
|
|
69
|
+
if (value instanceof Set) {
|
|
70
|
+
const copy = /* @__PURE__ */ new Set();
|
|
71
|
+
visited.set(value, copy);
|
|
72
|
+
setForEach.call(value, (member) => copy.add(transform(member)));
|
|
73
|
+
return copy;
|
|
74
|
+
}
|
|
75
|
+
return void 0;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
//#endregion
|
|
79
|
+
export { copyStructured, defineField, omit };
|
|
80
|
+
//# sourceMappingURL=structured.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"structured.js","names":["target: object","key: string","value: unknown","value: object","visited: Map<object, object>","transform: (value: unknown) => unknown","transformField: TransformField","transformMapKey: boolean","copy: Error","result: unknown"],"sources":["../src/structured.ts"],"sourcesContent":["const mapForEach = Map.prototype.forEach;\nconst setForEach = Set.prototype.forEach;\nconst errorIsError = (Error as ErrorConstructor & {\n isError?: (value: unknown) => boolean;\n}).isError;\nconst errorCopies = new WeakSet<object>();\nconst errorPrototypes = [\n AggregateError.prototype,\n EvalError.prototype,\n RangeError.prototype,\n ReferenceError.prototype,\n SyntaxError.prototype,\n TypeError.prototype,\n URIError.prototype,\n Error.prototype,\n];\n\nexport const omit = Symbol();\n\nexport type TransformField = (\n key: string,\n value: unknown,\n) => unknown;\n\nexport function defineField(\n target: object,\n key: string,\n value: unknown,\n enumerable = true,\n): void {\n Object.defineProperty(target, key, {\n value,\n enumerable,\n configurable: true,\n writable: true,\n });\n}\n\nfunction errorPrototype(value: object): Error | undefined {\n if (errorIsError != null && !errorIsError(value) && !errorCopies.has(value)) {\n return undefined;\n }\n return errorPrototypes.find((p) =>\n Object.prototype.isPrototypeOf.call(p, value)\n ) ??\n (errorIsError == null ? undefined : Error.prototype);\n}\n\nexport function copyStructured(\n value: object,\n visited: Map<object, object>,\n transform: (value: unknown) => unknown,\n transformField: TransformField,\n transformMapKey: boolean,\n): object | undefined {\n const prototype = errorPrototype(value);\n if (prototype != null) {\n // Do not construct a native Error here. Inspecting or removing its\n // generated stack can execute application code on some runtimes.\n const copy: Error = Object.create(prototype);\n errorCopies.add(copy);\n visited.set(value, copy);\n const diagnostics = [\"name\", \"message\", \"cause\", \"errors\"];\n // Read known data descriptors individually. Do not enumerate\n // non-enumerable keys or request the stack descriptor.\n for (const key of new Set([...diagnostics, ...Object.keys(value)])) {\n if (\n key === \"stack\" || key === \"toJSON\" || key === \"toString\" ||\n key === \"valueOf\"\n ) continue;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (\n descriptor == null || !(\"value\" in descriptor) ||\n typeof descriptor.value === \"function\"\n ) continue;\n let result: unknown;\n try {\n result = transformField(key, descriptor.value);\n } catch {\n // Do not pass the original diagnostic or the failure to a sink.\n continue;\n }\n if (result === omit) continue;\n // Native renderers may coerce these diagnostics to strings.\n if ((key === \"name\" || key === \"message\") && typeof result !== \"string\") {\n continue;\n }\n defineField(copy, key, result, !diagnostics.includes(key));\n }\n return copy;\n }\n if (value instanceof Map) {\n const copy = new Map();\n visited.set(value, copy);\n mapForEach.call(value, (member, key) => {\n const result = typeof key === \"string\"\n ? transformField(key, member)\n : transform(member);\n if (result !== omit) {\n const outputKey = !transformMapKey && typeof key === \"string\"\n ? key\n : transform(key);\n copy.set(outputKey, result);\n }\n });\n return copy;\n }\n if (value instanceof Set) {\n const copy = new Set();\n visited.set(value, copy);\n setForEach.call(value, (member) => copy.add(transform(member)));\n return copy;\n }\n return undefined;\n}\n"],"mappings":";AAAA,MAAM,aAAa,IAAI,UAAU;AACjC,MAAM,aAAa,IAAI,UAAU;AACjC,MAAM,eAAgB,MAEnB;AACH,MAAM,8BAAc,IAAI;AACxB,MAAM,kBAAkB;CACtB,eAAe;CACf,UAAU;CACV,WAAW;CACX,eAAe;CACf,YAAY;CACZ,UAAU;CACV,SAAS;CACT,MAAM;AACP;AAED,MAAa,OAAO,QAAQ;AAO5B,SAAgB,YACdA,QACAC,KACAC,OACA,aAAa,MACP;AACN,QAAO,eAAe,QAAQ,KAAK;EACjC;EACA;EACA,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0B,QAAQ,WACjD,MACA,UAAU,IAAI;AAClB,SAAK,IAAI,WAAW,OAAO;GAC5B;EACF,EAAC;AACF,SAAO;CACR;AACD,KAAI,iBAAiB,KAAK;EACxB,MAAM,uBAAO,IAAI;AACjB,UAAQ,IAAI,OAAO,KAAK;AACxB,aAAW,KAAK,OAAO,CAAC,WAAW,KAAK,IAAI,UAAU,OAAO,CAAC,CAAC;AAC/D,SAAO;CACR;AACD;AACD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@logtape/redaction",
|
|
3
|
-
"version": "2.0.30-dev.
|
|
3
|
+
"version": "2.0.30-dev.1038",
|
|
4
4
|
"description": "Redact sensitive data from log messages",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"logging",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"dist/"
|
|
50
50
|
],
|
|
51
51
|
"peerDependencies": {
|
|
52
|
-
"@logtape/logtape": "^2.0.30-dev.
|
|
52
|
+
"@logtape/logtape": "^2.0.30-dev.1038+2b0b37df"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@alinea/suite": "^0.6.3",
|