rob-revisited/ide/ui/js/openapi-site.js

33 lines
1.7 KiB
JavaScript

// Pure helpers of the OpenAPI window (ide/ui/js/openapi.js): which description to open first, given the project's files, the
// local site's real address (http.openapi.site) and the source remembered from last time. Tested by openapi-site.test.mjs.
const origin = (url) => { try { return new URL(url).origin; } catch { return ''; } };
/** A remembered address that points at a placeholder of the local site (port 80 or 8000) that is not where the site answers now. */
export function isStaleLocal(saved, site) {
if (!/^https?:\/\//i.test(saved || '') || !site?.url) return false;
const o = origin(saved);
return ['http://localhost', 'http://localhost:8000', 'http://127.0.0.1', 'http://127.0.0.1:8000'].includes(o) && o !== origin(site.url);
}
/** The source to open: the remembered one (unless stale), else a file of the project, else the first address on the site. */
export function pickSource(found, site, saved) {
if (saved && !isStaleLocal(saved, site)) return saved;
return found?.files?.[0] || site?.urls?.[0] || found?.urls?.[0] || '';
}
/** The addresses and files offered in the source list: files first, then the site's addresses. */
export function sourceOptions(found, site) {
return [...new Set([...(found?.files || []), ...(site?.urls || found?.urls || [])])];
}
/** The site address a source belongs to (its origin), '' for a file. */
export function siteOf(source) {
return /^https?:\/\//i.test(source || '') ? origin(source) : '';
}
/** The file "Regenerate the schema" writes: var/openapi.json by default, else what the user chose. */
export function exportTarget(saved) {
const v = String(saved || '').trim();
return v || 'var/openapi.json';
}