lib/createId.js

/**
 * @module pete/lib/createId
 */
module.exports = createId;

/**
 * Create unique function-call identifier based on its location.
 *
 * It is created from filepath, line number and column number marking the point from which `callee` was called.
 *
 * WARNING:
 * Bun 1.2.x does not include column number when it is 0.
 * So when running tests with Bun, ID of test called from the beginnning of a line will be just `${file path}:${line number}`.
 *
 * Example results:
 * - "/app/examples/example1.js:7:1", when running with Node.js,
 * - "/app/examples/example1.js:7", when running with Bun.
 *
 * @alias module:pete/lib/createId
 * @see `constructorOpt` of {@link https://nodejs.org/api/errors.html#errors_error_capturestacktrace_targetobject_constructoropt}
 * @param {Function} callee   just like with `constructorOpt` passed to `Error.captureStackTrace`
 * @return {string}
 */
function createId (callee) {
	var dbg = {};
	Error.captureStackTrace(dbg, callee || createId);
	var stack = dbg.stack.split('\n');

	/*
	 * Node.js:
	 * [
	 *   'Error',
	 *   '    at Object.<anonymous> (/app/examples/example1.js:7:1)',
	 *   '    at Module._compile (node:internal/modules/cjs/loader:1692:14)',
	 *   '    at Object..js (node:internal/modules/cjs/loader:1824:10)',
	 *   '    at Module.load (node:internal/modules/cjs/loader:1427:32)',
	 *   '    at Module._load (node:internal/modules/cjs/loader:1250:12)',
	 *   '    at TracingChannel.traceSync (node:diagnostics_channel:322:14)',
	 *   '    at wrapModuleLoad (node:internal/modules/cjs/loader:235:24)',
	 *   '    at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:152:5)',
	 *   '    at node:internal/main/run_main_module:33:47'
	 * ]
	 */

	/*
	 * Bun:
	 * [ "Error", "    at <anonymous> (/app/examples/example1.js:7)", "    at <anonymous> (native:11:43)" ]
	 */

	return stack && stack[1] && stack[1].replace(/^\s*at (?:file:\/\/|[^(]+\()|\)[\w\W]*$/g, '');
}