oak-cli/lib/server/polyfill.js

108 lines
3.7 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.removePolyfill = exports.polyfillConsole = void 0;
const uuid_1 = require("uuid");
async function generateNewId(option) {
if (option?.shuffle && process.env.NODE_ENV === 'development') {
return (0, uuid_1.v4)();
}
return (0, uuid_1.v1)();
}
Object.assign(global, {
generateNewId,
});
// 存储所有的 polyfill 配置栈
const polyfillStack = [];
const originalConsoleMethods = {};
// 获取调用堆栈信息的工厂函数
const createGetCallerInfo = (trace) => () => {
if (!trace) {
return null;
}
const originalFunc = Error.prepareStackTrace;
let callerInfo = null;
try {
const err = new Error();
Error.prepareStackTrace = (err, stack) => stack;
const stack = err.stack;
const currentFile = stack[0].getFileName();
for (let i = 1; i < stack.length; i++) {
const callSite = stack[i];
if (currentFile !== callSite.getFileName()) {
callerInfo = callSite;
break;
}
}
}
catch (e) {
console.error(e);
}
Error.prepareStackTrace = originalFunc;
return callerInfo;
};
const polyfillConsole = (id, trace, formatter) => {
// 检查是否已经添加过相同 id 的 polyfill
if (polyfillStack.some(item => item.id === id)) {
return;
}
// 第一次调用时保存原始方法
if (polyfillStack.length === 0) {
originalConsoleMethods.info = console.info;
originalConsoleMethods.warn = console.warn;
originalConsoleMethods.error = console.error;
}
// 添加新的 polyfill 到栈顶
polyfillStack.push({ id, trace, formatter });
// 重新设置 console 方法
["info", "warn", "error"].forEach((level) => {
const levelStr = level;
const originalFunc = originalConsoleMethods[levelStr];
console[levelStr] = function (...args) {
let processedArgs = args;
// 从后往前执行所有 formatter
for (let i = polyfillStack.length - 1; i >= 0; i--) {
const item = polyfillStack[i];
if (item.formatter) {
const getCallerInfo = createGetCallerInfo(item.trace);
processedArgs = item.formatter({
level: levelStr,
caller: getCallerInfo(),
args: processedArgs,
});
}
}
originalFunc(...processedArgs);
};
});
console.info(`new console polyfill added: ${id}`);
};
exports.polyfillConsole = polyfillConsole;
// 可选:提供移除 polyfill 的功能
const removePolyfill = (id) => {
const index = polyfillStack.findIndex(item => item.id === id);
if (index === -1) {
return;
}
polyfillStack.splice(index, 1);
// 如果栈为空,恢复原始方法
if (polyfillStack.length === 0) {
console.info = originalConsoleMethods.info;
console.warn = originalConsoleMethods.warn;
console.error = originalConsoleMethods.error;
}
else {
// 否则重新应用所有 polyfill
const tempStack = [...polyfillStack];
polyfillStack.length = 0;
Object.keys(originalConsoleMethods).forEach(level => {
const levelStr = level;
console[levelStr] = originalConsoleMethods[levelStr];
});
tempStack.forEach(item => {
polyfillStack.length = 0; // 清空以便重新添加
(0, exports.polyfillConsole)(item.id, item.trace, item.formatter);
});
}
};
exports.removePolyfill = removePolyfill;