Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

utils.ts

42 lines1.0 KB

1import { types } from 'recast'
2​
3const b = types.builders
4​
5export function ensureStringArgument(
6 callExpression: types.namedTypes.CallExpression,
7 value: string,
8 preferredQuote?: "'" | '"',
9) {
10 const argument = callExpression.arguments[0]
11 if (!argument) {
12 let stringLiteral: types.namedTypes.StringLiteral
13 if (!preferredQuote) {
14 stringLiteral = b.stringLiteral.from({ value })
15 } else {
16 stringLiteral = b.stringLiteral.from({
17 value,
18 extra: {
19 rawValue: value,
20 raw: `${preferredQuote}${value}${preferredQuote}`,
21 },
22 })
23 }
24 callExpression.arguments.push(stringLiteral)
25 return true
26 } else if (argument.type === 'StringLiteral') {
27 if (argument.value !== value) {
28 argument.value = value
29 return true
30 }
31 } else if (argument.type === 'TemplateLiteral') {
32 if (
33 argument.quasis.length === 1 &&
34 argument.quasis[0] &&
35 argument.quasis[0].value.raw !== value
36 ) {
37 argument.quasis[0].value.raw = value
38 return true
39 }
40 }
41 return false