-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathextractSource.ts
39 lines (36 loc) · 1.07 KB
/
extractSource.ts
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
import { Backend } from '../src/backend/Backend'
import { Node, NodePath, getAstxMatchInfo } from '../src/types'
export function extractSource(
path: NodePath<Node, any>,
source: string,
backend: Backend
): string
export function extractSource(
path: NodePath<Node, any>[],
source: string,
backend: Backend
): string[]
export function extractSource(
path: NodePath<Node, any> | NodePath<Node, any>[],
source: string,
backend: Backend
): string | string[] {
if (Array.isArray(path))
return path.map((p) => extractSource(p, source, backend))
const { node } = path
const { start, end } = backend.location(node)
if (start == null || end == null)
throw new Error(`failed to get node source range`)
// const { typeAnnotation } = node as any
const astx = getAstxMatchInfo(node)
if (astx?.subcapture) {
return backend.generate(astx.subcapture).code
}
if (
node.type === 'TSPropertySignature' ||
node.type === 'TSMethodSignature'
) {
return source.substring(start, end).replace(/[,;]$/, '')
}
return source.substring(start, end)
}