-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
1163 lines (986 loc) · 33.2 KB
/
index.js
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generate = require('@babel/generator').default;
const t = require('@babel/types');
const codeFrameColumns = require('@babel/code-frame').codeFrameColumns;
function compile(code) {
const ast = parser.parse(code, { sourceType: 'module', plugins: ['jsx'] });
// * helper functions
function checkIfTargetJSXComponent(functionPath) {
const funcName = functionPath.node.id.name;
const programPath = functionPath.findParent(t.isProgram);
const exportNode = programPath.node.body.find(
(code) => code.type === 'ExportDefaultDeclaration'
);
if (exportNode.declaration.name !== funcName) {
return false;
}
// Remove ReturnStatement from BlockStatement
const funcCodeBlock = functionPath.node.body.body;
const blockLen = funcCodeBlock.length;
const lastElement = funcCodeBlock[blockLen - 1];
if (lastElement.type !== 'ReturnStatement') {
throw SyntaxError(
'The return statement should be at the end of the function.'
);
} else if (lastElement.argument.type !== 'JSXElement') {
throw SyntaxError(
'The default exported function should return a JSX element.'
);
}
return true;
}
function getErrorCodeFrame(path, message) {
const expMsg = codeFrameColumns(
code,
path.node.loc,
// { start: path.node.loc.start },
{ message }
);
return expMsg;
}
function getComponentBodyPath(path, componentFuncPath) {
const bodyNodePath = path.findParent(
(currPath) =>
currPath.parentKey === 'body' &&
currPath.parentPath.parentPath === componentFuncPath
);
return bodyNodePath;
}
function getVariablesNames(path) {
const out = [];
if (path.type === 'VariableDeclarator') {
if (path.get('id').type === 'ObjectPattern') {
const propertiesPath = path.get('id.properties');
const len = propertiesPath.length;
for (let i = 0; i < len; i++) {
out.push(propertiesPath[i].get(`key.name`).node);
}
} else {
out.push(path.get('id.name').node);
}
} else if (path.type === 'AssignmentExpression') {
out.push(path.get('left.name').node);
}
return out;
}
function getReactiveNodeForIdentifier(
identifierPath,
componentFuncPath,
compiledStatePaths
) {
// propUsed = true;
const $ = t.identifier('$'); // label
// Not reactive if passed as initial value to useState
const callExpr = identifierPath.findParent(t.isCallExpression);
if (callExpr && callExpr.node.callee.name === 'useState') {
return { parentToBeReplaced: null, reactiveLabel: null };
}
const alreadyReactive = identifierPath.findParent(t.isLabeledStatement);
if (alreadyReactive) {
return { parentToBeReplaced: null, reactiveLabel: null };
}
const parentFunctionPath = identifierPath.getFunctionParent();
const isNestedFunction = parentFunctionPath !== componentFuncPath;
if (isNestedFunction) {
return { parentToBeReplaced: null, reactiveLabel: null };
}
// TODO: handle conditional rendering
const isReturn = identifierPath.findParent(t.isReturnStatement);
if (isReturn) {
return { parentToBeReplaced: null, reactiveLabel: null };
}
let componentBodyPath = getComponentBodyPath(
identifierPath,
componentFuncPath
);
let reactiveLabel = null;
const bodyNode = componentBodyPath.node;
if (bodyNode && !compiledStatePaths.includes(bodyNode)) {
if (bodyNode.type === 'VariableDeclaration') {
const asnExp = t.assignmentExpression(
'=',
bodyNode.declarations[0].id,
bodyNode.declarations[0].init
);
const exprStmnt = t.expressionStatement(asnExp);
reactiveLabel = t.labeledStatement($, exprStmnt);
} else if (t.isStatement(bodyNode)) {
reactiveLabel = t.labeledStatement($, bodyNode);
} else {
componentBodyPath = null;
}
} else {
componentBodyPath = null;
}
return { parentToBeReplaced: componentBodyPath, reactiveLabel };
}
function getExportNodeForProp(propName) {
const identifier = t.identifier(propName);
const vDeclarator = t.variableDeclarator(identifier);
const vDeclaration = t.variableDeclaration('let', [vDeclarator]);
const namedExport = t.exportNamedDeclaration(vDeclaration, [], null);
return namedExport;
}
// !replaces identifier param with '$$props'
function getPropNames(funcPath) {
const params = funcPath.node.params;
const hasProps = !!params.length;
const propsObject = params[0];
let props = [];
if (!hasProps) {
return props;
}
if (propsObject.type === 'ObjectPattern') {
props = propsObject.properties.map((objProp) => objProp.value.name);
} else if (propsObject.type === 'Identifier') {
props = ['$$props'];
propsContainerObjName = propsObject.name;
funcPath.get('body').traverse({
Identifier(idPath) {
if (idPath.node.name === propsContainerObjName) {
idPath.replaceWith(t.identifier('$$props'));
}
},
VariableDeclarator(declPath) {
if (
declPath.node.init.name !== propsContainerObjName ||
declPath.node.id.type !== 'ObjectPattern'
) {
return;
}
props = props.concat(
declPath.node.id.properties.map((objProp) => objProp.value.name)
);
},
});
}
return props;
}
function getDeclarationForUseState(callExprPath) {
const lVal = callExprPath.container.id;
let vDeclaration = null;
let setterFunctionName = null;
let stateVariableName = null;
if (lVal.type === 'ArrayPattern') {
// array destructured form
stateVariableName = lVal.elements[0].name;
setterFunctionName = lVal.elements[1].name;
const argNode = callExprPath.node.arguments[0];
const vDectr = t.variableDeclarator(
t.identifier(stateVariableName),
argNode
);
vDeclaration = t.variableDeclaration('let', [vDectr]);
}
return { vDeclaration, stateVariableName, setterFunctionName };
}
function getAsmntNodeForSetter(idPath, stateVariableName, funcPath) {
let out = { callExprPath: null, asnExpr: null };
const callExprPath = idPath.findParent(t.isCallExpression);
if (!callExprPath) {
return out;
}
const firstArgPath = callExprPath.get('arguments.0');
let rhs = null;
const stateId = t.identifier(stateVariableName);
if (t.isFunction(firstArgPath)) {
rhs = t.callExpression(firstArgPath.node, [stateId]);
} else {
rhs = firstArgPath.node;
}
const asnExpr = t.assignmentExpression('=', stateId, rhs);
// callExpr.replaceWith(asnExpr);
return { callExprPath, asnExpr };
}
function buildSetterFunction(stateName, setterName) {
return t.functionDeclaration(
t.identifier(setterName),
[t.identifier('value')],
t.blockStatement([
t.expressionStatement(
t.assignmentExpression(
'=',
t.identifier(stateName),
t.identifier('value')
)
),
])
);
}
function getContainingFunction(path) {
const func = path.getFunctionParent() || {};
const name = null;
if (
func.type === 'FunctionExpression' ||
func.type === 'ArrowFunctionExpression'
) {
if (func.container.type === 'VariableDeclarator') {
name = func.container.id.name;
} else if (func.container.type === 'AssignmentExpression') {
name = func.container.left.name;
}
} else if (func.type === 'FunctionDeclaration') {
name = func.id.name;
}
return { name, path: func };
}
function isCallToBuiltInHook(callExprPath, hookName) {
const callee = callExprPath.node.callee;
if (callee.type === 'Identifier' && callee.name === hookName) {
return true;
} else if (
callee.type === 'MemberExpression' &&
callee.object.name === 'React' &&
callee.property.name === hookName
) {
return true;
}
return false;
}
function getDeclarationNames(bodyNodePath) {
let decl = [];
bodyNodePath.traverse({
VariableDeclarator(declPath) {
decl.push({
name: declPath.node.id.name,
path: declPath.get('init'),
});
},
AssignmentExpression(asmntPath) {
decl.push({
name: asmntPath.node.left.name,
path: asmntPath.get('right'),
});
},
FunctionDeclaration(funcPath) {
decl.push({
name: funcPath.node.id.name,
path: funcPath,
});
},
});
return decl;
}
// useEffect() helpers
function isOnMount(argsPath) {
const args = argsPath;
if (
args.length >= 2 &&
args[1].node.type === 'ArrayExpression' &&
args[1].node.elements.length === 0
) {
return true;
}
return false;
}
function buildNamedImportNode(specifiers, source) {
const specifierNodes = specifiers.map((sp) => {
return t.importSpecifier(t.identifier(sp), t.identifier(sp));
});
return t.importDeclaration(specifierNodes, t.stringLiteral(source));
}
function getReturnVal(callBackPath) {
let retVal = null;
if (callBackPath.get('body').type !== 'BlockStatement') {
retVal = callBackPath.get('body');
return retVal;
}
callBackPath.get('body').traverse({
ReturnStatement(retPath) {
retVal = retPath.get('argument');
},
});
return retVal;
}
function isAfterUpdate(argsPath) {
if (argsPath.length === 2) {
if (
argsPath[1].node.type === 'ArrayExpression' &&
argsPath[1].node.elements.length > 0
)
return true;
} else if (argsPath.length === 1) {
return true;
}
return false;
}
function removeReturn(callbackPath) {
let ret = null;
const callbackBody = callbackPath.node.body;
if (callbackBody.type !== 'BlockStatement') {
return callbackPath.findParent(t.isCallExpression);
}
callbackPath.traverse({
ReturnStatement(retPath) {
ret = retPath;
},
});
return ret;
}
// * list map helpers
function getListMapCode({ objName, elementName, jsxElem, key }) {
const out = `{#each ${objName} as ${elementName} (${key})}${
generate(jsxElem, {}).code
}{/each}`;
// keyNode.remove();
return out;
}
function getKeyAttrPath(callExprPath) {
let keypath = null;
callExprPath.traverse({
JSXAttribute(jsxAttrPath) {
if (jsxAttrPath.node.name.name !== 'key') {
return;
}
keypath = jsxAttrPath;
},
});
return keypath;
}
function buildHtmlxNode(codeString) {
const openingElem = t.jsxOpeningElement(t.jsxIdentifier('HTMLxBlock'), []);
const closingElem = t.jsxClosingElement(t.jsxIdentifier('HTMLxBlock'));
const jsxExpr = t.jsxExpressionContainer(t.stringLiteral(codeString));
const children = [jsxExpr];
return t.jsxElement(openingElem, closingElem, children);
}
// * processing functions
const compiledStateBodyNodePaths = [];
function processProps(idPath, funcPath, propsNames) {
// const propsNames = getPropNames(funcPath);
const identifierName = idPath.node.name;
// console.log('id: ' + identifierName);
// compile props
if (propsNames.includes(identifierName)) {
// console.log('prop used: ' + identifierName);
const {
parentToBeReplaced,
reactiveLabel,
} = getReactiveNodeForIdentifier(
idPath,
funcPath,
compiledStateBodyNodePaths
);
if (parentToBeReplaced) {
const isInDeclarator = idPath.findParent(t.isVariableDeclarator);
const isInAssngmt = idPath.findParent(t.isAssignmentExpression);
if (isInDeclarator || isInAssngmt) {
const varNames = getVariablesNames(isInDeclarator || isInAssngmt);
varNames.forEach((varName) => {
stateVariables[varName] = {
setterFunctionName: null,
decNode: null,
};
});
}
if (reactiveLabel) parentToBeReplaced.replaceWith(reactiveLabel);
else {
parentToBeReplaced.remove();
}
}
return true;
}
return false;
}
let useState = 'useState';
const stateVariables = {
/* setterFunctionName, decNode */
};
const setterFunctions = {};
const builtSetterFunctions = [];
const excludedBodyPaths = [];
const variablesParsedSoFar = {};
function processState(idPath, funcPath) {
// TODO: detect aliases
const isStateVariable = stateVariables[idPath.node.name] !== undefined;
if (isStateVariable) {
let parentDec = idPath.findParent(t.isVariableDeclaration);
let isStateDeclaration =
parentDec &&
stateVariables[idPath.node.name].decNode === parentDec.node;
if (isStateDeclaration) {
// Don't replace state declaration. After useState is replaced with VariableDeclaration,
// it is immediately revisited, we do not want to replace it
return false;
}
const isInDeclarator = idPath.findParent(t.isVariableDeclarator);
const isInAssngmt = idPath.findParent(t.isAssignmentExpression);
if (isInDeclarator || isInAssngmt) {
const varNames = getVariablesNames(isInDeclarator || isInAssngmt);
varNames.forEach((varName) => {
stateVariables[varName] = {
setterFunctionName: null,
decNode: null,
};
});
}
const {
parentToBeReplaced,
reactiveLabel,
} = getReactiveNodeForIdentifier(
idPath,
funcPath,
compiledStateBodyNodePaths
);
if (parentToBeReplaced) parentToBeReplaced.replaceWith(reactiveLabel);
return true;
}
// TODO: setter functions
const isSetter = setterFunctions[idPath.node.name] !== undefined;
if (isSetter) {
const { callExprPath, asnExpr } = getAsmntNodeForSetter(
idPath,
setterFunctions[idPath.node.name]
);
if (!callExprPath) {
const funcDecl = buildSetterFunction(
setterFunctions[idPath.node.name],
idPath.node.name
);
builtSetterFunctions.push(funcDecl);
return true;
}
callExprPath.replaceWith(asnExpr); // ! replace the function call
const hasLabeledParent = callExprPath.findParent(t.isLabeledStatement);
const isInsideFuncDecl = callExprPath.findParent(t.isFunction);
// ? function declarations
// ? return statement
if (!hasLabeledParent && !isInsideFuncDecl) {
const bodyNodePath = getComponentBodyPath(idPath, funcPath);
const labeledStatement = t.labeledStatement(
t.identifier('$'),
bodyNodePath.node
);
// ! if necessary, replace containing statement with a reactive one
bodyNodePath.replaceWith(labeledStatement);
}
}
let callExpr = idPath.findParent(t.isCallExpression);
if (callExpr && isCallToBuiltInHook(callExpr, 'useState')) {
const {
vDeclaration,
stateVariableName,
setterFunctionName,
} = getDeclarationForUseState(callExpr);
if (vDeclaration) {
const bodyNode = getComponentBodyPath(idPath, funcPath);
bodyNode.replaceWith(vDeclaration);
stateVariables[stateVariableName] = {
setterFunctionName,
decNode: vDeclaration,
};
setterFunctions[setterFunctionName] = stateVariableName;
compiledStateBodyNodePaths.push(vDeclaration);
return true;
}
// TODO: non-destructured pattern
}
return false;
}
const jsxVariables = {};
function processJSXVariable(idPath) {
const isRefToJSXVar = jsxVariables[idPath.node.name];
const isBeingReturned =
idPath.container && idPath.container.type === 'ReturnStatement';
const isRefedInJSXExpression = idPath.findParent(
t.isJSXExpressionContainer
);
if (!isRefToJSXVar || (!isBeingReturned && !isRefedInJSXExpression)) {
// * noop
return false;
}
idPath.replaceWith(jsxVariables[idPath.node.name]);
return true;
}
// * main
let scriptNodes = [];
const jsxElements = { mainJSXElementPath: {}, others: {} };
let htmlxCode = '';
const allJSXReturns = [];
const defaultExport = {};
traverse(ast, {
CallExpression(callExprPath) {
if (isCallToBuiltInHook(callExprPath, 'memo')) {
const firstArg = callExprPath.get('arguments.0');
callExprPath.replaceWith(firstArg);
return;
}
},
});
const exportDetectionPlugin = {
ExportDefaultDeclaration(exportPath) {
switch (exportPath.node.declaration.type) {
case 'Identifier':
defaultExport.id = exportPath.get('declaration');
break;
case 'FunctionDeclaration':
case 'ArrowFunctionExpression':
defaultExport.function = exportPath.get('declaration');
break;
case 'AssignmentExpression':
if (
exportPath.node.declaration.right.type !== 'FunctionDeclaration' &&
exportPath.node.declaration.right.type !== 'ArrowFunctionExpression'
) {
const expMsg = getErrorCodeFrame(
exportPath,
'Input file has to export a function that returns JSX'
);
throw Error(expMsg);
}
defaultExport.function = exportPath.get('declaration.right');
break;
default:
const expMsg = getErrorCodeFrame(
exportPath,
'Input file has to export a function that returns JSX'
);
throw Error(expMsg);
break;
}
excludedBodyPaths.push(exportPath);
},
ImportDeclaration(importPath) {
if (importPath.node.source.value === 'react') {
return;
}
scriptNodes.push(importPath.node);
},
};
traverse(ast, exportDetectionPlugin);
if (defaultExport.id) {
const findComponentFunctionPlugin = {
VariableDeclarator(vdPath) {
if (
vdPath.node.id.name !== defaultExport.id.node.name ||
vdPath.parentPath.parentPath.type !== 'Program'
) {
return;
}
if (
vdPath.node.init.type !== 'FunctionExpression' &&
vdPath.node.init.type !== 'ArrowFunctionExpression'
) {
const expMsg = getErrorCodeFrame(
defaultExport,
'Input file has to export a function that returns JSX'
);
throw Error(expMsg);
}
excludedBodyPaths.push(vdPath.parentPath);
defaultExport.function = vdPath.get('init');
},
AssignmentExpression(asmntPath) {
if (
asmntPath.node.left.name !== defaultExport.id.node.name ||
asmntPath.parentPath.parentPath.type !== 'Program'
) {
return;
}
if (
asmntPath.node.right.type !== 'FunctionExpression' &&
asmntPath.node.right.type !== 'ArrowFunctionExpression'
) {
const expMsg = getErrorCodeFrame(
defaultExport,
'Input file has to export a function that returns JSX'
);
throw Error(expMsg);
}
excludedBodyPaths.push(asmntPath.parentPath);
defaultExport.function = asmntPath.get('right');
},
FunctionDeclaration(funcPath) {
if (
funcPath.node.id.name !== defaultExport.id.node.name ||
funcPath.parentPath.type !== 'Program'
) {
return;
}
excludedBodyPaths.push(funcPath);
defaultExport.function = funcPath;
},
};
traverse(ast, findComponentFunctionPlugin);
}
if (!defaultExport.function) {
throw Error('Input file has to export a function that returns JSX');
}
const propsNames = getPropNames(defaultExport.function);
// * add export statement for each prop
propsNames.forEach((propName) => {
if (!propName.startsWith('$$'))
scriptNodes.push(getExportNodeForProp(propName));
});
const listMaps = [];
const funcPath = defaultExport.function;
traverse(ast, {
Program(rootPath) {
const bodyLen = rootPath.get('body').length;
// const bodyArr = rootPath.get('body').node
for (let i = 0; i < bodyLen; i++) {
let bodyNodePath = rootPath.get('body.' + i);
if (
bodyNodePath.type === 'ImportDeclaration' ||
excludedBodyPaths.find((exclPath) => bodyNodePath === exclPath)
) {
continue;
} else {
let declNames = getDeclarationNames(bodyNodePath);
if (declNames.length) {
// variablesOutsideComponent
declNames.forEach(
(dec) => (variablesParsedSoFar[dec.name] = dec.path)
);
}
if (bodyNodePath.type === 'ExportNamedDeclaration') {
if (!bodyNodePath.node.declaration) {
continue;
}
bodyNodePath = bodyNodePath.get('declaration');
}
scriptNodes.push(bodyNodePath.node);
}
}
},
// ! throws if JSX is found inside a loop, conditional body or a function
// ! that is not a callback to list.map
JSXElement(jsxPath) {
// !throw if inside loop
const isInLoop = jsxPath.findParent((path) => {
return (
t.isForXStatement(path) || t.isForStatement(path) || t.isWhile(path)
);
});
if (isInLoop) {
const msg = getErrorCodeFrame(
jsxPath,
'JSX inside loops cannot be compiled'
);
throw Error(msg);
}
// ! throw if inside conditional
const isInConditional = jsxPath.findParent(t.isConditional);
const isInJSXExpression =
isInConditional &&
isInConditional.container.type === 'JSXExpressionContainer';
if (isInConditional && !isInJSXExpression) {
const errMsg = getErrorCodeFrame(
jsxPath,
'JSX inside conditionals cannot be compiled'
);
throw Error(errMsg);
}
// ! throw if inside a function
const funcDecl = jsxPath.findParent(t.isFunction);
const callExpr = jsxPath.findParent(t.isCallExpression);
const funcIsInComponentBody = funcDecl === funcPath;
const funcIsCallbackPassedToListMap =
callExpr &&
callExpr.node.callee.type === 'MemberExpression' &&
callExpr.node.callee.property.name === 'map';
if (
funcDecl &&
!funcIsInComponentBody &&
!funcIsCallbackPassedToListMap
) {
const errMsg = getErrorCodeFrame(
jsxPath,
'It seems like you have a JSX element inside a function that is not the exported function. This cannot be compiled.'
);
throw Error(errMsg);
}
},
// ! modifies the jsxVariables object
VariableDeclarator(declaratorPath) {
const varName = declaratorPath.node.id.name;
const val = declaratorPath.node.init;
if (val && val.type === 'JSXElement') {
jsxVariables[varName] = declaratorPath.get('init');
}
},
// ! modifies the jsxVariables object
AssignmentExpression(assignmentPath) {
const varName = assignmentPath.node.left.name;
const val = assignmentPath.node.right;
if (val && val.type === 'JSXElement') {
jsxVariables[varName] = assignmentPath.get('right');
}
},
});
const namedImportsFromSvelte = {};
funcPath.get('body').traverse({
JSXAttribute(attrPath) {
// replace on<Event> attrs. E.g. onClick -> on:click
const attrName = attrPath.node.name.name;
const eventAttr = /^on([a-z]+)$/i.exec(attrName);
if (attrName === 'className') {
attrPath.get('name').replaceWith(t.jsxIdentifier('class'));
return;
}
if (eventAttr) {
const eventName = eventAttr[1];
const newAttrName = t.jsxNamespacedName(
t.jsxIdentifier('on'),
t.jsxIdentifier(eventName.toLowerCase())
);
attrPath.get('name').replaceWith(newAttrName);
}
},
});
funcPath.get('body').traverse({
// ! replace call to `list.map` with <HTMLxBlock> JSX element
CallExpression(callExprPath) {
const callNode = callExprPath.node;
if (isCallToBuiltInHook(callExprPath, 'useEffect')) {
const firstArg = callNode.arguments[0];
if (
firstArg.type !== 'FunctionExpression' &&
firstArg.type !== 'ArrowFunctionExpression'
) {
const msg = getErrorCodeFrame(
callExprPath,
'The first argument passed to useEffect must be a function expression.'
);
throw Error(msg);
}
// cleanup
const returnVal = getReturnVal(callExprPath.get('arguments.0'));
if (returnVal) {
// onDestroy
if (t.isFunction(returnVal) || t.isIdentifier(returnVal)) {
namedImportsFromSvelte.onDestroy = true;
const onDestroyCall = t.callExpression(t.identifier('onDestroy'), [
returnVal.node,
]);
callExprPath.insertAfter(onDestroyCall);
const pathToRemove = removeReturn(callExprPath.get('arguments.0'));
if (pathToRemove) {
pathToRemove.remove();
}
if (pathToRemove.node === callExprPath.node) {
return;
}
} else {
const msg = getErrorCodeFrame(
callExprPath,
'Cleanup function must be returned as a function expression.'
);
throw Error(msg);
}
}
if (isOnMount(callExprPath.get('arguments'))) {
// import for onMount
namedImportsFromSvelte.onMount = true;
// call expression, onMount(cb)
callExprPath.get('callee').replaceWith(t.identifier('onMount'));
callExprPath.set('arguments', [callExprPath.get('arguments.0').node]);
return;
}
if (isAfterUpdate(callExprPath.get('arguments'))) {
namedImportsFromSvelte.afterUpdate = true;
callExprPath.get('callee').replaceWith(t.identifier('afterUpdate'));
callExprPath.set('arguments', [callExprPath.get('arguments.0').node]);
return;
}
return;
}
if (isCallToBuiltInHook(callExprPath, 'useCallback')) {
const firstArg = callExprPath.get('arguments.0');
callExprPath.replaceWith(firstArg);
return;
}
if (isCallToBuiltInHook(callExprPath, 'useMemo')) {
const firstArg = callNode.arguments[0];
if (
firstArg.type !== 'FunctionExpression' &&
firstArg.type !== 'ArrowFunctionExpression'
) {
const msg = getErrorCodeFrame(
callExprPath,
'The first argument passed to useMemo must be a function expression, not a reference to a function.'
);
throw Error(msg);
}
const returnVal = getReturnVal(callExprPath.get('arguments.0'));
if (returnVal) {
// onDestroy
callExprPath.replaceWith(returnVal);
return;
}
}
if (isCallToBuiltInHook(callExprPath, 'useReducer')) {
const msg = getErrorCodeFrame(
callExprPath,
'useReducer not suppported yet'
);
throw Error(msg);
}
},
// ! props and state processing, JSX variable inlining
Identifier(idPath) {
const propsProcessed = processProps(idPath, funcPath, propsNames); // ! Side Effect: modifies AST
if (propsProcessed) return;
// ! modifies AST: replace `useState` call with declarations
// ! Replace state access and setterfunc call with reactive variables
let useStateReplaced = processState(idPath, funcPath);
if (useStateReplaced) return;
// ! modifies AST: replace references to variables with JSX values with inline JSX
// let jsxRemoved = processJSXVariable(idPath, funcPath);
// if (jsxRemoved) return;
},
});
funcPath.get('body').traverse({
VariableDeclarator(declaratorPath) {
const varName = declaratorPath.node.id.name;
const val = declaratorPath.node.init;
if (
val &&
val.type === 'JSXElement' &&
val.openingElement.name.name === 'HTMLxBlock'
) {
jsxVariables[varName] = declaratorPath.get('init');
}
},
AssignmentExpression(assignmentPath) {
const varName = assignmentPath.node.left.name;