blob: ada3c7f74796f74d790e26482be3e118ea8414ad [file]
async function fetchJson(url, fetchImpl, signal) {
const response = await fetchImpl(url.href, {signal});
if (!response.ok) throw new Error(`Search index HTTP ${response.status}`);
return response.json();
}
async function resolveIndex(candidate, fetchImpl, signal) {
if (candidate.searchParams.get('manifest') !== '1') return candidate;
const match = candidate.pathname.match(/\/(search-index(?:-[a-z0-9.-]+)?)-([a-f0-9]{16})\.json$/);
if (!match) throw new Error('Invalid search index build key');
const [, stem, buildKey] = match;
const manifest = await fetchJson(new URL(`search-manifest-${buildKey}.json`, candidate), fetchImpl, signal);
const hash = manifest?.[stem];
if (typeof hash !== 'string' || !/^[a-f0-9]{16}$/.test(hash)) throw new Error('Invalid search manifest entry');
return new URL(`${stem}-${hash}.json`, candidate);
}
// Only production pages use the configured asset CDN. Local previews and
// alternate hosts read their own index, just like their own same-origin worker.
export async function fetchSearchIndex(url, {
assetOrigin = '', siteOrigin = '', origin = globalThis.location?.origin,
timeoutMs = 60000, fetchImpl = globalThis.fetch,
} = {}) {
const source = new URL(url, origin);
if (source.origin !== origin) throw new Error('Unexpected search index origin');
const candidates = [source];
if (assetOrigin && siteOrigin && new URL(siteOrigin).origin === origin) {
// A leading slash would discard the configured /site/ asset prefix.
const base = assetOrigin.replace(/\/?$/, '/');
const cdn = new URL(source.pathname.replace(/^\/+/, '') + source.search, base);
if (!['http:', 'https:'].includes(cdn.protocol)) throw new Error('Invalid search asset origin');
if (cdn.origin !== source.origin) candidates.unshift(cdn);
}
let failure;
for (const candidate of candidates) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const index = await resolveIndex(candidate, fetchImpl, controller.signal);
const data = await fetchJson(index, fetchImpl, controller.signal);
if (!Array.isArray(data)) throw new Error('Invalid search index');
return data;
} catch (error) {
failure = error;
} finally {
clearTimeout(timeout);
}
}
throw failure;
}