import assert from 'node:assert';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import module, { createRequire } from 'node:module';
import { inspect } from 'node:util';
const require = createRequire(import.meta.url);
export const testCaptureStackTraceExists = () => {
try {
assert.strictEqual(typeof Error.captureStackTrace, 'function');
assert.strictEqual(typeof Error.stackTraceLimit, 'number');
return true;
} catch (e) {
console.error('testCaptureStackTraceExists FAIL:', e.message);
return false;
}
};
async function checkPreparedStackCacheLifetime(customStack) {
const descriptor = Object.getOwnPropertyDescriptor(Error, 'prepareStackTrace');
let hookCalls = 0;
try {
assert.strictEqual(typeof globalThis.gc, 'function');
if (customStack) {
Error.prepareStackTrace = error => {
hookCalls++;
return { error, message: error.message };
};
}
const held = Array.from({ length: 8 }, (_, i) => new Error(`held-${i}`));
const heldStacks = held.map(error => error.stack);
const unreadHeld = customStack
? []
: Array.from({ length: 8 }, (_, i) => new Error(`unread-held-${i}`));
function discardedErrors() {
return Array.from({ length: 64 }, () => {
const error = new Error('discarded');
error.self = error;
void error.stack;
return new WeakRef(error);
});
}
function discardedPlainCycles() {
return Array.from({ length: 64 }, () => {
const object = {};
object.self = object;
return new WeakRef(object);
});
}
function discardedPublicWeakEntries() {
const refs = [];
for (let i = 0; i < 32; i++) {
const mapKey = { marker: `public-map-key-${i}` };
const mapValue = { mapKey };
const setValue = { marker: `public-set-value-${i}` };
setValue.self = setValue;
publicWeakMap.set(mapKey, mapValue);
publicWeakSet.add(setValue);
refs.push(new WeakRef(mapKey), new WeakRef(setValue));
}
assert.match(inspect(publicWeakMap, { showHidden: true }), /public-map-key/);
assert.match(inspect(publicWeakSet, { showHidden: true }), /public-set-value/);
return refs;
}
const publicWeakMap = new WeakMap();
const publicWeakSet = new WeakSet();
const liveMapKey = { marker: 'live-map-key' };
const readdedMapKey = { marker: 'readded-map-key' };
const currentMapValue = { marker: 'current-map-value' };
const currentReaddedMapValue = { marker: 'current-readded-map-value' };
const liveSetValue = { marker: 'live-set-value' };
const readdedSetValue = { marker: 'readded-set-value' };
publicWeakMap.set(liveMapKey, { marker: 'stale-map-value' });
publicWeakMap.set(liveMapKey, currentMapValue);
publicWeakMap.set(readdedMapKey, { marker: 'stale-readded-map-value' });
publicWeakMap.delete(readdedMapKey);
publicWeakMap.set(readdedMapKey, currentReaddedMapValue);
publicWeakSet.add(liveSetValue);
publicWeakSet.add(liveSetValue);
publicWeakSet.add(readdedSetValue);
publicWeakSet.delete(readdedSetValue);
publicWeakSet.add(readdedSetValue);
const errors = discardedErrors();
const plain = discardedPlainCycles();
const publicWeakEntries = discardedPublicWeakEntries();
const callsBeforeGc = hookCalls;
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
await tick();
for (let i = 0; i < 3; i++) {
globalThis.gc();
await tick();
await tick();
}
assert.strictEqual(plain.filter(ref => ref.deref() === undefined).length, 64,
'GC positive control must collect plain cycles');
assert.strictEqual(errors.filter(ref => ref.deref() === undefined).length, 64,
'private prepared-stack cache must not retain discarded errors');
assert.strictEqual(publicWeakEntries.filter(ref => ref.deref() === undefined).length, 64,
'inspection bookkeeping must not retain public weak entries');
assert.strictEqual(publicWeakMap.get(liveMapKey), currentMapValue);
assert.strictEqual(publicWeakMap.get(readdedMapKey), currentReaddedMapValue);
assert.strictEqual(publicWeakSet.has(liveSetValue), true);
assert.strictEqual(publicWeakSet.has(readdedSetValue), true);
const inspectedWeakMap = inspect(publicWeakMap, { showHidden: true });
const inspectedWeakSet = inspect(publicWeakSet, { showHidden: true });
assert.doesNotMatch(inspectedWeakMap, /public-map-key/);
assert.doesNotMatch(inspectedWeakSet, /public-set-value/);
assert.match(inspectedWeakMap, /current-map-value/);
assert.match(inspectedWeakMap, /current-readded-map-value/);
assert.doesNotMatch(inspectedWeakMap, /stale-map-value/);
assert.doesNotMatch(inspectedWeakMap, /stale-readded-map-value/);
assert.strictEqual(inspectedWeakMap.match(/live-map-key/g)?.length, 1);
assert.strictEqual(inspectedWeakMap.match(/readded-map-key/g)?.length, 1);
assert.strictEqual(inspectedWeakSet.match(/live-set-value/g)?.length, 1);
assert.strictEqual(inspectedWeakSet.match(/readded-set-value/g)?.length, 1);
for (let i = 0; i < held.length; i++) {
assert.strictEqual(held[i].stack, heldStacks[i]);
if (customStack) assert.strictEqual(held[i].stack.error, held[i]);
else assert(held[i].stack.includes(`held-${i}`));
}
for (let i = 0; i < unreadHeld.length; i++) {
unreadHeld[i].name = 404;
assert.match(inspect(unreadHeld[i]),
new RegExp(`^404 \\[Error\\]: unread-held-${i}(?:\\n|$)`));
}
assert.strictEqual(hookCalls, callsBeforeGc, 'held stacks remain cached across GC');
return true;
} finally {
if (descriptor) Object.defineProperty(Error, 'prepareStackTrace', descriptor);
else delete Error.prepareStackTrace;
}
}
export async function testPreparedStackCacheDoesNotRetainErrors() {
return await checkPreparedStackCacheLifetime(false);
}
export async function testPreparedStackCacheDoesNotRetainCustomCycles() {
return await checkPreparedStackCacheLifetime(true);
}
export const testCaptureStackTraceBasic = () => {
try {
const obj = {};
Error.captureStackTrace(obj);
assert.strictEqual(typeof obj.stack, 'string');
assert(obj.stack.length > 0, 'stack should be non-empty');
return true;
} catch (e) {
console.error('testCaptureStackTraceBasic FAIL:', e.message);
return false;
}
};
export const testPrepareStackTrace = () => {
try {
let receivedCallSites = null;
const origPrepare = Error.prepareStackTrace;
Error.prepareStackTrace = function (error, callSites) {
receivedCallSites = callSites;
return callSites;
};
const obj = {};
Error.captureStackTrace(obj);
const stack = obj.stack;
Error.prepareStackTrace = origPrepare;
assert(Array.isArray(receivedCallSites), 'callSites should be an array');
assert(receivedCallSites.length > 0, 'callSites should be non-empty');
const site = receivedCallSites[0];
assert.strictEqual(typeof site.getFileName, 'function');
assert.strictEqual(typeof site.getLineNumber, 'function');
assert.strictEqual(typeof site.getColumnNumber, 'function');
assert.strictEqual(typeof site.getFunctionName, 'function');
return true;
} catch (e) {
console.error('testPrepareStackTrace FAIL:', e.message);
return false;
}
};
export const testCallSiteMethods = () => {
try {
let callSites = null;
const origPrepare = Error.prepareStackTrace;
Error.prepareStackTrace = function (error, sites) {
if (callSites === null) {
callSites = sites;
}
return 'custom-stack';
};
const obj = {};
Error.captureStackTrace(obj);
void obj.stack;
Error.prepareStackTrace = origPrepare;
assert(Array.isArray(callSites), 'callSites should be an array');
assert(callSites.length > 0, 'callSites should be non-empty');
const site = callSites[0];
const methods = [
'getThis', 'getTypeName', 'getFunction', 'getFunctionName',
'getMethodName', 'getFileName', 'getLineNumber', 'getColumnNumber',
'getEvalOrigin', 'isToplevel', 'isEval', 'isNative', 'isConstructor',
'isAsync', 'isPromiseAll', 'getPromiseIndex', 'getScriptNameOrSourceURL',
'toString'
];
for (const m of methods) {
assert.strictEqual(typeof site[m], 'function', `CallSite.${m} should be a function`);
}
assert(site.getFileName() === null || typeof site.getFileName() === 'string');
assert.strictEqual(typeof site.getLineNumber(), 'number');
assert.strictEqual(typeof site.getColumnNumber(), 'number');
assert.strictEqual(typeof site.isEval(), 'boolean');
assert.strictEqual(typeof site.isNative(), 'boolean');
assert.strictEqual(typeof site.isConstructor(), 'boolean');
assert.strictEqual(typeof site.isToplevel(), 'boolean');
assert.strictEqual(typeof site.toString(), 'string');
return true;
} catch (e) {
console.error('testCallSiteMethods FAIL:', e.message);
return false;
}
};
export const testLatePrepareStackTrace = () => {
const originalPrepare = Error.prepareStackTrace;
try {
Error.prepareStackTrace = undefined;
const lateTarget = {};
Error.captureStackTrace(lateTarget);
Error.prepareStackTrace = () => 'late-prepare';
assert.strictEqual(lateTarget.stack, 'late-prepare');
Error.prepareStackTrace = () => 'capture-time-prepare';
const removedTarget = {};
Error.captureStackTrace(removedTarget);
Error.prepareStackTrace = undefined;
assert.strictEqual(typeof removedTarget.stack, 'string');
assert.notStrictEqual(removedTarget.stack, 'capture-time-prepare');
return true;
} catch (e) {
console.error('testLatePrepareStackTrace FAIL:', e.message);
return false;
} finally {
Error.prepareStackTrace = originalPrepare;
}
};
export const testDefaultErrorStackHeaders = () => {
const originalPrepare = Error.prepareStackTrace;
try {
Error.prepareStackTrace = undefined;
assert.match(new Error('base').stack, /^Error: base(?:\n|$)/);
assert.match(new TypeError('native').stack, /^TypeError: native(?:\n|$)/);
assert.match(new Error().stack, /^Error(?:\n|$)/);
class CustomError extends Error {}
CustomError.prototype.name = 'CustomError';
assert.match(new CustomError('custom').stack, /^CustomError: custom(?:\n|$)/);
class EmptyNameError extends Error {}
EmptyNameError.prototype.name = '';
assert.match(new EmptyNameError('message-only').stack, /^message-only(?:\n|$)/);
const originalToString = Error.prototype.toString;
Error.prototype.toString = () => 'POISON';
const protectedHeader = new Error('protected').stack;
Error.prototype.toString = originalToString;
assert.match(protectedHeader, /^Error: protected(?:\n|$)/);
function captureNamedFrame() {
return new Error('named-frame').stack;
}
assert.match(captureNamedFrame().split('\n')[1], /^\s*at captureNamedFrame \(.+:\d+:\d+\)$/);
const originalObjectToString = Object.prototype.toString;
let protectedCallSiteStack;
try {
Object.prototype.toString = () => 'FAKE';
protectedCallSiteStack = new Error('protected-call-site').stack;
} finally {
Object.prototype.toString = originalObjectToString;
}
assert.doesNotMatch(protectedCallSiteStack, /FAKE/);
assert.match(protectedCallSiteStack.split('\n')[1], /^\s*at .+:\d+:\d+/);
return true;
} catch (e) {
console.error('testDefaultErrorStackHeaders FAIL:', e.message);
return false;
} finally {
Error.prepareStackTrace = originalPrepare;
}
};
export const testErrorInspectUsesCurrentName = () => {
try {
const error = new RangeError('foo');
error.name = 404;
assert.match(inspect(error), /^404 \[RangeError\]: foo(?:\n|$)/);
const manualStackError = new RangeError('foo');
manualStackError.stack = 'RangeError: foo\n at manual (x.js:1:2)';
manualStackError.name = 404;
assert.strictEqual(
inspect(manualStackError),
'RangeError: foo\n at manual (x.js:1:2)',
);
return true;
} catch (e) {
console.error('testErrorInspectUsesCurrentName FAIL:', e.message);
return false;
}
};
export const testAssertionListenerStackFrame = () => {
const emitter = new EventEmitter();
emitter.on('failure', assert);
try {
emitter.emit('failure', false);
} catch (error) {
return String(error.stack).split('\n')[1] || '';
}
return '';
};
export const testCjsCallSiteLineOffset = () => {
const originalPrepare = Error.prepareStackTrace;
const filename = '/v8-call-site-line-offset.cjs';
const mapFilename = '/v8-call-site-line-offset.cjs.map';
try {
module.setSourceMapsSupport(true);
Error.prepareStackTrace = (_error, sites) => sites[0];
fs.writeFileSync(filename, [
'function branch() {',
" throw Error('site');",
'}',
'branch();',
'//# sourceMappingURL=v8-call-site-line-offset.cjs.map',
].join('\n'));
fs.writeFileSync(mapFilename, JSON.stringify({
version: 3,
sources: ['v8-call-site-line-offset.ts'],
names: [],
mappings: 'AAAA;AACA;AACA;AACA',
}));
try {
require(filename);
} catch (error) {
return String(error.stack.getLineNumber());
}
return '';
} finally {
delete require.cache[filename];
Error.prepareStackTrace = originalPrepare;
}
};
export const testPrepareStackTraceDescriptors = () => {
try {
const customPrepare = () => 'custom-prepare';
Error.prepareStackTrace = customPrepare;
Object.defineProperty(Error, 'prepareStackTrace', { enumerable: false });
assert.strictEqual(Error.prepareStackTrace, customPrepare);
assert.strictEqual(new Error('partial-descriptor').stack, 'custom-prepare');
let getterCalls = 0;
Object.defineProperty(Error, 'prepareStackTrace', {
get() {
getterCalls++;
return customPrepare;
},
configurable: true,
});
assert.strictEqual(getterCalls, 0);
assert.strictEqual(new TypeError('accessor').stack, 'custom-prepare');
delete Error.prepareStackTrace;
assert.match(new Error('deleted').stack, /^Error: deleted(?:\n|$)/);
Object.defineProperty(Error, 'prepareStackTrace', {
value: customPrepare,
writable: true,
configurable: true,
});
Object.freeze(Error);
const descriptor = Object.getOwnPropertyDescriptor(Error, 'prepareStackTrace');
assert.strictEqual(descriptor.writable, false);
assert.strictEqual(descriptor.configurable, false);
assert.strictEqual(new Error('frozen').stack, 'custom-prepare');
return true;
} catch (e) {
console.error('testPrepareStackTraceDescriptors FAIL:', e.message);
return false;
}
};
export const testConstructorOpt = () => {
try {
let callSites = null;
const origPrepare = Error.prepareStackTrace;
Error.prepareStackTrace = function (error, sites) {
callSites = sites;
return sites;
};
function MyError(message) {
Error.captureStackTrace(this, MyError);
this.message = message;
}
function callerFunction() {
return new MyError('test');
}
const err = callerFunction();
const stack = err.stack;
Error.prepareStackTrace = origPrepare;
assert(Array.isArray(callSites) && callSites.length > 0);
const firstFn = callSites[0].getFunctionName();
assert.notStrictEqual(firstFn, 'MyError',
'constructorOpt should strip frames including the constructor');
return true;
} catch (e) {
console.error('testConstructorOpt FAIL:', e.message);
return false;
}
};
export const testStackTraceLimit = () => {
try {
const origLimit = Error.stackTraceLimit;
assert.strictEqual(typeof Error.stackTraceLimit, 'number');
Error.stackTraceLimit = 42;
assert.strictEqual(Error.stackTraceLimit, 42);
Error.stackTraceLimit = origLimit;
return true;
} catch (e) {
console.error('testStackTraceLimit FAIL:', e.message);
return false;
}
};
export const testDepdPattern = () => {
try {
function prepareObjectStackTrace(obj, stack) {
return stack;
}
function getStack() {
var limit = Error.stackTraceLimit;
var obj = {};
var prep = Error.prepareStackTrace;
Error.prepareStackTrace = prepareObjectStackTrace;
Error.stackTraceLimit = Math.max(10, limit);
Error.captureStackTrace(obj);
var stack = obj.stack.slice(1);
Error.prepareStackTrace = prep;
Error.stackTraceLimit = limit;
return stack;
}
function callSiteLocation(callSite) {
var file = callSite.getFileName() || '<anonymous>';
var line = callSite.getLineNumber();
var colm = callSite.getColumnNumber();
var site = [file, line, colm];
site.callSite = callSite;
site.name = callSite.getFunctionName();
return site;
}
function depd(namespace) {
var stack = getStack();
var site = callSiteLocation(stack[1]);
var file = site[0];
return { file, namespace };
}
const result = depd('test-namespace');
assert.strictEqual(result.namespace, 'test-namespace');
assert.strictEqual(typeof result.file, 'string');
return true;
} catch (e) {
console.error('testDepdPattern FAIL:', e.message);
return false;
}
};