-
-
Notifications
You must be signed in to change notification settings - Fork 218
/
maybe-box-node.ts
1174 lines (956 loc) 路 38.5 KB
/
maybe-box-node.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
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
import { logger } from '@pandacss/logger'
import { Bool } from 'lil-fp'
import type {
ArrayLiteralExpression,
BinaryExpression,
BindingElement,
ElementAccessExpression,
ExportDeclaration,
Expression,
Identifier,
ImportDeclaration,
ObjectLiteralElementLike,
ObjectLiteralExpression,
PropertyAccessExpression,
PropertySignature,
SourceFile,
SyntaxKind,
TemplateExpression,
TypeLiteralNode,
TypeNode,
VariableDeclaration,
} from 'ts-morph'
import { Node, ts } from 'ts-morph'
import { match } from 'ts-pattern'
import { box } from './box'
import { safeEvaluateNode } from './evaluate-node'
import { findIdentifierValueDeclaration } from './find-identifier-value-declaration'
import { isBoxNode, type BoxNode } from './box-factory'
import type { BoxContext, EvaluatedObjectResult, LiteralValue, MatchFnPropArgs, PrimitiveType } from './types'
import { isNotNullish, isObject, trimWhitespace, unwrapExpression } from './utils'
import { getObjectLiteralExpressionPropPairs } from './get-object-literal-expression-prop-pairs'
const cacheMap = new WeakMap<Node, MaybeBoxNodeReturn>()
const isCached = (node: Node) => cacheMap.has(node)
const getCached = (node: Node) => cacheMap.get(node)
const isPlusSyntax = (op: SyntaxKind) => op === ts.SyntaxKind.PlusToken
const isLogicalSyntax = (op: SyntaxKind) =>
op === ts.SyntaxKind.BarBarToken ||
op === ts.SyntaxKind.QuestionQuestionToken ||
op === ts.SyntaxKind.AmpersandAmpersandToken ||
op === ts.SyntaxKind.EqualsEqualsEqualsToken ||
op === ts.SyntaxKind.EqualsEqualsToken ||
op === ts.SyntaxKind.ExclamationEqualsEqualsToken ||
op === ts.SyntaxKind.ExclamationEqualsToken ||
op === ts.SyntaxKind.GreaterThanEqualsToken ||
op === ts.SyntaxKind.GreaterThanToken ||
op === ts.SyntaxKind.LessThanEqualsToken ||
op === ts.SyntaxKind.LessThanToken ||
op === ts.SyntaxKind.InstanceOfKeyword ||
op === ts.SyntaxKind.InKeyword
const isOperationSyntax = (op: SyntaxKind) =>
op === ts.SyntaxKind.AsteriskToken ||
op === ts.SyntaxKind.SlashToken ||
op === ts.SyntaxKind.PercentToken ||
op === ts.SyntaxKind.AsteriskAsteriskToken ||
op === ts.SyntaxKind.MinusToken
const canReturnWhenTrueInLogicalExpression = (op: ts.SyntaxKind) => {
return op === ts.SyntaxKind.BarBarToken || op === ts.SyntaxKind.QuestionQuestionToken
}
export type MaybeBoxNodeReturn = BoxNode | undefined
export function maybeBoxNode(
node: Node,
stack: Node[],
ctx: BoxContext,
matchProp?: (prop: MatchFnPropArgs) => boolean,
): MaybeBoxNodeReturn {
const cache = (value: MaybeBoxNodeReturn) => {
cacheMap.set(node, value)
return value
}
return (
match(node)
.when(isCached, getCached)
// <Box color="xxx" /> or <Box color={`xxx`} />
.when(Bool.or(Node.isStringLiteral, Node.isNoSubstitutionTemplateLiteral), (node) => {
const value = trimWhitespace(node.getLiteralValue())
return cache(box.literal(value, node, stack))
})
.when(Node.isObjectLiteralExpression, (node) => {
return cache(getObjectLiteralExpressionPropPairs(node, stack, ctx, matchProp))
})
// <Box truncate={true} /> or <Box truncate={false} />
.when(Bool.or(Node.isTrueLiteral, Node.isFalseLiteral), (node) => {
const value = node.getLiteralValue()
return cache(box.literal(value, node, stack))
})
// <Box color={123} />
.when(Node.isNumericLiteral, (node) => {
const value = node.getLiteralValue()
return cache(box.literal(value, node, stack))
})
// <Box color={null} />
.when(Node.isNullLiteral, (node) => {
return cache(box.literal(null, node, stack))
})
// <Box mt={-12} />
.when(Node.isPrefixUnaryExpression, (node) => {
const operand = node.getOperand()
const operator = node.getOperatorToken()
const boxNode = maybeBoxNode(operand, stack, ctx)
if (!box.isNumberLiteral(boxNode)) return
return cache(operator === ts.SyntaxKind.MinusToken ? box.literal(-Number(boxNode.value), node, stack) : boxNode)
})
// <ColorBox color={['red.300', 'green.400']} />
.when(Node.isArrayLiteralExpression, (node) => {
const boxNodes = node.getElements().map((element) => {
return maybeBoxNode(element, stack, ctx) ?? cache(box.unresolvable(element, stack))
}) as BoxNode[]
return cache(box.array(boxNodes, node, stack))
})
// <ColorBox color={staticColor} />
.when(Node.isIdentifier, (node) => {
return match(node.getText())
.with('undefined', () => cache(box.literal(undefined, node, stack)))
.otherwise(() => cache(maybeIdentifierValue(node, stack, ctx)))
})
// <ColorBox color={css`red.400`} />
.when(Node.isTemplateHead, (node) => {
return cache(box.literal(node.getLiteralText(), node, stack))
})
// <ColorBox color={`${color}.400`} />
.when(Node.isTemplateExpression, (node) => {
const value = maybeTemplateStringValue(node, stack, ctx)
return cache(box.literal(value, node, stack))
})
// css`font-size: 1.5em;`
.when(Node.isTaggedTemplateExpression, (node) => {
return cache(maybeBoxNode(node.getTemplate(), stack, ctx))
})
// <ColorBox color={colors[staticColor]} /> or <ColorBox color={colors["brand"]} />
.when(Node.isElementAccessExpression, (node) => {
return cache(getElementAccessedExpressionValue(node, stack, ctx))
})
// <ColorBox color={colors.brand} />
.when(Node.isPropertyAccessExpression, (node) => {
return cache(getPropertyAccessedExpressionValue(node, [], stack, ctx)!)
})
// <ColorBox color={useColorModeValue() ? darkValue : "whiteAlpha.100"} />
.when(Node.isConditionalExpression, (node) => {
if (ctx.flags?.skipConditions) {
return cache(box.unresolvable(node, stack))
}
const condExpr = unwrapExpression(node.getCondition())
const condBoxNode =
(Node.isIdentifier(condExpr)
? maybeBoxNode(condExpr, [], ctx)
: safeEvaluateNode<LiteralValue>(condExpr as Expression, stack, ctx)) ?? box.unresolvable(condExpr, stack)
const condValue = isBoxNode(condBoxNode) ? condBoxNode : box.from(condBoxNode, node, stack)
if (box.isEmptyInitializer(condValue)) return
if (box.isUnresolvable(condValue) || box.isConditional(condValue)) {
const whenTrueExpr = unwrapExpression(node.getWhenTrue())
const whenFalseExpr = unwrapExpression(node.getWhenFalse())
return cache(maybeResolveConditionalExpression({ whenTrueExpr, whenFalseExpr, node, stack }, ctx))
}
if (condValue.value) {
const whenTrueExpr = unwrapExpression(node.getWhenTrue())
const innerStack = [...stack] as Node[]
const maybeValue = maybeBoxNode(whenTrueExpr, innerStack, ctx)
return cache(maybeValue ?? box.unresolvable(whenTrueExpr, stack))
}
const whenFalseExpr = unwrapExpression(node.getWhenFalse())
const innerStack = [...stack] as Node[]
const maybeValue = maybeBoxNode(whenFalseExpr, innerStack, ctx)
return cache(maybeValue ?? box.unresolvable(node, stack))
})
// <ColorBox color={fn()} />
.when(Node.isCallExpression, (node) => {
const value = safeEvaluateNode<PrimitiveType | EvaluatedObjectResult>(node, stack, ctx)
if (!value) return
return cache(box.from(value, node, stack))
})
// <ColorBox color={isFocused && "red.400"} />
.when(Node.isBinaryExpression, (node) => {
const operatorKind = node.getOperatorToken().getKind()
return match(operatorKind)
.when(isPlusSyntax, () => {
const value =
tryComputingPlusTokenBinaryExpressionToString(node, stack, ctx) ??
safeEvaluateNode<string>(node, stack, ctx)
if (!value) return
return cache(box.from(value, node, stack))
})
.when(isLogicalSyntax, (op) => {
const whenTrueExpr = unwrapExpression(node.getLeft())
const whenFalseExpr = unwrapExpression(node.getRight())
const exprObject = {
whenTrueExpr,
whenFalseExpr,
node,
stack,
canReturnWhenTrue: canReturnWhenTrueInLogicalExpression(op),
} as const
return cache(maybeResolveConditionalExpression(exprObject, ctx))
})
.when(isOperationSyntax, () => {
return cache(box.literal(safeEvaluateNode(node, stack, ctx), node, stack))
})
.otherwise(() => undefined)
})
.otherwise(() => undefined)
)
}
export const onlyStringLiteral = (boxNode: MaybeBoxNodeReturn) => {
if (!boxNode) return
if (isBoxNode(boxNode) && box.isLiteral(boxNode) && typeof boxNode.value === 'string') {
return boxNode
}
}
const onlyNumberLiteral = (boxNode: MaybeBoxNodeReturn) => {
if (!boxNode) return
if (isBoxNode(boxNode) && box.isLiteral(boxNode) && typeof boxNode.value === 'number') {
return boxNode
}
}
const maybeStringLiteral = (node: Node, stack: Node[], ctx: BoxContext) =>
onlyStringLiteral(maybeBoxNode(node, stack, ctx))
export const maybePropName = (node: Node, stack: Node[], ctx: BoxContext) => {
logger.debug('prop-name', node.getKindName())
const boxed = maybeBoxNode(node, stack, ctx)
const strBox = onlyStringLiteral(boxed)
if (strBox) return strBox
const numberBox = onlyNumberLiteral(boxed)
if (numberBox) return numberBox
}
// <ColorBox color={isDark ? darkValue : "whiteAlpha.100"} />
const maybeResolveConditionalExpression = (
{
whenTrueExpr,
whenFalseExpr,
node,
stack,
canReturnWhenTrue,
}: {
whenTrueExpr: Node
whenFalseExpr: Node
node: Node
stack: Node[]
canReturnWhenTrue?: boolean
},
ctx: BoxContext,
) => {
// <ColorBox color={isDark ? { mobile: "blue.100", desktop: "blue.300" } : getColor()} />
const whenTrueValue = maybeBoxNode(whenTrueExpr, stack, ctx)
const whenFalseValue = maybeBoxNode(whenFalseExpr, stack, ctx)
logger.debug('cond', { before: true, whenTrueValue, whenFalseValue, canReturnWhenTrue })
//<ColorBox <ColorBox color={"blue.100" || "never.100"} />
//<ColorBox <ColorBox color={"blue.100" ?? "never.100"} />
if (canReturnWhenTrue && whenTrueValue && !box.isUnresolvable(whenTrueValue)) {
logger.debug('cond', { earlyReturn: true, whenTrueValue })
return whenTrueValue
}
logger.debug('cond', {
after: true,
// whenTrueLiteral: whenTrueExpr.getText(),
// whenFalseLiteral: whenFalseExpr.getText(),
whenTrueValue,
whenFalseValue,
})
// <ColorBox <ColorBox color={true && "never.100"} />
// whenTrueValue === true
// whenFalseValue === "never.100"
if (
Node.isBinaryExpression(node) &&
node.getOperatorToken().getKind() === ts.SyntaxKind.AmpersandAmpersandToken &&
whenTrueValue &&
whenFalseValue &&
box.isLiteral(whenTrueValue) &&
whenTrueValue.value === true
) {
return whenFalseValue
}
//<ColorBox <ColorBox color={true ? unextractable : unextractable} />
if (!whenTrueValue && !whenFalseValue) {
return
}
//<ColorBox <ColorBox color={true ? extractableNode : unextractable} />
if (whenTrueValue && !whenFalseValue) {
return whenTrueValue
}
//<ColorBox <ColorBox color={true ? unextractable : extractableNode} />
if (!whenTrueValue && whenFalseValue) {
return whenFalseValue
}
const whenTrue = whenTrueValue!
const whenFalse = whenFalseValue!
//<ColorBox <ColorBox color={true ? "blue.400" : "blue.400"} />
if (box.isLiteral(whenTrue) && box.isLiteral(whenFalse) && whenTrue.value === whenFalse.value) {
return whenTrue
}
//<ColorBox <ColorBox color={true ? extractableNode : extractableNode} />
return box.conditional(whenTrue, whenFalse, node, stack)
}
const findProperty = (node: ObjectLiteralElementLike, propName: string, _stack: Node[], ctx: BoxContext) => {
const stack = [..._stack]
logger.debug('find-prop', { propName, kind: node.getKindName() })
if (Node.isPropertyAssignment(node)) {
const name = node.getNameNode()
// logger.debug("find-prop", { name: name.getText(), kind: name.getKindName() });
if (Node.isIdentifier(name) && name.getText() === propName) {
stack.push(name)
return node
}
if (Node.isStringLiteral(name) && name.getLiteralText() === propName) {
stack.push(name)
return name.getLiteralText()
}
if (Node.isComputedPropertyName(name)) {
const expression = unwrapExpression(name.getExpression())
const computedPropNameBox = maybePropName(expression, stack, ctx)
if (!computedPropNameBox) return
if (String(computedPropNameBox.value) === propName) {
stack.push(name, expression)
return node
}
}
}
if (Node.isShorthandPropertyAssignment(node)) {
const name = node.getNameNode()
if (Node.isIdentifier(name) && name.getText() === propName) {
stack.push(name)
return node
}
}
}
const getObjectLiteralPropValue = (
initializer: ObjectLiteralExpression,
accessList: string[],
_stack: Node[],
ctx: BoxContext,
): MaybeBoxNodeReturn => {
const stack = [..._stack]
const propName = accessList.pop()!
const property =
initializer.getProperty(propName) ?? initializer.getProperties().find((p) => findProperty(p, propName, stack, ctx))
logger.debug('get-prop', {
propName,
accessList,
// shortcut: initializer.getProperty(propName),
// finder: initializer.getProperties().find((p) => findProperty(p, propName, stack, ctx)),
// property: property?.getText().slice(0, 100),
propertyKind: property?.getKindName(),
// properties: initializer.getProperties().map((p) => p.getText().slice(0, 100)),
// initializer: initializer.getText().slice(0, 100),
initializerKind: initializer.getKindName(),
})
if (!property) return
stack.push(property)
if (Node.isPropertyAssignment(property)) {
const propInit = property.getInitializer()
if (!propInit) return
logger.debug('get-prop', {
propAssignment: true,
// propInit: propInit.getText(),
propInitKind: propInit.getKindName(),
})
if (Node.isObjectLiteralExpression(propInit)) {
if (accessList.length > 0) {
return getObjectLiteralPropValue(propInit, accessList, stack, ctx)
}
return maybeBoxNode(propInit, stack, ctx)
}
const maybePropValue = maybeBoxNode(propInit, stack, ctx)
if (maybePropValue) {
return maybePropValue
}
}
if (Node.isShorthandPropertyAssignment(property)) {
const identifier = property.getNameNode()
logger.debug('get-prop', { shorthand: true, accessList, propInit: identifier.getText() })
if (accessList.length > 0) {
return maybePropIdentifierValue(identifier, accessList, stack, ctx)
}
const maybePropValue = maybeBoxNode(identifier, stack, ctx)
if (maybePropValue) {
return maybePropValue
}
}
}
const maybeTemplateStringValue = (template: TemplateExpression, stack: Node[], ctx: BoxContext) => {
const head = template.getHead()
const tail = template.getTemplateSpans()
const headValue = maybeStringLiteral(head, stack, ctx)
if (!headValue) return
const tailValues = tail.map((t) => {
const expression = t.getExpression()
const propBox = maybePropName(expression, stack, ctx)
// logger({ expression: expression.getText(), propBox });
if (!propBox) return
const literal = t.getLiteral()
return propBox.value + literal.getLiteralText()
})
// logger({ head: head.getText(), headValue, tailValues, tail: tail.map((t) => t.getText()) });
if (tailValues.every(isNotNullish)) {
return headValue.value + tailValues.join('')
}
}
const maybeBindingElementValue = (def: BindingElement, stack: Node[], propName: string, ctx: BoxContext) => {
const parent = def.getParent()
logger.debug('id-def', { parent: parent?.getKindName() })
if (!parent) return
const grandParent = parent.getParent()
logger.debug('id-def', { grandParent: grandParent?.getKindName() })
if (!grandParent) return
if (Node.isArrayBindingPattern(parent)) {
const index = parent.getChildIndex()
if (Number.isNaN(index)) return
if (Node.isVariableDeclaration(grandParent)) {
const init = grandParent.getInitializer()
logger.debug('id-def', { grandParentInit: init?.getKindName() })
if (!init) return
const initializer = unwrapExpression(init)
if (!Node.isArrayLiteralExpression(initializer)) return
const element = initializer.getElements()[index + 1]
logger.debug('id-def', { index, propName, elementKind: element?.getKindName() })
if (!element) return
const innerStack = [...stack, initializer, element]
const maybeObject = maybeBoxNode(element, innerStack, ctx)
if (!maybeObject) return
if (box.isObject(maybeObject)) {
const propValue = maybeObject.value[propName]
logger.debug('id-def', { propName, propValue })
return box.from(propValue, element, innerStack)
}
if (!box.isMap(maybeObject)) {
return maybeObject
}
const propValue = maybeObject.value.get(propName)
if (!propValue) return
logger.debug('id-def', { propName, propValue })
return propValue
}
}
// TODO
if (Node.isObjectBindingPattern(parent)) {
//
}
}
function maybePropDefinitionValue(def: Node, accessList: string[], _stack: Node[], ctx: BoxContext) {
const propName = accessList.at(-1)!
logger.debug('maybe-prop-def-value', { propName, accessList, kind: def.getKindName() })
if (Node.isVariableDeclaration(def)) {
const init = def.getInitializer()
logger.debug('maybe-prop-def-value', {
// init: init?.getText(),
kind: init?.getKindName(),
propName,
})
if (!init) {
const type = def.getTypeNode()
if (!type) return
if (Node.isTypeLiteral(type)) {
logger.debug('maybe-prop-def-value', { typeLiteral: true })
if (accessList.length > 0) {
const stack = [..._stack]
stack.push(type)
let propName = accessList.pop()!
let typeProp = type.getProperty(propName)
let typeLiteral = typeProp?.getTypeNode()
while (typeProp && accessList.length > 0 && typeLiteral && Node.isTypeLiteral(typeLiteral)) {
stack.push(typeProp, typeLiteral)
propName = accessList.pop()!
typeProp = typeLiteral.getProperty(propName)
typeLiteral = typeProp?.getTypeNode()
}
if (!typeLiteral) return
const typeValue = getTypeNodeValue(typeLiteral, stack, ctx)
logger.debug('maybe-prop-def-value', { propName, typeValue: Boolean(typeValue) })
return box.from(typeValue, typeLiteral, stack)
}
const propValue = getTypeLiteralNodePropValue(type, propName, _stack, ctx)
_stack.push(type)
return box.from(propValue, type, _stack)
}
return
}
const initializer = unwrapExpression(init)
logger.debug('maybe-prop-def-value', {
// initializer: initializer.getText(),
kind: initializer.getKindName(),
propName,
})
if (Node.isObjectLiteralExpression(initializer)) {
const propValue = getObjectLiteralPropValue(initializer, accessList, _stack, ctx)
if (!propValue) return
_stack.push(initializer)
return propValue
}
if (Node.isArrayLiteralExpression(initializer)) {
const index = Number(propName)
if (Number.isNaN(index)) return
const element = initializer.getElements()[index]
if (!element) return
_stack.push(initializer)
const boxed = maybeBoxNode(element, _stack, ctx)
if (boxed && isBoxNode(boxed) && box.isLiteral(boxed)) {
return boxed
}
}
const innerStack = [..._stack, initializer]
const maybeValue = maybeBoxNode(initializer, innerStack, ctx)
if (maybeValue) return maybeValue
}
if (Node.isBindingElement(def)) {
const value = maybeBindingElementValue(def, _stack, propName, ctx)
if (value) return value
}
}
const maybePropIdentifierValue = (
identifier: Identifier,
accessList: string[],
_stack: Node[],
ctx: BoxContext,
): BoxNode | undefined => {
const maybeValueDeclaration = findIdentifierValueDeclaration(identifier, _stack, ctx)
logger.debug('maybePropIdentifierValue', {
identifier: identifier.getText(),
hasValueDeclaration: Boolean(maybeValueDeclaration),
})
if (!maybeValueDeclaration) {
return box.unresolvable(identifier, _stack)
}
const declaration = unwrapExpression(maybeValueDeclaration)
logger.debug('maybePropIdentifierValue', { def: declaration.getKindName(), accessList })
const maybeValue = maybePropDefinitionValue(maybeValueDeclaration, accessList, _stack, ctx)
if (maybeValue) return maybeValue
return box.unresolvable(identifier, _stack)
}
// TODO pass & push in stack ?
const typeLiteralCache = new WeakMap<TypeLiteralNode, null | Map<string, LiteralValue>>()
const getTypeLiteralNodePropValue = (
type: TypeLiteralNode,
propName: string,
stack: Node[],
ctx: BoxContext,
): LiteralValue => {
if (typeLiteralCache.has(type)) {
const map = typeLiteralCache.get(type)
logger.debug('cached', { typeLiteralNodeProp: true, kind: type.getKindName() })
if (map === null) return
if (map?.has(propName)) {
return map.get(propName)
}
}
const members = type.getMembers()
const prop = members.find((member) => Node.isPropertySignature(member) && member.getName() === propName)
if (Node.isPropertySignature(prop) && prop.isReadonly()) {
const propType = prop.getTypeNode()
if (!propType) {
typeLiteralCache.set(type, null)
return
}
// logger.lazyScoped("type", () => ({
// propType: propType.getText().slice(0, 20),
// propTypeKind: propType.getKindName(),
// propName,
// }));
const propValue = getTypeNodeValue(propType, stack, ctx)
logger.debug('type', { propName, hasPropValue: isNotNullish(propValue) })
if (isNotNullish(propValue)) {
if (!typeLiteralCache.has(type)) {
typeLiteralCache.set(type, new Map())
}
const map = typeLiteralCache.get(type)!
map.set(propName, propValue)
return propValue
}
}
typeLiteralCache.set(type, null)
}
export function getNameLiteral(wrapper: Node) {
logger.debug('literal', { name: wrapper.getText(), kind: wrapper.getKindName() })
if (Node.isStringLiteral(wrapper)) return wrapper.getLiteralText()
return wrapper.getText()
}
const typeNodeCache = new WeakMap()
const getTypeNodeValue = (type: TypeNode, stack: Node[], ctx: BoxContext): LiteralValue => {
if (typeNodeCache.has(type)) {
logger.debug('cached', { typeNode: true, kind: type.getKindName() })
return typeNodeCache.get(type)
}
if (Node.isLiteralTypeNode(type)) {
const literal = type.getLiteral()
if (Node.isStringLiteral(literal)) {
const result = literal.getLiteralText()
logger.debug('type-value', { result })
typeNodeCache.set(type, result)
return result
}
}
if (Node.isTypeLiteral(type)) {
const members = type.getMembers()
if (!members.some((member) => !Node.isPropertySignature(member) || !member.isReadonly())) {
const props = members as PropertySignature[]
const entries = props
.map((member) => {
const nameNode = member.getNameNode()
const nameText = nameNode.getText()
const name = getNameLiteral(nameNode)
logger.debug('isTypeLiteral', { nameNodeKind: nameNode.getKindName(), name })
if (!name) return
const value = getTypeLiteralNodePropValue(type, nameText, stack, ctx)
return [name, value] as const
})
.filter(isNotNullish)
const result = Object.fromEntries(entries)
// logger.lazyScoped("type-value", () => ({ obj: Object.keys(obj) }));
typeNodeCache.set(type, result)
return result
}
}
typeNodeCache.set(type, undefined)
}
const maybeDefinitionValue = (def: Node, stack: Node[], ctx: BoxContext): BoxNode | undefined => {
logger.debug('maybe-def-value', { kind: def.getKindName() })
if (Node.isShorthandPropertyAssignment(def)) {
const propNameNode = def.getNameNode()
return maybePropIdentifierValue(propNameNode, [propNameNode.getText()], stack, ctx)
}
// const staticColor =
if (Node.isVariableDeclaration(def)) {
const init = def.getInitializer()
logger.debug('maybe-def-value', {
varDeclaration: true,
// initializer: init?.getText(),
kind: init?.getKindName(),
})
if (!init) {
const type = def.getTypeNode()
if (!type) return
logger.debug('maybe-def-value', { noInit: true, kind: type.getKindName() })
if (Node.isTypeLiteral(type)) {
stack.push(type)
const maybeTypeValue = getTypeNodeValue(type, stack, ctx)
if (isNotNullish(maybeTypeValue)) return box.from(maybeTypeValue, def, stack)
}
// skip evaluation if no initializer (only a type)
// since ts-evaluator will throw an error
return box.unresolvable(def, stack)
}
const initializer = unwrapExpression(init)
const innerStack = [...stack, initializer]
const maybeValue = maybeBoxNode(initializer, innerStack, ctx)
if (maybeValue) return maybeValue
}
if (Node.isBindingElement(def)) {
const init = def.getInitializer()
if (!init) {
const nameNode = def.getPropertyNameNode() ?? def.getNameNode()
const propName = nameNode.getText()
const innerStack = [...stack, nameNode]
logger.debug('maybe-def-value', { bindingElement: true, propName })
const value = maybeBindingElementValue(def, innerStack, propName, ctx)
if (value) return value
// skip evaluation if no initializer (only a type)
// since ts-evaluator will throw an error
return box.unresolvable(def, stack)
}
// { position = "absolute", ...props }
const initializer = unwrapExpression(init)
const innerStack = [...stack, initializer]
const maybeValue = maybeBoxNode(initializer, innerStack, ctx)
if (maybeValue) return maybeValue
}
}
export const getExportedVarDeclarationWithName = (
varName: string,
sourceFile: SourceFile,
stack: Node[],
ctx: BoxContext,
): VariableDeclaration | undefined => {
const maybeVar = sourceFile.getVariableDeclaration(varName)
logger.debug('getExportedVarDeclarationWithName', { varName, path: sourceFile.getFilePath(), hasVar: !!maybeVar })
if (maybeVar) return maybeVar
const exportDeclaration = resolveVarDeclarationFromExportWithName(varName, sourceFile, stack, ctx)
logger.debug('getExportedVarDeclarationWithName', { exportDeclaration: Boolean(exportDeclaration) })
if (!exportDeclaration) return
return exportDeclaration
}
const hasNamedExportWithName = (name: string, exportDeclaration: ExportDeclaration) => {
const namedExports = exportDeclaration.getNamedExports()
// no namedExports means it's a full re-export like this: `export * from "xxx"`
if (namedExports.length === 0) return true
for (const namedExport of namedExports) {
const exportedName = namedExport.getNameNode().getText()
logger.debug('export-declaration', { searching: name, exportedName })
if (exportedName === name) {
return true
}
}
}
/**
* Faster than declaration.getModuleSpecifierSourceFile()
*
* since it does NOT require a call to `initializeTypeChecker`
* > getModuleSpecifierSourceFile > getSymbol > getTypechecker > createTypeChecker > initializeTypeChecker
*
* which costs a minimum of around 90ms (and scales up with the file/project, could be hundreds of ms)
* @see https://github.com/dsherret/ts-morph/blob/42d811ed9a5177fc678a5bfec4923a2048124fe0/packages/ts-morph/src/compiler/ast/module/ExportDeclaration.ts#L160
*/
export const getModuleSpecifierSourceFile = (declaration: ExportDeclaration | ImportDeclaration) => {
const project = declaration.getProject()
const moduleName = declaration.getModuleSpecifierValue()
logger.debug('getModuleSpecifierSourceFile', { moduleName })
if (!moduleName) return
const containingFile = declaration.getSourceFile().getFilePath()
const resolved = ts.resolveModuleName(
moduleName,
containingFile,
project.getCompilerOptions(),
project.getModuleResolutionHost(),
)
logger.debug('getModuleSpecifierSourceFile', resolved)
if (!resolved.resolvedModule) return
const sourceFile = project.addSourceFileAtPath(resolved.resolvedModule.resolvedFileName)
logger.debug('getModuleSpecifierSourceFile', { found: Boolean(sourceFile) })
return sourceFile
}
function resolveVarDeclarationFromExportWithName(
symbolName: string,
sourceFile: SourceFile,
stack: Node[],
ctx: BoxContext,
): VariableDeclaration | undefined {
for (const exportDeclaration of sourceFile.getExportDeclarations()) {
const exportStack = [exportDeclaration] as Node[]
logger.debug('resolveVarDeclarationFromExportWithName', {
symbolName,
// exporDeclaration: exportDeclaration.getText(),
exporDeclarationKind: exportDeclaration.getKindName(),
})
if (!hasNamedExportWithName(symbolName, exportDeclaration)) continue
const maybeFile = getModuleSpecifierSourceFile(exportDeclaration)
if (!maybeFile) continue
exportStack.push(maybeFile)
const maybeVar = getExportedVarDeclarationWithName(symbolName, maybeFile, stack, ctx)
if (maybeVar) {
stack.push(...exportStack.concat(maybeVar))
return maybeVar
}
}
}
export const maybeIdentifierValue = (identifier: Identifier, _stack: Node[], ctx: BoxContext) => {
const valueDeclaration = findIdentifierValueDeclaration(identifier, _stack, ctx)
logger.debug('id-ref', { identifier: identifier.getText(), hasValueDeclaration: Boolean(valueDeclaration) })
if (!valueDeclaration) {
return box.unresolvable(identifier, _stack)
}
const declaration = unwrapExpression(valueDeclaration)
logger.debug('id-ref', { def: declaration.getKindName() })
const stack = [..._stack]
const maybeValue = maybeDefinitionValue(declaration, stack, ctx)
if (maybeValue) return maybeValue
return box.unresolvable(identifier, stack)
}
const tryComputingPlusTokenBinaryExpressionToString = (node: BinaryExpression, stack: Node[], ctx: BoxContext) => {
const left = unwrapExpression(node.getLeft())
const right = unwrapExpression(node.getRight())
const leftValue = maybePropName(left, stack, ctx)
const rightValue = maybePropName(right, stack, ctx)
if (!leftValue || !rightValue) return
logger.debug('tryComputingPlusTokenBinaryExpressionToString', {
leftValue,
rightValue,
})
if (isNotNullish(leftValue.value) && isNotNullish(rightValue.value)) {
return box.literal(String(leftValue.value) + String(rightValue.value), node, stack)
}
}
const getElementAccessedExpressionValue = (
expression: ElementAccessExpression,
_stack: Node[],
ctx: BoxContext,
): MaybeBoxNodeReturn => {
const elementAccessed = unwrapExpression(expression.getExpression())
const argExpr = expression.getArgumentExpression()
if (!argExpr) return
const arg = unwrapExpression(argExpr)
const stack = [..._stack, elementAccessed, arg]
const argLiteral = maybePropName(arg, stack, ctx)
// <ColorBox color={xxx["yyy"]} />
if (Node.isIdentifier(elementAccessed) && argLiteral) {
if (!isNotNullish(argLiteral.value)) return
return maybePropIdentifierValue(elementAccessed, [argLiteral.value.toString()], stack, ctx)
}
// <ColorBox color={xxx[yyy + "zzz"]} />
if (Node.isBinaryExpression(arg)) {
if (arg.getOperatorToken().getKind() !== ts.SyntaxKind.PlusToken) return
const propName = tryComputingPlusTokenBinaryExpressionToString(arg, stack, ctx) ?? maybePropName(arg, stack, ctx)
if (propName && Node.isIdentifier(elementAccessed)) {
if (!isNotNullish(propName.value)) return
return maybePropIdentifierValue(elementAccessed, [propName.value.toString()], stack, ctx)
}
}
// <ColorBox color={xxx[`yyy`]} />
if (Node.isTemplateExpression(arg)) {
const propName = maybeTemplateStringValue(arg, stack, ctx)
if (propName && Node.isIdentifier(elementAccessed)) {
return maybePropIdentifierValue(elementAccessed, [propName], stack, ctx)
}
}
// <ColorBox color={{ staticColor: "facebook.900" }["staticColor"]}></ColorBox>
if (Node.isObjectLiteralExpression(elementAccessed) && argLiteral) {
if (!isNotNullish(argLiteral.value)) return
return getObjectLiteralPropValue(elementAccessed, [argLiteral.value.toString()], stack, ctx)
}
// <ColorBox color={xxx[yyy.zzz]} />
if (Node.isPropertyAccessExpression(arg)) {
return getPropertyAccessedExpressionValue(arg, [], stack, ctx)
}
// tokens.colors.blue["400"]
if (Node.isPropertyAccessExpression(elementAccessed) && argLiteral && isNotNullish(argLiteral.value)) {
const propRefValue = getPropertyAccessedExpressionValue(elementAccessed, [], stack, ctx)
if (!propRefValue) return box.unresolvable(elementAccessed, stack)
const propName = argLiteral.value.toString()