diff --git a/lib/getPluginName.js b/lib/getPluginName.js index 70e9711..1490b50 100644 --- a/lib/getPluginName.js +++ b/lib/getPluginName.js @@ -1,7 +1,9 @@ 'use strict' +const { basename, extname } = require('node:path') + const FP_STACK_TRACE_REG = /at\s(?:.*\.)?plugin\s.*\n\s*(.*)/ -const FILE_NAME_REG = /(\w*(\.\w*)*)\..*/ +const LOCATION_REG = /:\d+:\d+\)?$/ module.exports = function getPluginName (fn) { if (fn.name.length > 0) return fn.name @@ -19,7 +21,9 @@ module.exports = function getPluginName (fn) { function extractPluginName (stack) { const m = stack.match(FP_STACK_TRACE_REG) - // get last section of path and match for filename - return m ? m[1].split(/[/\\]/).slice(-1)[0].match(FILE_NAME_REG)[1] : 'anonymous' + if (!m) return 'anonymous' + + const fileName = basename(m[1].replaceAll('\\', '/')).replace(LOCATION_REG, '') + return basename(fileName, extname(fileName)) } module.exports.extractPluginName = extractPluginName diff --git a/test/extractPluginName.test.js b/test/extractPluginName.test.js index 23097e6..8e1bec5 100644 --- a/test/extractPluginName.test.js +++ b/test/extractPluginName.test.js @@ -39,11 +39,16 @@ at TAP.process (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test. at TAP.sub (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:185:10) at TAP.test (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:209:17)` +const hyphenatedStack = `Error: anonymous function +at plugin (/home/leonardo/desktop/fastify-plugin/index.js:24:20) +at Test.test (/home/leonardo/desktop/fastify-plugin/test/my-plugin.js:9:14)` + const anonymousStack = 'Unable to parse this' test('extractPluginName tests', (t) => { - t.plan(3) + t.plan(4) t.assert.strictEqual(extractPluginName(winStack), 'hello.test') t.assert.strictEqual(extractPluginName(nixStack), 'this.is.a.test') + t.assert.strictEqual(extractPluginName(hyphenatedStack), 'my-plugin') t.assert.strictEqual(extractPluginName(anonymousStack), 'anonymous') })