| 56 | }; |
| 57 | |
| 58 | export const findVersion = ( |
| 59 | id: string, |
| 60 | tag: string, |
| 61 | versions: string[], |
| 62 | ): string => { |
| 63 | if (tag === 'latest') { |
| 64 | // Get latest version in list |
| 65 | const latest = versions.shift(); |
| 66 | |
| 67 | if (latest) return latest; |
| 68 | throw new StatusError( |
| 69 | 404, |
| 70 | `Not found. Version ${tag} not found for ${id}.`, |
| 71 | ); |
| 72 | } |
| 73 | |
| 74 | const semver = tag.split('.'); |
| 75 | |
| 76 | // If the tag is a full semver, return it |
| 77 | if (semver.length === 3) { |
| 78 | const version = versions.find((version) => version === tag); |
| 79 | if (version) return version; |
| 80 | throw new StatusError( |
| 81 | 404, |
| 82 | `Not found. Version ${tag} not found for ${id}.`, |
| 83 | ); |
| 84 | } |
| 85 | |
| 86 | // Find latest version that matches the minor version |
| 87 | if (semver.length === 2) { |
| 88 | const [major, minor] = semver; |
| 89 | |
| 90 | const version = versions |
| 91 | // Filter out the major and minor versions that don't match |
| 92 | .filter((version) => version.startsWith(`${major}.${minor}`)) |
| 93 | // Sort the versions in descending order |
| 94 | .sort((a, b) => { |
| 95 | const aPatch = a.split('.')[2]; |
| 96 | const bPatch = b.split('.')[2]; |
| 97 | if (aPatch > bPatch) return -1; |
| 98 | if (aPatch < bPatch) return 1; |
| 99 | return 0; |
| 100 | }) |
| 101 | // Return the first version |
| 102 | .shift(); |
| 103 | |
| 104 | if (version) return version; |
| 105 | throw new StatusError( |
| 106 | 404, |
| 107 | `Not found. Version ${tag} not found for ${id}.`, |
| 108 | ); |
| 109 | } |
| 110 | |
| 111 | // Find latest version that matches the major version |
| 112 | if (semver.length === 1) { |
| 113 | const [major] = semver; |
| 114 | |
| 115 | const version = versions |