293 lines
15 KiB
JavaScript
293 lines
15 KiB
JavaScript
// The OpenAPI window (right): the project's API description (API Platform's /api/docs.jsonopenapi or /api/docs.json from the running
|
|
// site, NelmioApiDocBundle's /api/doc.json, an openapi.yaml / .json file of the project, or any address), its operations grouped by
|
|
// tag with their parameters, request bodies and answers (models rendered with an example), a search; "Try it" opens an operation
|
|
// filled in the HTTP Client (path parameters, required query ones, Accept / Content-Type, an example body, the auth), "Add all to a
|
|
// collection" makes a request file of each. Read by the IDE's PHP: ide/src/HttpClient/OpenApi.php (http.openapi.*).
|
|
import { backend } from './backend.js';
|
|
import { el, clear, icon, notify, prefs, t } from './ui.js';
|
|
import { pickSource, sourceOptions, siteOf, exportTarget } from './openapi-site.js';
|
|
|
|
if (!document.querySelector('link[data-hc-css]')) document.head.append(el('link', { rel: 'stylesheet', dataset: { hcCss: '1' }, href: new URL('../css/http-client.css', import.meta.url).href }));
|
|
|
|
const TYPE = (s) => {
|
|
if (!s) return '';
|
|
if (s.cycle) return s['x-ref'] || 'object';
|
|
if (s.type === 'array') return `${TYPE(s.items || {})}[]`;
|
|
const base = s['x-ref'] || (Array.isArray(s.type) ? s.type.join(' | ') : s.type) || (s.oneOf ? 'oneOf' : s.anyOf ? 'anyOf' : s.properties ? 'object' : 'any');
|
|
return base + (s.format ? ` (${s.format})` : '') + (s.enum ? ` ∈ {${s.enum.slice(0, 6).join(', ')}}` : '');
|
|
};
|
|
|
|
/** A schema as a tree of its properties (open to 2 levels, the rest on a click). */
|
|
function schemaTree(schema, depth = 0) {
|
|
const box = el('div.oa-schema');
|
|
const props = schema?.properties || schema?.items?.properties;
|
|
const required = new Set(schema?.required || schema?.items?.required || []);
|
|
if (!props) { box.append(el('code.oa-type', {}, TYPE(schema))); return box; }
|
|
for (const [name, s] of Object.entries(props)) {
|
|
const sub = s.properties || s.items?.properties;
|
|
const row = el('div.oa-prop', {}, el('span.oa-pname', {}, name), required.has(name) ? el('span.oa-req', { title: t('required') }, '*') : null,
|
|
el('code.oa-type', {}, TYPE(s)), s.readOnly ? el('span.oa-tag', {}, t('read only')) : null, s.description ? el('span.oa-desc', {}, s.description) : null);
|
|
box.append(row);
|
|
if (sub && !s.cycle) {
|
|
const child = el('div.oa-child');
|
|
const open = () => { if (!child.firstChild) child.append(schemaTree(s, depth + 1)); child.hidden = !child.hidden; };
|
|
row.classList.add('oa-open');
|
|
row.prepend(el('span.oa-caret', {}, '▸'));
|
|
row.addEventListener('click', () => { open(); row.firstChild.textContent = child.hidden ? '▸' : '▾'; });
|
|
child.hidden = true;
|
|
box.append(child);
|
|
if (depth < 1) { open(); row.firstChild.textContent = '▾'; }
|
|
}
|
|
}
|
|
return box;
|
|
}
|
|
|
|
function example(value) {
|
|
return el('pre.oa-example', {}, typeof value === 'string' ? value : JSON.stringify(value, null, 2));
|
|
}
|
|
|
|
export class OpenApiPanel {
|
|
constructor(app) {
|
|
this.app = app;
|
|
this.node = el('div.oa-view');
|
|
this.spec = null;
|
|
this.source = prefs.get(`openapiSource:${app.projectKey}`, '');
|
|
this.found = null;
|
|
this.site = null;
|
|
this.exportFile = exportTarget(prefs.get(`openapiExport:${app.projectKey}`, ''));
|
|
this.query = '';
|
|
this.opened = new Set();
|
|
this.render();
|
|
this.find();
|
|
}
|
|
|
|
title() { return 'OpenAPI'; }
|
|
|
|
async find() {
|
|
try { this.found = await backend.invoke('http.openapi.find'); } catch { this.found = { files: [], urls: [] }; }
|
|
this.render();
|
|
await this.probeSite();
|
|
this.source = pickSource(this.found, this.site, this.source);
|
|
this.render();
|
|
// a site that already answers: its description opens by itself
|
|
if (!this.spec && this.source && (!siteOf(this.source) || this.site?.running)) this.load();
|
|
}
|
|
|
|
/** The local site's real address (web:serve's port, the compose file's published port, .env) and whether it answers. */
|
|
async probeSite() {
|
|
try { this.site = await backend.invoke('http.openapi.site'); } catch { this.site = null; }
|
|
if (this.site?.running) this.stopWaiting();
|
|
this.renderSite();
|
|
return this.site;
|
|
}
|
|
|
|
stopWaiting() { clearInterval(this.waiting); this.waiting = null; }
|
|
|
|
/** "Start the site": the Run window's "Serve the site" configuration, then the address is asked again until the site answers. */
|
|
startSite() {
|
|
const config = this.app.runner?.configs.find((c) => c.id === 'web:serve');
|
|
if (!config) { notify(t('This project has no "Serve the site" run configuration: start its containers yourself.'), 'info'); return; }
|
|
this.app.runner.start(config);
|
|
this.stopWaiting();
|
|
const begun = Date.now();
|
|
this.waiting = setInterval(async () => {
|
|
const site = await this.probeSite();
|
|
if (site?.running) {
|
|
this.source = pickSource(this.found, site, this.source);
|
|
if (!this.spec) this.load(this.source);
|
|
} else if (Date.now() - begun > 180000) this.stopWaiting();
|
|
}, 3000);
|
|
this.renderSite();
|
|
}
|
|
|
|
/** "Regenerate the schema": the project's own console writes it to a file (even with the site stopped), then it is loaded. */
|
|
async regenerate() {
|
|
this.exporting = true;
|
|
this.error = null;
|
|
this.render();
|
|
try {
|
|
const r = await backend.invoke('http.openapi.export', { output: this.exportFile });
|
|
prefs.set(`openapiExport:${this.app.projectKey}`, this.exportFile);
|
|
notify(t('Schema written to {file}.', { file: r.file }), 'success', { title: 'OpenAPI' });
|
|
this.found = await backend.invoke('http.openapi.find').catch(() => this.found);
|
|
this.exporting = false;
|
|
await this.load(r.file);
|
|
return;
|
|
} catch (e) {
|
|
this.error = e.message;
|
|
}
|
|
this.exporting = false;
|
|
this.render();
|
|
}
|
|
|
|
async load(source = this.source) {
|
|
this.source = source.trim();
|
|
prefs.set(`openapiSource:${this.app.projectKey}`, this.source);
|
|
this.loading = true;
|
|
this.error = null;
|
|
this.render();
|
|
try {
|
|
const r = await backend.invoke('http.openapi.load', { source: this.source, verify: !this.insecure });
|
|
this.spec = r.spec;
|
|
} catch (e) {
|
|
this.spec = null;
|
|
this.error = e.message;
|
|
}
|
|
this.loading = false;
|
|
this.render();
|
|
}
|
|
|
|
/** The HTTP Client's collections (the target of Try it / Add all). */
|
|
collections() { return this.app.httpClient?.instance?.data?.collections || []; }
|
|
|
|
/** The line under the bar: the local site's address, running or not (and the button that starts it). */
|
|
renderSite() {
|
|
if (!this.siteNode) return;
|
|
clear(this.siteNode);
|
|
const site = this.site;
|
|
if (!site) return;
|
|
const waiting = !!this.waiting;
|
|
this.siteNode.append(el('span.oa-site-dot' + (site.running ? '.on' : '')), el('span', {}, t('Local site')), el('code', {}, site.url),
|
|
el('span.oa-site-state', {}, site.running ? t('running') : waiting ? t('starting…') : t('not running')));
|
|
if (!site.running && !waiting) this.siteNode.append(el('button.btn', { onclick: () => this.startSite() }, t('Start the site')));
|
|
}
|
|
|
|
render() {
|
|
clear(this.node);
|
|
const options = sourceOptions(this.found, this.site);
|
|
const input = el('input.input.oa-source', { value: this.source, list: 'oaSources', spellcheck: false, placeholder: t('openapi.yaml, or https://localhost:8000/api/docs.json'),
|
|
onkeydown: (e) => { if (e.key === 'Enter') this.load(input.value); } });
|
|
this.node.append(el('div.oa-bar', {}, input, el('datalist', { id: 'oaSources' }, ...options.map((o) => el('option', { value: o }))),
|
|
el('button.btn.primary', { onclick: () => this.load(input.value) }, this.spec ? t('Reload') : t('Load'))));
|
|
this.siteNode = el('div.oa-site');
|
|
this.node.append(this.siteNode);
|
|
this.renderSite();
|
|
if (this.site?.exportable || !this.site) {
|
|
const file = el('input.input.oa-export', { value: this.exportFile, spellcheck: false, title: t('The file of the project the schema is written to'),
|
|
oninput: (e) => { this.exportFile = e.target.value; } });
|
|
this.node.append(el('div.oa-bar', {}, el('button.btn', { disabled: this.exporting || (this.site && !this.site.exportable), title: t('Runs the project\'s console (api:openapi:export or nelmio:apidoc:dump), writes the file, loads it: the site does not need to run'),
|
|
onclick: () => this.regenerate() }, this.exporting ? t('Regenerating…') : t('Regenerate the schema')), file));
|
|
}
|
|
this.node.append(el('label.oa-check', {}, el('input', { type: 'checkbox', checked: !!this.insecure, onchange: (e) => { this.insecure = e.target.checked; } }), t('Accept a self-signed certificate')));
|
|
if (this.loading) { this.node.append(el('div.oa-empty', {}, t('Reading the description…'))); return; }
|
|
if (this.error) this.node.append(el('div.oa-error', {}, this.error, this.found?.framework ? el('p', {}, t('Is the site running? {framework} serves its description at {url}.', { framework: this.found.framework, url: this.site?.urls?.[0] || this.found.urls[0] })) : null));
|
|
if (!this.spec) {
|
|
if (!this.error) {
|
|
this.node.append(el('div.oa-empty', {}, el('p', {}, t('Load the project\'s API description: a file of the project, or the address of the running site.')),
|
|
...options.map((o) => el('button.btn.oa-pick', { onclick: () => this.load(o) }, o))));
|
|
}
|
|
return;
|
|
}
|
|
const s = this.spec;
|
|
const colls = this.collections();
|
|
this.target = this.target && colls.some((c) => c.id === this.target) ? this.target : colls[0]?.id || '';
|
|
this.node.append(el('div.oa-head', {}, el('h3', {}, s.title, el('span.oa-version', {}, s.version), el('span.oa-version', {}, 'OpenAPI ' + s.openapi)),
|
|
s.servers.length ? el('div.oa-servers', {}, ...s.servers.map((u) => el('code', {}, u))) : null,
|
|
s.description ? el('div.oa-desc', {}, s.description.slice(0, 600)) : null),
|
|
el('div.oa-bar', {},
|
|
el('input.input', { placeholder: t('Search the operations'), value: this.query, oninput: (e) => { this.query = e.target.value; this.renderOps(); } }),
|
|
el('select.input', { title: t('Collection of the HTTP Client'), onchange: (e) => { this.target = e.target.value; } },
|
|
...colls.map((c) => el('option', { value: c.id, selected: c.id === this.target }, c.name)), el('option', { value: '', selected: !this.target }, t('A new collection'))),
|
|
el('button.btn', { title: t('A request file for each operation, a folder per tag'), onclick: () => this.importAll() }, t('Add All to the Collection'))));
|
|
this.opsNode = el('div.oa-ops');
|
|
this.node.append(this.opsNode);
|
|
this.renderOps();
|
|
}
|
|
|
|
renderOps() {
|
|
clear(this.opsNode);
|
|
const q = this.query.trim().toLowerCase();
|
|
let shown = 0;
|
|
for (const tag of this.spec.tags) {
|
|
const ops = tag.operations.filter((op) => !q || `${op.method} ${op.path} ${op.summary} ${op.operationId} ${tag.name}`.toLowerCase().includes(q));
|
|
if (!ops.length) continue;
|
|
shown += ops.length;
|
|
this.opsNode.append(el('div.oa-tag', {}, el('b', {}, tag.name), tag.description ? el('span.oa-desc', {}, tag.description) : null));
|
|
for (const op of ops) this.opsNode.append(this.operation(op));
|
|
}
|
|
if (!shown) this.opsNode.append(el('div.oa-empty', {}, t('No operation matches.')));
|
|
if (!q && this.spec.schemas.length) {
|
|
this.opsNode.append(el('div.oa-tag', {}, el('b', {}, t('Models'))));
|
|
for (const m of this.spec.schemas) {
|
|
const open = this.opened.has('model:' + m.name);
|
|
const box = el('div.oa-op');
|
|
box.append(el('div.oa-op-head', { onclick: () => { if (open) this.opened.delete('model:' + m.name); else this.opened.add('model:' + m.name); this.renderOps(); } },
|
|
el('span.oa-caret', {}, open ? '▾' : '▸'), el('span.oa-model', {}, m.name)));
|
|
if (open) box.append(el('div.oa-op-body', {}, el('div.oa-cols', {}, schemaTree(m.schema), example(m.example))));
|
|
this.opsNode.append(box);
|
|
}
|
|
}
|
|
}
|
|
|
|
operation(op) {
|
|
const open = this.opened.has(op.id);
|
|
const box = el(`div.oa-op${op.deprecated ? '.deprecated' : ''}`);
|
|
box.append(el('div.oa-op-head', { onclick: () => { if (open) this.opened.delete(op.id); else this.opened.add(op.id); this.renderOps(); } },
|
|
el(`span.hc-method.m-${op.method}`, {}, op.method), el('code.oa-path', {}, op.path), el('span.oa-summary', {}, op.summary),
|
|
op.security.length ? el('span.oa-lock', { title: t('Needs auth: {names}', { names: op.security.join(', ') }) }, icon('user')) : null,
|
|
el('button.btn.oa-try', { onclick: (e) => { e.stopPropagation(); this.tryIt(op); } }, t('Try it'))));
|
|
if (!open) return box;
|
|
const body = el('div.oa-op-body');
|
|
if (op.description) body.append(el('div.oa-desc', {}, op.description));
|
|
if (op.parameters.length) {
|
|
body.append(el('h5', {}, t('Parameters')), el('table.hc-table', {}, el('tbody', {}, ...op.parameters.map((p) => el('tr', {},
|
|
el('td', {}, el('b', {}, p.name), p.required ? el('span.oa-req', {}, '*') : null), el('td', {}, el('span.oa-tag', {}, p.in)), el('td', {}, el('code.oa-type', {}, TYPE(p.schema))),
|
|
el('td', {}, p.description || '', p.example !== null && p.example !== undefined && typeof p.example !== 'object' ? el('code.oa-ex', {}, String(p.example)) : null))))));
|
|
}
|
|
if (op.requestBody) {
|
|
body.append(el('h5', {}, t('Request body'), op.requestBody.required ? el('span.oa-req', {}, '*') : null));
|
|
for (const [type, media] of Object.entries(op.requestBody.content)) {
|
|
body.append(el('div.oa-media', {}, el('code', {}, type)), el('div.oa-cols', {}, schemaTree(media.schema), example(media.example)));
|
|
}
|
|
}
|
|
body.append(el('h5', {}, t('Answers')));
|
|
for (const resp of op.responses) {
|
|
body.append(el('div.oa-resp', {}, el(`span.hc-status.${resp.code.startsWith('2') ? 'ok' : resp.code.startsWith('3') ? 'redir' : resp.code.startsWith('4') ? 'warn' : 'err'}`, {}, resp.code),
|
|
el('span', {}, resp.description)));
|
|
for (const [type, media] of Object.entries(resp.content)) {
|
|
body.append(el('div.oa-media', {}, el('code', {}, type)), el('div.oa-cols', {}, schemaTree(media.schema), example(media.example)));
|
|
}
|
|
}
|
|
box.append(body);
|
|
return box;
|
|
}
|
|
|
|
async client() {
|
|
this.app.showTool('httpClient');
|
|
return this.app.httpClient.ready();
|
|
}
|
|
|
|
async ensureCollection() {
|
|
if (this.target) return this.target;
|
|
const { id } = await backend.invoke('http.collection.create', { name: this.spec.title.replace(/[^A-Za-z0-9 ._-]+/g, '-').slice(0, 60) || 'API' });
|
|
const base = this.spec.servers[0];
|
|
if (base) await backend.invoke('http.env.save', { collection: id, environments: { local: { vars: { baseUrl: base }, secrets: [] } }, secrets: {} });
|
|
this.target = id;
|
|
return id;
|
|
}
|
|
|
|
async tryIt(op) {
|
|
try {
|
|
const panel = await this.client();
|
|
const collection = await this.ensureCollection();
|
|
await panel.load();
|
|
const { request } = await backend.invoke('http.openapi.request', { source: this.source, id: op.id, collection });
|
|
panel.openDraft(request, collection);
|
|
this.render();
|
|
} catch (e) { notify(e.message, 'error', { title: 'OpenAPI' }); }
|
|
}
|
|
|
|
async importAll() {
|
|
try {
|
|
const collection = await this.ensureCollection();
|
|
const r = await backend.invoke('http.openapi.import', { source: this.source, collection });
|
|
notify(t('{n} requests added to the collection.', { n: r.imported }), 'success', { title: 'OpenAPI' });
|
|
const panel = await this.client();
|
|
panel.open.add(collection);
|
|
await panel.load();
|
|
this.render();
|
|
} catch (e) { notify(e.message, 'error', { title: 'OpenAPI' }); }
|
|
}
|
|
|
|
shown() { if (!this.found) this.find(); }
|
|
}
|