* Get the latest version of a package from npm with caching and timeout
(packageName)
| 49 | * Get the latest version of a package from npm with caching and timeout |
| 50 | */ |
| 51 | async function getLatestVersion(packageName) { |
| 52 | // Check cache first |
| 53 | if (versionCache.has(packageName)) { |
| 54 | return versionCache.get(packageName) |
| 55 | } |
| 56 | |
| 57 | try { |
| 58 | // Add timeout to prevent hanging |
| 59 | const controller = new AbortController() |
| 60 | const timeoutId = setTimeout(() => controller.abort(), 10000) // 10 second timeout |
| 61 | |
| 62 | const response = await fetch( |
| 63 | `https://registry.npmjs.org/${packageName}/latest`, |
| 64 | { |
| 65 | signal: controller.signal, |
| 66 | headers: { |
| 67 | 'User-Agent': 'create-tsrouter-app-outdated-checker', |
| 68 | }, |
| 69 | }, |
| 70 | ) |
| 71 | |
| 72 | clearTimeout(timeoutId) |
| 73 | |
| 74 | if (!response.ok) { |
| 75 | throw new Error(`HTTP ${response.status}`) |
| 76 | } |
| 77 | |
| 78 | const data = await response.json() |
| 79 | const version = data.version |
| 80 | |
| 81 | // Cache the result |
| 82 | versionCache.set(packageName, version) |
| 83 | return version |
| 84 | } catch (error) { |
| 85 | if (error.name === 'AbortError') { |
| 86 | console.warn( |
| 87 | `${colors.yellow}Warning: Timeout fetching latest version for ${packageName}${colors.reset}`, |
| 88 | ) |
| 89 | } else { |
| 90 | console.warn( |
| 91 | `${colors.yellow}Warning: Could not fetch latest version for ${packageName}: ${error.message}${colors.reset}`, |
| 92 | ) |
| 93 | } |
| 94 | |
| 95 | // Cache null result to avoid retrying |
| 96 | versionCache.set(packageName, null) |
| 97 | return null |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /** |
| 102 | * Check if a version range satisfies the latest version |