918 lines
58 KiB
JavaScript
918 lines
58 KiB
JavaScript
// The HTTP Client window (bottom): requests in collections (http-requests/<collection>/*.http, plain text files of the project, made
|
|
// to be committed), environments with {{variables}} (secret ones kept on this computer only), auth (bearer, basic, API key, OAuth2,
|
|
// JWT logged in and refreshed by itself), pre-request / post-response scripts and their tests (a Web Worker without network:
|
|
// http-script-worker.js), the history, the answer (status, time, size, headers, cookies, body pretty / raw / table / preview,
|
|
// JSONPath filter, search with Ctrl+F, copy as curl), import / export of .http and Bruno .bru files, and the collections shared
|
|
// with the members of the jumphp.net project. Requests are sent by the IDE's PHP: ide/src/HttpClient (HttpClientCommands).
|
|
import { backend } from './backend.js';
|
|
import { el, clear, icon, notify, prefs, t, confirm, prompt, dialog, menu, copyText, timeAgo } from './ui.js';
|
|
import { monaco } from './editor.js';
|
|
import { responsePreview } from './http-preview.js';
|
|
import { splitUrl, joinUrl, toCurl, prettyBody, headerValue, runScript, jsonPath, size } from './http-model.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 METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
|
|
const AUTH_TYPES = [['inherit', 'Inherit from the collection'], ['none', 'No auth'], ['bearer', 'Bearer token'], ['basic', 'Basic'], ['apikey', 'API key'],
|
|
['oauth2', 'OAuth2'], ['jwt', 'JWT (login request)']];
|
|
const BODY_TYPES = [['none', 'No body'], ['json', 'JSON'], ['xml', 'XML'], ['text', 'Text'], ['form', 'Form (urlencoded)']];
|
|
const CONTENT_TYPES = { json: 'application/json', xml: 'application/xml', text: 'text/plain', form: 'application/x-www-form-urlencoded' };
|
|
const EMPTY_RUN = { globals: {}, locals: {}, request: {}, tests: [], logs: [], error: null };
|
|
const SNIPPETS = [
|
|
['Test: the status is 200', 'client.test("status is 200", () => {\n client.assert(response.status === 200, "status " + response.status);\n});'],
|
|
['Test: the answer is JSON', 'client.test("JSON answer", () => {\n expect(response.contentType.mimeType).to.match(/json/);\n});'],
|
|
['Keep a value of the answer in a variable', 'client.global.set("id", response.body.id);'],
|
|
['Keep a value found with a JSONPath', 'client.global.set("token", jsonpath(response.body, "$.token")[0]);'],
|
|
['Log the answer', 'console.log(response.status, response.body);'],
|
|
];
|
|
|
|
/** A script in the sandbox (a Web Worker without network, stopped after 3 s). */
|
|
function sandbox(code, ctx) {
|
|
if (!String(code || '').trim()) return Promise.resolve(EMPTY_RUN);
|
|
return new Promise((resolve) => {
|
|
let worker;
|
|
try { worker = new Worker(new URL('./http-script-worker.js', import.meta.url), { type: 'module' }); } catch { resolve(runScript(code, ctx)); return; }
|
|
const timer = setTimeout(() => { worker.terminate(); resolve({ ...EMPTY_RUN, error: t('The script ran for more than 3 seconds: stopped.') }); }, 3000);
|
|
worker.onmessage = (e) => { clearTimeout(timer); worker.terminate(); resolve(e.data); };
|
|
worker.onerror = (e) => { e.preventDefault?.(); clearTimeout(timer); worker.terminate(); resolve(runScript(code, ctx)); };
|
|
worker.postMessage({ code, ctx });
|
|
});
|
|
}
|
|
|
|
const clone = (o) => JSON.parse(JSON.stringify(o));
|
|
const statusClass = (s) => (!s ? 'err' : s < 300 ? 'ok' : s < 400 ? 'redir' : s < 500 ? 'warn' : 'err');
|
|
|
|
/** The body's kind from its Content-Type header. */
|
|
function bodyType(req) {
|
|
if (!String(req.body || '').trim()) return 'none';
|
|
const ct = String(headerValue(req.headers, 'content-type') || '').toLowerCase();
|
|
if (ct.includes('json')) return 'json';
|
|
if (ct.includes('xml')) return 'xml';
|
|
if (ct.includes('x-www-form-urlencoded')) return 'form';
|
|
return /^\s*[[{]/.test(req.body) ? 'json' : 'text';
|
|
}
|
|
|
|
/** A small Monaco editor (a text area when Monaco is not there). */
|
|
function codeEditor(host, value, language, { readOnly = false, onChange, minimal = true } = {}) {
|
|
if (!monaco) {
|
|
const area = el('textarea.input.hc-fallback', { value, spellcheck: false, readOnly, oninput: () => onChange?.(area.value) });
|
|
host.append(area);
|
|
return { getValue: () => area.value, setValue: (v) => { area.value = v; }, dispose: () => null, layout: () => null, setLanguage: () => null };
|
|
}
|
|
const model = monaco.editor.createModel(value, language);
|
|
const editor = monaco.editor.create(host, {
|
|
model, readOnly, minimap: { enabled: false }, lineNumbers: minimal ? 'off' : 'on', glyphMargin: false, folding: !minimal, scrollBeyondLastLine: false,
|
|
automaticLayout: true, fontSize: 12.5, renderLineHighlight: 'none', overviewRulerLanes: 0, tabSize: 2, wordWrap: 'on',
|
|
theme: document.documentElement.dataset.theme === 'light' ? 'jumphp-light' : 'jumphp-dark',
|
|
});
|
|
if (onChange) model.onDidChangeContent(() => onChange(model.getValue()));
|
|
return { editor, getValue: () => model.getValue(), setValue: (v) => model.setValue(v), dispose: () => { editor.dispose(); model.dispose(); },
|
|
layout: () => editor.layout(), setLanguage: (l) => monaco.editor.setModelLanguage(model, l) };
|
|
}
|
|
|
|
/** Name / value rows (headers, query parameters, form fields, variables), edited in place; an empty last row adds one. */
|
|
export function kvTable(rows, onChange, { keyLabel = 'Name', valueLabel = 'Value', secret } = {}) {
|
|
const box = el('div.hc-kv');
|
|
const draw = () => {
|
|
clear(box);
|
|
box.append(el('div.hc-kv-row.head', {}, el('span', {}, t(keyLabel)), el('span', {}, t(valueLabel)), secret ? el('span.hc-kv-flag', {}, t('Secret')) : null, el('span.hc-kv-del')));
|
|
[...rows, null].forEach((row, i) => {
|
|
const isNew = row === null;
|
|
const r = row || ['', ''];
|
|
const key = el('input.input', { value: r[0], placeholder: isNew ? t('Add…') : '', spellcheck: false, oninput: (e) => {
|
|
if (isNew) { rows.push([e.target.value, '']); onChange(); draw(); box.querySelectorAll('.hc-kv-row')[i + 1]?.querySelector('input')?.focus(); return; }
|
|
r[0] = e.target.value; onChange();
|
|
} });
|
|
const isSecret = secret?.has(r[0]);
|
|
const value = el('input.input', { value: r[1], type: isSecret ? 'password' : 'text', placeholder: isSecret && secret.stored?.(r[0]) ? t('kept on this computer') : '', spellcheck: false, disabled: isNew,
|
|
oninput: (e) => { r[1] = e.target.value; onChange(); } });
|
|
box.append(el('div.hc-kv-row', {}, key, value,
|
|
secret ? el('label.hc-kv-flag', { title: t('Secret: its value is kept on this computer only, never in the project') },
|
|
el('input', { type: 'checkbox', checked: !!isSecret, disabled: isNew, onchange: (e) => { secret.toggle(r[0], e.target.checked); onChange(); draw(); } })) : null,
|
|
isNew ? el('span.hc-kv-del') : el('button.icon-btn.hc-kv-del', { title: t('Remove'), onclick: () => { rows.splice(rows.indexOf(row), 1); onChange(); draw(); } }, icon('close'))));
|
|
});
|
|
};
|
|
draw();
|
|
return box;
|
|
}
|
|
|
|
/** The auth's fields (a request's, or a collection's default). */
|
|
function authEditor(auth, onChange, { inherit = true, requests = [], status } = {}) {
|
|
const box = el('div.hc-auth');
|
|
const field = (key, label, { type = 'text', placeholder = '', options } = {}) => {
|
|
const input = options
|
|
? el('select.input', { onchange: (e) => { auth[key] = e.target.value; onChange(); draw(); } }, ...options.map(([v, l]) => el('option', { value: v, selected: (auth[key] ?? options[0][0]) === v }, t(l))))
|
|
: el('input.input', { value: auth[key] ?? '', type, placeholder, spellcheck: false, oninput: (e) => { auth[key] = e.target.value; onChange(); } });
|
|
return el('label.hc-field', {}, el('span', {}, t(label)), input);
|
|
};
|
|
const draw = () => {
|
|
clear(box);
|
|
box.append(field('type', 'Type', { options: AUTH_TYPES.filter(([v]) => inherit || v !== 'inherit') }));
|
|
const type = auth.type || 'inherit';
|
|
if (type === 'bearer') box.append(field('token', 'Token', { placeholder: '{{token}}' }));
|
|
if (type === 'basic') box.append(field('username', 'User name', { placeholder: '{{username}}' }), field('password', 'Password', { placeholder: '{{password}}' }));
|
|
if (type === 'apikey') {
|
|
box.append(field('in', 'Sent in', { options: [['header', 'A header'], ['query', 'The query string']] }), field('name', 'Name', { placeholder: 'X-API-Key' }),
|
|
field('value', 'Value', { placeholder: '{{apiKey}}' }));
|
|
}
|
|
if (type === 'oauth2') {
|
|
box.append(field('grant', 'Grant', { options: [['client_credentials', 'Client credentials'], ['password', 'Password']] }),
|
|
field('tokenUrl', 'Token URL', { placeholder: 'https://auth.example.com/oauth/token' }), field('clientId', 'Client id', { placeholder: '{{clientId}}' }),
|
|
field('clientSecret', 'Client secret', { placeholder: '{{clientSecret}}' }), field('scope', 'Scope'),
|
|
field('clientAuth', 'Client sent', { options: [['body', 'In the body'], ['basic', 'As Basic auth']] }));
|
|
if (auth.grant === 'password') box.append(field('username', 'User name', { placeholder: '{{username}}' }), field('password', 'Password', { placeholder: '{{password}}' }));
|
|
}
|
|
if (type === 'jwt') {
|
|
box.append(field('login', 'Login request', { options: [['', '—'], ...requests.map((r) => [r.path, `${r.method} ${r.name}`])] }),
|
|
field('path', 'Token in the answer (JSONPath)', { placeholder: '$.token' }), field('var', 'Kept in the variable', { placeholder: 'token' }),
|
|
field('header', 'Header', { placeholder: 'Authorization' }), field('prefix', 'Prefix', { placeholder: 'Bearer' }),
|
|
el('p.hc-hint', {}, t('The login request is sent when there is no token yet, when its "exp" is past, or once when the API answers 401. The token is kept on this computer only.')));
|
|
}
|
|
if (type !== 'inherit' && type !== 'none') box.append(el('p.hc-hint', {}, t('Write {{variables}} here: the secret ones (Environments…) never go into the project.')));
|
|
if (status) box.append(status);
|
|
};
|
|
draw();
|
|
return box;
|
|
}
|
|
|
|
export class HttpClientPanel {
|
|
constructor(app) {
|
|
this.app = app;
|
|
this.node = el('div.hc-view', { tabindex: -1 });
|
|
this.data = { collections: [] };
|
|
this.tabs = [];
|
|
this.current = null;
|
|
this.side = prefs.get('httpSide', 'collections');
|
|
this.subTab = 'params';
|
|
this.respTab = 'body';
|
|
this.respMode = 'pretty';
|
|
this.open = new Set(prefs.get(`httpOpen:${app.projectKey}`, []));
|
|
this.node.addEventListener('keydown', (e) => {
|
|
if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); e.stopPropagation(); this.save(); }
|
|
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); this.send(); }
|
|
});
|
|
this.sideNode = el('div.hc-side');
|
|
this.reqNode = el('div.hc-request');
|
|
this.respNode = el('div.hc-response');
|
|
this.node.append(this.toolbar(), el('div.hc-main', {}, this.sideNode, this.reqNode, this.respNode));
|
|
this.load();
|
|
}
|
|
|
|
title() { return 'HTTP Client'; }
|
|
|
|
// data ----------------------------------------------------------------------------------------------------------
|
|
|
|
async load() {
|
|
try { this.data = await backend.invoke('http.list'); } catch (e) { this.data = { collections: [], error: e.message }; }
|
|
this.renderToolbar();
|
|
this.renderSide();
|
|
if (!this.current) this.renderRequest();
|
|
}
|
|
|
|
/** "Refresh from the API": the organised collection made / updated from the code or the OpenAPI description, then a summary. */
|
|
async refreshApi() {
|
|
this.refreshing = true;
|
|
this.renderToolbar();
|
|
try {
|
|
const r = await backend.invoke('http.api.refresh', { collection: 'API' });
|
|
const n = r.summary;
|
|
notify(t('{added} added, {updated} updated, {kept} kept (edited by you), {removed} removed, {unchanged} unchanged.', n), 'success', { title: t('Collection {name}', { name: r.collection }) });
|
|
this.open.add(r.collection);
|
|
prefs.set(`httpOpen:${this.app.projectKey}`, [...this.open]);
|
|
} catch (e) { notify(e.message, 'error', { title: t('Refresh from the API (OpenAPI / API Platform)') }); }
|
|
this.refreshing = false;
|
|
await this.load();
|
|
}
|
|
|
|
collection(id) { return this.data.collections.find((c) => c.id === id); }
|
|
|
|
envOf(collection) {
|
|
const c = this.collection(collection);
|
|
const saved = prefs.get(`httpEnv:${this.app.projectKey}:${collection}`, null);
|
|
return c?.environments.includes(saved) ? saved : (c?.environments[0] || '');
|
|
}
|
|
|
|
setEnv(collection, env) { prefs.set(`httpEnv:${this.app.projectKey}:${collection}`, env); this.renderToolbar(); }
|
|
|
|
/** The requests of a collection, flat (the JWT login chooser). */
|
|
requestsOf(collection) {
|
|
const out = [];
|
|
const walk = (items) => items.forEach((i) => (i.type === 'folder' ? walk(i.items) : out.push(i)));
|
|
walk(this.collection(collection)?.items || []);
|
|
return out;
|
|
}
|
|
|
|
// tool bar ------------------------------------------------------------------------------------------------------
|
|
|
|
toolbar() {
|
|
this.toolNode = el('div.hc-toolbar');
|
|
return this.toolNode;
|
|
}
|
|
|
|
renderToolbar() {
|
|
clear(this.toolNode);
|
|
const coll = this.current?.collection || this.data.collections[0]?.id || '';
|
|
const c = this.collection(coll);
|
|
const envSelect = el('select.input.hc-env', { title: t('Environment'), disabled: !c, onchange: (e) => this.setEnv(coll, e.target.value) },
|
|
...(c?.environments.length ? c.environments.map((n) => el('option', { value: n, selected: n === this.envOf(coll) }, n)) : [el('option', { value: '' }, t('No environment'))]));
|
|
this.toolNode.append(
|
|
el('button.btn', { onclick: () => this.newRequest() }, icon('plus'), t('New Request')),
|
|
el('button.btn.primary', { 'data-tour': 'http-refresh-api', title: t('One organised collection: a folder per resource, a request per operation, from API Platform or the OpenAPI description. Your edited requests are kept.'),
|
|
disabled: !!this.refreshing, onclick: () => this.refreshApi() }, icon('refresh'), this.refreshing ? t('Refreshing…') : t('Refresh from the API (OpenAPI / API Platform)')),
|
|
el('button.icon-btn', { title: t('New Collection…'), onclick: () => this.newCollection() }, icon('folder')),
|
|
el('button.icon-btn', { title: t('Import…'), onclick: () => this.importDialog(coll) }, icon('download')),
|
|
el('span.hc-spacer'),
|
|
el('span.hc-label', {}, c ? c.name : ''),
|
|
envSelect,
|
|
el('button.icon-btn', { title: t('Environments…'), disabled: !c, onclick: () => this.environments(coll) }, icon('settings')),
|
|
el('button.icon-btn', { title: t('OpenAPI Viewer'), onclick: () => this.app.showTool?.('openapi') }, icon('library')),
|
|
el('button.icon-btn', { title: t('Refresh'), onclick: () => this.load() }, icon('refresh')),
|
|
);
|
|
}
|
|
|
|
// the side: collections and history ------------------------------------------------------------------------------
|
|
|
|
renderSide() {
|
|
clear(this.sideNode);
|
|
const tabs = el('div.hc-tabs', {}, ...[['collections', 'Collections'], ['history', 'History']].map(([id, label]) =>
|
|
el(`button.hc-tab${this.side === id ? '.on' : ''}`, { onclick: () => { this.side = id; prefs.set('httpSide', id); this.renderSide(); } }, t(label))));
|
|
const body = el('div.hc-side-body');
|
|
this.sideNode.append(tabs, body);
|
|
if (this.side === 'history') { this.renderHistory(body); return; }
|
|
if (this.data.error) body.append(el('div.hc-error', {}, this.data.error));
|
|
if (!this.data.collections.length) {
|
|
body.append(el('div.hc-empty', {}, el('p', {}, t('No collection yet. A collection is a folder of request files in {dir}/, made to be committed.', { dir: this.data.dir || 'http-requests' })),
|
|
el('button.btn.primary', { onclick: () => this.newCollection() }, t('New Collection…')),
|
|
el('button.btn', { onclick: () => this.app.showTool?.('openapi') }, t('From an OpenAPI description…'))));
|
|
return;
|
|
}
|
|
for (const c of this.data.collections) {
|
|
const key = c.id;
|
|
const opened = this.open.has(key) || this.data.collections.length === 1;
|
|
body.append(el('div.hc-row.coll', { onclick: () => this.toggle(key), oncontextmenu: (e) => { e.preventDefault(); this.collectionMenu(c, e); } },
|
|
el('span.hc-caret', {}, opened ? '▾' : '▸'), icon('folder'), el('span.hc-name', {}, c.name),
|
|
c.settings?.share?.project ? el('span.hc-shared', { title: t('Shared with the members of {project}', { project: c.settings.share.project }) }, icon('user')) : null,
|
|
el('button.icon-btn.hc-more', { title: t('More'), onclick: (e) => { e.stopPropagation(); this.collectionMenu(c, e); } }, icon('more'))));
|
|
if (opened) this.renderItems(body, c, c.items, 1);
|
|
}
|
|
}
|
|
|
|
toggle(key) {
|
|
if (this.open.has(key)) this.open.delete(key); else this.open.add(key);
|
|
prefs.set(`httpOpen:${this.app.projectKey}`, [...this.open]);
|
|
this.renderSide();
|
|
}
|
|
|
|
renderItems(body, c, items, depth) {
|
|
for (const item of items) {
|
|
const pad = { paddingLeft: `${depth * 14 + 4}px` };
|
|
if (item.type === 'folder') {
|
|
const key = `${c.id}/${item.path}`;
|
|
const opened = this.open.has(key);
|
|
body.append(el('div.hc-row', { style: pad, 'data-tour': 'http-folder-' + item.name, onclick: () => this.toggle(key), oncontextmenu: (e) => { e.preventDefault(); this.itemMenu(c, item, e); } },
|
|
el('span.hc-caret', {}, opened ? '▾' : '▸'), icon('folder'), el('span.hc-name', {}, item.name)));
|
|
if (opened) this.renderItems(body, c, item.items, depth + 1);
|
|
} else {
|
|
const sel = this.current?.collection === c.id && this.current?.path === item.path;
|
|
body.append(el(`div.hc-row${sel ? '.sel' : ''}`, { style: pad, title: item.path, 'data-tour': 'http-request-' + item.method, onclick: () => this.openRequest(c.id, item.path),
|
|
oncontextmenu: (e) => { e.preventDefault(); this.itemMenu(c, item, e); } },
|
|
el('span.hc-caret'), el(`span.hc-method.m-${item.method}`, {}, item.method), el('span.hc-name', {}, item.name)));
|
|
}
|
|
}
|
|
}
|
|
|
|
collectionMenu(c, e) {
|
|
menu([
|
|
{ label: t('New Request'), icon: 'plus', action: () => this.newRequest(c.id) },
|
|
{ label: t('New Folder…'), icon: 'folder', action: () => this.newFolder(c.id, '') },
|
|
{ label: t('Collection Settings (Auth, Headers)…'), icon: 'settings', action: () => this.collectionSettings(c.id) },
|
|
{ label: t('Environments…'), icon: 'globe', action: () => this.environments(c.id) },
|
|
'-',
|
|
{ label: t('Share with the Project\'s Members…'), icon: 'user', action: () => this.shareDialog(c.id) },
|
|
c.settings?.share?.project ? { label: t('Sync Now'), icon: 'refresh', action: () => this.sync(c.id) } : null,
|
|
'-',
|
|
{ label: t('Import…'), icon: 'download', action: () => this.importDialog(c.id) },
|
|
{ label: t('Export as .http'), icon: 'upload', action: () => this.exportDialog(c.id, '', 'http') },
|
|
{ label: t('Export as .bru (Bruno)'), icon: 'upload', action: () => this.exportDialog(c.id, '', 'bru') },
|
|
{ label: t('Forget the Tokens and Script Values'), icon: 'logout', action: () => this.logout(c.id) },
|
|
'-',
|
|
{ label: t('Rename…'), icon: 'edit', action: () => this.renameCollection(c) },
|
|
{ label: t('Delete'), icon: 'trash', action: () => this.deleteCollection(c) },
|
|
].filter(Boolean), e);
|
|
}
|
|
|
|
itemMenu(c, item, e) {
|
|
const folder = item.type === 'folder';
|
|
menu([
|
|
folder ? { label: t('New Request'), icon: 'plus', action: () => this.newRequest(c.id, item.path) } : { label: t('Open'), icon: 'file', action: () => this.openRequest(c.id, item.path) },
|
|
folder ? { label: t('New Folder…'), icon: 'folder', action: () => this.newFolder(c.id, item.path + '/') } : { label: t('Duplicate'), icon: 'copy', action: () => this.duplicate(c.id, item.path) },
|
|
folder ? null : { label: t('Open as Text'), icon: 'code', action: () => this.app.editors?.open(`${this.data.dir}/${c.id}/${item.path}`) },
|
|
{ label: t('Export as .http'), icon: 'upload', action: () => this.exportDialog(c.id, item.path, 'http') },
|
|
{ label: t('Export as .bru (Bruno)'), icon: 'upload', action: () => this.exportDialog(c.id, item.path, 'bru') },
|
|
'-',
|
|
{ label: t('Rename…'), icon: 'edit', action: () => this.renameItem(c.id, item) },
|
|
{ label: t('Delete'), icon: 'trash', action: async () => {
|
|
if (!(await confirm(t('Delete {name}?', { name: item.name }), item.path, { ok: t('Delete'), danger: true }))) return;
|
|
await backend.invoke('http.remove', { collection: c.id, path: item.path });
|
|
this.tabs = this.tabs.filter((tb) => !(tb.collection === c.id && (tb.path === item.path || tb.path?.startsWith(item.path + '/'))));
|
|
if (this.current && !this.tabs.includes(this.current)) this.current = this.tabs[0] || null;
|
|
await this.load();
|
|
this.renderRequest();
|
|
} },
|
|
].filter(Boolean), e);
|
|
}
|
|
|
|
async renderHistory(body) {
|
|
let entries = [];
|
|
try { entries = (await backend.invoke('http.history')).entries; } catch (e) { body.append(el('div.hc-error', {}, e.message)); return; }
|
|
body.append(el('div.hc-side-tools', {}, el('span.hc-hint', {}, t('On this computer only, secrets masked.')),
|
|
entries.length ? el('button.icon-btn', { title: t('Clear the History'), onclick: async () => { await backend.invoke('http.history.clear'); this.renderSide(); } }, icon('trash')) : null));
|
|
if (!entries.length) body.append(el('div.hc-empty', {}, t('No request sent yet.')));
|
|
for (const e of entries) {
|
|
body.append(el('div.hc-row.hist', { title: e.request.url, onclick: () => this.openHistory(e.id) },
|
|
el(`span.hc-method.m-${e.request.method}`, {}, e.request.method),
|
|
el('span.hc-name', {}, e.name || e.request.url.replace(/^https?:\/\/[^/]+/, '')),
|
|
el(`span.hc-status.${statusClass(e.response.status)}`, {}, e.response.status || '—'),
|
|
el('span.hc-ago', {}, timeAgo(Math.max(0, Date.now() / 1000 - e.time)))));
|
|
}
|
|
}
|
|
|
|
async openHistory(id) {
|
|
const { entry } = await backend.invoke('http.history.get', { id });
|
|
if (!entry) return;
|
|
const req = { name: entry.name || t('From the history'), method: entry.request.method, url: entry.request.url, headers: entry.request.headers.filter(([n]) => !/^(host|content-length|connection|user-agent|accept-encoding)$/i.test(n)),
|
|
body: entry.request.body, auth: { type: 'none' }, pre: '', post: '', options: { redirects: true, verify: true, timeout: null }, vars: {}, description: '', seq: 0 };
|
|
const tab = this.addTab({ collection: entry.collection || this.data.collections[0]?.id || '', path: null, request: req, saved: null });
|
|
tab.response = { request: entry.request, response: { ...entry.response, binary: false }, missing: [], auth: {} };
|
|
this.renderRequest();
|
|
this.renderResponse();
|
|
}
|
|
|
|
// tabs ------------------------------------------------------------------------------------------------------------
|
|
|
|
addTab(tab) {
|
|
tab.id = 'h' + Math.random().toString(36).slice(2);
|
|
tab.response = null;
|
|
tab.run = null;
|
|
this.tabs.push(tab);
|
|
if (this.tabs.length > 10) this.tabs.splice(this.tabs.findIndex((x) => x !== tab && !this.dirty(x)), 1);
|
|
this.current = tab;
|
|
return tab;
|
|
}
|
|
|
|
dirty(tab) { return tab.saved === null || JSON.stringify(tab.request) !== tab.saved; }
|
|
|
|
async openRequest(collection, path) {
|
|
let tab = this.tabs.find((x) => x.collection === collection && x.path === path);
|
|
if (!tab) {
|
|
try {
|
|
const { request } = await backend.invoke('http.request.read', { collection, path });
|
|
delete request.path;
|
|
tab = this.addTab({ collection, path, request, saved: JSON.stringify(request) });
|
|
} catch (e) { notify(e.message, 'error', { title: 'HTTP Client' }); return; }
|
|
}
|
|
this.current = tab;
|
|
this.renderToolbar();
|
|
this.renderSide();
|
|
this.renderRequest();
|
|
this.renderResponse();
|
|
}
|
|
|
|
/** A request made elsewhere (the OpenAPI viewer's Try it), not saved yet. */
|
|
openDraft(request, collection) {
|
|
this.addTab({ collection: collection || this.data.collections[0]?.id || '', path: null, request, saved: null });
|
|
this.subTab = request.body ? 'body' : 'params';
|
|
this.renderToolbar();
|
|
this.renderRequest();
|
|
this.renderResponse();
|
|
}
|
|
|
|
closeTab(tab) {
|
|
const i = this.tabs.indexOf(tab);
|
|
this.tabs.splice(i, 1);
|
|
if (this.current === tab) this.current = this.tabs[Math.min(i, this.tabs.length - 1)] || null;
|
|
this.renderSide();
|
|
this.renderRequest();
|
|
this.renderResponse();
|
|
}
|
|
|
|
// the request -----------------------------------------------------------------------------------------------------
|
|
|
|
renderRequest() {
|
|
for (const ed of this.editors || []) ed.dispose();
|
|
this.editors = [];
|
|
clear(this.reqNode);
|
|
const strip = el('div.hc-reqtabs', {}, ...this.tabs.map((tb) => el(`div.hc-reqtab${tb === this.current ? '.on' : ''}`, { title: tb.path || '', onclick: () => {
|
|
this.current = tb; this.renderToolbar(); this.renderSide(); this.renderRequest(); this.renderResponse();
|
|
} }, el(`span.hc-method.m-${tb.request.method}`, {}, tb.request.method), el('span', {}, tb.request.name), this.dirty(tb) ? el('span.hc-dot', { title: t('Not saved') }, '●') : null,
|
|
el('button.icon-btn', { title: t('Close'), onclick: (e) => { e.stopPropagation(); this.closeTab(tb); } }, icon('close')))));
|
|
this.reqNode.append(strip);
|
|
const tab = this.current;
|
|
if (!tab) {
|
|
this.reqNode.append(el('div.hc-empty', {}, t('Choose a request, or make a new one (Ctrl+Enter sends it, Ctrl+S saves it).')));
|
|
return;
|
|
}
|
|
const r = tab.request;
|
|
const changed = () => { this.refreshDirty(); };
|
|
const methodSel = el('select.input.hc-method-sel', { onchange: (e) => { r.method = e.target.value; changed(); this.renderSide(); } },
|
|
...[...new Set([...METHODS, r.method])].map((m) => el('option', { value: m, selected: m === r.method }, m)));
|
|
const url = el('input.input.hc-url', { value: r.url, spellcheck: false, placeholder: '{{baseUrl}}/api/…', oninput: (e) => { r.url = e.target.value; changed(); if (this.subTab === 'params') this.drawSub(); } });
|
|
const sendBtn = el('button.btn.primary.hc-send', { 'data-tour': 'http-send', onclick: () => (tab.sending ? this.cancel() : this.send()) }, tab.sending ? t('Cancel') : t('Send'));
|
|
this.sendBtn = sendBtn;
|
|
const name = el('input.input.hc-reqname', { value: r.name, spellcheck: false, oninput: (e) => { r.name = e.target.value; changed(); } });
|
|
this.reqNode.append(
|
|
el('div.hc-line', {}, name, el('button.btn', { title: 'Ctrl+S', onclick: () => this.save() }, t('Save')),
|
|
el('button.icon-btn', { title: t('More'), onclick: (e) => menu([
|
|
{ label: t('Copy as curl'), icon: 'copy', action: () => this.copyCurl() },
|
|
{ label: t('Show the .http Text'), icon: 'code', action: () => this.showText() },
|
|
], e) }, icon('more'))),
|
|
el('div.hc-line', {}, methodSel, url, sendBtn));
|
|
const subs = [['params', 'Params'], ['headers', 'Headers'], ['body', 'Body'], ['auth', 'Auth'], ['scripts', 'Scripts'], ['settings', 'Settings']];
|
|
const count = { params: splitUrl(r.url).params.length, headers: r.headers.length, body: r.body ? '●' : '', scripts: (r.pre ? 1 : 0) + (r.post ? 1 : 0) || '',
|
|
auth: r.auth?.type && r.auth.type !== 'inherit' ? '●' : '' };
|
|
this.reqNode.append(el('div.hc-tabs', {}, ...subs.map(([id, label]) => el(`button.hc-tab${this.subTab === id ? '.on' : ''}`, { onclick: () => { this.subTab = id; this.renderRequest(); } },
|
|
t(label), count[id] ? el('span.hc-count', {}, String(count[id])) : null))));
|
|
this.subNode = el('div.hc-sub');
|
|
this.reqNode.append(this.subNode);
|
|
this.drawSub();
|
|
}
|
|
|
|
refreshDirty() {
|
|
const tab = this.current;
|
|
const on = this.reqNode.querySelector('.hc-reqtab.on');
|
|
if (!tab || !on) return;
|
|
on.querySelector('.hc-dot')?.remove();
|
|
if (this.dirty(tab)) on.insertBefore(el('span.hc-dot', { title: t('Not saved') }, '●'), on.lastChild);
|
|
}
|
|
|
|
drawSub() {
|
|
const tab = this.current;
|
|
const r = tab.request;
|
|
for (const ed of this.subEditors || []) ed.dispose();
|
|
this.subEditors = [];
|
|
clear(this.subNode);
|
|
const changed = () => this.refreshDirty();
|
|
if (this.subTab === 'params') {
|
|
const u = splitUrl(r.url);
|
|
const rows = u.params;
|
|
this.subNode.append(kvTable(rows, () => {
|
|
r.url = joinUrl(u.base, rows, u.hash);
|
|
const input = this.reqNode.querySelector('.hc-url');
|
|
if (input) input.value = r.url;
|
|
changed();
|
|
}));
|
|
const vars = [...new Set([...r.url.matchAll(/\{\{\s*([^{}$]+?)\s*\}\}/g)].map((m) => m[1]))];
|
|
if (vars.length) this.subNode.append(el('p.hc-hint', {}, t('Variables: {names}', { names: vars.join(', ') })));
|
|
// the request's own variables (a path parameter of an OpenAPI operation: "@id = 1"), edited here
|
|
r.vars = r.vars && typeof r.vars === 'object' && !Array.isArray(r.vars) ? r.vars : {};
|
|
const own = Object.keys(r.vars);
|
|
if (own.length) {
|
|
this.subNode.append(el('div.hc-section', {}, t('Request variables')));
|
|
for (const name of own) {
|
|
const input = el('input.input', { value: String(r.vars[name] ?? ''), spellcheck: 'false', 'aria-label': name });
|
|
input.addEventListener('input', () => { r.vars[name] = input.value; changed(); });
|
|
this.subNode.append(el('label.hc-row', {}, el('code', {}, `{{${name}}}`), input));
|
|
}
|
|
}
|
|
} else if (this.subTab === 'headers') {
|
|
this.subNode.append(kvTable(r.headers, changed));
|
|
const c = this.collection(tab.collection);
|
|
if (c?.settings?.headers?.length) this.subNode.append(el('p.hc-hint', {}, t('And the collection\'s: {names}', { names: c.settings.headers.map((h) => h[0]).join(', ') })));
|
|
} else if (this.subTab === 'body') {
|
|
const type = bodyType(r);
|
|
const setType = (next) => {
|
|
r.headers = r.headers.filter(([n]) => n.toLowerCase() !== 'content-type');
|
|
if (next !== 'none') r.headers.push(['Content-Type', CONTENT_TYPES[next]]);
|
|
if (next === 'none') r.body = '';
|
|
else if (next === 'json' && !r.body.trim()) r.body = '{\n \n}';
|
|
changed();
|
|
this.drawSub();
|
|
};
|
|
this.subNode.append(el('div.hc-line', {}, el('select.input', { onchange: (e) => setType(e.target.value) },
|
|
...BODY_TYPES.map(([v, l]) => el('option', { value: v, selected: v === type }, t(l)))),
|
|
type === 'json' ? el('button.btn', { onclick: () => { try { r.body = JSON.stringify(JSON.parse(r.body), null, 2); this.drawSub(); changed(); } catch (e) { notify(e.message, 'error'); } } }, t('Format')) : null));
|
|
if (type === 'form') {
|
|
const rows = r.body.split('&').filter(Boolean).map((p) => p.split('=').map((s) => { try { return decodeURIComponent(s.replace(/\+/g, ' ')); } catch { return s; } }));
|
|
this.subNode.append(kvTable(rows, () => {
|
|
r.body = rows.filter(([k]) => k).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v ?? '').replace(/%7B%7B/g, '{{').replace(/%7D%7D/g, '}}')}`).join('&');
|
|
changed();
|
|
}));
|
|
} else if (type !== 'none') {
|
|
const host = el('div.hc-code');
|
|
this.subNode.append(host);
|
|
this.subEditors.push(codeEditor(host, r.body, type === 'text' ? 'plaintext' : type, { onChange: (v) => { r.body = v; changed(); } }));
|
|
} else {
|
|
this.subNode.append(el('p.hc-hint', {}, t('This request has no body.')));
|
|
}
|
|
} else if (this.subTab === 'auth') {
|
|
r.auth ||= { type: 'inherit' };
|
|
const status = el('div.hc-auth-status');
|
|
this.subNode.append(authEditor(r.auth, changed, { requests: this.requestsOf(tab.collection), status }));
|
|
const c = this.collection(tab.collection);
|
|
if ((r.auth.type || 'inherit') === 'inherit') {
|
|
status.append(el('p.hc-hint', {}, t('The collection\'s auth: {type}.', { type: c?.settings?.auth?.type || 'none' })),
|
|
c ? el('button.btn', { onclick: () => this.collectionSettings(c.id) }, t('Collection Settings (Auth, Headers)…')) : null);
|
|
}
|
|
if (tab.response?.auth?.expires) status.append(el('p.hc-hint', {}, t('Token valid until {time}.', { time: new Date(tab.response.auth.expires * 1000).toLocaleTimeString() })));
|
|
if (c) status.append(el('button.btn', { onclick: () => this.logout(c.id) }, t('Forget the Tokens and Script Values')));
|
|
} else if (this.subTab === 'scripts') {
|
|
for (const [key, label, phase] of [['pre', 'Before the request (pre-request script)', 'pre'], ['post', 'After the answer (post-response script, tests)', 'post']]) {
|
|
const host = el('div.hc-code.small');
|
|
this.subNode.append(el('div.hc-line', {}, el('b', {}, t(label)), el('span.hc-spacer'),
|
|
phase === 'post' ? el('button.btn', { onclick: (e) => menu(SNIPPETS.map(([l, code]) => ({ label: t(l), action: () => {
|
|
r.post = (r.post ? r.post.replace(/\s*$/, '\n\n') : '') + code; changed(); this.drawSub();
|
|
} })), e) }, t('Snippets')) : null), host);
|
|
this.subEditors.push(codeEditor(host, r[key] || '', 'javascript', { onChange: (v) => { r[key] = v; changed(); } }));
|
|
}
|
|
this.subNode.append(el('p.hc-hint', {}, t('client.global.set(name, value) keeps a variable for the environment (on this computer); client.test(name, fn) and expect() make tests; response.body is the answer (JSON parsed). Bruno\'s bru / res / test work too. The scripts run without network.')));
|
|
} else if (this.subTab === 'settings') {
|
|
r.options ||= {};
|
|
const check = (key, label) => el('label.hc-check', {}, el('input', { type: 'checkbox', checked: r.options[key] !== false, onchange: (e) => { r.options[key] = e.target.checked; changed(); } }), t(label));
|
|
this.subNode.append(check('redirects', 'Follow redirects'), check('verify', 'Check TLS certificates (off: a local site\'s own certificate)'),
|
|
el('label.hc-field', {}, el('span', {}, t('Timeout (seconds)')), el('input.input', { type: 'number', min: 1, value: r.options.timeout || '', placeholder: '30',
|
|
oninput: (e) => { r.options.timeout = Number(e.target.value) || null; changed(); } })),
|
|
el('label.hc-field', {}, el('span', {}, t('Description')), el('textarea.input', { rows: 4, value: r.description || '', oninput: (e) => { r.description = e.target.value; changed(); } })));
|
|
}
|
|
}
|
|
|
|
async save() {
|
|
const tab = this.current;
|
|
if (!tab) return;
|
|
try {
|
|
if (!tab.collection || !this.collection(tab.collection)) {
|
|
const id = this.data.collections[0]?.id || (await backend.invoke('http.collection.create', { name: 'API' })).id;
|
|
tab.collection = id;
|
|
}
|
|
if (tab.path) await backend.invoke('http.request.save', { collection: tab.collection, path: tab.path, request: tab.request });
|
|
else tab.path = (await backend.invoke('http.request.add', { collection: tab.collection, folder: tab.folder || '', request: tab.request })).path;
|
|
tab.saved = JSON.stringify(tab.request);
|
|
await this.load();
|
|
this.renderRequest();
|
|
} catch (e) { notify(e.message, 'error', { title: 'HTTP Client' }); }
|
|
}
|
|
|
|
async newRequest(collection, folder = '') {
|
|
collection ||= this.current?.collection || this.data.collections[0]?.id;
|
|
if (!collection) collection = (await backend.invoke('http.collection.create', { name: 'API' })).id;
|
|
const name = await prompt(t('New Request'), { value: t('New request') });
|
|
if (!name) return;
|
|
const request = { name, method: 'GET', url: '{{baseUrl}}/', headers: [], body: '', auth: { type: 'inherit' }, pre: '', post: '', options: { redirects: true, verify: true, timeout: null }, vars: {}, description: '', seq: 0 };
|
|
const { path } = await backend.invoke('http.request.add', { collection, folder, request });
|
|
this.open.add(collection);
|
|
if (folder) this.open.add(`${collection}/${folder.replace(/\/$/, '')}`);
|
|
await this.load();
|
|
this.subTab = 'params';
|
|
await this.openRequest(collection, path);
|
|
this.reqNode.querySelector('.hc-url')?.focus();
|
|
}
|
|
|
|
async duplicate(collection, path) {
|
|
const { request } = await backend.invoke('http.request.read', { collection, path });
|
|
delete request.path;
|
|
request.name += ' ' + t('(copy)');
|
|
const folder = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';
|
|
const r = await backend.invoke('http.request.add', { collection, folder, request });
|
|
await this.load();
|
|
this.openRequest(collection, r.path);
|
|
}
|
|
|
|
async newFolder(collection, parent) {
|
|
const name = await prompt(t('New Folder…'));
|
|
if (!name) return;
|
|
await backend.invoke('http.folder.add', { collection, path: parent + name });
|
|
this.open.add(collection);
|
|
this.load();
|
|
}
|
|
|
|
async newCollection() {
|
|
const name = await prompt(t('New Collection…'), { value: 'API' });
|
|
if (!name) return;
|
|
try {
|
|
const { id } = await backend.invoke('http.collection.create', { name });
|
|
this.open.add(id);
|
|
await this.load();
|
|
this.environments(id);
|
|
} catch (e) { notify(e.message, 'error'); }
|
|
}
|
|
|
|
async renameCollection(c) {
|
|
const to = await prompt(t('Rename…'), { value: c.id });
|
|
if (!to || to === c.id) return;
|
|
try {
|
|
await backend.invoke('http.collection.rename', { collection: c.id, to });
|
|
for (const tb of this.tabs) if (tb.collection === c.id) tb.collection = to;
|
|
this.load();
|
|
} catch (e) { notify(e.message, 'error'); }
|
|
}
|
|
|
|
async deleteCollection(c) {
|
|
if (!(await confirm(t('Delete {name}?', { name: c.name }), t('Its request files are deleted from the project.'), { ok: t('Delete'), danger: true }))) return;
|
|
await backend.invoke('http.collection.remove', { collection: c.id });
|
|
this.tabs = this.tabs.filter((x) => x.collection !== c.id);
|
|
this.current = this.tabs[0] || null;
|
|
await this.load();
|
|
this.renderRequest();
|
|
this.renderResponse();
|
|
}
|
|
|
|
async renameItem(collection, item) {
|
|
const base = item.path.split('/').pop();
|
|
const to = await prompt(t('Rename…'), { value: base });
|
|
if (!to || to === base) return;
|
|
const dir = item.path.includes('/') ? item.path.slice(0, item.path.lastIndexOf('/') + 1) : '';
|
|
const target = dir + (item.type === 'request' && !to.endsWith('.http') ? to + '.http' : to);
|
|
try {
|
|
await backend.invoke('http.move', { collection, from: item.path, to: target });
|
|
for (const tb of this.tabs) if (tb.collection === collection && tb.path === item.path) tb.path = target;
|
|
this.load();
|
|
} catch (e) { notify(e.message, 'error'); }
|
|
}
|
|
|
|
async logout(collection) {
|
|
await backend.invoke('http.vars.clear', { collection, env: this.envOf(collection) });
|
|
notify(t('The tokens and the values scripts set are forgotten for {env}.', { env: this.envOf(collection) || '—' }), 'info', { title: 'HTTP Client' });
|
|
}
|
|
|
|
// sending ----------------------------------------------------------------------------------------------------------
|
|
|
|
async send() {
|
|
const tab = this.current;
|
|
if (!tab || tab.sending) return;
|
|
tab.sending = true;
|
|
this.renderRequest();
|
|
this.renderResponse();
|
|
const coll = this.collection(tab.collection) ? tab.collection : '';
|
|
const env = coll ? this.envOf(coll) : '';
|
|
try {
|
|
const req = clone(tab.request);
|
|
let vars = {};
|
|
if (coll) vars = (await backend.invoke('http.vars', { collection: coll, env, request: req })).vars;
|
|
const pre = await sandbox(req.pre, { phase: 'pre', vars, env: vars, request: { method: req.method, url: req.url, headers: req.headers, body: req.body } });
|
|
if (pre.request.headers) for (const [n, v] of pre.request.headers) { req.headers = req.headers.filter(([x]) => x.toLowerCase() !== n.toLowerCase()); req.headers.push([n, v]); }
|
|
if (pre.request.body != null) req.body = pre.request.body;
|
|
if (pre.request.url) req.url = pre.request.url;
|
|
if (coll && Object.keys(pre.globals).length) await backend.invoke('http.vars.set', { collection: coll, env, values: pre.globals });
|
|
const result = await backend.invoke('http.send', { collection: coll, env, request: { ...req, path: tab.path || '' }, overrides: { ...pre.globals, ...pre.locals } });
|
|
// a 500 page that says a table or the database is missing: the Doctrine window's schema banner
|
|
if (result.response.status >= 500 && !result.response.binary && /doesn't exist|Unknown database|does not exist|no such table/i.test(result.response.body || '')) backend.invoke('doctrine.schema.observe', { text: String(result.response.body).slice(0, 20000) }).catch(() => null);
|
|
let post = EMPTY_RUN;
|
|
if (!result.response.error && req.post) {
|
|
post = await sandbox(req.post, { phase: 'post', vars: { ...vars, ...pre.globals, ...pre.locals }, env: vars, request: result.request,
|
|
response: { status: result.response.status, headers: result.response.headers, body: result.response.binary ? '' : result.response.body, time: result.response.time } });
|
|
if (coll && Object.keys(post.globals).length) await backend.invoke('http.vars.set', { collection: coll, env, values: post.globals });
|
|
}
|
|
tab.response = result;
|
|
tab.run = { tests: [...pre.tests, ...post.tests], logs: [...pre.logs, ...post.logs], errors: [pre.error && `${t('Pre-request script')}: ${pre.error}`, post.error && `${t('Post-response script')}: ${post.error}`].filter(Boolean) };
|
|
if (tab.run.tests.length && this.respTab === 'body' && tab.run.tests.some((x) => !x.passed)) this.respTab = 'tests';
|
|
if (result.missing?.length) notify(t('Unknown variables: {names}', { names: result.missing.join(', ') }), 'warning', { title: 'HTTP Client' });
|
|
} catch (e) {
|
|
tab.response = { request: { method: tab.request.method, url: tab.request.url, headers: [], body: '' }, response: { error: e.message }, missing: [], auth: {} };
|
|
tab.run = null;
|
|
} finally {
|
|
tab.sending = false;
|
|
}
|
|
if (this.current === tab) { this.renderRequest(); this.renderResponse(); }
|
|
if (this.side === 'history') this.renderSide();
|
|
}
|
|
|
|
async cancel() {
|
|
await backend.invoke('http.cancel').catch(() => null);
|
|
}
|
|
|
|
async copyCurl() {
|
|
const tab = this.current;
|
|
if (!tab) return;
|
|
let sent = tab.response?.request;
|
|
if (!sent) {
|
|
// not sent yet: the request with its variables resolved, through the IDE (the same values as a Send)
|
|
const coll = this.collection(tab.collection) ? tab.collection : '';
|
|
sent = coll ? await backend.invoke('http.vars', { collection: coll, env: this.envOf(coll), request: tab.request }).then(({ vars }) => {
|
|
const r = (s) => String(s).replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (m, n) => vars[n] ?? m);
|
|
return { method: tab.request.method, url: r(tab.request.url), headers: tab.request.headers.map(([n, v]) => [r(n), r(v)]), body: r(tab.request.body) };
|
|
}) : tab.request;
|
|
}
|
|
await copyText(toCurl({ ...sent, insecure: tab.request.options?.verify === false, redirects: tab.request.options?.redirects }));
|
|
notify(t('Copied as curl.'), 'success');
|
|
}
|
|
|
|
async showText() {
|
|
const { text } = await backend.invoke('http.text', { request: this.current.request });
|
|
const host = el('div.hc-code.tall');
|
|
const d = dialog({ title: t('Show the .http Text'), body: host, wide: true, buttons: [{ label: 'Copy', action: () => { copyText(text); return false; } }, { label: 'Close', primary: true }] });
|
|
const ed = codeEditor(host, text, 'plaintext', { readOnly: true, minimal: false });
|
|
const close = d.close;
|
|
d.close = () => { ed.dispose(); close(); };
|
|
}
|
|
|
|
// the answer ------------------------------------------------------------------------------------------------------
|
|
|
|
renderResponse() {
|
|
this.respEditor?.dispose();
|
|
this.respEditor = null;
|
|
clear(this.respNode);
|
|
const tab = this.current;
|
|
if (!tab) return;
|
|
if (tab.sending) { this.respNode.append(el('div.hc-empty', {}, el('span.hc-spin'), t('Sending…'))); return; }
|
|
const result = tab.response;
|
|
if (!result) { this.respNode.append(el('div.hc-empty', {}, t('The answer shows here.'))); return; }
|
|
const r = result.response;
|
|
if (r.error) {
|
|
this.respNode.append(el('div.hc-status-line', {}, el('span.hc-status.err', {}, t('No answer'))), el('div.hc-error', {}, r.error));
|
|
return;
|
|
}
|
|
const tests = tab.run?.tests || [];
|
|
const passed = tests.filter((x) => x.passed).length;
|
|
const cookies = r.headers.filter(([n]) => n.toLowerCase() === 'set-cookie');
|
|
this.respNode.append(el('div.hc-status-line', {},
|
|
el(`span.hc-status.${statusClass(r.status)}`, {}, `${r.status} ${r.reason || ''}`),
|
|
el('span.hc-meta', { title: `connect ${r.timings?.connect ?? 0} ms · TLS ${r.timings?.tls ?? 0} ms · ${t('wait')} ${r.timings?.wait ?? 0} ms · ${t('download')} ${r.timings?.download ?? 0} ms` }, `${r.time} ms`),
|
|
el('span.hc-meta', {}, size(r.size || 0)),
|
|
r.redirects?.length ? el('span.hc-meta', { title: r.redirects.map(([s, from, to]) => `${s} ${from} → ${to}`).join('\n') }, t('{n} redirects', { n: r.redirects.length })) : null,
|
|
result.auth?.refreshed ? el('span.hc-meta.ok', {}, t('logged in')) : null,
|
|
tests.length ? el(`span.hc-meta.${passed === tests.length ? 'ok' : 'err'}`, {}, t('{passed}/{total} tests', { passed, total: tests.length })) : null,
|
|
el('span.hc-spacer'),
|
|
el('button.icon-btn', { title: t('Copy as curl'), onclick: () => this.copyCurl() }, icon('terminal')),
|
|
el('button.icon-btn', { title: t('Copy the Body'), onclick: () => { copyText(r.binary ? '' : r.body); notify(t('Copied.'), 'success'); } }, icon('copy'))));
|
|
const tabs = [['body', 'Body'], ['headers', `${t('Headers')} (${r.headers.length})`], ['cookies', `${t('Cookies')} (${cookies.length})`],
|
|
['tests', `${t('Tests')}${tests.length ? ` (${passed}/${tests.length})` : ''}`], ['timeline', 'Timeline']];
|
|
this.respNode.append(el('div.hc-tabs', {}, ...tabs.map(([id, label]) => el(`button.hc-tab${this.respTab === id ? '.on' : ''}`, { onclick: () => { this.respTab = id; this.renderResponse(); } }, t(label)))));
|
|
const body = el('div.hc-resp-body');
|
|
this.respNode.append(body);
|
|
if (this.respTab === 'headers') body.append(this.table(r.headers));
|
|
else if (this.respTab === 'cookies') {
|
|
body.append(cookies.length ? this.table(cookies.map(([, v]) => { const [pair, ...attrs] = v.split(';'); const i = pair.indexOf('='); return [pair.slice(0, i).trim(), pair.slice(i + 1), attrs.join(';').trim()]; }), ['Name', 'Value', 'Attributes'])
|
|
: el('div.hc-empty', {}, t('The answer sets no cookie.')),
|
|
el('div.hc-line', {}, el('span.hc-hint', {}, t('Cookies are sent back to the same site until the IDE closes.')),
|
|
el('button.btn', { onclick: async () => { await backend.invoke('http.cookies.clear'); notify(t('Cookies cleared.'), 'success'); } }, t('Clear the Cookies'))));
|
|
} else if (this.respTab === 'tests') {
|
|
if (!tests.length && !tab.run?.errors?.length && !tab.run?.logs?.length) body.append(el('div.hc-empty', {}, t('No test: add some in the Scripts tab (client.test).')));
|
|
for (const e of tab.run?.errors || []) body.append(el('div.hc-error', {}, e));
|
|
for (const x of tests) body.append(el(`div.hc-test.${x.passed ? 'ok' : 'err'}`, {}, el('span', {}, x.passed ? '✓' : '✗'), el('span', {}, x.name), x.error ? el('code', {}, x.error) : null));
|
|
if (tab.run?.logs?.length) body.append(el('pre.hc-logs', {}, tab.run.logs.join('\n')));
|
|
} else if (this.respTab === 'timeline') {
|
|
const sent = result.request;
|
|
body.append(el('pre.hc-logs', {}, [`${sent.method} ${sent.url}`, ...sent.headers.map(([n, v]) => `${n}: ${/^(authorization|cookie)$/i.test(n) ? v.replace(/^(\S+\s)?(.{6}).*/, '$1$2…') : v}`),
|
|
sent.body ? '\n' + sent.body.slice(0, 4000) : '', '',
|
|
...(r.redirects || []).map(([s, from, to]) => `↪ ${s} ${from} → ${to}`),
|
|
`← HTTP/${r.version} ${r.status} ${r.reason} (${r.remote})`,
|
|
`connect ${r.timings?.connect ?? 0} ms · TLS ${r.timings?.tls ?? 0} ms · ${t('wait')} ${r.timings?.wait ?? 0} ms · ${t('download')} ${r.timings?.download ?? 0} ms`].join('\n')));
|
|
} else this.renderBody(body, r);
|
|
}
|
|
|
|
table(rows, head = ['Name', 'Value']) {
|
|
return el('table.hc-table', {}, el('thead', {}, el('tr', {}, ...head.map((h) => el('th', {}, t(h))))),
|
|
el('tbody', {}, ...rows.map((row) => el('tr', {}, ...row.map((c) => el('td', {}, String(c)))))));
|
|
}
|
|
|
|
renderBody(box, r) {
|
|
const ct = String(headerValue(r.headers, 'content-type') || '');
|
|
if (r.binary) {
|
|
if (/^image\//i.test(ct)) box.append(el('div.hc-image', {}, el('img', { src: `data:${ct.split(';')[0]};base64,${r.body}` })));
|
|
else box.append(el('div.hc-empty', {}, t('A binary answer ({type}, {size}).', { type: ct || '?', size: size(r.size) })));
|
|
return;
|
|
}
|
|
const pretty = prettyBody(r.body, ct);
|
|
const rows = pretty.json ? (Array.isArray(pretty.json) ? pretty.json : pretty.json.member || pretty.json['hydra:member'] || null) : null;
|
|
const modes = [['pretty', 'Pretty'], ['raw', 'Raw'], ...(Array.isArray(rows) && rows.length && typeof rows[0] === 'object' ? [['table', 'Table']] : []), ...(pretty.kind === 'html' ? [['preview', 'Preview']] : [])];
|
|
if (!modes.some(([m]) => m === this.respMode)) this.respMode = 'pretty';
|
|
const filter = el('input.input.hc-filter', { placeholder: t('JSONPath filter, e.g. $.member[*].title'), value: this.filter || '', spellcheck: false,
|
|
oninput: (e) => { this.filter = e.target.value; apply(); } });
|
|
box.append(el('div.hc-line', {}, ...modes.map(([m, l]) => el(`button.hc-chip${this.respMode === m ? '.on' : ''}`, { onclick: () => { this.respMode = m; this.renderResponse(); } }, t(l))),
|
|
pretty.json && this.respMode === 'pretty' ? filter : null,
|
|
r.truncated ? el('span.hc-hint', {}, t('(cut at 10 MB)')) : null));
|
|
if (this.respMode === 'preview') {
|
|
responsePreview(box, r, this.current?.request?.options?.verify !== false);
|
|
return;
|
|
}
|
|
if (this.respMode === 'table') {
|
|
const cols = [...new Set(rows.slice(0, 200).flatMap((x) => Object.keys(x || {})))].slice(0, 30);
|
|
const cell = (v) => (v === null || v === undefined ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v));
|
|
box.append(el('div.hc-table-wrap', {}, this.table(rows.slice(0, 1000).map((x) => cols.map((c) => cell(x?.[c]))), cols)));
|
|
return;
|
|
}
|
|
const host = el('div.hc-code.resp');
|
|
box.append(host);
|
|
const text = this.respMode === 'raw' ? r.body : pretty.text;
|
|
this.respEditor = codeEditor(host, text, this.respMode === 'raw' ? 'plaintext' : { json: 'json', xml: 'xml', html: 'html' }[pretty.kind] || 'plaintext', { readOnly: true, minimal: false });
|
|
const apply = () => {
|
|
if (!this.respEditor || !pretty.json) return;
|
|
const f = (this.filter || '').trim();
|
|
if (!f) { this.respEditor.setValue(pretty.text); filter.classList.remove('bad'); return; }
|
|
try { this.respEditor.setValue(JSON.stringify(jsonPath(pretty.json, f), null, 2)); filter.classList.remove('bad'); } catch { filter.classList.add('bad'); }
|
|
};
|
|
if (this.filter && this.respMode === 'pretty') apply();
|
|
}
|
|
|
|
// dialogs -----------------------------------------------------------------------------------------------------
|
|
|
|
async environments(collection) {
|
|
let data;
|
|
try { data = await backend.invoke('http.env.get', { collection }); } catch (e) { notify(e.message, 'error'); return; }
|
|
const envs = Object.entries(data.environments).map(([name, e]) => ({ name, rows: Object.entries(e.vars), secrets: new Set(Object.keys(e.secrets)), stored: e.secrets, values: {} }));
|
|
for (const env of envs) for (const s of env.secrets) if (!env.rows.some(([k]) => k === s)) env.rows.push([s, '']);
|
|
let cur = envs[0] || null;
|
|
const body = el('div.hc-envs');
|
|
const draw = () => {
|
|
clear(body);
|
|
const list = el('div.hc-env-list', {}, ...envs.map((env) => el(`div.hc-row${env === cur ? '.sel' : ''}`, { onclick: () => { cur = env; draw(); } }, icon('globe'), el('span.hc-name', {}, env.name),
|
|
el('button.icon-btn', { title: t('Remove'), onclick: (e) => { e.stopPropagation(); envs.splice(envs.indexOf(env), 1); cur = envs[0] || null; draw(); } }, icon('close')))),
|
|
el('button.btn', { onclick: async () => {
|
|
const name = await prompt(t('New Environment'), { value: envs.length ? 'prod' : 'local' });
|
|
if (!name || envs.some((x) => x.name === name)) return;
|
|
const env = { name, rows: cur ? cur.rows.map(([k, v]) => [k, cur.secrets.has(k) ? '' : v]) : [['baseUrl', 'http://localhost:8000']], secrets: new Set(cur?.secrets || []), stored: {}, values: {} };
|
|
envs.push(env); cur = env; draw();
|
|
} }, icon('plus'), t('New Environment')));
|
|
const right = el('div.hc-env-vars');
|
|
if (cur) {
|
|
const env = cur;
|
|
right.append(el('p.hc-hint', {}, t('Plain values go into {file} (committed); secret ones are kept on this computer only and never shared.', { file: data.file })),
|
|
kvTable(env.rows, () => null, { keyLabel: 'Variable', secret: { has: (k) => env.secrets.has(k), stored: (k) => !!env.stored[k], toggle: (k, on) => (on ? env.secrets.add(k) : env.secrets.delete(k)) } }));
|
|
}
|
|
body.append(list, right);
|
|
};
|
|
draw();
|
|
dialog({ title: t('Environments of {name}', { name: this.collection(collection)?.name || collection }), body, wide: true, buttons: [{ label: 'Cancel' }, { label: 'Save', primary: true, action: async () => {
|
|
const environments = {};
|
|
const secrets = {};
|
|
for (const env of envs) {
|
|
const vars = {};
|
|
secrets[env.name] = {};
|
|
for (const [k, v] of env.rows) {
|
|
if (!k) continue;
|
|
if (env.secrets.has(k)) { if (v !== '') secrets[env.name][k] = v; } else vars[k] = v;
|
|
}
|
|
for (const old of Object.keys(env.stored)) if (!env.secrets.has(old)) secrets[env.name][old] = null;
|
|
environments[env.name] = { vars, secrets: [...env.secrets].filter((k) => env.rows.some(([x]) => x === k)) };
|
|
}
|
|
await backend.invoke('http.env.save', { collection, environments, secrets });
|
|
await this.load();
|
|
} }] });
|
|
}
|
|
|
|
async collectionSettings(collection) {
|
|
const c = this.collection(collection);
|
|
if (!c) return;
|
|
const settings = clone(c.settings);
|
|
settings.auth ||= { type: 'none' };
|
|
settings.headers ||= [];
|
|
const body = el('div.hc-settings', {},
|
|
el('label.hc-field', {}, el('span', {}, t('Name')), el('input.input', { value: settings.name || c.name, oninput: (e) => { settings.name = e.target.value; } })),
|
|
el('h4', {}, t('Auth of its requests (those set to Inherit)')),
|
|
authEditor(settings.auth, () => null, { inherit: false, requests: this.requestsOf(collection) }),
|
|
el('h4', {}, t('Headers of every request')), kvTable(settings.headers, () => null));
|
|
dialog({ title: t('Collection Settings (Auth, Headers)…'), body, wide: true, buttons: [{ label: 'Cancel' }, { label: 'Save', primary: true, action: async () => {
|
|
await backend.invoke('http.collection.settings', { collection, settings });
|
|
await this.load();
|
|
if (this.current) this.drawSub();
|
|
} }] });
|
|
}
|
|
|
|
importDialog(collection) {
|
|
const path = el('input.input', { placeholder: t('A .http / .bru file or a Bruno collection folder (of the project, or a full path)'), spellcheck: false });
|
|
const text = el('textarea.input.hc-import', { rows: 10, spellcheck: false, placeholder: t('…or paste requests here (.http, or a .bru file)') });
|
|
const format = el('select.input', {}, el('option', { value: 'http' }, '.http'), el('option', { value: 'bru' }, '.bru (Bruno)'));
|
|
const target = el('select.input', {}, ...this.data.collections.map((c) => el('option', { value: c.id, selected: c.id === collection }, c.name)), el('option', { value: '' }, t('A new collection')));
|
|
dialog({ title: t('Import…'), wide: true, body: el('div.hc-settings', {}, el('label.hc-field', {}, el('span', {}, t('Into')), target), path, el('div.hc-line', {}, format), text),
|
|
buttons: [{ label: 'Cancel' }, { label: 'Import', primary: true, action: async () => {
|
|
let id = target.value;
|
|
if (!id) id = (await backend.invoke('http.collection.create', { name: 'Imported' })).id;
|
|
const r = await backend.invoke('http.import', { collection: id, path: path.value.trim(), text: text.value, format: format.value });
|
|
notify(t('{n} requests imported.', { n: r.imported }), 'success', { title: 'HTTP Client' });
|
|
this.open.add(id);
|
|
await this.load();
|
|
} }] });
|
|
}
|
|
|
|
async exportDialog(collection, path, format) {
|
|
const r = await backend.invoke('http.export', { collection, path, format });
|
|
const host = el('div.hc-code.tall');
|
|
const d = dialog({ title: t('{n} requests exported', { n: r.count }), body: host, wide: true, buttons: [{ label: 'Copy', action: () => { copyText(r.text); notify(t('Copied.'), 'success'); return false; } }, { label: 'Close', primary: true }] });
|
|
const ed = codeEditor(host, r.text, 'plaintext', { readOnly: true, minimal: false });
|
|
const close = d.close;
|
|
d.close = () => { ed.dispose(); close(); };
|
|
}
|
|
|
|
shareDialog(collection) {
|
|
const c = this.collection(collection);
|
|
const project = el('input.input', { value: c?.settings?.share?.project || this.data.linked || '', placeholder: 'my-game', spellcheck: false });
|
|
dialog({ title: t('Share with the Project\'s Members…'), body: el('div.hc-settings', {},
|
|
el('p', {}, t('The collection is kept on jumphp.net with the project: its members get it in their IDE, read or write as the project\'s rights say. Each Sync sends your changes and brings theirs. Secret values and tokens never leave this computer.')),
|
|
el('label.hc-field', {}, el('span', {}, t('jumphp.net project')), project),
|
|
this.data.signedIn ? null : el('p.hc-error', {}, t('Sign in with jumphp.net first.'))),
|
|
buttons: [{ label: 'Cancel' }, { label: 'Sync Now', primary: true, action: () => this.sync(collection, project.value.trim()) }] });
|
|
}
|
|
|
|
async sync(collection, project = '') {
|
|
try {
|
|
const r = await backend.invoke('http.share.sync', { collection, project });
|
|
const parts = [t('{n} received', { n: r.pulled.length }), t('{n} sent', { n: r.pushed.length })];
|
|
if (r.deleted.length) parts.push(t('{n} deleted', { n: r.deleted.length }));
|
|
if (r.conflicts.length) parts.push(t('{n} changed on both sides: theirs kept beside yours as .theirs.http', { n: r.conflicts.length }));
|
|
if (r.readOnly) parts.push(t('read only for you'));
|
|
notify(parts.join(' · '), r.conflicts.length ? 'warning' : 'success', { title: t('Synced with {project}', { project: r.project }) });
|
|
await this.load();
|
|
} catch (e) { notify(e.message, 'error', { title: 'HTTP Client' }); }
|
|
}
|
|
|
|
shown() { this.respEditor?.layout(); for (const ed of this.subEditors || []) ed.layout(); }
|
|
}
|