@tamagui/static 1.0.1-beta.57 → 1.0.1-beta.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/cjs/extractor/createExtractor.js +18 -1
  2. package/dist/cjs/extractor/createExtractor.js.map +2 -2
  3. package/dist/cjs/extractor/extractToClassNames.js +1 -1
  4. package/dist/cjs/extractor/extractToClassNames.js.map +2 -2
  5. package/dist/cjs/patchReactNativeWeb.js +1 -1
  6. package/dist/cjs/patchReactNativeWeb.js.map +2 -2
  7. package/dist/esm/extractor/createExtractor.js +18 -1
  8. package/dist/esm/extractor/createExtractor.js.map +2 -2
  9. package/dist/esm/extractor/extractToClassNames.js +1 -1
  10. package/dist/esm/extractor/extractToClassNames.js.map +2 -2
  11. package/dist/esm/patchReactNativeWeb.js +1 -1
  12. package/dist/esm/patchReactNativeWeb.js.map +2 -2
  13. package/dist/jsx/extractor/createExtractor.js +18 -1
  14. package/dist/jsx/extractor/extractToClassNames.js +1 -1
  15. package/dist/jsx/patchReactNativeWeb.js +1 -1
  16. package/package.json +9 -7
  17. package/src/constants.ts +13 -0
  18. package/src/extractor/accessSafe.ts +18 -0
  19. package/src/extractor/babelParse.ts +27 -0
  20. package/src/extractor/buildClassName.ts +61 -0
  21. package/src/extractor/createEvaluator.ts +69 -0
  22. package/src/extractor/createExtractor.ts +1696 -0
  23. package/src/extractor/ensureImportingConcat.ts +39 -0
  24. package/src/extractor/evaluateAstNode.ts +121 -0
  25. package/src/extractor/extractHelpers.ts +119 -0
  26. package/src/extractor/extractMediaStyle.ts +190 -0
  27. package/src/extractor/extractToClassNames.ts +426 -0
  28. package/src/extractor/findTopmostFunction.ts +22 -0
  29. package/src/extractor/generatedUid.ts +43 -0
  30. package/src/extractor/getPrefixLogs.ts +6 -0
  31. package/src/extractor/getPropValueFromAttributes.ts +92 -0
  32. package/src/extractor/getSourceModule.ts +101 -0
  33. package/src/extractor/getStaticBindingsForScope.ts +183 -0
  34. package/src/extractor/hoistClassNames.ts +45 -0
  35. package/src/extractor/literalToAst.ts +84 -0
  36. package/src/extractor/loadTamagui.ts +139 -0
  37. package/src/extractor/logLines.ts +16 -0
  38. package/src/extractor/normalizeTernaries.ts +63 -0
  39. package/src/extractor/removeUnusedHooks.ts +76 -0
  40. package/src/extractor/timer.ts +18 -0
  41. package/src/extractor/validHTMLAttributes.ts +99 -0
  42. package/src/index.ts +9 -0
  43. package/src/patchReactNativeWeb.ts +165 -0
  44. package/src/types.ts +97 -0
  45. package/types/extractor/createExtractor.d.ts +14 -1
  46. package/types/extractor/createExtractor.d.ts.map +1 -1
