Open History to see the last commit
1import { analyzeModule, unwrapExpression } from '@tanstack/router-utils'
2import { bindingIdentifiers, is } from 'yuku-ast'
3import { buildLineIndex, indexToLineColumn } from './sourceLocation'
4import { getOrCreate } from './utils'
5import type * as t from '@yuku-toolchain/types'
6import type { Binding, Module } from 'yuku-analyzer'
7import type { LineIndex, TransformResult } from './sourceLocation'
8β
9export type UsagePos = { line: number; column0: number }
10type BoundaryEnv = 'client' | 'server'
11type ImportBindingInfo = { importedLocalNames: Set<string> }
12type UsageCacheKey = `${BoundaryEnv | 'post'}::${string}`
13β
14export type ImportAnalysis = {
15 module: Module
16 lineIndex: LineIndex
17 importSourcesInOrder: Array<string>
18 importSpecifierLocationIndex: Map<string, number>
19 importBindingsBySource: Map<string, ImportBindingInfo>
20 mockExportNamesBySource: Map<string, Array<string>>
21 namedExports: Array<string>
22 usageByKey: Map<UsageCacheKey, UsagePos | null>
23}
24β
25function mayContainImportOrExport(code: string): boolean {
26 return code.includes('import') || code.includes('export')
27}
28β
29function makeTransientResult(
30 code: string,
31 filename?: string,
32 perf?: TransformResult['perf'],
33): TransformResult {
34 return {
35 code,
36 filename,
37 map: undefined,
38 originalCode: undefined,
39 ...(perf ? { perf } : {}),
40 }
41}
42β
43function getOrAnalyzeModule(result: TransformResult): Module {
44 if (result.analyzedModule) {
45 result.perf?.count('analysis.parseAst.cached')
46 return result.analyzedModule
47 }
48 const startedAt = result.perf ? performance.now() : 0
49 result.perf?.count('analysis.parseAst.calls')
50 try {
51 const module = analyzeModule({
52 code: result.code,
53 filename: result.filename,
54 })
55 result.analyzedModule = module
56 return module
57 } finally {
58 if (result.perf) {
59 result.perf.time('analysis.parseAst', startedAt)
60 }
61 }
62}
63β
64function unwrapNode(node: t.Node): t.Node {
65 return is.Expression(node) ? unwrapExpression(node) : node
66}
67β
68function getModuleExportName(node: t.Identifier | t.StringLiteral): string {
69 return is.Identifier(node) ? node.name : node.value
70}
71β
72function getStringLiteralValueStart(node: t.StringLiteral): number {
73 return node.start + 1
74}
75β
76function isTypeOnlyImportDeclaration(node: t.ImportDeclaration): boolean {
77 return (
78 node.importKind === 'type' ||
79 (node.specifiers.length > 0 &&
80 node.specifiers.every(
81 (specifier) =>
82 is.ImportSpecifier(specifier) && specifier.importKind === 'type',
83 ))
84 )
85}
86β
87function isTypeOnlyExportNamedDeclaration(
88 node: t.ExportNamedDeclaration,
89): boolean {
90 return (
91 node.exportKind === 'type' ||
92 (!!node.source &&
93 !node.declaration &&
94 node.specifiers.length > 0 &&
95 node.specifiers.every((specifier) => specifier.exportKind === 'type'))
96 )
97}
98β
99export function isValidExportName(name: string): boolean {
100 return name !== 'default' && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)
101}
102β
103function buildImportAnalysis(result: TransformResult): ImportAnalysis {
104 const module = getOrAnalyzeModule(result)
105β
106 const importSourcesInOrder: Array<string> = []
107 const importSpecifierLocationIndex = new Map<string, number>()
108 const importBindingsBySource = new Map<string, ImportBindingInfo>()
109 const memberBindingSources = new Map<Binding, Set<string>>()
110 const mockNamesBySource = new Map<string, Set<string>>()
111 const namedExports = new Set<string>()
112β
113 const getBindingInfo = (source: string): ImportBindingInfo =>
114 getOrCreate(importBindingsBySource, source, () => ({
115 importedLocalNames: new Set<string>(),
116 }))
117β
118 const addSpecifierLocation = (node: t.StringLiteral) => {
119 importSourcesInOrder.push(node.value)
120β
121 const index = getStringLiteralValueStart(node)
122 const prev = importSpecifierLocationIndex.get(node.value)
123 if (prev == null || index < prev) {
124 importSpecifierLocationIndex.set(node.value, index)
125 }
126 }
127β
128 const addMockName = (source: string, name: string) => {
129 if (name === 'default' || name.length === 0) {
130 return
131 }
132 getOrCreate(mockNamesBySource, source, () => new Set<string>()).add(name)
133 }
134β
135 const addMemberBinding = (localName: string, source: string) => {
136 const binding = module.rootScope.find(localName)
137 if (binding) {
138 getOrCreate(memberBindingSources, binding, () => new Set<string>()).add(
139 source,
140 )
141 }
142 }
143β
144 const addNamedExport = (name: string) => {
145 if (name !== 'default' && name.length > 0) {
146 namedExports.add(name)
147 }
148 }
149β
150 const visit = (node: t.Node): void => {
151 if (is.ImportDeclaration(node)) {
152 const isTypeOnly = isTypeOnlyImportDeclaration(node)
153 if (!isTypeOnly) {
154 addSpecifierLocation(node.source)
155 const source = node.source.value
156 const bindingInfo = getBindingInfo(source)
157 for (const specifier of node.specifiers) {
158 if (is.ImportNamespaceSpecifier(specifier)) {
159 bindingInfo.importedLocalNames.add(specifier.local.name)
160 addMemberBinding(specifier.local.name, source)
161 continue
162 }
163β
164 if (is.ImportDefaultSpecifier(specifier)) {
165 bindingInfo.importedLocalNames.add(specifier.local.name)
166 addMemberBinding(specifier.local.name, source)
167 continue
168 }
169β
170 if (!is.ImportSpecifier(specifier)) {
171 continue
172 }
173 if (specifier.importKind === 'type') {
174 continue
175 }
176β
177 bindingInfo.importedLocalNames.add(specifier.local.name)
178 const importedName = getModuleExportName(specifier.imported)
179 if (importedName !== 'default') {
180 addMockName(source, importedName)
181 }
182 }
183 }
184 } else if (is.ExportNamedDeclaration(node)) {
185 const isTypeOnly = isTypeOnlyExportNamedDeclaration(node)
186 if (!isTypeOnly && node.source && is.StringLiteral(node.source)) {
187 addSpecifierLocation(node.source)
188 }
189β
190 if (!isTypeOnly && node.source?.value) {
191 const source = node.source.value
192 for (const specifier of node.specifiers) {
193 if (!is.ExportSpecifier(specifier)) {
194 continue
195 }
196 if (specifier.exportKind === 'type') {
197 continue
198 }
199 addMockName(source, getModuleExportName(specifier.local))
200 }
201 }
202β
203 if (!isTypeOnly) {
204 if (node.declaration) {
205 const decl = node.declaration
206 if (is.FunctionDeclaration(decl) || is.ClassDeclaration(decl)) {
207 if (decl.id?.name) {
208 addNamedExport(decl.id.name)
209 }
210 } else if (is.VariableDeclaration(decl)) {
211 for (const d of decl.declarations) {
212 bindingIdentifiers(d.id).forEach((id) => addNamedExport(id.name))
213 }
214 }
215 }
216β
217 for (const specifier of node.specifiers) {
218 if (!is.ExportSpecifier(specifier)) {
219 continue
220 }
221 if (specifier.exportKind === 'type') {
222 continue
223 }
224 const exportedName = getModuleExportName(specifier.exported)
225 addNamedExport(exportedName)
226 }
227 }
228 } else if (is.ExportAllDeclaration(node)) {
229 if (node.exportKind !== 'type') {
230 addSpecifierLocation(node.source)
231 }
232 } else if (is.ImportExpression(node)) {
233 const source = unwrapNode(node.source)
234 if (is.StringLiteral(source)) {
235 addSpecifierLocation(source)
236 }
237 } else if (is.MemberExpression(node)) {
238 const object = unwrapNode(node.object)
239 if (is.Identifier(object)) {
240 const sources = memberBindingSources.get(module.bindingOf(object)!)
241 if (sources) {
242 const property = node.property
243 for (const source of sources) {
244 if (!node.computed && is.Identifier(property)) {
245 addMockName(source, property.name)
246 } else if (node.computed && is.StringLiteral(property)) {
247 addMockName(source, property.value)
248 }
249 }
250 }
251 }
252 }
253 }
254β
255 module.walk({ enter: visit })
256β
257 const mockExportNamesBySource = new Map<string, Array<string>>()
258 for (const [source, names] of mockNamesBySource) {
259 mockExportNamesBySource.set(source, Array.from(names).sort())
260 }
261β
262 const lineIndex = result.lineIndex ?? buildLineIndex(result.code)
263 result.lineIndex = lineIndex
264β
265 const analysis = {
266 module,
267 lineIndex,
268 importSourcesInOrder,
269 importSpecifierLocationIndex,
270 importBindingsBySource,
271 mockExportNamesBySource,
272 namedExports: Array.from(namedExports).sort(),
273 usageByKey: new Map(),
274 }
275β
276 return analysis
277}
278β
279export function getOrCreateImportAnalysis(
280 result: TransformResult,
281): ImportAnalysis {
282 if (!result.analysis) {
283 result.analysis = buildImportAnalysis(result)
284 }
285β
286 return result.analysis
287}
288β
289export function getImportSourcesFromResult(
290 result: TransformResult,
291): Array<string> {
292 if (!mayContainImportOrExport(result.code)) {
293 return []
294 }
295β
296 return getOrCreateImportAnalysis(result).importSourcesInOrder
297}
298β
299export function getImportSources(
300 code: string,
301 filename?: string,
302 perf?: TransformResult['perf'],
303): Array<string> {
304 return getImportSourcesFromResult(makeTransientResult(code, filename, perf))
305}
306β
307export function getImportSpecifierLocationFromResult(
308 result: TransformResult,
309 source: string,
310): number {
311 return (
312 getOrCreateImportAnalysis(result).importSpecifierLocationIndex.get(
313 source,
314 ) ?? -1
315 )
316}
317β
318export function getMockExportNamesBySourceFromResult(
319 result: TransformResult,
320): Map<string, Array<string>> {
321 return getOrCreateImportAnalysis(result).mockExportNamesBySource
322}
323β
324export function getMockExportNamesBySource(
325 code: string,
326 filename?: string,
327 perf?: TransformResult['perf'],
328): Map<string, Array<string>> {
329 return getMockExportNamesBySourceFromResult(
330 makeTransientResult(code, filename, perf),
331 )
332}
333β
334export function getNamedExportsFromResult(
335 result: TransformResult,
336): Array<string> {
337 return getOrCreateImportAnalysis(result).namedExports
338}
339β
340export function getNamedExports(
341 code: string,
342 filename?: string,
343 perf?: TransformResult['perf'],
344): Array<string> {
345 return getNamedExportsFromResult(makeTransientResult(code, filename, perf))
346}
347β
348function isCompilerSafeBoundaryCall(
349 call: t.CallExpression,
350 fnNode: t.Function | t.ArrowFunctionExpression,
351 envType: BoundaryEnv,
352): boolean {
353 const directArgument = call.arguments.some(
354 (arg) => unwrapNode(arg) === fnNode,
355 )
356 if (!directArgument) {
357 return false
358 }
359β
360 const callee = unwrapNode(call.callee)
361β
362 if (is.Identifier(callee)) {
363 return envType === 'client'
364 ? callee.name === 'createServerOnlyFn'
365 : callee.name === 'createClientOnlyFn'
366 }
367β
368 if (!is.MemberExpression(callee) || callee.computed) {
369 return false
370 }
371β
372 if (!is.Identifier(callee.property)) {
373 return false
374 }
375β
376 const prop = callee.property.name
377 const rootName = getCalleeRootName(callee.object)
378β
379 if (envType === 'client') {
380 if (prop === 'handler') {
381 return rootName === 'createServerFn' || /ServerFn$/.test(rootName ?? '')
382 }
383β
384 if (prop === 'server') {
385 return (
386 rootName === 'createMiddleware' ||
387 rootName === 'createIsomorphicFn' ||
388 /Middleware$/.test(rootName ?? '')
389 )
390 }
391β
392 return false
393 }
394β
395 if (prop === 'client') {
396 return rootName === 'createIsomorphicFn'
397 }
398β
399 return false
400}
401β
402function getCalleeRootName(node: t.Node): string | undefined {
403 node = unwrapNode(node)
404 if (is.Identifier(node)) {
405 return node.name
406 }
407β
408 if (is.CallExpression(node)) {
409 return getCalleeRootName(node.callee)
410 }
411β
412 if (is.MemberExpression(node)) {
413 return getCalleeRootName(node.object)
414 }
415β
416 return undefined
417}
418β
419function transparentParent(module: Module, node: t.Node) {
420 let parent = module.parentOf(node)
421 while (parent && unwrapNode(parent) === unwrapNode(node)) {
422 node = parent
423 parent = module.parentOf(node)
424 }
425 return { node, parent }
426}
427β
428function isInsideCompilerSafeBoundary(
429 module: Module,
430 node: t.Node,
431 envType: BoundaryEnv,
432): boolean {
433 let ancestor = module.parentOf(node)
434 while (ancestor) {
435 if (is.Function(ancestor)) {
436 const { parent: call } = transparentParent(module, ancestor)
437 if (
438 is.CallExpression(call) &&
439 isCompilerSafeBoundaryCall(call, ancestor, envType)
440 ) {
441 return true
442 }
443 }
444 ancestor = module.parentOf(ancestor)
445 }
446 return false
447}
448β
449function findUsagePosInAnalysis(
450 result: TransformResult,
451 source: string,
452 envType?: BoundaryEnv,
453): UsagePos | undefined {
454 const analysis = getOrCreateImportAnalysis(result)
455 const cacheKey: UsageCacheKey = `${envType ?? 'post'}::${source}`
456 if (analysis.usageByKey.has(cacheKey)) {
457 return analysis.usageByKey.get(cacheKey) ?? undefined
458 }
459 const module = analysis.module
460 const imported =
461 analysis.importBindingsBySource.get(source)?.importedLocalNames
462 const bindings = new Set<Binding>()
463 for (const name of imported ?? []) {
464 const binding = module.rootScope.find(name)
465 if (binding) {
466 bindings.add(binding)
467 }
468 }
469 let preferred: UsagePos | undefined
470 let anyUsage: UsagePos | undefined
471 for (const reference of module.references) {
472 if (
473 !reference.binding ||
474 !bindings.has(reference.binding) ||
475 reference.inTypePosition
476 ) {
477 continue
478 }
479 const node = reference.node
480 if (envType && isInsideCompilerSafeBoundary(module, node, envType)) {
481 continue
482 }
483 const { node: expression, parent } = transparentParent(module, node)
484 const { line, column } = indexToLineColumn(analysis.lineIndex, node.start)
485 const pos = { line, column0: column - 1 }
486 const isPreferred =
487 ((is.CallExpression(parent) || is.NewExpression(parent)) &&
488 parent.callee === expression) ||
489 (is.MemberExpression(parent) && parent.object === expression)
490 if (isPreferred) {
491 preferred ??= pos
492 } else {
493 anyUsage ??= pos
494 }
495 if (preferred && anyUsage) {
496 break
497 }
498 }
499 const pos = preferred ?? anyUsage ?? null
500 analysis.usageByKey.set(cacheKey, pos)
501 return pos ?? undefined
502}
503β
504export function findPostCompileUsagePosFromResult(
505 result: TransformResult,
506 source: string,
507): UsagePos | undefined {
508 return findUsagePosInAnalysis(result, source)
509}
510β
511export function findPostCompileUsagePos(
512 code: string,
513 source: string,
514): UsagePos | undefined {
515 return findPostCompileUsagePosFromResult(makeTransientResult(code), source)
516}
517β
518export function findOriginalUnsafeUsagePosFromResult(
519 result: TransformResult,
520 source: string,
521 envType: BoundaryEnv,
522): UsagePos | undefined {
523 return findUsagePosInAnalysis(result, source, envType)
524}
525β
526export function findOriginalUnsafeUsagePos(
527 code: string,
528 source: string,
529 envType: BoundaryEnv,
530): UsagePos | undefined {
531 return findOriginalUnsafeUsagePosFromResult(
532 makeTransientResult(code),
533 source,
534 envType,
535 )
536}