268 lines
15 KiB
JavaScript
268 lines
15 KiB
JavaScript
// The HTTP Client's pure parts (no DOM): JSONPath (the same as ide/src/HttpClient/JsonPath.php), the URL's query parameters,
|
|
// "copy as curl", pretty bodies, and the scripts' sandbox API run by http-script-worker.js (a Web Worker without network):
|
|
//
|
|
// pre-request: request.variables.set(name, value) (this request only), client.global.set(name, value) (kept for the environment),
|
|
// request.environment.get(name), req.setHeader(name, value), req.setBody(text), req.setUrl(url)
|
|
// post-response: response.status, response.body (JSON parsed), response.headers.valueOf(name), response.contentType.mimeType,
|
|
// response.responseTime; client.test(name, fn), client.assert(cond, message), client.log(...)
|
|
// both: test(name, fn), expect(value).to.equal / eql / be.a / have.property / include / match / above / below / lengthOf,
|
|
// .not, .to.be.ok / true / false / null / undefined / empty; jsonpath(data, '$.a.b'); console.log
|
|
// Bruno's names: bru.setVar / getVar / setEnvVar / getEnvVar, res.status, res.body, res.getStatus(), res.getBody(), res.getHeader(),
|
|
// res.getResponseTime(), req.getUrl() / getMethod() / getHeader() / getBody()
|
|
|
|
/** Every match of a JSONPath ($, .name, ['name'], [0], [-1], [*], .*, ..name). */
|
|
export function jsonPath(data, path) {
|
|
let nodes = [data];
|
|
for (const [kind, key] of jsonPathTokens(path)) {
|
|
const next = [];
|
|
for (const node of nodes) {
|
|
if (kind === 'deep') deep(node, key, next);
|
|
else if (kind === 'all') { if (node && typeof node === 'object') next.push(...Object.values(node)); }
|
|
else if (Array.isArray(node) && typeof key === 'number') { const i = key < 0 ? node.length + key : key; if (i in node) next.push(node[i]); }
|
|
else if (node && typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, String(key))) next.push(node[String(key)]);
|
|
}
|
|
nodes = next;
|
|
}
|
|
return nodes;
|
|
}
|
|
|
|
export const jsonPathFirst = (data, path) => jsonPath(data, path)[0];
|
|
|
|
function deep(node, key, out) {
|
|
if (!node || typeof node !== 'object') return;
|
|
if (key === '*') out.push(...Object.values(node));
|
|
else if (Object.prototype.hasOwnProperty.call(node, key)) out.push(node[key]);
|
|
for (const child of Object.values(node)) deep(child, key, out);
|
|
}
|
|
|
|
export function jsonPathTokens(path) {
|
|
let p = String(path || '').trim();
|
|
if (p === '' || p === '$') return [];
|
|
if (p[0] !== '$') p = '$.' + p.replace(/^\.+/, '');
|
|
const out = [];
|
|
let i = 1;
|
|
while (i < p.length) {
|
|
if (p.startsWith('..', i)) {
|
|
i += 2;
|
|
const m = /^(\*|[A-Za-z0-9_$@-]+)/.exec(p.slice(i)) || /^\[\s*['"]([^'"]*)['"]\s*\]/.exec(p.slice(i));
|
|
if (m) { out.push(['deep', m[1]]); i += m[0].length; }
|
|
continue;
|
|
}
|
|
if (p[i] === '.') {
|
|
i++;
|
|
const m = /^(\*|[^.[]+)/.exec(p.slice(i));
|
|
if (m) { out.push(m[1] === '*' ? ['all', '*'] : ['key', m[1]]); i += m[1].length; }
|
|
continue;
|
|
}
|
|
const m = p[i] === '[' && /^\[\s*(?:(-?\d+)|(\*)|'([^']*)'|"([^"]*)")\s*\]/.exec(p.slice(i));
|
|
if (m) {
|
|
if (m[1] !== undefined) out.push(['key', Number(m[1])]);
|
|
else if (m[2]) out.push(['all', '*']);
|
|
else out.push(['key', m[3] ?? m[4]]);
|
|
i += m[0].length;
|
|
continue;
|
|
}
|
|
throw new Error(`JSONPath: cannot read '${path}' at ${i + 1}`);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** 'https://x/a?b=1&c#h' -> {base: 'https://x/a', params: [['b', '1'], ['c', '']], hash: '#h'} (values kept as typed, {{vars}} included). */
|
|
export function splitUrl(url) {
|
|
let rest = String(url || '');
|
|
let hash = '';
|
|
const h = rest.indexOf('#');
|
|
if (h >= 0 && !/\{\{[^}]*#/.test(rest)) { hash = rest.slice(h); rest = rest.slice(0, h); }
|
|
const q = rest.indexOf('?');
|
|
if (q < 0) return { base: rest, params: [], hash };
|
|
const params = rest.slice(q + 1).split('&').filter((s) => s !== '').map((pair) => {
|
|
const e = pair.indexOf('=');
|
|
return e < 0 ? [pair, ''] : [pair.slice(0, e), pair.slice(e + 1)];
|
|
});
|
|
return { base: rest.slice(0, q), params, hash };
|
|
}
|
|
|
|
export function joinUrl(base, params, hash = '') {
|
|
const q = params.filter(([k]) => String(k).trim() !== '').map(([k, v]) => (v === '' || v == null ? k : `${k}=${v}`)).join('&');
|
|
return base + (q ? '?' + q : '') + (hash || '');
|
|
}
|
|
|
|
/** A shell command doing the same request (what was sent: the variables resolved, the auth applied). */
|
|
export function toCurl(req) {
|
|
const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'";
|
|
const parts = ['curl'];
|
|
const method = String(req.method || 'GET').toUpperCase();
|
|
if (method !== 'GET' || req.body) parts.push('-X', method);
|
|
parts.push(q(req.url));
|
|
for (const [name, value] of req.headers || []) {
|
|
if (/^(host|content-length|connection|accept-encoding)$/i.test(name)) continue;
|
|
parts.push('-H', q(`${name}: ${value}`));
|
|
}
|
|
if (req.body) parts.push('--data-raw', q(req.body));
|
|
if (req.insecure) parts.push('-k');
|
|
if (req.redirects !== false) parts.push('-L');
|
|
return parts.join(' ');
|
|
}
|
|
|
|
/** The header's value (the first one, any case). */
|
|
export function headerValue(headers, name) {
|
|
const h = (headers || []).find(([n]) => String(n).toLowerCase() === String(name).toLowerCase());
|
|
return h ? h[1] : undefined;
|
|
}
|
|
|
|
/** What a body is, and its text made readable. */
|
|
export function prettyBody(text, contentType = '') {
|
|
const type = String(contentType).toLowerCase();
|
|
const s = String(text ?? '');
|
|
if (/json/.test(type) || /^\s*[[{]/.test(s)) {
|
|
try { return { kind: 'json', text: JSON.stringify(JSON.parse(s), null, 2), json: JSON.parse(s) }; } catch { /* not JSON after all */ }
|
|
}
|
|
if (/html/.test(type)) return { kind: 'html', text: s };
|
|
if (/xml/.test(type) || /^\s*<\?xml/.test(s)) return { kind: 'xml', text: formatXml(s) };
|
|
return { kind: 'text', text: s };
|
|
}
|
|
|
|
export function formatXml(xml) {
|
|
const tokens = String(xml).match(/<[^>]+>|[^<]+/g) || [];
|
|
const lines = [];
|
|
let depth = 0;
|
|
for (let i = 0; i < tokens.length; i++) {
|
|
const tok = tokens[i].trim();
|
|
if (tok === '') continue;
|
|
const pad = ' '.repeat(depth);
|
|
if (/^<\//.test(tok)) { depth = Math.max(0, depth - 1); lines.push(' '.repeat(depth) + tok); continue; }
|
|
if (/^<[^!?][^>]*[^/]>$|^<[A-Za-z]>$/.test(tok)) {
|
|
// <a>text</a> on one line
|
|
const text = tokens[i + 1] ?? '';
|
|
if (!/^</.test(text) && /^<\//.test(tokens[i + 2] ?? '')) { lines.push(pad + tok + text.trim() + tokens[i + 2].trim()); i += 2; continue; }
|
|
lines.push(pad + tok);
|
|
depth++;
|
|
continue;
|
|
}
|
|
lines.push(pad + tok);
|
|
}
|
|
return lines.join('\n');
|
|
}
|
|
|
|
/** Bytes as "1.2 KB". */
|
|
export function size(bytes) {
|
|
if (bytes < 1024) return `${bytes} B`;
|
|
if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
return `${(bytes / 1048576).toFixed(1)} MB`;
|
|
}
|
|
|
|
// --- the scripts ------------------------------------------------------------------------------------------------------
|
|
|
|
function deepEqual(a, b) {
|
|
if (a === b) return true;
|
|
if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return Number.isNaN(a) && Number.isNaN(b);
|
|
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
const ka = Object.keys(a);
|
|
if (ka.length !== Object.keys(b).length) return false;
|
|
return ka.every((k) => deepEqual(a[k], b[k]));
|
|
}
|
|
|
|
const show = (v) => { try { return typeof v === 'string' ? JSON.stringify(v) : JSON.stringify(v) ?? String(v); } catch { return String(v); } };
|
|
|
|
/** A small expect() in chai's words. */
|
|
export function expect(actual) {
|
|
const make = (negate) => {
|
|
const check = (ok, message) => { if (negate ? ok : !ok) throw new Error((negate ? 'not: ' : '') + message); };
|
|
const typeOf = (v) => (v === null ? 'null' : Array.isArray(v) ? 'array' : typeof v);
|
|
const api = {
|
|
equal: (v) => check(actual === v, `expected ${show(actual)} to equal ${show(v)}`),
|
|
eql: (v) => check(deepEqual(actual, v), `expected ${show(actual)} to deeply equal ${show(v)}`),
|
|
a: (type) => check(typeOf(actual) === String(type).toLowerCase(), `expected ${show(actual)} to be a ${type}`),
|
|
property: (name, ...value) => {
|
|
const has = actual != null && typeof actual === 'object' && name in actual;
|
|
check(has && (value.length === 0 || deepEqual(actual[name], value[0])), `expected ${show(actual)} to have property ${show(name)}${value.length ? ' ' + show(value[0]) : ''}`);
|
|
},
|
|
include: (v) => check(typeof actual === 'string' ? actual.includes(v) : Array.isArray(actual) ? actual.some((x) => deepEqual(x, v))
|
|
: actual && typeof actual === 'object' && Object.entries(v || {}).every(([k, x]) => deepEqual(actual[k], x)), `expected ${show(actual)} to include ${show(v)}`),
|
|
match: (re) => check(new RegExp(re).test(String(actual)), `expected ${show(actual)} to match ${re}`),
|
|
above: (n) => check(actual > n, `expected ${show(actual)} to be above ${n}`),
|
|
below: (n) => check(actual < n, `expected ${show(actual)} to be below ${n}`),
|
|
least: (n) => check(actual >= n, `expected ${show(actual)} to be at least ${n}`),
|
|
most: (n) => check(actual <= n, `expected ${show(actual)} to be at most ${n}`),
|
|
lengthOf: (n) => check(actual != null && actual.length === n, `expected ${show(actual)} to have length ${n}`),
|
|
oneOf: (list) => check(list.some((x) => deepEqual(x, actual)), `expected ${show(actual)} to be one of ${show(list)}`),
|
|
};
|
|
api.equals = api.equal; api.eq = api.equal; api.an = api.a; api.contain = api.include; api.contains = api.include; api.includes = api.include;
|
|
api.greaterThan = api.above; api.lessThan = api.below; api.length = api.lengthOf;
|
|
const chain = {};
|
|
for (const word of ['to', 'be', 'been', 'is', 'that', 'which', 'and', 'has', 'have', 'with', 'of', 'same', 'deep']) {
|
|
Object.defineProperty(chain, word, { get: () => chain });
|
|
}
|
|
Object.assign(chain, api);
|
|
Object.defineProperty(chain, 'not', { get: () => make(!negate) });
|
|
Object.defineProperty(chain, 'ok', { get: () => check(!!actual, `expected ${show(actual)} to be truthy`) });
|
|
Object.defineProperty(chain, 'true', { get: () => check(actual === true, `expected ${show(actual)} to be true`) });
|
|
Object.defineProperty(chain, 'false', { get: () => check(actual === false, `expected ${show(actual)} to be false`) });
|
|
Object.defineProperty(chain, 'null', { get: () => check(actual === null, `expected ${show(actual)} to be null`) });
|
|
Object.defineProperty(chain, 'undefined', { get: () => check(actual === undefined, `expected ${show(actual)} to be undefined`) });
|
|
Object.defineProperty(chain, 'empty', { get: () => check(actual != null && (typeof actual === 'object' ? Object.keys(actual).length === 0 : actual.length === 0), `expected ${show(actual)} to be empty`) });
|
|
Object.defineProperty(chain, 'exist', { get: () => check(actual != null, `expected ${show(actual)} to exist`) });
|
|
return chain;
|
|
};
|
|
return make(false);
|
|
}
|
|
|
|
/**
|
|
* Runs a script with the API above. ctx: {phase: 'pre'|'post', vars: {name: value}, env: {name: value},
|
|
* request: {method, url, headers: [[n, v]], body}, response?: {status, headers, body (text), time}}.
|
|
* Returns {globals: {name: value|null} (to keep), locals: {name: value} (this request), request: changes, tests: [{name, passed, error}],
|
|
* logs: [string], error: string|null}.
|
|
*/
|
|
export function runScript(code, ctx = {}) {
|
|
const out = { globals: {}, locals: {}, request: {}, tests: [], logs: [], error: null };
|
|
if (!String(code || '').trim()) return out;
|
|
const vars = { ...(ctx.vars || {}) };
|
|
const env = ctx.env || {};
|
|
const str = (v) => (v == null ? null : typeof v === 'string' ? v : typeof v === 'object' ? JSON.stringify(v) : String(v));
|
|
const log = (...a) => out.logs.push(a.map((x) => (typeof x === 'string' ? x : show(x))).join(' '));
|
|
const runTest = (name, fn) => {
|
|
try { if (typeof fn === 'function') fn(); out.tests.push({ name: String(name), passed: true }); } catch (e) { out.tests.push({ name: String(name), passed: false, error: String(e?.message || e) }); }
|
|
};
|
|
const setGlobal = (k, v) => { out.globals[k] = str(v); vars[k] = str(v); };
|
|
const req = ctx.request || {};
|
|
const reqHeaders = [...(req.headers || [])];
|
|
const request = {
|
|
method: req.method, url: req.url, body: req.body,
|
|
headers: { all: () => reqHeaders.map(([name, value]) => ({ name, value })), findByName: (n) => headerValue(reqHeaders, n) ?? null },
|
|
variables: { set: (k, v) => { out.locals[k] = str(v); vars[k] = str(v); }, get: (k) => vars[k] ?? null },
|
|
environment: { get: (k) => env[k] ?? vars[k] ?? null },
|
|
};
|
|
const setHeader = (n, v) => { out.request.headers = [...(out.request.headers || []).filter(([x]) => x.toLowerCase() !== String(n).toLowerCase()), [String(n), str(v)]]; };
|
|
const r = ctx.response;
|
|
let response;
|
|
let res;
|
|
if (r) {
|
|
const ct = headerValue(r.headers, 'content-type') || '';
|
|
let body = r.body;
|
|
if (/json/i.test(ct) || /^\s*[[{]/.test(String(body))) { try { body = JSON.parse(r.body); } catch { /* text */ } }
|
|
const headers = { valueOf: (n) => headerValue(r.headers, n) ?? null, valuesOf: (n) => (r.headers || []).filter(([x]) => x.toLowerCase() === String(n).toLowerCase()).map(([, v]) => v) };
|
|
response = { status: r.status, body, headers, contentType: { mimeType: ct.split(';')[0].trim(), charset: (/charset=([^;]+)/i.exec(ct) || [])[1] || '' }, responseTime: r.time };
|
|
res = { status: r.status, body, headers: Object.fromEntries((r.headers || []).map(([n, v]) => [n.toLowerCase(), v])), responseTime: r.time,
|
|
getStatus: () => r.status, getBody: () => body, getHeader: (n) => headerValue(r.headers, n), getHeaders: () => res.headers, getResponseTime: () => r.time };
|
|
}
|
|
const client = {
|
|
global: { set: setGlobal, get: (k) => vars[k] ?? null, clear: (k) => { out.globals[k] = null; delete vars[k]; }, isEmpty: () => Object.keys(vars).length === 0 },
|
|
test: runTest,
|
|
assert: (cond, message) => { if (!cond) throw new Error(message || 'assertion failed'); },
|
|
log,
|
|
};
|
|
const bru = { setVar: setGlobal, getVar: (k) => vars[k], setEnvVar: setGlobal, getEnvVar: (k) => env[k] ?? vars[k], interpolate: (s) => String(s).replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (m, n) => vars[n] ?? m) };
|
|
const reqApi = { ...request, getUrl: () => out.request.url ?? req.url, getMethod: () => req.method, getHeader: (n) => headerValue(out.request.headers || reqHeaders, n),
|
|
getBody: () => out.request.body ?? req.body, setHeader, setBody: (b) => { out.request.body = str(b); }, setUrl: (u) => { out.request.url = String(u); } };
|
|
const consoleApi = { log, info: log, warn: log, error: log, debug: log };
|
|
const names = ['client', 'request', 'response', 'bru', 'req', 'res', 'test', 'expect', 'jsonpath', 'console',
|
|
'fetch', 'XMLHttpRequest', 'WebSocket', 'EventSource', 'importScripts', 'self', 'window', 'document', 'globalThis', 'indexedDB', 'localStorage', 'caches', 'Worker', 'postMessage'];
|
|
try {
|
|
// eslint-disable-next-line no-new-func
|
|
const fn = new Function(...names, '"use strict";\n' + code);
|
|
fn(client, reqApi, response, bru, reqApi, res, runTest, expect, (d, p) => jsonPath(d, p), consoleApi);
|
|
} catch (e) {
|
|
out.error = String(e?.message || e);
|
|
}
|
|
return out;
|
|
}
|