* Resolve a custom hook reference using name-based lookup
(name: string, fromFile: string, context: ResolutionContext, language?: string)
| 2453 | * Resolve a custom hook reference using name-based lookup |
| 2454 | */ |
| 2455 | function resolveHook(name: string, fromFile: string, context: ResolutionContext, language?: string): string | null { |
| 2456 | const candidates = context.getNodesByName(name); |
| 2457 | if (candidates.length === 0) return null; |
| 2458 | |
| 2459 | // A hook nested inside another function is only callable in there. |
| 2460 | const nested = (n: Node): boolean => |
| 2461 | context.getNodesInFile(n.filePath).some((f) => |
| 2462 | f.id !== n.id && (f.kind === 'function' || f.kind === 'method') && f.startLine <= n.startLine && f.endLine >= n.endLine && |
| 2463 | (f.startLine < n.startLine || f.endLine > n.endLine)); |
| 2464 | const hooks = candidates.filter((n) => n.kind === 'function' && n.name.startsWith('use') && !nested(n)); |
| 2465 | if (hooks.length === 0) return null; |
| 2466 | const sameFile = hooks.find((n) => n.filePath === fromFile); |
| 2467 | if (sameFile) return sameFile.id; |
| 2468 | // A JS/TS module reaches another file's hook only by importing it — the |
| 2469 | // import resolver's to follow (an imported name never gets here) — never |
| 2470 | // by name alone. |
| 2471 | if (isEsmLanguage(language)) return null; |
| 2472 | |
| 2473 | // Prefer hooks directories |
| 2474 | const HOOK_DIRS = ['/hooks/', '/src/hooks/', '/lib/hooks/', '/utils/hooks/']; |
| 2475 | const preferred = hooks.filter((n) => |
| 2476 | HOOK_DIRS.some((d) => n.filePath.includes(d)) |
| 2477 | ); |
| 2478 | if (preferred.length > 0) return preferred[0]!.id; |
| 2479 | |
| 2480 | return hooks[0]!.id; |
| 2481 | } |
| 2482 | |
| 2483 | /** |
| 2484 | * Resolve a context reference using name-based lookup |
no test coverage detected