Skip to content

Commit

Permalink
fixup! lib: add util.getCallSite() API
Browse files Browse the repository at this point in the history
  • Loading branch information
RafaelGSS committed Aug 20, 2024
1 parent 7d1b8ea commit 8d9f30a
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 4 deletions.
6 changes: 4 additions & 2 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,10 @@ function parseEnv(content) {
* Returns the callSite
* @returns {object}
*/
function getCallSite() {
return binding.getCallSite();
function getCallSite(frames = 10) {
// Using kDefaultMaxCallStackSizeToCapture as reference
validateNumber(frames, 'frames', 1, 200);
return binding.getCallSite(frames);
};

// Keep the `exports =` so that various functions can still be monkeypatched
Expand Down
7 changes: 6 additions & 1 deletion src/node_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,13 @@ static void GetCallSite(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = env->isolate();

CHECK_EQ(args.Length(), 1);
CHECK(args[0]->IsNumber());
const uint32_t frames = args[0].As<Uint32>()->Value();

// +1 for disregarding node:util
Local<StackTrace> stack =
StackTrace::CurrentStackTrace(isolate, env->stack_trace_limit());
StackTrace::CurrentStackTrace(isolate, frames + 1);
Local<Array> callsites = Array::New(isolate);

// Frame 0 is node:util. It should be skipped.
Expand Down
50 changes: 49 additions & 1 deletion test/parallel/test-util-getCallSite.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

require('../common');
const common = require('../common');

const fixtures = require('../common/fixtures');
const file = fixtures.path('get-call-site.js');
Expand All @@ -19,6 +19,54 @@ const assert = require('node:assert');
);
}

{
const callsite = getCallSite(3);
assert.strictEqual(callsite.length, 3);
assert.match(
callsite[0].scriptName,
/test-util-getCallSite/,
'node:util should be ignored',
);
}

{
const callsite = getCallSite(3.6);
assert.strictEqual(callsite.length, 3);
}

{
const callsite = getCallSite(3.4);
assert.strictEqual(callsite.length, 3);
}

{
assert.throws(() => {
// Max than kDefaultMaxCallStackSizeToCapture
getCallSite(201);
}, common.expectsError({
code: 'ERR_OUT_OF_RANGE'
}));
assert.throws(() => {
getCallSite(-1);
}, common.expectsError({
code: 'ERR_OUT_OF_RANGE'
}));
assert.throws(() => {
getCallSite({});
}, common.expectsError({
code: 'ERR_INVALID_ARG_TYPE'
}));
}

{
const callsite = getCallSite(1);
assert.strictEqual(callsite.length, 1);
assert.match(
callsite[0].scriptName,
/test-util-getCallSite/,
'node:util should be ignored',
);
}

{
const { status, stderr, stdout } = spawnSync(
Expand Down

0 comments on commit 8d9f30a

Please sign in to comment.