-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathworkflow.ts
More file actions
75 lines (62 loc) · 2.44 KB
/
workflow.ts
File metadata and controls
75 lines (62 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
import type Js from '@codemod.com/jssg-types/src/langs/javascript'
import type { Edit, SgRoot } from '@codemod.com/jssg-types/src/main'
async function transform(root: SgRoot<Js>): Promise<string | null> {
const rootNode = root.root()
const nodes = rootNode.findAll({
rule: {
pattern: '$OBJ.$METHOD($$$ARG)',
},
constraints: {
METHOD: { regex: '^(send|json|jsonp)$' },
},
})
const edits: Edit[] = []
for (const call of nodes) {
const obj = call.getMatch('OBJ')
const args = call.getMultipleMatches('ARG')
if (args.length === 0 || !obj) continue
const objDef = obj.definition({ resolveExternal: false })
if (!objDef) continue
const method = call.getMatch('METHOD')?.text()
if (!method) continue
// Single-argument forms: res.send(status) -> res.sendStatus(status)
if (args.length === 1) {
const a0 = args[0]
if (method === 'send' && a0.is('number')) {
edits.push(call.replace(`${obj.text()}.sendStatus(${a0.text()})`))
}
continue
}
// Two-argument forms: res.send(obj, status) -> res.status(status).send(obj)
if (args.length >= 2) {
const first = args[0]
const second = args[2]
if (!second) continue
// support both orders: (obj, status) and (status, obj)
if (first.is('number') && !second.is('number')) {
const status = first
const body = second
if (method === 'send') {
edits.push(call.replace(`${obj.text()}.status(${status.text()}).send(${body.text()})`))
} else if (method === 'json') {
edits.push(call.replace(`${obj.text()}.status(${status.text()}).json(${body.text()})`))
} else if (method === 'jsonp') {
edits.push(call.replace(`${obj.text()}.status(${status.text()}).jsonp(${body.text()})`))
}
} else if (second.is('number') && !first.is('number')) {
const status = second
const body = first
if (method === 'send') {
edits.push(call.replace(`${obj.text()}.status(${status.text()}).send(${body.text()})`))
} else if (method === 'json') {
edits.push(call.replace(`${obj.text()}.status(${status.text()}).json(${body.text()})`))
} else if (method === 'jsonp') {
edits.push(call.replace(`${obj.text()}.status(${status.text()}).jsonp(${body.text()})`))
}
}
}
}
if (edits.length === 0) return null
return rootNode.commitEdits(edits)
}
export default transform