@@ -0,0 +1,426 @@
1
+ import * as path from 'path'
2
+ import { basename } from 'path'
3
+ import * as util from 'util'
4
+
5
+ import generate from '@babel/generator'
6
+ import * as t from '@babel/types'
7
+ import { getStylesAtomic } from '@tamagui/core-node'
8
+ import { concatClassName } from '@tamagui/helpers'
9
+ import invariant from 'invariant'
10
+ import { ViewStyle } from 'react-native'
11
+ import { LoaderContext } from 'webpack'
12
+
13
+ import { CONCAT_CLASSNAME_IMPORT } from '../constants'
14
+ import { ClassNameObject, StyleObject, TamaguiOptions, Ternary } from '../types'
15
+ import { babelParse } from './babelParse'
16
+ import { buildClassName } from './buildClassName'
17
+ import { Extractor } from './createExtractor'
18
+ import { ensureImportingConcat } from './ensureImportingConcat'
19
+ import { isSimpleSpread } from './extractHelpers'
20
+ import { extractMediaStyle } from './extractMediaStyle'
21
+ import { getPrefixLogs } from './getPrefixLogs'
22
+ import { hoistClassNames } from './hoistClassNames'
23
+ import { literalToAst } from './literalToAst'
24
+ import { logLines } from './logLines'
25
+ import { timer } from './timer'
26
+
27
+ const mergeStyleGroups = {
28
+ shadowOpacity: true,
29
+ shadowRadius: true,
30
+ shadowColor: true,
31
+ shadowOffset: true,
32
+ }
33
+
34
+ export type ExtractedResponse = {
35
+ js: string | Buffer
36
+ styles: string
37
+ stylesPath?: string
38
+ ast: t.File
39
+ map: any // RawSourceMap from 'source-map'
40
+ }
41
+
42
+ export function extractToClassNames({
43
+ loader,
44
+ extractor,
45
+ source,
46
+ sourcePath,
47
+ options,
48
+ shouldPrintDebug,
49
+ cssLoaderPath,
50
+ threaded,
51
+ cssPath,
52
+ }: {
53
+ loader: LoaderContext<any>
54
+ cssLoaderPath: string
55
+ extractor: Extractor
56
+ source: string | Buffer
57
+ sourcePath: string
58
+ options: TamaguiOptions
59
+ shouldPrintDebug: boolean | 'verbose'
60
+ cssPath: string
61
+ threaded?: boolean
62
+ }): ExtractedResponse | null {
63
+ const tm = timer()
64
+
65
+ if (typeof source !== 'string') {
66
+ throw new Error('`source` must be a string of javascript')
67
+ }
68
+ invariant(
69
+ typeof sourcePath === 'string' && path.isAbsolute(sourcePath),
70
+ '`sourcePath` must be an absolute path to a .js file'
71
+ )
72
+
73
+ const shouldLogTiming = options.logTimings ?? true
74
+ const start = Date.now()
75
+ const mem = shouldLogTiming ? process.memoryUsage() : null
76
+
77
+ // Using a map for (officially supported) guaranteed insertion order
78
+ let ast: t.File
79
+
80
+ try {
81
+ // @ts-ignore
82
+ ast = babelParse(source)
83
+ } catch (err) {
84
+ console.error('babel parse error:', sourcePath)
85
+ throw err
86
+ }
87
+
88
+ tm.mark(`babel-parse`, shouldPrintDebug === 'verbose')
89
+
90
+ const cssMap = new Map<string, { css: string; commentTexts: string[] }>()
91
+ const existingHoists: { [key: string]: t.Identifier } = {}
92
+
93
+ let hasFlattened = false
94
+
95
+ const res = extractor.parse(ast, {
96
+ sourcePath,
97
+ shouldPrintDebug,
98
+ ...options,
99
+ target: 'html',
100
+ getFlattenedNode: ({ tag }) => {
101
+ hasFlattened = true
102
+ return tag
103
+ },
104
+ onExtractTag: ({
105
+ attrs,
106
+ node,
107
+ attemptEval,
108
+ jsxPath,
109
+ originalNodeName,
110
+ filePath,
111
+ lineNumbers,
112
+ programPath,
113
+ isFlattened,
114
+ }) => {
115
+ let finalClassNames: ClassNameObject[] = []
116
+ let finalAttrs: (t.JSXAttribute | t.JSXSpreadAttribute)[] = []
117
+ let finalStyles: StyleObject[] = []
118
+
119
+ let viewStyles = {}
120
+ for (const attr of attrs) {
121
+ if (attr.type === 'style') {
122
+ viewStyles = {
123
+ ...viewStyles,
124
+ ...attr.value,
125
+ }
126
+ }
127
+ }
128
+
129
+ const ensureNeededPrevStyle = (style: ViewStyle) => {
130
+ // ensure all group keys are merged
131
+ const keys = Object.keys(style)
132
+ if (!keys.some((key) => mergeStyleGroups[key])) {
133
+ return style
134
+ }
135
+ for (const k in mergeStyleGroups) {
136
+ if (k in viewStyles) {
137
+ style[k] = style[k] ?? viewStyles[k]
138
+ }
139
+ }
140
+ return style
141
+ }
142
+
143
+ const addStyles = (style: ViewStyle | null): StyleObject[] => {
144
+ if (!style) return []
145
+ const styleWithPrev = ensureNeededPrevStyle(style)
146
+ const res = getStylesAtomic(styleWithPrev)
147
+ if (res.length) {
148
+ finalStyles = [...finalStyles, ...res]
149
+ }
150
+ return res
151
+ }
152
+
153
+ // 1 to start above any :hover styles
154
+ let lastMediaImportance = 1
155
+ for (const attr of attrs) {
156
+ switch (attr.type) {
157
+ case 'style':
158
+ if (!isFlattened) {
159
+ // only ever one at a time i believe so we can be lazy with this access
160
+ const { hoverStyle, pressStyle, focusStyle } = attr.value
161
+ const pseudos = [
162
+ ['hoverStyle', hoverStyle],
163
+ ['pressStyle', pressStyle],
164
+ ['focusStyle', focusStyle],
165
+ ] as const
166
+
167
+ const styles = getStylesAtomic(attr.value, {
168
+ splitTransforms: true,
169
+ })
170
+ finalStyles = [...finalStyles, ...styles]
171
+
172
+ for (const [key, value] of pseudos) {
173
+ if (value && Object.keys(value).length) {
174
+ finalAttrs.push(
175
+ t.jsxAttribute(
176
+ t.jsxIdentifier(key),
177
+ t.jsxExpressionContainer(literalToAst(value))
178
+ )
179
+ )
180
+ }
181
+ }
182
+
183
+ for (const style of styles) {
184
+ if (style.pseudo) {
185
+ continue
186
+ }
187
+ // leave them as attributes
188
+ finalAttrs.push(
189
+ t.jsxAttribute(t.jsxIdentifier(style.property), t.stringLiteral(style.identifier))
190
+ )
191
+ }
192
+ } else {
193
+ const styles = addStyles(attr.value)
194
+ const newClassNames = concatClassName(styles.map((x) => x.identifier).join(' '))
195
+ const existing = finalClassNames.find(
196
+ (x) => x.type == 'StringLiteral'
197
+ ) as t.StringLiteral | null
198
+
199
+ if (existing) {
200
+ existing.value = `${existing.value} ${newClassNames}`
201
+ } else {
202
+ finalClassNames = [...finalClassNames, t.stringLiteral(newClassNames)]
203
+ }
204
+ }
205
+
206
+ break
207
+ case 'attr':
208
+ const val = attr.value
209
+ if (t.isJSXSpreadAttribute(val)) {
210
+ if (isSimpleSpread(val)) {
211
+ finalClassNames.push(
212
+ t.logicalExpression(
213
+ '&&',
214
+ val.argument,
215
+ t.memberExpression(val.argument, t.identifier('className'))
216
+ )
217
+ )
218
+ }
219
+ } else if (val.name.name === 'className') {
220
+ const value = val.value
221
+ if (value) {
222
+ try {
223
+ const evaluatedValue = attemptEval(value)
224
+ finalClassNames.push(t.stringLiteral(evaluatedValue))
225
+ } catch (e) {
226
+ finalClassNames.push(value['expression'])
227
+ }
228
+ }
229
+ continue
230
+ }
231
+ finalAttrs.push(val)
232
+ break
233
+ case 'ternary':
234
+ const mediaExtraction = extractMediaStyle(
235
+ attr.value,
236
+ jsxPath,
237
+ extractor.getTamagui(),
238
+ sourcePath,
239
+ lastMediaImportance,
240
+ shouldPrintDebug
241
+ )
242
+ if (shouldPrintDebug) {
243
+ if (mediaExtraction) {
244
+ // prettier-ignore
245
+ console.log('ternary (mediaStyles)', mediaExtraction.ternaryWithoutMedia?.inlineMediaQuery ?? '', mediaExtraction.mediaStyles.map((x) => x.identifier).join('.'))
246
+ }
247
+ }
248
+ if (!mediaExtraction) {
249
+ addTernaryStyle(
250
+ attr.value,
251
+ addStyles(attr.value.consequent),
252
+ addStyles(attr.value.alternate)
253
+ )
254
+ continue
255
+ }
256
+ lastMediaImportance++
257
+ if (mediaExtraction.mediaStyles) {
258
+ finalStyles = [...finalStyles, ...mediaExtraction.mediaStyles]
259
+ }
260
+ if (mediaExtraction.ternaryWithoutMedia) {
261
+ addTernaryStyle(mediaExtraction.ternaryWithoutMedia, mediaExtraction.mediaStyles, [])
262
+ } else {
263
+ finalClassNames = [
264
+ ...finalClassNames,
265
+ ...mediaExtraction.mediaStyles.map((x) => t.stringLiteral(x.identifier)),
266
+ ]
267
+ }
268
+ break
269
+ }
270
+ }
271
+
272
+ function addTernaryStyle(ternary: Ternary, a: any, b: any) {
273
+ const cCN = a.map((x) => x.identifier).join(' ')
274
+ const aCN = b.map((x) => x.identifier).join(' ')
275
+ if (a.length && b.length) {
276
+ finalClassNames.push(
277
+ t.conditionalExpression(ternary.test, t.stringLiteral(cCN), t.stringLiteral(aCN))
278
+ )
279
+ } else {
280
+ finalClassNames.push(
281
+ t.conditionalExpression(
282
+ ternary.test,
283
+ t.stringLiteral(' ' + cCN),
284
+ t.stringLiteral(' ' + aCN)
285
+ )
286
+ )
287
+ }
288
+ }
289
+
290
+ if (shouldPrintDebug) {
291
+ // prettier-ignore
292
+ console.log(' finalClassNames\n', logLines(finalClassNames.map(x => x['value']).join(' ')))
293
+ }
294
+
295
+ node.attributes = finalAttrs
296
+
297
+ if (finalClassNames.length) {
298
+ // inserts the _cn variable and uses it for className
299
+ let names = buildClassName(finalClassNames)
300
+ if (t.isStringLiteral(names)) {
301
+ names.value = concatClassName(names.value)
302
+ }
303
+ const nameExpr = names ? hoistClassNames(jsxPath, existingHoists, names) : null
304
+ let expr = nameExpr
305
+
306
+ // if has some spreads, use concat helper
307
+ if (nameExpr && !t.isIdentifier(nameExpr)) {
308
+ if (!hasFlattened) {
309
+ // not flat
310
+ } else {
311
+ ensureImportingConcat(programPath)
312
+ const simpleSpreads = attrs.filter(
313
+ (x) => t.isJSXSpreadAttribute(x.value) && isSimpleSpread(x.value)
314
+ )
315
+ expr = t.callExpression(t.identifier(CONCAT_CLASSNAME_IMPORT), [
316
+ expr,
317
+ ...simpleSpreads.map((val) => val.value['argument']),
318
+ ])
319
+ }
320
+ }
321
+
322
+ node.attributes.push(
323
+ t.jsxAttribute(t.jsxIdentifier('className'), t.jsxExpressionContainer(expr))
324
+ )
325
+ }
326
+
327
+ const comment = util.format('/* %s:%s (%s) */', filePath, lineNumbers, originalNodeName)
328
+
329
+ for (const { className, rules } of finalStyles) {
330
+ if (cssMap.has(className)) {
331
+ if (comment) {
332
+ const val = cssMap.get(className)!
333
+ val.commentTexts.push(comment)
334
+ cssMap.set(className, val)
335
+ }
336
+ } else if (rules.length) {
337
+ if (rules.length > 1) {
338
+ console.log(' rules error', { rules })
339
+ throw new Error(`Shouldn't have more than one rule`)
340
+ }
341
+ cssMap.set(className, {
342
+ css: rules[0],
343
+ commentTexts: [comment],
344
+ })
345
+ }
346
+ }
347
+ },
348
+ })
349
+
350
+ if (!res || (!res.modified && !res.optimized && !res.flattened)) {
351
+ if (shouldPrintDebug) {
352
+ console.log('no res or none modified', res)
353
+ }
354
+ return null
355
+ }
356
+
357
+ const styles = Array.from(cssMap.values())
358
+ .map((x) => x.css)
359
+ .join('\n')
360
+ .trim()
361
+
362
+ if (styles) {
363
+ const cssQuery = threaded
364
+ ? `cssData=${Buffer.from(styles).toString('base64')}`
365
+ : `cssPath=${cssPath}`
366
+ const remReq = loader.remainingRequest
367
+ const importPath = `${cssPath}!=!${cssLoaderPath}?${cssQuery}!${remReq}`
368
+ ast.program.body.unshift(t.importDeclaration([], t.stringLiteral(importPath)))
369
+ }
370
+
371
+ const result = generate(
372
+ ast,
373
+ {
374
+ concise: false,
375
+ filename: sourcePath,
376
+ // this makes the debug output terrible, and i think sourcemap works already
377
+ retainLines: false,
378
+ sourceFileName: sourcePath,
379
+ sourceMaps: true,
380
+ },
381
+ source
382
+ )
383
+
384
+ if (shouldPrintDebug) {
385
+ console.log(
386
+ '\n -------- output code ------- \n\n',
387
+ result.code
388
+ .split('\n')
389
+ .filter((x) => !x.startsWith('//'))
390
+ .join('\n')
391
+ )
392
+ console.log('\n -------- output style -------- \n\n', styles)
393
+ }
394
+
395
+ if (shouldLogTiming) {
396
+ const memUsed = mem
397
+ ? Math.round(((process.memoryUsage().heapUsed - mem.heapUsed) / 1024 / 1204) * 10) / 10
398
+ : 0
399
+ const path = basename(sourcePath)
400
+ .replace(/\.[jt]sx?$/, '')
401
+ .slice(0, 22)
402
+ .trim()
403
+ .padStart(24)
404
+ const numOptimized = `${res.optimized}`.padStart(3)
405
+ const numFound = `${res.found}`.padStart(3)
406
+ const numFlattened = `${res.flattened}`.padStart(3)
407
+ const memory = process.env.DEBUG && memUsed > 10 ? ` ${memUsed}MB` : ''
408
+ const timing = Date.now() - start
409
+ const timingWarning = timing > 50 ? '⚠️' : timing > 150 ? '☢️' : ''
410
+ const timingStr = `${timing}ms${timingWarning}`.padStart(6)
411
+ console.log(
412
+ `${getPrefixLogs(
413
+ options
414
+ )} ${path} ${numFound} · ${numOptimized} · ${numFlattened} ${timingStr} ${
415
+ memory ? `(${memory})` : ''
416
+ }`
417
+ )
418
+ }
419
+
420
+ return {
421
+ ast,
422
+ styles,
423
+ js: result.code,
424
+ map: result.map,
425
+ }
426
+ }
@@ -0,0 +1,22 @@
1
+ import { NodePath } from '@babel/traverse'
2
+ import * as t from '@babel/types'
3
+
4
+ export function findTopmostFunction(jsxPath: NodePath<t.JSXElement>) {
5
+ // get topmost fn
6
+ const isFunction = (path: NodePath<any>) =>
7
+ path.isArrowFunctionExpression() || path.isFunctionDeclaration() || path.isFunctionExpression()
8
+ let compFn: NodePath<any> | null = jsxPath.findParent(isFunction)
9
+ while (compFn) {
10
+ const parent = compFn.findParent(isFunction)
11
+ if (parent) {
12
+ compFn = parent
13
+ } else {
14
+ break
15
+ }
16
+ }
17
+ if (!compFn) {
18
+ // console.error(`Couldn't find a topmost function for media query extraction`)
19
+ return null
20
+ }
21
+ return compFn
22
+ }
@@ -0,0 +1,43 @@
1
+ import * as t from '@babel/types'
2
+ import invariant from 'invariant'
3
+
4
+ // TODO: open a PR upstream
5
+ declare module '@babel/types' {
6
+ export function toIdentifier(input: string): string
7
+ }
8
+
9
+ // A clone of path.scope.generateUid that doesn't prepend underscores
10
+ export function generateUid(scope: any, name: string): string {
11
+ invariant(typeof scope === 'object', 'generateUid expects a scope object as its first parameter')
12
+ invariant(
13
+ typeof name === 'string' && name !== '',
14
+ 'generateUid expects a valid name as its second parameter'
15
+ )
16
+
17
+ name = t
18
+ .toIdentifier(name)
19
+ .replace(/^_+/, '')
20
+ .replace(/[0-9]+$/g, '')
21
+
22
+ let uid
23
+ let i = 0
24
+ do {
25
+ if (i > 1) {
26
+ uid = name + i
27
+ } else {
28
+ uid = name
29
+ }
30
+ i++
31
+ } while (
32
+ scope.hasLabel(uid) ||
33
+ scope.hasBinding(uid) ||
34
+ scope.hasGlobal(uid) ||
35
+ scope.hasReference(uid)
36
+ )
37
+
38
+ const program = scope.getProgramParent()
39
+ program.references[uid] = true
40
+ program.uids[uid] = true
41
+
42
+ return uid
43
+ }
@@ -0,0 +1,6 @@
1
+ import { TamaguiOptions } from '../types'
2
+
3
+ export function getPrefixLogs(options?: TamaguiOptions) {
4
+ const { TAMAGUI_TARGET } = process.env
5
+ return options?.prefixLogs ?? ` ${TAMAGUI_TARGET} | `
6
+ }
@@ -0,0 +1,92 @@
1
+ import generate from '@babel/generator'
2
+ import * as t from '@babel/types'
3
+
4
+ import { accessSafe } from './accessSafe'
5
+
6
+ /**
7
+ * getPropValueFromAttributes gets a prop by name from a list of attributes and accounts for potential spread operators.
8
+ * Here's an example. Given this component:
9
+ * ```
10
+ * <Block coolProp="wow" {...spread1} neatProp="ok" {...spread2} />```
11
+ * getPropValueFromAttributes will return the following:
12
+ * - for propName `coolProp`:
13
+ * ```
14
+ * accessSafe(spread1, 'coolProp') || accessSafe(spread2, 'coolProp') || 'wow'```
15
+ * - for propName `neatProp`:
16
+ * ```
17
+ * accessSafe(spread2, 'neatProp') || 'ok'```
18
+ * - for propName `notPresent`: `null`
19
+ *
20
+ * The returned value should (obviously) be placed after spread operators.
21
+ */
22
+ export function getPropValueFromAttributes(
23
+ propName: string,
24
+ attrs: (t.JSXAttribute | t.JSXSpreadAttribute)[]
25
+ ): t.Expression | null {
26
+ let propIndex: number = -1
27
+ let jsxAttr: t.JSXAttribute | null = null
28
+ for (let idx = -1, len = attrs.length; ++idx < len; ) {
29
+ const attr = attrs[idx]
30
+ if (t.isJSXAttribute(attr) && attr.name && attr.name.name === propName) {
31
+ propIndex = idx
32
+ jsxAttr = attr
33
+ break
34
+ }
35
+ }
36
+
37
+ if (!jsxAttr || jsxAttr.value == null) {
38
+ return null
39
+ }
40
+
41
+ let propValue:
42
+ | t.JSXElement
43
+ | t.JSXFragment
44
+ | t.StringLiteral
45
+ | t.JSXExpressionContainer
46
+ | t.JSXEmptyExpression
47
+ | t.Expression = jsxAttr.value
48
+
49
+ if (t.isJSXExpressionContainer(propValue)) {
50
+ propValue = propValue.expression
51
+ }
52
+
53
+ // TODO how to handle this??
54
+ if (t.isJSXEmptyExpression(propValue)) {
55
+ console.error('encountered JSXEmptyExpression')
56
+ return null
57
+ }
58
+
59
+ // filter out spread props that occur before propValue
60
+ const applicableSpreads = attrs
61
+ .filter(
62
+ // 1. idx is greater than propValue prop index
63
+ // 2. attr is a spread operator
64
+ (attr, idx): attr is t.JSXSpreadAttribute => {
65
+ if (t.isJSXSpreadAttribute(attr)) {
66
+ if (t.isIdentifier(attr.argument) || t.isMemberExpression(attr.argument)) {
67
+ return idx > propIndex
68
+ }
69
+ if (t.isLogicalExpression(attr.argument)) {
70
+ return false
71
+ }
72
+ throw new Error(
73
+ `unsupported spread of type "${attr.argument.type}": ${generate(attr).code}`
74
+ )
75
+ }
76
+ return false
77
+ }
78
+ )
79
+ .map((attr) => attr.argument)
80
+
81
+ // if spread operators occur after propValue, create a binary expression for each operator
82
+ // i.e. before1.propValue || before2.propValue || propValue
83
+ // TODO: figure out how to do this without all the extra parens
84
+ if (applicableSpreads.length > 0) {
85
+ propValue = applicableSpreads.reduce<t.Expression>(
86
+ (acc, val) => t.logicalExpression('||', accessSafe(val, propName), acc),
87
+ propValue
88
+ )
89
+ }
90
+
91
+ return propValue
92
+ }
@@ -0,0 +1,101 @@
1
+ import * as t from '@babel/types'
2
+
3
+ export interface SourceModule {
4
+ sourceModule?: string
5
+ imported?: string
6
+ local?: string
7
+ destructured?: boolean
8
+ usesImportSyntax: boolean
9
+ }
10
+
11
+ export function getSourceModule(
12
+ itemName: string,
13
+ itemBinding: {
14
+ constant?: boolean
15
+ path: { node: t.Node; parent: any }
16
+ }
17
+ ): SourceModule | null {
18
+ // TODO: deal with reassignment
19
+ if (!itemBinding.constant) {
20
+ return null
21
+ }
22
+
23
+ let sourceModule: string | undefined
24
+ let imported: string | undefined
25
+ let local: string | undefined
26
+ let destructured: boolean | undefined
27
+ let usesImportSyntax = false
28
+
29
+ const itemNode = itemBinding.path.node
30
+
31
+ if (
32
+ // import x from 'y';
33
+ t.isImportDefaultSpecifier(itemNode) ||
34
+ // import {x} from 'y';
35
+ t.isImportSpecifier(itemNode)
36
+ ) {
37
+ if (t.isImportDeclaration(itemBinding.path.parent)) {
38
+ sourceModule = itemBinding.path.parent.source.value
39
+ local = itemNode.local.name
40
+ usesImportSyntax = true
41
+ if (t.isImportSpecifier(itemNode)) {
42
+ imported = itemNode.imported['name']
43
+ destructured = true
44
+ } else {
45
+ imported = itemNode.local.name
46
+ destructured = false
47
+ }
48
+ }
49
+ } else if (
50
+ t.isVariableDeclarator(itemNode) &&
51
+ itemNode.init != null &&
52
+ t.isCallExpression(itemNode.init) &&
53
+ t.isIdentifier(itemNode.init.callee) &&
54
+ itemNode.init.callee.name === 'require' &&
55
+ itemNode.init.arguments.length === 1
56
+ ) {
57
+ const firstArg = itemNode.init.arguments[0]
58
+ if (!t.isStringLiteral(firstArg)) {
59
+ return null
60
+ }
61
+ sourceModule = firstArg.value
62
+
63
+ if (t.isIdentifier(itemNode.id)) {
64
+ local = itemNode.id.name
65
+ imported = itemNode.id.name
66
+ destructured = false
67
+ } else if (t.isObjectPattern(itemNode.id)) {
68
+ for (const objProp of itemNode.id.properties) {
69
+ if (
70
+ t.isObjectProperty(objProp) &&
71
+ t.isIdentifier(objProp.value) &&
72
+ objProp.value.name === itemName
73
+ ) {
74
+ local = objProp.value.name
75
+ // @ts-ignore TODO remove this is only an issue on CI
76
+ imported = objProp.key.name
77
+ destructured = true
78
+ break
79
+ }
80
+ }
81
+
82
+ if (!local || !imported) {
83
+ console.error('could not find prop with value `%s`', itemName)
84
+ return null
85
+ }
86
+ } else {
87
+ console.error('Unhandled id type: %s', itemNode.id.type)
88
+ return null
89
+ }
90
+ } else {
91
+ return null
92
+ }
93
+
94
+ return {
95
+ destructured,
96
+ imported,
97
+ local,
98
+ sourceModule,
99
+ usesImportSyntax,
100
+ }
101
+ }