-
Notifications
You must be signed in to change notification settings - Fork 7.8k
/
ExpressionExtension.ts
219 lines (196 loc) · 7.12 KB
/
ExpressionExtension.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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import { DateTime } from 'luxon';
import { ExpressionExtensionError } from '../ExpressionError';
import { parse, visit, types, print } from 'recast';
import { arrayExtensions } from './ArrayExtensions';
import { dateExtensions } from './DateExtensions';
import { numberExtensions } from './NumberExtensions';
import { stringExtensions } from './StringExtensions';
const EXPRESSION_EXTENDER = 'extend';
function isBlank(value: unknown) {
return value === null || value === undefined || !value;
}
function isPresent(value: unknown) {
return !isBlank(value);
}
const EXTENSION_OBJECTS = [arrayExtensions, dateExtensions, numberExtensions, stringExtensions];
// eslint-disable-next-line @typescript-eslint/ban-types
const genericExtensions: Record<string, Function> = {
isBlank,
isPresent,
};
const EXPRESSION_EXTENSION_METHODS = Array.from(
new Set([
...Object.keys(stringExtensions.functions),
...Object.keys(numberExtensions.functions),
...Object.keys(dateExtensions.functions),
...Object.keys(arrayExtensions.functions),
...Object.keys(genericExtensions),
]),
);
const isExpressionExtension = (str: string) => EXPRESSION_EXTENSION_METHODS.some((m) => m === str);
export const hasExpressionExtension = (str: string): boolean =>
EXPRESSION_EXTENSION_METHODS.some((m) => str.includes(m));
export const hasNativeMethod = (method: string): boolean => {
if (hasExpressionExtension(method)) {
return false;
}
const methods = method
.replace(/[^\w\s]/gi, ' ')
.split(' ')
.filter(Boolean); // DateTime.now().toLocaleString().format() => [DateTime,now,toLocaleString,format]
return methods.every((methodName) => {
return [String.prototype, Array.prototype, Number.prototype, Date.prototype].some(
(nativeType) => {
if (methodName in nativeType) {
return true;
}
return false;
},
);
});
};
/**
* recast's types aren't great and we need to use a lot of anys
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const findParent = <T>(path: T, matcher: (path: T) => boolean): T | undefined => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
let parent = path.parentPath;
while (parent) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
if (matcher(parent)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return parent;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
parent = parent.parentPath;
}
return;
};
/**
* A function to inject an extender function call into the AST of an expression.
* This uses recast to do the transform.
*
* ```ts
* 'a'.method('x') // becomes
* extend('a', 'method', ['x']);
*
* 'a'.first('x').second('y') // becomes
* extend(extend('a', 'first', ['x']), 'second', ['y']));
* ```
*/
export const extendTransform = (expression: string): { code: string } | undefined => {
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const ast = parse(expression);
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
visit(ast, {
visitIdentifier(path) {
this.traverse(path);
if (
isExpressionExtension(path.node.name) &&
// types.namedTypes.MemberExpression.check(path.parent)
path.parentPath?.value?.type === 'MemberExpression'
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const callPath: any = findParent(path, (p) => p.value?.type === 'CallExpression');
if (!callPath || callPath.value?.type !== 'CallExpression') {
return;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
callPath.replace(
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
types.builders.callExpression(types.builders.identifier(EXPRESSION_EXTENDER), [
path.parentPath.value.object,
types.builders.stringLiteral(path.node.name),
// eslint-disable-next-line
types.builders.arrayExpression(callPath.node.arguments),
]),
);
}
},
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument
return print(ast);
} catch (e) {
return;
}
};
function isDate(input: unknown): boolean {
if (typeof input !== 'string') {
return false;
}
return DateTime.fromISO(input).isValid;
}
/**
* Extender function injected by expression extension plugin to allow calls to extensions.
*
* ```ts
* extend(input, "functionName", [...args]);
* ```
*/
export function extend(input: unknown, functionName: string, args: unknown[]) {
// eslint-disable-next-line @typescript-eslint/ban-types
let foundFunction: Function | undefined;
if (Array.isArray(input)) {
foundFunction = arrayExtensions.functions[functionName];
} else if (isDate(input)) {
// If it's a string date (from $json), convert it to a Date object
input = new Date(input as string);
foundFunction = dateExtensions.functions[functionName];
} else if (typeof input === 'string') {
foundFunction = stringExtensions.functions[functionName];
} else if (typeof input === 'number') {
foundFunction = numberExtensions.functions[functionName];
} else if (input && (DateTime.isDateTime(input) || input instanceof Date)) {
foundFunction = dateExtensions.functions[functionName];
}
// Look for generic or builtin
if (!foundFunction) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const inputAny: any = input;
// This is likely a builtin we're implementing for another type
// (e.g. toLocaleString). We'll just call it
if (
inputAny &&
functionName &&
functionName in inputAny &&
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
typeof inputAny[functionName] === 'function'
) {
// I was having weird issues with eslint not finding rules on this line.
// Just disabling all eslint rules for now.
// eslint-disable-next-line
return inputAny[functionName](...args);
}
// Use a generic version if available
foundFunction = genericExtensions[functionName];
}
// No type specific or generic function found. Check to see if
// any types have a function with that name. Then throw an error
// letting the user know the available types.
if (!foundFunction) {
const haveFunction = EXTENSION_OBJECTS.filter((v) => functionName in v.functions);
if (!haveFunction.length) {
// This shouldn't really be possible but we should cover it anyway
throw new ExpressionExtensionError(`Unknown expression function: ${functionName}`);
}
if (haveFunction.length > 1) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const lastType = `"${haveFunction.pop()!.typeName}"`;
const typeNames = `${haveFunction.map((v) => `"${v.typeName}"`).join(', ')}, and ${lastType}`;
throw new ExpressionExtensionError(
`${functionName}() is only callable on types ${typeNames}`,
);
} else {
throw new ExpressionExtensionError(
`${functionName}() is only callable on type "${haveFunction[0].typeName}"`,
);
}
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return foundFunction(input, args);
}