|
| 1 | +import parseLink from 'parse-link-header'; |
| 2 | + |
| 3 | +import { registryAPI, repositoriesPerPage, tagsPerPage, usePortusExplore } from '@/options'; |
| 4 | + |
| 5 | +async function paginatable(path, n, last = null) { |
| 6 | + const url = new URL(`${await registryAPI()}${path}`); |
| 7 | + if (n) url.searchParams.append('n', n); |
| 8 | + if (last) url.searchParams.append('last', last); |
| 9 | + |
| 10 | + const response = await fetch(url); |
| 11 | + let nextLast = null; |
| 12 | + if (response.headers.has('Link')) { |
| 13 | + const links = parseLink(response.headers.get('Link')); |
| 14 | + if (links && links.next) { |
| 15 | + nextLast = links.next.last; |
| 16 | + } |
| 17 | + } |
| 18 | + return Object.assign(await response.json(), { nextLast }); |
| 19 | +} |
| 20 | + |
| 21 | +async function get(path) { |
| 22 | + const url = new URL(`${await registryAPI()}${path}`); |
| 23 | + const response = await fetch(url); |
| 24 | + return response.json(); |
| 25 | +} |
| 26 | + |
| 27 | +async function head(path) { |
| 28 | + const url = new URL(`${await registryAPI()}${path}`); |
| 29 | + const response = await fetch(url, { method: 'HEAD' }); |
| 30 | + return response.headers; |
| 31 | +} |
| 32 | + |
| 33 | + |
| 34 | +async function repos(last = null) { |
| 35 | + if (await usePortusExplore()) { |
| 36 | + // TODO: Use the Portus API when it enables anonymous access |
| 37 | + const response = await fetch(`${await registryAPI()}/explore?explore%5Bsearch%5D=`); |
| 38 | + const html = await response.text(); |
| 39 | + |
| 40 | + // unconventionally parse out JSON from HTML |
| 41 | + const startString = 'window.repositories = '; |
| 42 | + const endString = ';</script>'; |
| 43 | + const string = html.substring( |
| 44 | + html.lastIndexOf(startString) + startString.length, |
| 45 | + html.indexOf(endString), |
| 46 | + ); |
| 47 | + return JSON.parse(string); |
| 48 | + } |
| 49 | + return paginatable('/v2/_catalog', await repositoriesPerPage(), last); |
| 50 | +} |
| 51 | + |
| 52 | +async function repo(name) { |
| 53 | + return get(`/v2/${name}`); |
| 54 | +} |
| 55 | + |
| 56 | +async function tags(name, last = null) { |
| 57 | + return paginatable(`/v2/${name}/tags/list`, await tagsPerPage(), last); |
| 58 | +} |
| 59 | + |
| 60 | +async function tag(name, ref) { |
| 61 | + return get(`/v2/${name}/manifests/${ref}`); |
| 62 | +} |
| 63 | + |
| 64 | +async function blob(name, digest) { |
| 65 | + const headers = await head(`/v2/${name}/blobs/${digest}`); |
| 66 | + return { |
| 67 | + contentLength: parseInt(headers.get('Content-Length'), 10), |
| 68 | + }; |
| 69 | +} |
| 70 | + |
| 71 | +export { |
| 72 | + repos, |
| 73 | + repo, |
| 74 | + tags, |
| 75 | + tag, |
| 76 | + blob, |
| 77 | +}; |
0 commit comments