-
-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathcaller.ts
More file actions
103 lines (91 loc) · 2.44 KB
/
Copy pathcaller.ts
File metadata and controls
103 lines (91 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Copied from arktype https://github.com/arktypeio/arktype/tree/main/dev/attest/src
import { getCurrentLine, getFramesFromError } from './getCurrentLine.js'
import path from 'node:path'
import * as process from 'node:process'
import { fileURLToPath } from 'node:url'
import { isDeepStrictEqual } from 'node:util'
export type GetCallStackOptions = {
offset?: number
}
export const getCallStack = ({ offset = 0 }: GetCallStackOptions = {}) => {
const frames = getFramesFromError(new Error())
frames.splice(1, 1 + offset)
return frames
}
export type LinePosition = {
line: number
char: number
}
export type SourcePosition = LinePosition & {
file: string
method: string
}
export type CallerOfOptions = {
formatPath?: FormatFilePathOptions
upStackBy?: number
skip?: (position: SourcePosition) => boolean
methodName?: string
}
const nonexistentCurrentLine = {
line: -1,
char: -1,
method: '',
file: '',
}
export type FormatFilePathOptions = {
relative?: string | boolean
seperator?: string
}
export const formatFilePath = (
original: string,
{ relative, seperator }: FormatFilePathOptions,
) => {
let formatted = original
if (original.startsWith('file:///')) {
formatted = fileURLToPath(original)
}
if (relative) {
formatted = path.relative(
typeof relative === 'string' ? relative : process.cwd(),
formatted,
)
}
if (seperator) {
formatted = formatted.replace(new RegExp(`\\${path.sep}`, 'g'), seperator)
}
return formatted
}
export const caller = (options: CallerOfOptions = {}): SourcePosition => {
let upStackBy = options.upStackBy ?? 0
if (!options.methodName) {
upStackBy = 3
}
let match: SourcePosition | undefined
while (!match) {
const location = getCurrentLine({
method: options.methodName as string,
frames: upStackBy,
})
if (!location || isDeepStrictEqual(location, nonexistentCurrentLine)) {
throw new Error(
`No caller of '${
options.methodName
}' matches given options: ${JSON.stringify(options, null, 4)}.`,
)
}
const candidate = {
...location,
file: formatFilePath(location.file, options.formatPath ?? {}),
}
if (options.skip?.(candidate)) {
upStackBy++
} else {
match = candidate
}
}
return match
}
export const callsAgo = (
num: number,
options: Omit<CallerOfOptions, 'upStackBy'> = {},
) => caller({ methodName: 'callsAgo', upStackBy: num, ...options })