Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions lib/getPluginName.js
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
7 changes: 6 additions & 1 deletion test/extractPluginName.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})