-
-
Notifications
You must be signed in to change notification settings - Fork 217
/
parser.ts
401 lines (350 loc) 路 13.4 KB
/
parser.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
import { BoxNodeMap, extract, unbox, type BoxNode, type Unboxed, box } from '@pandacss/extractor'
import { logger } from '@pandacss/logger'
import { astish, memo } from '@pandacss/shared'
import type { SourceFile } from 'ts-morph'
import { Node } from 'ts-morph'
import { match } from 'ts-pattern'
import { getImportDeclarations } from './import'
import { createParserResult } from './parser-result'
import type { ConfigTsOptions, RecipeConfig, ResultItem, Runtime } from '@pandacss/types'
import { resolveTsPathPattern } from '@pandacss/config/ts-path'
type ParserPatternNode = {
name: string
type: 'pattern'
props?: string[]
baseName: string
}
type ParserRecipeNode = {
name: string
type: 'recipe'
props: string[]
baseName: string
jsx: RecipeConfig['jsx']
}
export type ParserNodeOptions = ParserPatternNode | ParserRecipeNode
const isNodeRecipe = (node: ParserNodeOptions): node is ParserRecipeNode => node.type === 'recipe'
const cvaProps = ['compoundVariants', 'defaultVariants', 'variants', 'base']
const isCva = (map: BoxNodeMap['value']) => cvaProps.some((prop) => map.has(prop))
export type ParserOptions = {
importMap: Record<'css' | 'recipe' | 'pattern' | 'jsx', string[]>
jsx?: {
factory: string
nodes: ParserNodeOptions[]
isStyleProp: (prop: string) => boolean
}
getRecipesByJsxName: (jsxName: string) => RecipeConfig[]
tsOptions?: ConfigTsOptions
join: Runtime['path']['join']
}
// create strict regex from array of strings
function createImportMatcher(mod: string, values?: string[]) {
const regex = values ? new RegExp(`^(${values.join('|')})$`) : /.*/
return {
mod,
regex,
match(value: string) {
return regex.test(value)
},
}
}
const combineResult = (unboxed: Unboxed) => {
return [...unboxed.conditions, unboxed.raw, ...unboxed.spreadConditions]
}
const fallback = (box: BoxNode) => ({
value: undefined,
getNode: () => box.getNode(),
getStack: () => box.getStack(),
})
type GetEvaluateOptions = NonNullable<Parameters<typeof extract>['0']['getEvaluateOptions']>
type EvalOptions = ReturnType<GetEvaluateOptions>
const defaultEnv: EvalOptions['environment'] = { preset: 'NONE' }
export function createParser(options: ParserOptions) {
const { jsx, getRecipesByJsxName, tsOptions, join } = options
const importMap = Object.fromEntries(Object.entries(options.importMap).map(([key, value]) => [key, join(...value)]))
// Create regex for each import map
const importRegex = [
createImportMatcher(importMap.css, ['css', 'cva']),
createImportMatcher(importMap.recipe),
createImportMatcher(importMap.pattern),
]
if (jsx) {
importRegex.push(createImportMatcher(importMap.jsx, [jsx.factory, ...jsx.nodes.map((node) => node.name)]))
}
return function parse(sourceFile: SourceFile | undefined) {
if (!sourceFile) return
const filePath = sourceFile.getFilePath()
// Get all import declarations
const imports = getImportDeclarations(sourceFile, {
match(value) {
let found: string | boolean = false
for (const { regex, mod } of importRegex) {
// if none of the imported values match the regex, skip
if (!regex.test(value.name)) continue
// this checks that `yyy` contains {outdir}/{folder} in `import xxx from yyy`
if (value.mod.includes(mod)) {
found = true
break
}
// that might be a TS path mapping, it could be completely different from the actual path
if (tsOptions?.pathMappings) {
const filename = resolveTsPathPattern(tsOptions.pathMappings, value.mod)
if (filename?.includes(mod)) {
found = mod
break
}
}
}
return found
},
})
const collector = createParserResult()
logger.debug(
'ast:import',
imports.value.length ? `Found import { ${imports} } in ${filePath}` : `No import found in ${filePath}`,
)
const [css] = importRegex
const jsxFactoryAlias = jsx ? imports.getAlias(jsx.factory) : 'styled'
const isValidPattern = imports.createMatch(importMap.pattern)
const isValidRecipe = imports.createMatch(importMap.recipe)
const isValidStyleFn = (name: string) => name === jsx?.factory
const isFactory = (name: string) => Boolean(jsx && name.startsWith(jsxFactoryAlias))
const jsxPatternNodes = new RegExp(
`^(${jsx?.nodes
.filter((node) => node.type === 'pattern')
.map((node) => node.name)
.join('|')})$`,
)
const recipes = new Set<string>()
const patterns = new Set<string>()
imports.value.forEach((importDeclaration) => {
const { alias } = importDeclaration
if (isValidRecipe(alias)) {
recipes.add(alias)
}
if (isValidPattern(alias)) {
patterns.add(alias)
}
})
const functions = new Map<string, Map<string, boolean>>()
const components = new Map<string, Map<string, boolean>>()
const propertiesMap = new Map<string, boolean>()
const recipePropertiesByName = new Map<string, Set<string>>()
const recipeJsxLists = (jsx?.nodes ?? []).filter(isNodeRecipe).reduce(
(acc, recipe) => {
recipePropertiesByName.set(recipe.baseName, new Set(recipe.props ?? []))
recipe.jsx?.forEach((jsx) => {
if (typeof jsx === 'string') {
acc.string.add(jsx)
} else {
acc.regex.push(jsx)
}
})
return acc
},
{ string: new Set<string>(), regex: [] as RegExp[] },
)
const cvaAlias = imports.getAlias('cva')
const cssAlias = imports.getAlias('css')
if (options.jsx) {
options.jsx.nodes.forEach((node) => {
const alias = imports.getAlias(node.name)
node.props?.forEach((prop) => propertiesMap.set(prop, true))
functions.set(node.baseName, propertiesMap)
functions.set(alias, propertiesMap)
components.set(alias, propertiesMap)
})
}
const isJsxTagRecipe = memo(
(tagName: string) =>
recipeJsxLists.string.has(tagName) || recipeJsxLists.regex.some((regex) => regex.test(tagName)),
)
const matchTag = memo((tagName: string) => {
// ignore fragments
if (!tagName) return false
return components.has(tagName) || isUpperCase(tagName) || isFactory(tagName) || isJsxTagRecipe(tagName)
})
const matchTagProp = memo((tagName: string, propName: string) => {
if (
Boolean(components.get(tagName)?.has(propName)) ||
options.jsx?.isStyleProp(propName) ||
propertiesMap.has(propName)
)
return true
if (isJsxTagRecipe(tagName)) {
const recipeList = getRecipesByJsxName(tagName)
return recipeList.some((recipe) => recipePropertiesByName.get(recipe.name)?.has(propName))
}
return false
})
const matchFn = memo((fnName: string) => {
if (recipes.has(fnName) || patterns.has(fnName)) return true
if (fnName === cvaAlias || fnName === cssAlias || isFactory(fnName)) return true
return functions.has(fnName)
})
const measure = logger.time.debug(`Tokens extracted from ${filePath}`)
const extractResultByName = extract({
ast: sourceFile,
components: {
matchTag: (prop) => matchTag(prop.tagName),
matchProp: (prop) => matchTagProp(prop.tagName, prop.propName),
},
functions: {
matchFn: (prop) => matchFn(prop.fnName),
matchProp: () => true,
matchArg: (prop) => {
// skip resolving `badge` here: `panda("span", badge)`
if (prop.fnName === jsxFactoryAlias && prop.index === 1 && Node.isIdentifier(prop.argNode)) return false
return true
},
},
taggedTemplates: {
matchTaggedTemplate: (tag) => matchFn(tag.fnName),
},
getEvaluateOptions: (node) => ({ node: node as any, environment: defaultEnv }),
flags: { skipTraverseFiles: true },
})
measure()
extractResultByName.forEach((result, alias) => {
const name = imports.getName(alias)
logger.debug(`ast:${name}`, name !== alias ? { kind: result.kind, alias } : { kind: result.kind })
if (result.kind === 'function') {
match(name)
.when(css.match, (name: 'css' | 'cva') => {
result.queryList.forEach((query) => {
if (query.kind === 'call-expression') {
collector.set(name, {
name,
box: (query.box.value[0] as BoxNodeMap) ?? fallback(query.box),
data: combineResult(unbox(query.box.value[0])),
})
} else if (query.kind === 'tagged-template') {
const obj = astish(query.box.value as string)
collector.set(name, {
name,
box: query.box ?? fallback(query.box),
data: [obj],
})
}
})
})
// stack({ ... })
.when(isValidPattern, (name) => {
result.queryList.forEach((query) => {
if (query.kind === 'call-expression') {
collector.setPattern(name, {
name,
box: (query.box.value[0] as BoxNodeMap) ?? fallback(query.box),
data: combineResult(unbox(query.box.value[0])),
})
}
})
})
// button({ ... })
.when(isValidRecipe, (name) => {
result.queryList.forEach((query) => {
if (query.kind === 'call-expression') {
collector.setRecipe(name, {
name,
box: (query.box.value[0] as BoxNodeMap) ?? fallback(query.box),
data: combineResult(unbox(query.box.value[0])),
})
}
})
})
// panda("span", { ... }) or panda("div", badge)
// or panda("span", { color: "red.100", ... })
// or panda('span')` color: red; `
.when(isValidStyleFn, () => {
result.queryList.forEach((query) => {
if (query.kind === 'call-expression' && query.box.value[1]) {
const map = query.box.value[1]
const result: ResultItem = {
name,
box: (map as BoxNodeMap) ?? fallback(query.box),
data: combineResult(unbox(map)),
}
// CallExpression factory inline recipe
// panda("span", { base: {}, variants: { ... } })
if (box.isMap(map) && isCva(map.value)) {
collector.setCva(result)
} else {
// CallExpression factory css
// panda("span", { color: "red.100", ... })
collector.set('css', result)
}
} else if (query.kind === 'tagged-template') {
// TaggedTemplateExpression factory css
// panda('span')` color: red; `
const obj = astish(query.box.value as string)
collector.set('css', {
name,
box: query.box ?? fallback(query.box),
data: [obj],
})
}
})
})
// panda.span({ ... }) or panda.div` ...`
.when(isFactory, (name) => {
result.queryList.forEach((query) => {
if (query.kind === 'call-expression') {
const map = query.box.value[0]
const result: ResultItem = {
name,
box: (map as BoxNodeMap) ?? fallback(query.box),
data: combineResult(unbox(map)),
}
// PropertyAccess factory inline recipe
// panda.span({ base: {}, variants: { ... } })
if (box.isMap(map) && isCva(map.value)) {
collector.setCva(result)
} else {
// PropertyAccess factory css
// panda.span({ ... })
collector.set('css', result)
}
} else if (query.kind === 'tagged-template') {
const obj = astish(query.box.value as string)
collector.set('css', {
name,
box: query.box ?? fallback(query.box),
data: [obj],
})
}
})
})
.otherwise(() => {
//
})
//
} else if (result.kind === 'component') {
//
result.queryList.forEach((query) => {
//
const data = combineResult(unbox(query.box))
match(name)
.when(isFactory, (name) => {
collector.setJsx({ name, box: query.box, type: 'jsx-factory', data })
})
.when(
(name) => jsxPatternNodes.test(name),
(name) => {
collector.setPattern(name, { type: 'jsx-pattern', name, box: query.box, data })
},
)
.when(isJsxTagRecipe, (name) => {
const recipeList = getRecipesByJsxName(name)
recipeList.map((recipe) => {
collector.setRecipe(recipe.name, { type: 'jsx-recipe', name, box: query.box, data })
})
})
.otherwise(() => {
collector.setJsx({ name, box: query.box, type: 'jsx', data })
})
})
}
})
return collector
}
}
const isUpperCase = (value: string) => value[0] === value[0]?.toUpperCase()