-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathCubePropContextTranspiler.ts
More file actions
340 lines (307 loc) · 13.4 KB
/
Copy pathCubePropContextTranspiler.ts
File metadata and controls
340 lines (307 loc) · 13.4 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
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import * as t from '@babel/types';
import R from 'ramda';
import type { NodePath } from '@babel/traverse';
import {
SymbolResolver,
TranspilerCubeResolver,
TranspilerInterface,
TranspilerSymbolResolver,
TraverseObject
} from './transpiler.interface';
/* this list was generated by getTransformPatterns() with additional variants for snake_case */
export const transpiledFieldsPatterns: Array<RegExp> = [
/\.sql$/,
/sql$/,
/(sqlTable|sql_table)$/,
/^measures\.[_a-zA-Z][_a-zA-Z0-9]*\.(drillMemberReferences|drillMembers|drill_members)$/,
/^measures\.[_a-zA-Z][_a-zA-Z0-9]*\.(orderBy|order_by)\.[0-9]+\.sql$/,
/^measures\.[_a-zA-Z][_a-zA-Z0-9]*\.(timeShift|time_shift)\.[0-9]+\.(timeDimension|time_dimension)$/,
/^measures\.[_a-zA-Z][_a-zA-Z0-9]*\.(reduceBy|reduce_by|groupBy|group_by|addGroupBy|add_group_by)$/,
/^(measures|dimensions)\.[_a-zA-Z][_a-zA-Z0-9]*\.filter\.(exclude|keepOnly|keep_only)$/,
/^measures\.[_a-zA-Z][_a-zA-Z0-9]*\.grain\.(exclude|keepOnly|keep_only|include)$/,
/^(measures|dimensions)\.[_a-zA-Z][_a-zA-Z0-9]*\.case\.switch$/,
/^dimensions\.[_a-zA-Z][_a-zA-Z0-9]*\.(reduceBy|reduce_by|groupBy|group_by|addGroupBy|add_group_by|key)$/,
/^(preAggregations|pre_aggregations)\.[_a-zA-Z][_a-zA-Z0-9]*\.indexes\.[_a-zA-Z][_a-zA-Z0-9]*\.columns$/,
/^(preAggregations|pre_aggregations)\.[_a-zA-Z][_a-zA-Z0-9]*\.(timeDimensionReference|timeDimension|time_dimension|segments|dimensions|measures|rollups|segmentReferences|dimensionReferences|measureReferences|rollupReferences)$/,
/^(preAggregations|pre_aggregations)\.[_a-zA-Z][_a-zA-Z0-9]*\.(timeDimensions|time_dimensions)\.\d+\.dimension$/,
/^(preAggregations|pre_aggregations)\.[_a-zA-Z][_a-zA-Z0-9]*\.(outputColumnTypes|output_column_types)\.\d+\.member$/,
/^contextMembers$/,
/^views$/,
/^(viewGroup|view_group)$/,
/^(viewGroups|view_groups)$/,
/^includes$/,
/^excludes$/,
/^hierarchies\.[_a-zA-Z][_a-zA-Z0-9]*\.levels$/,
/^cubes\.[0-9]+\.(joinPath|join_path)$/,
/^folders\.[0-9]+\.includes\.[0-9]+\.(joinPath|join_path)$/,
/^(accessPolicy|access_policy)\.[0-9]+\.(rowLevel|row_level)\.filters\.[0-9]+.*\.member$/,
/^(accessPolicy|access_policy)\.[0-9]+\.(rowLevel|row_level)\.filters\.[0-9]+.*\.values$/,
/^(accessPolicy|access_policy)\.[0-9]+\.conditions.[0-9]+\.if$/,
/^(defaultFilters|default_filters)\.[0-9]+\.member$/,
/^(defaultFilters|default_filters)\.[0-9]+\.values$/,
/^(defaultFilters|default_filters)\.[0-9]+\.unless$/,
/^(measures|dimensions)\.[_a-zA-Z][_a-zA-Z0-9]*\.mask\.sql$/,
];
export const transpiledFields: Set<String> = new Set<String>();
transpiledFieldsPatterns?.forEach((r) => {
const fields = r.toString().replace(/.*?([_a-zA-Z|][_a-zA-Z0-9|]*)([^_a-zA-Z0-9|]*)$/, '$1').split('|');
fields.forEach((f) => transpiledFields.add(f));
});
export class CubePropContextTranspiler implements TranspilerInterface {
public constructor(
protected readonly cubeSymbols: TranspilerSymbolResolver,
protected readonly cubeDictionary: TranspilerCubeResolver,
protected readonly viewCompiler: TranspilerSymbolResolver,
) {
}
public traverseObject(): TraverseObject {
return {
CallExpression: (path) => {
if (t.isIdentifier(path.node.callee)) {
const args = path.get('arguments');
if (path.node.callee.name === 'cube' || path.node.callee.name === 'view') {
if (args?.[args.length - 1]) {
const cubeName = args[0].node.type === 'StringLiteral' && args[0].node.value ||
args[0].node.type === 'TemplateLiteral' &&
args[0].node.quasis.length &&
args[0].node.quasis[0].value.cooked;
args[args.length - 1].traverse(this.sqlAndReferencesFieldVisitor(cubeName as string));
args[args.length - 1].traverse(
this.knownIdentifiersInjectVisitor('extends', name => this.cubeDictionary.resolveCube(name))
);
}
} else if (path.node.callee.name === 'context' || path.node.callee.name === 'view_group') {
args[args.length - 1].traverse(this.sqlAndReferencesFieldVisitor(null));
}
}
}
};
}
protected transformObjectProperty(path: NodePath<t.ObjectProperty>, resolveSymbol: SymbolResolver) {
CubePropContextTranspiler.replaceValueWithArrowFunction(resolveSymbol, path.get('value'));
}
public static replaceValueWithArrowFunction(resolveSymbol: (name: string) => any, value: NodePath<any>) {
// If the current value is already an arrow function, update its parameters and keep the body
if (t.isArrowFunctionExpression(value.node)) {
const bodyPath = value.get('body') as NodePath<any>;
const knownIds = CubePropContextTranspiler.collectKnownIdentifiersAndTransform(
resolveSymbol,
bodyPath,
);
value.replaceWith(
t.arrowFunctionExpression(
knownIds.map(i => t.identifier(i)),
value.node.body,
false,
),
);
} else {
const knownIds = CubePropContextTranspiler.collectKnownIdentifiersAndTransform(
resolveSymbol,
value,
);
value.replaceWith(
t.arrowFunctionExpression(
knownIds.map(i => t.identifier(i)),
// @todo Replace any with assert expression
<any>value.node,
false,
),
);
}
}
protected sqlAndReferencesFieldVisitor(cubeName: string | null | undefined): TraverseObject {
const resolveSymbol = n => this.viewCompiler.resolveSymbol(cubeName, n) ||
this.cubeSymbols.resolveSymbol(cubeName, n) ||
this.cubeSymbols.isCurrentCube(n);
return {
ObjectProperty: (path) => {
if (((path.node.key.type === 'Identifier' && path.node.key.name === 'joins') ||
(path.node.key.type === 'StringLiteral' && path.node.key.value === 'joins'))
&& t.isObjectExpression(path.node.value)) {
const fullPath = CubePropContextTranspiler.fullPath(path);
if (fullPath === 'joins') {
this.convertJoinsObjectToArray(path);
}
}
if ((path.node.key.type === 'Identifier' && transpiledFields.has(path.node.key.name)) ||
(path.node.key.type === 'StringLiteral' && transpiledFields.has(path.node.key.value))) {
const fullPath = CubePropContextTranspiler.fullPath(path);
// eslint-disable-next-line no-restricted-syntax
for (const p of transpiledFieldsPatterns) {
if (fullPath.match(p)) {
this.transformObjectProperty(path, resolveSymbol);
return;
}
}
}
}
};
}
protected convertJoinsObjectToArray(path: NodePath<t.ObjectProperty>) {
const valuePath = path.get('value');
if (!valuePath.isObjectExpression()) {
return;
}
const elements: t.ObjectExpression[] = [];
for (const prop of valuePath.get('properties')) {
if (!prop.isObjectProperty()) {
return;
}
const keyNode = prop.node.key;
const valueNode = prop.node.value;
if (
(t.isIdentifier(keyNode) || t.isStringLiteral(keyNode)) &&
t.isObjectExpression(valueNode)
) {
const nameProp = t.objectProperty(
t.identifier('name'),
t.stringLiteral(t.isIdentifier(keyNode) ? keyNode.name : keyNode.value)
);
const newProps = [nameProp, ...valueNode.properties];
const objectExpr = t.objectExpression(newProps);
elements.push(objectExpr);
}
}
valuePath.replaceWith(t.arrayExpression(elements));
}
protected static fullPath(path: NodePath): string {
// @ts-ignore
let fp = path?.node?.key?.name || path?.node?.key?.value || '';
let pp: NodePath<t.Node> | null | undefined = path?.parentPath;
while (pp) {
if (pp?.parentPath?.node?.type === 'ArrayExpression') {
fp = `0.${fp}`;
pp = pp?.parentPath;
// @ts-ignore
} else if (pp?.parentPath?.node?.key?.type === 'Identifier') {
// @ts-ignore
fp = `${pp?.parentPath?.node?.key?.name || '0'}.${fp}`;
pp = pp?.parentPath?.parentPath;
// @ts-ignore
} else if (pp?.parentPath?.node?.key?.type === 'StringLiteral') {
// @ts-ignore
fp = `${pp?.parentPath?.node?.key?.value || '0'}.${fp}`;
pp = pp?.parentPath?.parentPath;
} else break;
}
return fp;
}
protected knownIdentifiersInjectVisitor(field: RegExp | string, resolveSymbol: SymbolResolver): TraverseObject {
return {
ObjectProperty: (path) => {
if ((path.node.key.type === 'Identifier' && path.node.key.name.match(field)) ||
(path.node.key.type === 'StringLiteral' && path.node.key.value.match(field))) {
this.transformObjectProperty(path, resolveSymbol);
}
}
};
}
protected static collectKnownIdentifiersAndTransform(resolveSymbol: SymbolResolver, path: NodePath): string[] {
const identifiers: string[] = [];
const isAccessPolicy = this.isAccessPolicyPath(path);
if (path.node.type === 'Identifier') {
CubePropContextTranspiler.transformCubeCloudShorthandIdentifier(path as NodePath<t.Identifier>, identifiers, isAccessPolicy, resolveSymbol);
if (path.node.type === 'Identifier') {
CubePropContextTranspiler.matchAndTransformIdentifier(path, resolveSymbol, identifiers);
}
}
path.traverse({
Identifier: (p) => {
CubePropContextTranspiler.transformCubeCloudShorthandIdentifier(p, identifiers, isAccessPolicy, resolveSymbol);
CubePropContextTranspiler.matchAndTransformIdentifier(p, resolveSymbol, identifiers);
},
MemberExpression: (p) => {
CubePropContextTranspiler.transformCubeCloudShorthandMemberExpression(p, isAccessPolicy, resolveSymbol);
}
});
return R.uniq(identifiers);
}
protected static matchAndTransformIdentifier(path, resolveSymbol: SymbolResolver, identifiers: string[]) {
if (
(!path.parent ||
(path.parent.type !== 'MemberExpression' || path.parent.type === 'MemberExpression' && path.key !== 'property')
) &&
resolveSymbol(path.node.name)
) {
identifiers.push(path.node.name);
}
}
private static readonly CUBE_CLOUD_SHORTHAND_IDENTIFIERS = ['userAttributes', 'user_attributes', 'groups'];
private static isAccessPolicyPath(path: NodePath): boolean {
// @ts-ignore
const target = (!path?.node?.key && path?.parentPath && t.isObjectProperty(path.parentPath.node))
? path.parentPath
: path;
const fp = this.fullPath(target);
return fp.startsWith('accessPolicy') || fp.startsWith('access_policy');
}
private static securityContextIdentifier(isAccessPolicy: boolean): t.Identifier {
return t.identifier(isAccessPolicy ? 'securityContext' : 'SECURITY_CONTEXT');
}
private static isShadowedByFunctionParam(name: string, path: NodePath): boolean {
let current: NodePath | null = path.parentPath;
while (current) {
const { node } = current;
if (
(t.isArrowFunctionExpression(node) || t.isFunctionExpression(node)) &&
node.params.some(p => t.isIdentifier(p) && p.name === name)
) {
return true;
}
current = current.parentPath;
}
return false;
}
protected static transformCubeCloudShorthandIdentifier(path: NodePath<t.Identifier>, identifiers: string[], isAccessPolicy: boolean, resolveSymbol: SymbolResolver) {
if (!this.CUBE_CLOUD_SHORTHAND_IDENTIFIERS.includes(path.node.name)) {
return;
}
if (resolveSymbol(path.node.name)) {
return;
}
if (
path.parent &&
(path.parent.type === 'MemberExpression' || path.parent.type === 'OptionalMemberExpression') &&
path.key === 'property'
) {
return;
}
if (this.isShadowedByFunctionParam(path.node.name, path)) {
return;
}
const contextId = this.securityContextIdentifier(isAccessPolicy);
const cubeCloud = t.memberExpression(contextId, t.identifier('cubeCloud'));
const prop = path.node.name === 'user_attributes' ? 'userAttributes' : path.node.name;
const newExpr = t.memberExpression(cubeCloud, t.identifier(prop));
path.replaceWith(newExpr);
identifiers.push(contextId.name);
}
protected static transformCubeCloudShorthandMemberExpression(path: NodePath<t.MemberExpression>, isAccessPolicy: boolean, resolveSymbol: SymbolResolver) {
if (
t.isIdentifier(path.node.object) &&
this.CUBE_CLOUD_SHORTHAND_IDENTIFIERS.includes(path.node.object.name) &&
!resolveSymbol(path.node.object.name) &&
!this.isShadowedByFunctionParam(path.node.object.name, path)
) {
const contextId = this.securityContextIdentifier(isAccessPolicy);
const cubeCloud = t.memberExpression(contextId, t.identifier('cubeCloud'));
const prop = path.node.object.name === 'user_attributes' ? 'userAttributes' : path.node.object.name;
const shorthand = t.memberExpression(cubeCloud, t.identifier(prop));
const newMemberExpression = t.memberExpression(shorthand, path.node.property, path.node.computed);
path.replaceWith(newMemberExpression);
} else if (
(t.isMemberExpression(path.node.object) || t.isOptionalMemberExpression(path.node.object)) &&
t.isIdentifier(path.node.object.property, { name: 'user_attributes' }) &&
!path.node.object.computed
) {
const newObject = t.memberExpression(
path.node.object.object,
t.identifier('userAttributes'),
false
);
const newMemberExpression = t.memberExpression(newObject, path.node.property, path.node.computed);
path.replaceWith(newMemberExpression);
}
}
}