@neodx/log
Version:
A lightweight universal logging framework
69 lines (65 loc) • 2.21 kB
JavaScript
import { n as hasOwn } from '../_internal/read-arguments-BklHPmep.mjs';
export {
c as createLoggerAutoFactory,
r as readArguments
} from '../_internal/read-arguments-BklHPmep.mjs';
/**
* Safe version of JSON.stringify, prevents circular refs
* @example serializeJSON({ record: { value: 1, name: 'age' }, valid: false })
*/ const serializeJSON = (value, space) => JSON.stringify(value, createJSONReplacer(), space);
const cycleRef = (tokens = []) => `[Circular${tokens.length > 0 ? ' ' + tokens.join('.') : ''}]`;
function createJSONReplacer() {
const stack = [];
const keys = [];
const getCircularKey = index => cycleRef(index > 0 ? keys.slice(0, index) : []);
return function replacer(key, value) {
if (stack.length === 0) {
stack.push(value);
return value;
}
const thisIndex = stack.indexOf(this);
const thisInStack = thisIndex >= 0;
if (thisInStack) {
stack.splice(thisIndex + 1);
keys.splice(thisIndex, Infinity, key);
} else {
stack.push(this);
keys.push(key);
}
if (stack.includes(value)) {
return getCircularKey(stack.indexOf(value));
}
return value;
};
}
/**
* Tiny implementation of printf function.
* Supports only "%s" (string) and "%d" (number).
* @see https://github.com/floatdrop/pff
* @example printf('%s in %ds.', ['Done', 12]) => "Done on 12s."
*/ function printf(template, replaces) {
const currentReplaces = Array.from(replaces);
const [leading, ...parts] = template.split('%');
const result = parts.reduce(
(acc, part) => {
const tokenName = part[0];
const format = hasOwn(tokenFormatters, tokenName) ? tokenFormatters[tokenName] : null;
acc.push(format ? format(currentReplaces.shift()) : '%');
acc.push(format ? part.slice(tokenName.length) : part);
return acc;
},
[leading]
);
return result.join('');
}
const tokenFormatters = {
s: value => String(value),
d: value => Math.floor(Number(value)),
i: value => Number.parseInt(String(value), 10),
f: value => Number.parseFloat(String(value)),
o: serializeJSON,
O: serializeJSON,
j: serializeJSON
};
export { printf, serializeJSON };
//# sourceMappingURL=index.mjs.map