@@ -176,35 +176,21 @@ export function getCallerFrame(depth: number): string | undefined {
176176 return lines . slice ( depth ) . join ( '\n' )
177177}
178178
179- /**
180- * Extract the directory path from a stack trace line.
181- *
182- * Matches patterns like:
183- * - "at <anonymous> (/path/to/file.js:1:1)"
184- * - "at /path/to/file.js:1:1"
185- * - "at <anonymous> (file:///C:/path/to/file.js:1:1)"
186- * - "at (file:///C:/path/to/file.js:1:1)"
187- * @param line A line from a stack trace
188- * @returns The directory of the file, or undefined if not found
189- */
190- export function matchFileDir ( line : string ) : string | undefined {
191- const match = line . match (
192- / (?: f i l e : \/ \/ \/ ) ? ( [ A - Z a - z ] : ) ? ( [ / \\ ] [ ^ : ] + ) (?: : \d + : \d + ) ? \) ? /
193- )
194- if ( match ) {
195- // Extract the full matched path
196- let filePath = match [ 0 ]
197-
198- // Remove file:/// protocol prefix if present
199- filePath = filePath . replace ( / ^ f i l e : \/ \/ \/ / , '' )
200-
201- // Remove trailing closing parenthesis if present
202- filePath = filePath . replace ( / \) $ / , '' )
203-
204- // Remove :line:column suffix if present
205- filePath = filePath . replace ( / : \d + : \d + $ / , '' )
179+ // adopted from https://github.com/sindresorhus/callsites
180+ export function callsites ( depth : number ) : NodeJS . CallSite [ ] {
181+ const _originalPrepareStackTrace = Error . prepareStackTrace
182+ try {
183+ let result : NodeJS . CallSite [ ] = [ ]
184+ Error . prepareStackTrace = ( _ , callSites ) => {
185+ const callSitesWithoutCurrent = callSites . slice ( depth )
186+ result = callSitesWithoutCurrent
187+ return callSitesWithoutCurrent
188+ }
206189
207- return path . dirname ( filePath )
190+ new Error ( ) . stack
191+ return result
192+ } finally {
193+ Error . prepareStackTrace = _originalPrepareStackTrace
208194 }
209195}
210196
@@ -215,18 +201,18 @@ export function matchFileDir(line: string): string | undefined {
215201 * @returns The caller's directory path, or undefined if not available
216202 */
217203export function getCallerDirectory ( depth : number ) : string | undefined {
218- const caller = getCallerFrame ( depth + 1 ) // +1 depth to skip this function (getCallerDirectory)
219- if ( ! caller ) {
220- return
204+ // +1 depth to skip this function (getCallerDirectory)
205+ const callSites = callsites ( depth + 1 )
206+ if ( callSites . length === 0 ) {
207+ return undefined
221208 }
222209
223- const lines = caller . split ( '\n' )
224- if ( lines . length === 0 ) {
225- return
210+ const fileName = callSites [ 0 ] . getFileName ( )
211+ if ( ! fileName ) {
212+ return undefined
226213 }
227214
228- const firstLine = lines [ 0 ]
229- return matchFileDir ( firstLine )
215+ return path . dirname ( fileName )
230216}
231217
232218/**
0 commit comments