JavaScript Python PHP
import * as __pacote0 from "yaml";
import * as __pacote1 from "shell-quote";
function executar(values) {
const variant = values.variant ?? "rest";
function convertSelected() {
if (variant === "rest") {
const parameters = { ...{"method":"GET","url":"","headers":"{\"Content-Type\":\"application/json\"}","body":""}, ...values };
const isAlias = __pacote0["isAlias"];
const isMap = __pacote0["isMap"];
const isScalar = __pacote0["isScalar"];
const isSeq = __pacote0["isSeq"];
const LineCounter = __pacote0["LineCounter"];
const parseDocument = __pacote0["parseDocument"];
function convert(values) {
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
function parseJsonCompatible(input, format, onObjectKeys) {
if (!input.trim())
throw new Error(`Informe um documento ${format}.`);
if (input.length > 1_000_000)
throw new Error('A entrada excede o limite de 1 milhão de caracteres.');
if (format === 'JSON') {
// Syntax check only: do not use the rounded numeric values from JSON.parse.
try {
JSON.parse(input);
}
catch (cause) {
throw new Error(`JSON inválido: ${cause instanceof Error ? cause.message : 'erro de sintaxe'}`);
}
}
const lines = new LineCounter();
const doc = parseDocument(input, { version: '1.2', schema: format === 'JSON' ? 'json' : 'core', intAsBigInt: true, uniqueKeys: true, lineCounter: lines, prettyErrors: true, resolveKnownTags: false });
const issue = doc.errors[0] ?? doc.warnings[0];
if (issue)
throw new Error(`${format} inválido (${issue.code}): ${issue.message}`);
if (doc.directives?.yaml.version !== '1.2')
throw new Error('Somente YAML 1.2 é aceito para preservar os tipos de JSON.');
let count = 0;
function fail(message, node) {
const offset = node?.range?.[0];
const position = offset === undefined ? '' : (() => { const { line, col } = lines.linePos(offset); return ` (linha ${line}, coluna ${col})`; })();
throw new Error(message + position);
}
function convert(node, depth = 0) {
if (++count > 100_000 || depth > 100)
fail('Documento muito complexo: limite de 100 níveis ou 100 mil nós.', node);
if (!node)
return null;
if (isAlias(node))
fail('Aliases YAML não são aceitos: JSON não preserva referências ou ciclos.', node);
if (node.tag && !SAFE_TAGS.has(node.tag))
fail(`Tag não permitida: ${node.tag}.`, node);
if (isScalar(node)) {
const value = node.value;
if (typeof value === 'bigint') {
if (value === BigInt(0) && node.source?.startsWith('-'))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER))
fail('Inteiro fora do intervalo seguro de JSON/JavaScript. Use uma string entre aspas para preservar todos os dígitos.', node);
return Number(value);
}
if (typeof value === 'number') {
if (!Number.isFinite(value))
fail('JSON não representa NaN ou infinito.', node);
if (Number.isInteger(value) && !Number.isSafeInteger(value))
fail('Número inteiro fora do intervalo seguro. Use uma string entre aspas para preservar a precisão.', node);
if (value === 0 && /[1-9]/.test((node.source ?? '').split(/[eE]/)[0]))
fail('Número pequeno demais para a precisão de JavaScript. Use uma string entre aspas.', node);
if (Object.is(value, -0))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
return value;
}
if (value === null || typeof value === 'string' || typeof value === 'boolean')
return value;
fail('Valor não representável em JSON.', node);
}
if (isSeq(node))
return node.items.map(item => convert(item, depth + 1));
if (isMap(node)) {
const result = Object.create(null);
const keys = [];
for (const pair of node.items) {
if (!isScalar(pair.key) || typeof pair.key.value !== 'string')
fail('Chaves de objetos devem ser strings; chaves numéricas, booleanas ou complexas não são preservadas em JSON.', pair.key);
const key = pair.key.value;
if (format === 'YAML' && key === '<<' && pair.key.type === 'PLAIN')
fail('Chaves de merge YAML (<<) não são aceitas.', pair.key);
if (Object.hasOwn(result, key))
fail(`Chave duplicada: ${key}.`, pair.key);
keys.push(key);
result[key] = convert(pair.value, depth + 1);
}
onObjectKeys?.(result, keys);
return result;
}
fail('Estrutura não representável em JSON.', node);
}
if (!doc.contents)
throw new Error('Informe um documento com um valor; use null para um valor nulo.');
return convert(doc.contents);
}
function text(value, label) {
if (typeof value !== 'string')
throw new Error(label + ': informe texto.');
if (value.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
return value;
}
function json(input, label, objectOnly = false) {
try {
const value = parseJsonCompatible(text(input, label), 'JSON');
if (objectOnly && (!value || typeof value !== 'object' || Array.isArray(value)))
throw new Error('Informe um objeto JSON.');
return value;
}
catch (cause) {
throw new Error(label + ': ' + (cause instanceof Error ? cause.message : 'JSON inválido.'));
}
}
function result(value) {
const output = JSON.stringify(value, null, 2);
if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.');
return output;
}
function method(value) {
const input = text(value, 'Método').trim();
if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].includes(input))
throw new Error('Método HTTP não suportado.');
return input;
}
function address(value, mock) {
const input = text(value, mock ? 'Caminho' : 'URL').trim();
if (!input || /[\s\\\x00-\x1f\x7f]/.test(input) || input.includes('#') || /%(?![\da-f]{2})/i.test(input))
throw new Error('Informe uma URL/caminho sem espaços, controles, barras invertidas, fragmentos ou escapes percentuais inválidos.');
const relative = input.startsWith('/') && !input.startsWith('//');
if (mock && (!relative || input.includes('?')))
throw new Error('O mock exige caminho local iniciado por /, sem domínio ou parâmetros; exemplo: /usuarios.');
if (!relative && !/^https?:\/\/[^/]/i.test(input))
throw new Error('Use HTTP, HTTPS ou um caminho local iniciado por /.');
const parsed = new URL(input, 'https://example.invalid');
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password)
throw new Error('URLs com credenciais ou protocolos diferentes de HTTP/HTTPS não são aceitas.');
return input;
}
function headers(input) {
const value = json(text(input, 'Cabeçalhos').trim() || '{}', 'Cabeçalhos', true);
const seen = new Set();
for (const [key, content] of Object.entries(value)) {
if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(key))
throw new Error('Nome de cabeçalho inválido: ' + key);
if (seen.has(key.toLowerCase()))
throw new Error('Cabeçalho repetido, ignorando maiúsculas: ' + key);
seen.add(key.toLowerCase());
if (typeof content !== 'string' || /[\x00-\x08\x0a-\x1f\x7f]/.test(content))
throw new Error('Cabeçalho ' + key + ': use uma string sem controles ou quebras de linha.');
}
return value;
}
function generateRestPayload(values) {
const verb = method(values.method);
const body = text(values.body, 'Corpo');
const output = { method: verb, url: address(values.url, false), headers: headers(values.headers) };
if (body.trim()) {
if (['GET', 'HEAD'].includes(verb))
throw new Error('GET e HEAD não recebem corpo nesta ferramenta; deixe o corpo vazio ou escolha outro método.');
output.body = json(body, 'Corpo da requisição');
}
return result(output);
}
return generateRestPayload(values);
}
return convert(parameters);
}
if (variant === "curl") {
const parameters = { ...{"method":"GET","url":"","headers":"{}","body":""}, ...values };
const isAlias = __pacote0["isAlias"];
const isMap = __pacote0["isMap"];
const isScalar = __pacote0["isScalar"];
const isSeq = __pacote0["isSeq"];
const LineCounter = __pacote0["LineCounter"];
const parseDocument = __pacote0["parseDocument"];
function convert(values) {
function generateCurl(values) {
const url = address(text(values.url, 'URL').trim());
const verb = method(text(values.method, 'Método'));
const source = text(values.headers, 'Cabeçalhos');
const object = parseJsonCompatible(source.trim() ? source : '{}', 'JSON');
if (!object || Array.isArray(object) || typeof object !== 'object')
throw new Error('Cabeçalhos: informe um objeto JSON com valores string.');
const entries = [];
for (const [name, value] of Object.entries(object)) {
if (typeof value !== 'string')
throw new Error('Cada valor de cabeçalho deve ser uma string.');
header(name, value, entries);
}
const body = text(values.body, 'Corpo');
const data = finish({ method: verb, url, headers: entries, ...(body !== '' ? { body } : {}) });
const quote = (value) => "'" + value.replace(/'/g, "'\\''") + "'";
const args = ['curl', '--request', quote(data.method), '--url', quote(data.url)];
for (const [name, value] of data.headers)
args.push('--header', quote(name + ': ' + value));
if (data.body !== undefined)
args.push('--data-raw', quote(data.body));
return args.join(' ');
}
function parseJsonCompatible(input, format, onObjectKeys) {
if (!input.trim())
throw new Error(`Informe um documento ${format}.`);
if (input.length > 1_000_000)
throw new Error('A entrada excede o limite de 1 milhão de caracteres.');
if (format === 'JSON') {
// Syntax check only: do not use the rounded numeric values from JSON.parse.
try {
JSON.parse(input);
}
catch (cause) {
throw new Error(`JSON inválido: ${cause instanceof Error ? cause.message : 'erro de sintaxe'}`);
}
}
const lines = new LineCounter();
const doc = parseDocument(input, { version: '1.2', schema: format === 'JSON' ? 'json' : 'core', intAsBigInt: true, uniqueKeys: true, lineCounter: lines, prettyErrors: true, resolveKnownTags: false });
const issue = doc.errors[0] ?? doc.warnings[0];
if (issue)
throw new Error(`${format} inválido (${issue.code}): ${issue.message}`);
if (doc.directives?.yaml.version !== '1.2')
throw new Error('Somente YAML 1.2 é aceito para preservar os tipos de JSON.');
let count = 0;
function fail(message, node) {
const offset = node?.range?.[0];
const position = offset === undefined ? '' : (() => { const { line, col } = lines.linePos(offset); return ` (linha ${line}, coluna ${col})`; })();
throw new Error(message + position);
}
function convert(node, depth = 0) {
if (++count > 100_000 || depth > 100)
fail('Documento muito complexo: limite de 100 níveis ou 100 mil nós.', node);
if (!node)
return null;
if (isAlias(node))
fail('Aliases YAML não são aceitos: JSON não preserva referências ou ciclos.', node);
if (node.tag && !SAFE_TAGS.has(node.tag))
fail(`Tag não permitida: ${node.tag}.`, node);
if (isScalar(node)) {
const value = node.value;
if (typeof value === 'bigint') {
if (value === BigInt(0) && node.source?.startsWith('-'))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER))
fail('Inteiro fora do intervalo seguro de JSON/JavaScript. Use uma string entre aspas para preservar todos os dígitos.', node);
return Number(value);
}
if (typeof value === 'number') {
if (!Number.isFinite(value))
fail('JSON não representa NaN ou infinito.', node);
if (Number.isInteger(value) && !Number.isSafeInteger(value))
fail('Número inteiro fora do intervalo seguro. Use uma string entre aspas para preservar a precisão.', node);
if (value === 0 && /[1-9]/.test((node.source ?? '').split(/[eE]/)[0]))
fail('Número pequeno demais para a precisão de JavaScript. Use uma string entre aspas.', node);
if (Object.is(value, -0))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
return value;
}
if (value === null || typeof value === 'string' || typeof value === 'boolean')
return value;
fail('Valor não representável em JSON.', node);
}
if (isSeq(node))
return node.items.map(item => convert(item, depth + 1));
if (isMap(node)) {
const result = Object.create(null);
const keys = [];
for (const pair of node.items) {
if (!isScalar(pair.key) || typeof pair.key.value !== 'string')
fail('Chaves de objetos devem ser strings; chaves numéricas, booleanas ou complexas não são preservadas em JSON.', pair.key);
const key = pair.key.value;
if (format === 'YAML' && key === '<<' && pair.key.type === 'PLAIN')
fail('Chaves de merge YAML (<<) não são aceitas.', pair.key);
if (Object.hasOwn(result, key))
fail(`Chave duplicada: ${key}.`, pair.key);
keys.push(key);
result[key] = convert(pair.value, depth + 1);
}
onObjectKeys?.(result, keys);
return result;
}
fail('Estrutura não representável em JSON.', node);
}
if (!doc.contents)
throw new Error('Informe um documento com um valor; use null para um valor nulo.');
return convert(doc.contents);
}
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
function text(value, label) {
if (typeof value !== 'string' || value.length > 100_000)
throw new Error(`${label}: informe texto com até 100 mil caracteres.`);
if (/[\u0000\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value) || value.includes('\0'))
throw new Error(`${label}: NUL ou Unicode inválido.`);
return value;
}
function method(value) {
if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].includes(value))
throw new Error('Método suportado: GET, POST, PUT, PATCH, DELETE, HEAD ou OPTIONS.');
return value;
}
function address(value) {
if (!/^https?:\/\//i.test(value) || /[\s\\\u0000-\u001f\u007f]/u.test(value) || /%(?![\da-f]{2})/i.test(value))
throw new Error('Informe uma URL HTTP/HTTPS absoluta, sem espaços, controles ou escapes percentuais inválidos.');
let url;
try {
url = new URL(value);
}
catch {
throw new Error('URL inválida.');
}
if (url.username || url.password || url.hash)
throw new Error('A URL não pode conter credenciais embutidas ou fragmento.');
// curl expands braces/ranges; this subset never silently expands multiple URLs.
if (/[{}[\]]/.test(value.replace(/\/\/\[[\da-f:]+\]/i, '//ipv6')))
throw new Error('Globbing de URL com chaves ou colchetes não é suportado; use escapes percentuais.');
return value;
}
function header(name, value, entries) {
if (!/^[!#$%&'*+.^_`|~\da-z-]+$/i.test(name) || /[\u0000-\u0008\u000a-\u001f\u007f]/.test(value))
throw new Error('Cabeçalho inválido: nome HTTP e valor sem quebras de linha ou controles são obrigatórios.');
if (!value.trim())
throw new Error('Cabeçalhos vazios ou removidos não são suportados nesta conversão.');
if (/[^\t\x20-\x7e]/.test(value))
throw new Error('Valores de cabeçalhos devem ser ASCII para preservar os bytes entre cURL e Fetch; use Unicode no corpo ou escape na URL.');
if (entries.some(([key]) => key.toLowerCase() === name.toLowerCase()))
throw new Error('Cabeçalho duplicado: ' + name);
if (['host', 'content-length', 'cookie', 'set-cookie', 'connection', 'transfer-encoding', 'accept-encoding', 'origin', 'referer', 'user-agent', 'proxy-authorization', 'expect', 'trailer', 'te', 'upgrade', 'via', 'date', 'dnt', 'keep-alive', 'permissions-policy', 'access-control-request-method', 'access-control-request-headers'].includes(name.toLowerCase()) || /^(sec-|proxy-)/i.test(name) || ['x-http-method', 'x-http-method-override', 'x-method-override'].includes(name.toLowerCase()) && /^(connect|trace|track)$/i.test(value))
throw new Error('Cabeçalho não portável para Fetch no navegador: ' + name);
entries.push([name, value]);
}
function finish(data) {
if (data.body !== undefined && ['GET', 'HEAD'].includes(data.method))
throw new Error('GET e HEAD com corpo não são suportados; o navegador não preservaria a requisição.');
if (data.body !== undefined && !data.headers.some(([name]) => name.toLowerCase() === 'content-type'))
data.headers.push(['Content-Type', 'application/x-www-form-urlencoded']);
if (data.headers.length > 100)
throw new Error('Limite de 100 cabeçalhos.');
return data;
}
return generateCurl(values);
}
return convert(parameters);
}
if (variant === "fetch") {
const parameters = { ...{"command":""}, ...values };
const parseShell = __pacote1["parse"];
function convert(values) {
function curlToJavascript(input, target) {
if (!['fetch', 'axios'].includes(target))
throw new Error('Destino de conversão inválido.');
const data = parseCurl(input);
// Computed keys also preserve __proto__ as data in a copied JS object literal.
const quote = (value) => JSON.stringify(value).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
const headers = '{' + data.headers.map(([name, value]) => '[' + quote(name) + ']: ' + quote(value)).join(', ') + '}';
const lines = [target === 'axios' ? 'import axios from "axios";\n' : '', 'async function executar() {'];
if (target === 'fetch') {
lines.push(' const response = await fetch(' + quote(data.url) + ', {', ' method: ' + quote(data.method) + ',', ' headers: ' + headers + ',', ' credentials: "omit",', ' redirect: "manual",');
if (data.body !== undefined)
lines.push(' body: ' + quote(data.body) + ',');
lines.push(' });', ' return response;', '}');
}
else {
lines.push(' const response = await axios({', ' url: ' + quote(data.url) + ',', ' method: ' + quote(data.method) + ',', ' headers: ' + headers + ',', ' withCredentials: false,', ' maxRedirects: 0,', ' validateStatus: () => true,', ' transformRequest: [(data) => data],', ' transformResponse: [(data) => data],', ' responseType: "text",');
if (data.body !== undefined)
lines.push(' data: ' + quote(data.body) + ',');
lines.push(' });', ' return response;', '}');
}
return lines.filter((line, index) => line !== '' || index !== 0).join('\n');
}
function parseCurl(input) {
const words = shellWords(text(input, 'Comando cURL').trim());
if (words.shift() !== 'curl')
throw new Error('A entrada deve começar com curl (sintaxe POSIX, sem executar o comando).');
let verb, url, body;
const entries = [];
for (let index = 0; index < words.length; index++) {
let option = words[index], inline;
if (option.startsWith('--') && option.includes('=')) {
const at = option.indexOf('=');
inline = option.slice(at + 1);
option = option.slice(0, at);
}
const supported = ['-X', '--request', '-H', '--header', '--url', '-d', '--data', '--data-raw', '--data-binary'];
if (supported.includes(option)) {
const value = inline ?? words[++index];
if (value === undefined)
throw new Error('Falta o valor da opção ' + option + '.');
if (option === '-X' || option === '--request') {
if (verb !== undefined)
throw new Error('Método repetido não é suportado.');
verb = method(value);
}
else if (option === '--url') {
if (url !== undefined)
throw new Error('Somente uma URL é permitida.');
url = address(value);
}
else if (option === '-H' || option === '--header') {
const at = value.indexOf(':');
if (at < 1)
throw new Error('Cabeçalho precisa seguir Nome: valor; arquivos @ não são suportados.');
header(value.slice(0, at), value.slice(at + 1).replace(/^[\t ]+/, ''), entries);
}
else {
if (body !== undefined)
throw new Error('Múltiplos corpos/opções de dados não são suportados.');
if (option !== '--data-raw' && value.startsWith('@'))
throw new Error('Leitura de arquivos ou stdin (@) não é suportada; use corpo literal com --data-raw.');
if (['-d', '--data'].includes(option) && /[\r\n]/.test(value))
throw new Error('--data com quebras de linha não é suportado; use --data-raw ou --data-binary literal.');
body = value;
}
}
else if (option.startsWith('-'))
throw new Error('Opção cURL não suportada: ' + option + '. Não será ignorada.');
else {
if (url !== undefined)
throw new Error('Argumento extra ou múltiplas URLs não são suportados: ' + option);
url = address(option);
}
}
if (!url)
throw new Error('Informe uma URL HTTP/HTTPS no comando.');
return finish({ method: verb ?? (body !== undefined ? 'POST' : 'GET'), url, headers: entries, ...(body !== undefined ? { body } : {}) });
}
function text(value, label) {
if (typeof value !== 'string' || value.length > 100_000)
throw new Error(`${label}: informe texto com até 100 mil caracteres.`);
if (/[\u0000\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value) || value.includes('\0'))
throw new Error(`${label}: NUL ou Unicode inválido.`);
return value;
}
function method(value) {
if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].includes(value))
throw new Error('Método suportado: GET, POST, PUT, PATCH, DELETE, HEAD ou OPTIONS.');
return value;
}
function address(value) {
if (!/^https?:\/\//i.test(value) || /[\s\\\u0000-\u001f\u007f]/u.test(value) || /%(?![\da-f]{2})/i.test(value))
throw new Error('Informe uma URL HTTP/HTTPS absoluta, sem espaços, controles ou escapes percentuais inválidos.');
let url;
try {
url = new URL(value);
}
catch {
throw new Error('URL inválida.');
}
if (url.username || url.password || url.hash)
throw new Error('A URL não pode conter credenciais embutidas ou fragmento.');
// curl expands braces/ranges; this subset never silently expands multiple URLs.
if (/[{}[\]]/.test(value.replace(/\/\/\[[\da-f:]+\]/i, '//ipv6')))
throw new Error('Globbing de URL com chaves ou colchetes não é suportado; use escapes percentuais.');
return value;
}
function header(name, value, entries) {
if (!/^[!#$%&'*+.^_`|~\da-z-]+$/i.test(name) || /[\u0000-\u0008\u000a-\u001f\u007f]/.test(value))
throw new Error('Cabeçalho inválido: nome HTTP e valor sem quebras de linha ou controles são obrigatórios.');
if (!value.trim())
throw new Error('Cabeçalhos vazios ou removidos não são suportados nesta conversão.');
if (/[^\t\x20-\x7e]/.test(value))
throw new Error('Valores de cabeçalhos devem ser ASCII para preservar os bytes entre cURL e Fetch; use Unicode no corpo ou escape na URL.');
if (entries.some(([key]) => key.toLowerCase() === name.toLowerCase()))
throw new Error('Cabeçalho duplicado: ' + name);
if (['host', 'content-length', 'cookie', 'set-cookie', 'connection', 'transfer-encoding', 'accept-encoding', 'origin', 'referer', 'user-agent', 'proxy-authorization', 'expect', 'trailer', 'te', 'upgrade', 'via', 'date', 'dnt', 'keep-alive', 'permissions-policy', 'access-control-request-method', 'access-control-request-headers'].includes(name.toLowerCase()) || /^(sec-|proxy-)/i.test(name) || ['x-http-method', 'x-http-method-override', 'x-method-override'].includes(name.toLowerCase()) && /^(connect|trace|track)$/i.test(value))
throw new Error('Cabeçalho não portável para Fetch no navegador: ' + name);
entries.push([name, value]);
}
function finish(data) {
if (data.body !== undefined && ['GET', 'HEAD'].includes(data.method))
throw new Error('GET e HEAD com corpo não são suportados; o navegador não preservaria a requisição.');
if (data.body !== undefined && !data.headers.some(([name]) => name.toLowerCase() === 'content-type'))
data.headers.push(['Content-Type', 'application/x-www-form-urlencoded']);
if (data.headers.length > 100)
throw new Error('Limite de 100 cabeçalhos.');
return data;
}
function shellWords(source) {
let mode = '', escaped = false, normalized = '';
for (let index = 0; index < source.length; index++) {
const char = source[index];
if (escaped) {
escaped = false;
if (char === '\n')
normalized = normalized.slice(0, -1);
else
normalized += char;
continue;
}
normalized += char;
if (mode !== "'" && char === '\\') {
escaped = true;
continue;
}
if (char === "'" && mode !== '"') {
mode = mode ? '' : "'";
continue;
}
if (char === '"' && mode !== "'") {
mode = mode ? '' : '"';
continue;
}
if (mode !== "'" && (char === '$' || char === '`'))
throw new Error('Expansões de variáveis, substituições e aspas ANSI-C não são suportadas (posição ' + (index + 1) + ').');
if (!mode && /[;&|<>()[\]{}*?~#\r\n]/.test(char))
throw new Error('Operador, glob, comentário ou quebra de linha sem continuação não suportado (posição ' + (index + 1) + '). Coloque URLs e dados entre aspas.');
}
if (mode || escaped)
throw new Error('Aspas ou escape incompletos no comando cURL.');
const words = parseShell(normalized, () => { throw new Error('Expansões não são suportadas.'); });
if (words.some(word => typeof word !== 'string'))
throw new Error('Somente um comando cURL literal é permitido; operadores não são suportados.');
if (words.length > 1000)
throw new Error('Limite de 1000 argumentos.');
return words;
}
return curlToJavascript(values.command, "fetch");
}
return convert(parameters);
}
if (variant === "axios") {
const parameters = { ...{"command":""}, ...values };
const parseShell = __pacote1["parse"];
function convert(values) {
function curlToJavascript(input, target) {
if (!['fetch', 'axios'].includes(target))
throw new Error('Destino de conversão inválido.');
const data = parseCurl(input);
// Computed keys also preserve __proto__ as data in a copied JS object literal.
const quote = (value) => JSON.stringify(value).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
const headers = '{' + data.headers.map(([name, value]) => '[' + quote(name) + ']: ' + quote(value)).join(', ') + '}';
const lines = [target === 'axios' ? 'import axios from "axios";\n' : '', 'async function executar() {'];
if (target === 'fetch') {
lines.push(' const response = await fetch(' + quote(data.url) + ', {', ' method: ' + quote(data.method) + ',', ' headers: ' + headers + ',', ' credentials: "omit",', ' redirect: "manual",');
if (data.body !== undefined)
lines.push(' body: ' + quote(data.body) + ',');
lines.push(' });', ' return response;', '}');
}
else {
lines.push(' const response = await axios({', ' url: ' + quote(data.url) + ',', ' method: ' + quote(data.method) + ',', ' headers: ' + headers + ',', ' withCredentials: false,', ' maxRedirects: 0,', ' validateStatus: () => true,', ' transformRequest: [(data) => data],', ' transformResponse: [(data) => data],', ' responseType: "text",');
if (data.body !== undefined)
lines.push(' data: ' + quote(data.body) + ',');
lines.push(' });', ' return response;', '}');
}
return lines.filter((line, index) => line !== '' || index !== 0).join('\n');
}
function parseCurl(input) {
const words = shellWords(text(input, 'Comando cURL').trim());
if (words.shift() !== 'curl')
throw new Error('A entrada deve começar com curl (sintaxe POSIX, sem executar o comando).');
let verb, url, body;
const entries = [];
for (let index = 0; index < words.length; index++) {
let option = words[index], inline;
if (option.startsWith('--') && option.includes('=')) {
const at = option.indexOf('=');
inline = option.slice(at + 1);
option = option.slice(0, at);
}
const supported = ['-X', '--request', '-H', '--header', '--url', '-d', '--data', '--data-raw', '--data-binary'];
if (supported.includes(option)) {
const value = inline ?? words[++index];
if (value === undefined)
throw new Error('Falta o valor da opção ' + option + '.');
if (option === '-X' || option === '--request') {
if (verb !== undefined)
throw new Error('Método repetido não é suportado.');
verb = method(value);
}
else if (option === '--url') {
if (url !== undefined)
throw new Error('Somente uma URL é permitida.');
url = address(value);
}
else if (option === '-H' || option === '--header') {
const at = value.indexOf(':');
if (at < 1)
throw new Error('Cabeçalho precisa seguir Nome: valor; arquivos @ não são suportados.');
header(value.slice(0, at), value.slice(at + 1).replace(/^[\t ]+/, ''), entries);
}
else {
if (body !== undefined)
throw new Error('Múltiplos corpos/opções de dados não são suportados.');
if (option !== '--data-raw' && value.startsWith('@'))
throw new Error('Leitura de arquivos ou stdin (@) não é suportada; use corpo literal com --data-raw.');
if (['-d', '--data'].includes(option) && /[\r\n]/.test(value))
throw new Error('--data com quebras de linha não é suportado; use --data-raw ou --data-binary literal.');
body = value;
}
}
else if (option.startsWith('-'))
throw new Error('Opção cURL não suportada: ' + option + '. Não será ignorada.');
else {
if (url !== undefined)
throw new Error('Argumento extra ou múltiplas URLs não são suportados: ' + option);
url = address(option);
}
}
if (!url)
throw new Error('Informe uma URL HTTP/HTTPS no comando.');
return finish({ method: verb ?? (body !== undefined ? 'POST' : 'GET'), url, headers: entries, ...(body !== undefined ? { body } : {}) });
}
function text(value, label) {
if (typeof value !== 'string' || value.length > 100_000)
throw new Error(`${label}: informe texto com até 100 mil caracteres.`);
if (/[\u0000\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value) || value.includes('\0'))
throw new Error(`${label}: NUL ou Unicode inválido.`);
return value;
}
function method(value) {
if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].includes(value))
throw new Error('Método suportado: GET, POST, PUT, PATCH, DELETE, HEAD ou OPTIONS.');
return value;
}
function address(value) {
if (!/^https?:\/\//i.test(value) || /[\s\\\u0000-\u001f\u007f]/u.test(value) || /%(?![\da-f]{2})/i.test(value))
throw new Error('Informe uma URL HTTP/HTTPS absoluta, sem espaços, controles ou escapes percentuais inválidos.');
let url;
try {
url = new URL(value);
}
catch {
throw new Error('URL inválida.');
}
if (url.username || url.password || url.hash)
throw new Error('A URL não pode conter credenciais embutidas ou fragmento.');
// curl expands braces/ranges; this subset never silently expands multiple URLs.
if (/[{}[\]]/.test(value.replace(/\/\/\[[\da-f:]+\]/i, '//ipv6')))
throw new Error('Globbing de URL com chaves ou colchetes não é suportado; use escapes percentuais.');
return value;
}
function header(name, value, entries) {
if (!/^[!#$%&'*+.^_`|~\da-z-]+$/i.test(name) || /[\u0000-\u0008\u000a-\u001f\u007f]/.test(value))
throw new Error('Cabeçalho inválido: nome HTTP e valor sem quebras de linha ou controles são obrigatórios.');
if (!value.trim())
throw new Error('Cabeçalhos vazios ou removidos não são suportados nesta conversão.');
if (/[^\t\x20-\x7e]/.test(value))
throw new Error('Valores de cabeçalhos devem ser ASCII para preservar os bytes entre cURL e Fetch; use Unicode no corpo ou escape na URL.');
if (entries.some(([key]) => key.toLowerCase() === name.toLowerCase()))
throw new Error('Cabeçalho duplicado: ' + name);
if (['host', 'content-length', 'cookie', 'set-cookie', 'connection', 'transfer-encoding', 'accept-encoding', 'origin', 'referer', 'user-agent', 'proxy-authorization', 'expect', 'trailer', 'te', 'upgrade', 'via', 'date', 'dnt', 'keep-alive', 'permissions-policy', 'access-control-request-method', 'access-control-request-headers'].includes(name.toLowerCase()) || /^(sec-|proxy-)/i.test(name) || ['x-http-method', 'x-http-method-override', 'x-method-override'].includes(name.toLowerCase()) && /^(connect|trace|track)$/i.test(value))
throw new Error('Cabeçalho não portável para Fetch no navegador: ' + name);
entries.push([name, value]);
}
function finish(data) {
if (data.body !== undefined && ['GET', 'HEAD'].includes(data.method))
throw new Error('GET e HEAD com corpo não são suportados; o navegador não preservaria a requisição.');
if (data.body !== undefined && !data.headers.some(([name]) => name.toLowerCase() === 'content-type'))
data.headers.push(['Content-Type', 'application/x-www-form-urlencoded']);
if (data.headers.length > 100)
throw new Error('Limite de 100 cabeçalhos.');
return data;
}
function shellWords(source) {
let mode = '', escaped = false, normalized = '';
for (let index = 0; index < source.length; index++) {
const char = source[index];
if (escaped) {
escaped = false;
if (char === '\n')
normalized = normalized.slice(0, -1);
else
normalized += char;
continue;
}
normalized += char;
if (mode !== "'" && char === '\\') {
escaped = true;
continue;
}
if (char === "'" && mode !== '"') {
mode = mode ? '' : "'";
continue;
}
if (char === '"' && mode !== "'") {
mode = mode ? '' : '"';
continue;
}
if (mode !== "'" && (char === '$' || char === '`'))
throw new Error('Expansões de variáveis, substituições e aspas ANSI-C não são suportadas (posição ' + (index + 1) + ').');
if (!mode && /[;&|<>()[\]{}*?~#\r\n]/.test(char))
throw new Error('Operador, glob, comentário ou quebra de linha sem continuação não suportado (posição ' + (index + 1) + '). Coloque URLs e dados entre aspas.');
}
if (mode || escaped)
throw new Error('Aspas ou escape incompletos no comando cURL.');
const words = parseShell(normalized, () => { throw new Error('Expansões não são suportadas.'); });
if (words.some(word => typeof word !== 'string'))
throw new Error('Somente um comando cURL literal é permitido; operadores não são suportados.');
if (words.length > 1000)
throw new Error('Limite de 1000 argumentos.');
return words;
}
return curlToJavascript(values.command, "axios");
}
return convert(parameters);
}
if (variant === "headers") {
const parameters = { ...{"contentType":"application/json","accept":"application/json","bearerToken":"","headers":"{}","format":"JSON"}, ...values };
const isAlias = __pacote0["isAlias"];
const isMap = __pacote0["isMap"];
const isScalar = __pacote0["isScalar"];
const isSeq = __pacote0["isSeq"];
const LineCounter = __pacote0["LineCounter"];
const parseDocument = __pacote0["parseDocument"];
function convert(values) {
function generateHttpHeaders(values) {
const data = Object.create(null);
const add = (key, value) => {
if (Object.keys(data).some(name => name.toLowerCase() === key.toLowerCase()))
throw new Error('Cabeçalho repetido entre os campos e o JSON adicional: ' + key);
data[key] = value;
};
const optional = (input, title) => {
const value = text(input, title);
if (/[\x00-\x1f\x7f]/.test(value))
throw new Error(title + ': controles e quebras de linha não são permitidos.');
return value.trim();
};
const contentType = optional(values.contentType, 'Content-Type');
const accept = optional(values.accept, 'Accept');
const token = optional(values.bearerToken, 'Token Bearer');
if (contentType)
add('Content-Type', contentType);
if (accept)
add('Accept', accept);
if (token) {
if (!/^[A-Za-z0-9\-._~+/]+=*$/.test(token))
throw new Error('Token Bearer inválido: informe apenas o token, sem prefixo Bearer, espaços ou controles.');
add('Authorization', 'Bearer ' + token);
}
for (const [key, value] of Object.entries(portableHeaders(values.headers)))
add(key, value);
const checked = checkPortableHeaders(data);
if (values.format === 'JSON')
return result(checked);
if (values.format === 'Texto')
return Object.entries(checked).map(([key, value]) => key + ': ' + value).join('\n');
throw new Error('Escolha JSON ou Texto como formato de saída.');
}
function text(value, label) {
if (typeof value !== 'string')
throw new Error(label + ': informe texto.');
if (value.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
return value;
}
function result(value) {
const output = JSON.stringify(value, null, 2);
if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.');
return output;
}
function checkPortableHeaders(data) {
if (Object.keys(data).length > 100)
throw new Error('Limite de 100 cabeçalhos.');
for (const value of Object.values(data))
if (/[^\t\x20-\x7e]/.test(value))
throw new Error('Valores de cabeçalhos devem ser ASCII, sem quebras de linha. Use Unicode no corpo JSON.');
return data;
}
function portableHeaders(input) {
return checkPortableHeaders(headers(input));
}
function label(input, title, max, optional = false) {
const source = text(input, title);
if (/[\x00-\x1f\x7f]/.test(source))
throw new Error(title + ': controles não são permitidos.');
const value = source.trim();
if ((!value && !optional) || value.length > max || /[\x00-\x1f\x7f\ud800-\udfff]/u.test(value))
throw new Error(`${title}: use texto válido, sem controles, com ${optional ? 'até' : '1 a'} ${max} caracteres.`);
return value;
}
function headers(input) {
const value = json(text(input, 'Cabeçalhos').trim() || '{}', 'Cabeçalhos', true);
const seen = new Set();
for (const [key, content] of Object.entries(value)) {
if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(key))
throw new Error('Nome de cabeçalho inválido: ' + key);
if (seen.has(key.toLowerCase()))
throw new Error('Cabeçalho repetido, ignorando maiúsculas: ' + key);
seen.add(key.toLowerCase());
if (typeof content !== 'string' || /[\x00-\x08\x0a-\x1f\x7f]/.test(content))
throw new Error('Cabeçalho ' + key + ': use uma string sem controles ou quebras de linha.');
}
return value;
}
function json(input, label, objectOnly = false) {
try {
const value = parseJsonCompatible(text(input, label), 'JSON');
if (objectOnly && (!value || typeof value !== 'object' || Array.isArray(value)))
throw new Error('Informe um objeto JSON.');
return value;
}
catch (cause) {
const message = cause && typeof cause === 'object' && 'message' in cause && typeof cause.message === 'string' ? cause.message : 'JSON inválido.';
throw new Error(label + ': ' + message);
}
}
function parseJsonCompatible(input, format, onObjectKeys) {
if (!input.trim())
throw new Error(`Informe um documento ${format}.`);
if (input.length > 1_000_000)
throw new Error('A entrada excede o limite de 1 milhão de caracteres.');
if (format === 'JSON') {
// Syntax check only: do not use the rounded numeric values from JSON.parse.
try {
JSON.parse(input);
}
catch (cause) {
throw new Error(`JSON inválido: ${cause instanceof Error ? cause.message : 'erro de sintaxe'}`);
}
}
const lines = new LineCounter();
const doc = parseDocument(input, { version: '1.2', schema: format === 'JSON' ? 'json' : 'core', intAsBigInt: true, uniqueKeys: true, lineCounter: lines, prettyErrors: true, resolveKnownTags: false });
const issue = doc.errors[0] ?? doc.warnings[0];
if (issue)
throw new Error(`${format} inválido (${issue.code}): ${issue.message}`);
if (doc.directives?.yaml.version !== '1.2')
throw new Error('Somente YAML 1.2 é aceito para preservar os tipos de JSON.');
let count = 0;
function fail(message, node) {
const offset = node?.range?.[0];
const position = offset === undefined ? '' : (() => { const { line, col } = lines.linePos(offset); return ` (linha ${line}, coluna ${col})`; })();
throw new Error(message + position);
}
function convert(node, depth = 0) {
if (++count > 100_000 || depth > 100)
fail('Documento muito complexo: limite de 100 níveis ou 100 mil nós.', node);
if (!node)
return null;
if (isAlias(node))
fail('Aliases YAML não são aceitos: JSON não preserva referências ou ciclos.', node);
if (node.tag && !SAFE_TAGS.has(node.tag))
fail(`Tag não permitida: ${node.tag}.`, node);
if (isScalar(node)) {
const value = node.value;
if (typeof value === 'bigint') {
if (value === BigInt(0) && node.source?.startsWith('-'))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER))
fail('Inteiro fora do intervalo seguro de JSON/JavaScript. Use uma string entre aspas para preservar todos os dígitos.', node);
return Number(value);
}
if (typeof value === 'number') {
if (!Number.isFinite(value))
fail('JSON não representa NaN ou infinito.', node);
if (Number.isInteger(value) && !Number.isSafeInteger(value))
fail('Número inteiro fora do intervalo seguro. Use uma string entre aspas para preservar a precisão.', node);
if (value === 0 && /[1-9]/.test((node.source ?? '').split(/[eE]/)[0]))
fail('Número pequeno demais para a precisão de JavaScript. Use uma string entre aspas.', node);
if (Object.is(value, -0))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
return value;
}
if (value === null || typeof value === 'string' || typeof value === 'boolean')
return value;
fail('Valor não representável em JSON.', node);
}
if (isSeq(node))
return node.items.map(item => convert(item, depth + 1));
if (isMap(node)) {
const result = Object.create(null);
const keys = [];
for (const pair of node.items) {
if (!isScalar(pair.key) || typeof pair.key.value !== 'string')
fail('Chaves de objetos devem ser strings; chaves numéricas, booleanas ou complexas não são preservadas em JSON.', pair.key);
const key = pair.key.value;
if (format === 'YAML' && key === '<<' && pair.key.type === 'PLAIN')
fail('Chaves de merge YAML (<<) não são aceitas.', pair.key);
if (Object.hasOwn(result, key))
fail(`Chave duplicada: ${key}.`, pair.key);
keys.push(key);
result[key] = convert(pair.value, depth + 1);
}
onObjectKeys?.(result, keys);
return result;
}
fail('Estrutura não representável em JSON.', node);
}
if (!doc.contents)
throw new Error('Informe um documento com um valor; use null para um valor nulo.');
return convert(doc.contents);
}
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
return generateHttpHeaders(values);
}
return convert(parameters);
}
throw new Error("Selecione uma modalidade válida de API.");
}
return convertSelected();
}
import json
import math
import re
from urllib.parse import urlsplit
import shlex
def executar(values):
variant = values.get("variant", "rest")
if variant == "rest":
parameters = {**{"method": "GET", "url": "", "headers": "{\"Content-Type\":\"application/json\"}", "body": ""}, **values}
def convert(values):
def text(value, label):
if not isinstance(value, str): raise ValueError(label + ': informe texto')
if len(value.encode('utf-16-le', errors='surrogatepass')) // 2 > 100000: raise ValueError(label + ': limite de 100 mil caracteres')
return value
def read(source, label, object_only=False):
text(source, label)
if not source.strip(): raise ValueError(label + ': informe JSON')
def pairs(items):
output = {}
for key, value in items:
if key in output: raise ValueError('Chave duplicada: ' + key)
output[key] = value
return output
def number(token):
if '.' not in token and 'e' not in token.lower() and len(token.lstrip('-')) > 16: raise ValueError('Inteiro fora do intervalo seguro; use string')
value = float(token) if '.' in token or 'e' in token.lower() else int(token)
if not math.isfinite(value): raise ValueError('Número não finito')
if value == 0 and (token.startswith('-') or re.search('[1-9]', token.lower().split('e')[0])): raise ValueError('Zero negativo ou underflow')
if value % 1 == 0 and abs(value) > 9007199254740991: raise ValueError('Inteiro fora do intervalo seguro; use string')
return value
def reject(value): raise ValueError('Constante JSON inválida: ' + value)
value = json.loads(source, object_pairs_hook=pairs, parse_int=number, parse_float=number, parse_constant=reject)
count = 0
def walk(value, depth=0):
nonlocal count
count += 1
if count > 100000 or depth > 100: raise ValueError('Limite de 100 níveis ou 100 mil nós JSON')
if isinstance(value, dict):
for child in value.values(): walk(child, depth + 1)
elif isinstance(value, list):
for child in value: walk(child, depth + 1)
walk(value)
if object_only and not isinstance(value, dict): raise ValueError(label + ': informe um objeto JSON')
return value
def output(value):
result = json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False)
if len(result.encode('utf-16-le', errors='surrogatepass')) // 2 > 1000000: raise ValueError('Resultado excede 1 milhão de caracteres')
return result
def method(value):
value = text(value, 'Método').strip()
if value not in ('GET','POST','PUT','PATCH','DELETE','HEAD','OPTIONS'): raise ValueError('Método HTTP não suportado')
return value
def address(value, mock):
value = text(value, 'Caminho' if mock else 'URL').strip()
if not value or re.search(r'[\s\\\x00-\x1f\x7f]', value) or '#' in value or re.search(r'%(?![0-9a-fA-F]{2})', value): raise ValueError('URL/caminho inválido')
relative = value.startswith('/') and not value.startswith('//')
if mock and (not relative or '?' in value): raise ValueError('O mock exige caminho local sem domínio ou parâmetros')
if not relative and not re.match(r'https?://[^/]', value, re.I): raise ValueError('Use HTTP, HTTPS ou caminho local iniciado por /')
parsed = urlsplit('https://example.invalid' + value if relative else value)
if parsed.scheme not in ('http','https') or not parsed.hostname or parsed.username is not None or parsed.password is not None: raise ValueError('URL com credenciais ou protocolo inválido')
if parsed.port is not None and not 0 <= parsed.port <= 65535: raise ValueError('Porta inválida')
return value
def headers(value):
data = read(text(value, 'Cabeçalhos').strip() or '{}', 'Cabeçalhos', True)
seen = set()
for key, content in data.items():
if not re.fullmatch(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+", key): raise ValueError('Nome de cabeçalho inválido: ' + key)
if key.lower() in seen: raise ValueError('Cabeçalho repetido: ' + key)
seen.add(key.lower())
if not isinstance(content, str) or re.search(r'[\x00-\x08\x0a-\x1f\x7f]', content): raise ValueError('Cabeçalho deve ser string sem controles')
return data
def generate_rest(values):
verb = method(values['method'])
body = text(values['body'], 'Corpo')
data = {'method': verb, 'url': address(values['url'], False), 'headers': headers(values['headers'])}
if body.strip():
if verb in ('GET','HEAD'): raise ValueError('GET/HEAD exigem corpo vazio')
data['body'] = read(body, 'Corpo da requisição')
return output(data)
return generate_rest(values)
return convert(parameters)
if variant == "curl":
parameters = {**{"method": "GET", "url": "", "headers": "{}", "body": ""}, **values}
def convert(values):
def header(name, value, entries):
if not isinstance(value, str) or not re.fullmatch("[!#$%&'*+.^_`|~\\da-z-]+", name, re.I) or re.search('[\\x00-\\x08\\x0a-\\x1f\\x7f]', value):
raise ValueError('Cabeçalho inválido')
if not value.strip():
raise ValueError('Cabeçalho vazio não suportado')
if re.search('[^\\t\\x20-\\x7e]', value):
raise ValueError('Valores de cabeçalhos devem ser ASCII')
if any((key.lower() == name.lower() for (key, _) in entries)):
raise ValueError('Cabeçalho duplicado: ' + name)
blocked = ('host', 'content-length', 'cookie', 'set-cookie', 'connection', 'transfer-encoding', 'accept-encoding', 'origin', 'referer', 'user-agent', 'proxy-authorization', 'expect', 'trailer', 'te', 'upgrade', 'via', 'date', 'dnt', 'keep-alive', 'permissions-policy', 'access-control-request-method', 'access-control-request-headers')
if name.lower() in blocked or re.match('^(sec-|proxy-)', name, re.I) or (name.lower() in ('x-http-method', 'x-http-method-override', 'x-method-override') and value.upper() in ('CONNECT', 'TRACE', 'TRACK')):
raise ValueError('Cabeçalho não portável para Fetch: ' + name)
entries.append((name, value))
def method(value):
if value not in ('GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'):
raise ValueError('Método HTTP não suportado')
return value
def address(value):
if not re.match('^https?://', value, re.I) or re.search('[\\s\\\\\\x00-\\x1f\\x7f]|%(?![\\da-fA-F]{2})', value):
raise ValueError('URL HTTP/HTTPS inválida')
parsed = urlsplit(value)
if not parsed.hostname or parsed.username or parsed.password or parsed.fragment or (parsed.port is not None and parsed.port > 65535):
raise ValueError('URL com credenciais, fragmento ou porta inválida')
if re.search('[{}\\[\\]]', re.sub('//\\[[\\da-f:]+\\]', '//ipv6', value, flags=re.I)):
raise ValueError('Globbing de URL não suportado')
return value
def finish(data):
if 'body' in data and data['method'] in ('GET', 'HEAD'):
raise ValueError('GET/HEAD com corpo não suportado')
if 'body' in data and (not any((name.lower() == 'content-type' for (name, _) in data['headers']))):
data['headers'].append(('Content-Type', 'application/x-www-form-urlencoded'))
if len(data['headers']) > 100:
raise ValueError('Limite de 100 cabeçalhos')
return data
def text(value, label):
if not isinstance(value, str) or len(value.encode('utf-16-le', errors='surrogatepass')) // 2 > 100000:
raise ValueError(label + ': informe texto com até 100 mil caracteres')
if '\x00' in value or any((55296 <= ord(c) <= 57343 for c in value)):
raise ValueError(label + ': NUL ou Unicode inválido')
return value
def read(source, label, object_only=False):
text(source, label)
if not source.strip():
raise ValueError(label + ': informe JSON')
def pairs(items):
result = {}
for (key, value) in items:
if key in result:
raise ValueError('Chave duplicada: ' + key)
result[key] = value
return result
def number(token):
if '.' not in token and 'e' not in token.lower() and (len(token.lstrip('-')) > 16):
raise ValueError('Inteiro fora do intervalo seguro; use string')
value = float(token) if '.' in token or 'e' in token.lower() else int(token)
if not math.isfinite(value):
raise ValueError('Número não finito')
if value == 0 and (token.startswith('-') or re.search('[1-9]', token.lower().split('e')[0])):
raise ValueError('Zero negativo ou underflow')
if value % 1 == 0 and abs(value) > 9007199254740991:
raise ValueError('Inteiro fora do intervalo seguro; use string')
return value
def reject(value):
raise ValueError('Constante JSON inválida: ' + value)
value = json.loads(source, object_pairs_hook=pairs, parse_int=number, parse_float=number, parse_constant=reject)
count = 0
def walk(value, depth=0):
nonlocal count
count += 1
if count > 100000 or depth > 100:
raise ValueError('Limite de 100 níveis ou 100 mil nós JSON')
if isinstance(value, dict):
for child in value.values():
walk(child, depth + 1)
elif isinstance(value, list):
for child in value:
walk(child, depth + 1)
walk(value)
if object_only and (not isinstance(value, dict)):
raise ValueError(label + ': informe objeto JSON')
return value
def generate_curl(values):
(url, verb) = (address(text(values['url'], 'URL').strip()), method(text(values['method'], 'Método')))
(source, entries) = (text(values['headers'], 'Cabeçalhos'), [])
data = read(source if source.strip() else '{}', 'Cabeçalhos', True)
for (name, value) in data.items():
header(name, value, entries)
body = text(values['body'], 'Corpo')
data = {'method': verb, 'url': url, 'headers': entries}
if body != '':
data['body'] = body
data = finish(data)
def quote(value):
return "'" + value.replace("'", "'\\''") + "'"
args = ['curl', '--request', quote(data['method']), '--url', quote(data['url'])]
for (name, value) in data['headers']:
args += ['--header', quote(name + ': ' + value)]
if 'body' in data:
args += ['--data-raw', quote(data['body'])]
return ' '.join(args)
return generate_curl(values)
return convert(parameters)
if variant == "fetch":
parameters = {**{"command": ""}, **values}
def convert(values):
def header(name, value, entries):
if not isinstance(value, str) or not re.fullmatch("[!#$%&'*+.^_`|~\\da-z-]+", name, re.I) or re.search('[\\x00-\\x08\\x0a-\\x1f\\x7f]', value):
raise ValueError('Cabeçalho inválido')
if not value.strip():
raise ValueError('Cabeçalho vazio não suportado')
if re.search('[^\\t\\x20-\\x7e]', value):
raise ValueError('Valores de cabeçalhos devem ser ASCII')
if any((key.lower() == name.lower() for (key, _) in entries)):
raise ValueError('Cabeçalho duplicado: ' + name)
blocked = ('host', 'content-length', 'cookie', 'set-cookie', 'connection', 'transfer-encoding', 'accept-encoding', 'origin', 'referer', 'user-agent', 'proxy-authorization', 'expect', 'trailer', 'te', 'upgrade', 'via', 'date', 'dnt', 'keep-alive', 'permissions-policy', 'access-control-request-method', 'access-control-request-headers')
if name.lower() in blocked or re.match('^(sec-|proxy-)', name, re.I) or (name.lower() in ('x-http-method', 'x-http-method-override', 'x-method-override') and value.upper() in ('CONNECT', 'TRACE', 'TRACK')):
raise ValueError('Cabeçalho não portável para Fetch: ' + name)
entries.append((name, value))
def address(value):
if not re.match('^https?://', value, re.I) or re.search('[\\s\\\\\\x00-\\x1f\\x7f]|%(?![\\da-fA-F]{2})', value):
raise ValueError('URL HTTP/HTTPS inválida')
parsed = urlsplit(value)
if not parsed.hostname or parsed.username or parsed.password or parsed.fragment or (parsed.port is not None and parsed.port > 65535):
raise ValueError('URL com credenciais, fragmento ou porta inválida')
if re.search('[{}\\[\\]]', re.sub('//\\[[\\da-f:]+\\]', '//ipv6', value, flags=re.I)):
raise ValueError('Globbing de URL não suportado')
return value
def method(value):
if value not in ('GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'):
raise ValueError('Método HTTP não suportado')
return value
def text(value, label):
if not isinstance(value, str) or len(value.encode('utf-16-le', errors='surrogatepass')) // 2 > 100000:
raise ValueError(label + ': informe texto com até 100 mil caracteres')
if '\x00' in value or any((55296 <= ord(c) <= 57343 for c in value)):
raise ValueError(label + ': NUL ou Unicode inválido')
return value
def finish(data):
if 'body' in data and data['method'] in ('GET', 'HEAD'):
raise ValueError('GET/HEAD com corpo não suportado')
if 'body' in data and (not any((name.lower() == 'content-type' for (name, _) in data['headers']))):
data['headers'].append(('Content-Type', 'application/x-www-form-urlencoded'))
if len(data['headers']) > 100:
raise ValueError('Limite de 100 cabeçalhos')
return data
def shell_words(source):
(mode, escaped) = ('', False)
for (index, char) in enumerate(source):
if escaped:
escaped = False
continue
if mode != "'" and char == '\\':
escaped = True
continue
if char == "'" and mode != '"':
mode = '' if mode else "'"
continue
if char == '"' and mode != "'":
mode = '' if mode else '"'
continue
if mode != "'" and char in '$`':
raise ValueError('Expansão não suportada na posição ' + str(index + 1))
if not mode and char in ';&|<>()[\\]{}*?~#\r\n':
raise ValueError('Operador/glob/comentário não suportado na posição ' + str(index + 1))
if mode or escaped:
raise ValueError('Aspas ou escape incompletos')
(cleaned, mode, index) = ('', '', 0)
while index < len(source):
char = source[index]
if char == '\\' and mode != "'" and (index + 1 < len(source)):
if source[index + 1] == '\n':
index += 2
continue
if mode == '"' and source[index + 1] in '$`':
cleaned += source[index + 1]
index += 2
continue
cleaned += source[index:index + 2]
index += 2
continue
if char in '\'"' and (not mode or mode == char):
mode = '' if mode else char
cleaned += char
index += 1
words = shlex.split(cleaned, comments=False, posix=True)
if len(words) > 1000:
raise ValueError('Limite de 1000 argumentos')
return words
def parse_curl(source):
words = shell_words(text(source, 'Comando cURL').strip())
if not words or words.pop(0) != 'curl':
raise ValueError('A entrada deve começar com curl')
(verb, url, body, has_body, entries, index) = (None, None, '', False, [], 0)
supported = ('-X', '--request', '-H', '--header', '--url', '-d', '--data', '--data-raw', '--data-binary')
while index < len(words):
(option, inline) = (words[index], None)
if option.startswith('--') and '=' in option:
(option, inline) = option.split('=', 1)
if option in supported:
if inline is None:
index += 1
if index >= len(words):
raise ValueError('Falta valor de ' + option)
value = words[index]
else:
value = inline
if option in ('-X', '--request'):
if verb is not None:
raise ValueError('Método repetido')
verb = method(value)
elif option == '--url':
if url is not None:
raise ValueError('Múltiplas URLs')
url = address(value)
elif option in ('-H', '--header'):
at = value.find(':')
if at < 1:
raise ValueError('Cabeçalho precisa de Nome: valor')
header(value[:at], value[at + 1:].lstrip('\t '), entries)
else:
if has_body:
raise ValueError('Múltiplos corpos')
if option != '--data-raw' and value.startswith('@'):
raise ValueError('Arquivo/entrada @ não suportado')
if option in ('-d', '--data') and re.search('[\\r\\n]', value):
raise ValueError('Use --data-raw para corpo multilinha')
(body, has_body) = (value, True)
elif option.startswith('-'):
raise ValueError('Opção cURL não suportada: ' + option)
else:
if url is not None:
raise ValueError('Argumento extra ou múltiplas URLs')
url = address(option)
index += 1
if url is None:
raise ValueError('Informe uma URL HTTP/HTTPS')
data = {'method': verb or ('POST' if has_body else 'GET'), 'url': url, 'headers': entries}
if has_body:
data['body'] = body
return finish(data)
def convert_curl(source, target):
data = parse_curl(source)
def quote(value):
return json.dumps(value, ensure_ascii=False, separators=(',', ':')).replace('\u2028', '\\u2028').replace('\u2029', '\\u2029')
headers = '{' + ', '.join(('[' + quote(name) + ']: ' + quote(value) for (name, value) in data['headers'])) + '}'
lines = ['import axios from "axios";\n'] if target == 'axios' else []
lines += ['async function executar() {']
if target == 'fetch':
lines += [' const response = await fetch(' + quote(data['url']) + ', {', ' method: ' + quote(data['method']) + ',', ' headers: ' + headers + ',', ' credentials: "omit",', ' redirect: "manual",']
if 'body' in data:
lines += [' body: ' + quote(data['body']) + ',']
lines += [' });', ' return response;', '}']
else:
lines += [' const response = await axios({', ' url: ' + quote(data['url']) + ',', ' method: ' + quote(data['method']) + ',', ' headers: ' + headers + ',', ' withCredentials: false,', ' maxRedirects: 0,', ' validateStatus: () => true,', ' transformRequest: [(data) => data],', ' transformResponse: [(data) => data],', ' responseType: "text",']
if 'body' in data:
lines += [' data: ' + quote(data['body']) + ',']
lines += [' });', ' return response;', '}']
return '\n'.join(lines)
return convert_curl(values["command"], 'fetch')
return convert(parameters)
if variant == "axios":
parameters = {**{"command": ""}, **values}
def convert(values):
def header(name, value, entries):
if not isinstance(value, str) or not re.fullmatch("[!#$%&'*+.^_`|~\\da-z-]+", name, re.I) or re.search('[\\x00-\\x08\\x0a-\\x1f\\x7f]', value):
raise ValueError('Cabeçalho inválido')
if not value.strip():
raise ValueError('Cabeçalho vazio não suportado')
if re.search('[^\\t\\x20-\\x7e]', value):
raise ValueError('Valores de cabeçalhos devem ser ASCII')
if any((key.lower() == name.lower() for (key, _) in entries)):
raise ValueError('Cabeçalho duplicado: ' + name)
blocked = ('host', 'content-length', 'cookie', 'set-cookie', 'connection', 'transfer-encoding', 'accept-encoding', 'origin', 'referer', 'user-agent', 'proxy-authorization', 'expect', 'trailer', 'te', 'upgrade', 'via', 'date', 'dnt', 'keep-alive', 'permissions-policy', 'access-control-request-method', 'access-control-request-headers')
if name.lower() in blocked or re.match('^(sec-|proxy-)', name, re.I) or (name.lower() in ('x-http-method', 'x-http-method-override', 'x-method-override') and value.upper() in ('CONNECT', 'TRACE', 'TRACK')):
raise ValueError('Cabeçalho não portável para Fetch: ' + name)
entries.append((name, value))
def address(value):
if not re.match('^https?://', value, re.I) or re.search('[\\s\\\\\\x00-\\x1f\\x7f]|%(?![\\da-fA-F]{2})', value):
raise ValueError('URL HTTP/HTTPS inválida')
parsed = urlsplit(value)
if not parsed.hostname or parsed.username or parsed.password or parsed.fragment or (parsed.port is not None and parsed.port > 65535):
raise ValueError('URL com credenciais, fragmento ou porta inválida')
if re.search('[{}\\[\\]]', re.sub('//\\[[\\da-f:]+\\]', '//ipv6', value, flags=re.I)):
raise ValueError('Globbing de URL não suportado')
return value
def method(value):
if value not in ('GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'):
raise ValueError('Método HTTP não suportado')
return value
def text(value, label):
if not isinstance(value, str) or len(value.encode('utf-16-le', errors='surrogatepass')) // 2 > 100000:
raise ValueError(label + ': informe texto com até 100 mil caracteres')
if '\x00' in value or any((55296 <= ord(c) <= 57343 for c in value)):
raise ValueError(label + ': NUL ou Unicode inválido')
return value
def finish(data):
if 'body' in data and data['method'] in ('GET', 'HEAD'):
raise ValueError('GET/HEAD com corpo não suportado')
if 'body' in data and (not any((name.lower() == 'content-type' for (name, _) in data['headers']))):
data['headers'].append(('Content-Type', 'application/x-www-form-urlencoded'))
if len(data['headers']) > 100:
raise ValueError('Limite de 100 cabeçalhos')
return data
def shell_words(source):
(mode, escaped) = ('', False)
for (index, char) in enumerate(source):
if escaped:
escaped = False
continue
if mode != "'" and char == '\\':
escaped = True
continue
if char == "'" and mode != '"':
mode = '' if mode else "'"
continue
if char == '"' and mode != "'":
mode = '' if mode else '"'
continue
if mode != "'" and char in '$`':
raise ValueError('Expansão não suportada na posição ' + str(index + 1))
if not mode and char in ';&|<>()[\\]{}*?~#\r\n':
raise ValueError('Operador/glob/comentário não suportado na posição ' + str(index + 1))
if mode or escaped:
raise ValueError('Aspas ou escape incompletos')
(cleaned, mode, index) = ('', '', 0)
while index < len(source):
char = source[index]
if char == '\\' and mode != "'" and (index + 1 < len(source)):
if source[index + 1] == '\n':
index += 2
continue
if mode == '"' and source[index + 1] in '$`':
cleaned += source[index + 1]
index += 2
continue
cleaned += source[index:index + 2]
index += 2
continue
if char in '\'"' and (not mode or mode == char):
mode = '' if mode else char
cleaned += char
index += 1
words = shlex.split(cleaned, comments=False, posix=True)
if len(words) > 1000:
raise ValueError('Limite de 1000 argumentos')
return words
def parse_curl(source):
words = shell_words(text(source, 'Comando cURL').strip())
if not words or words.pop(0) != 'curl':
raise ValueError('A entrada deve começar com curl')
(verb, url, body, has_body, entries, index) = (None, None, '', False, [], 0)
supported = ('-X', '--request', '-H', '--header', '--url', '-d', '--data', '--data-raw', '--data-binary')
while index < len(words):
(option, inline) = (words[index], None)
if option.startswith('--') and '=' in option:
(option, inline) = option.split('=', 1)
if option in supported:
if inline is None:
index += 1
if index >= len(words):
raise ValueError('Falta valor de ' + option)
value = words[index]
else:
value = inline
if option in ('-X', '--request'):
if verb is not None:
raise ValueError('Método repetido')
verb = method(value)
elif option == '--url':
if url is not None:
raise ValueError('Múltiplas URLs')
url = address(value)
elif option in ('-H', '--header'):
at = value.find(':')
if at < 1:
raise ValueError('Cabeçalho precisa de Nome: valor')
header(value[:at], value[at + 1:].lstrip('\t '), entries)
else:
if has_body:
raise ValueError('Múltiplos corpos')
if option != '--data-raw' and value.startswith('@'):
raise ValueError('Arquivo/entrada @ não suportado')
if option in ('-d', '--data') and re.search('[\\r\\n]', value):
raise ValueError('Use --data-raw para corpo multilinha')
(body, has_body) = (value, True)
elif option.startswith('-'):
raise ValueError('Opção cURL não suportada: ' + option)
else:
if url is not None:
raise ValueError('Argumento extra ou múltiplas URLs')
url = address(option)
index += 1
if url is None:
raise ValueError('Informe uma URL HTTP/HTTPS')
data = {'method': verb or ('POST' if has_body else 'GET'), 'url': url, 'headers': entries}
if has_body:
data['body'] = body
return finish(data)
def convert_curl(source, target):
data = parse_curl(source)
def quote(value):
return json.dumps(value, ensure_ascii=False, separators=(',', ':')).replace('\u2028', '\\u2028').replace('\u2029', '\\u2029')
headers = '{' + ', '.join(('[' + quote(name) + ']: ' + quote(value) for (name, value) in data['headers'])) + '}'
lines = ['import axios from "axios";\n'] if target == 'axios' else []
lines += ['async function executar() {']
if target == 'fetch':
lines += [' const response = await fetch(' + quote(data['url']) + ', {', ' method: ' + quote(data['method']) + ',', ' headers: ' + headers + ',', ' credentials: "omit",', ' redirect: "manual",']
if 'body' in data:
lines += [' body: ' + quote(data['body']) + ',']
lines += [' });', ' return response;', '}']
else:
lines += [' const response = await axios({', ' url: ' + quote(data['url']) + ',', ' method: ' + quote(data['method']) + ',', ' headers: ' + headers + ',', ' withCredentials: false,', ' maxRedirects: 0,', ' validateStatus: () => true,', ' transformRequest: [(data) => data],', ' transformResponse: [(data) => data],', ' responseType: "text",']
if 'body' in data:
lines += [' data: ' + quote(data['body']) + ',']
lines += [' });', ' return response;', '}']
return '\n'.join(lines)
return convert_curl(values["command"], 'axios')
return convert(parameters)
if variant == "headers":
parameters = {**{"contentType": "application/json", "accept": "application/json", "bearerToken": "", "headers": "{}", "format": "JSON"}, **values}
def convert(values):
def label(value, title, limit, optional=False):
value = text(value, title)
if re.search('[\\x00-\\x1f\\x7f]', value):
raise ValueError('Controles não permitidos')
value = value.strip()
if not value and (not optional) or len(value.encode('utf-16-le', errors='surrogatepass')) // 2 > limit or re.search('[\\x00-\\x1f\\x7f\\ud800-\\udfff]', value):
raise ValueError(title + ': texto inválido ou fora do limite')
return value
def read(source, label, object_only=False):
text(source, label)
if not source.strip():
raise ValueError(label + ': informe JSON')
def pairs(items):
result = {}
for (key, value) in items:
if key in result:
raise ValueError('Chave duplicada: ' + key)
result[key] = value
return result
def number(token):
if '.' not in token and 'e' not in token.lower() and (len(token.lstrip('-')) > 16):
raise ValueError('Inteiro fora do intervalo seguro; use string')
value = float(token) if '.' in token or 'e' in token.lower() else int(token)
if not math.isfinite(value):
raise ValueError('Número não finito')
if value == 0 and (token.startswith('-') or re.search('[1-9]', token.lower().split('e')[0])):
raise ValueError('Zero negativo ou underflow')
if value % 1 == 0 and abs(value) > 9007199254740991:
raise ValueError('Inteiro fora do intervalo seguro; use string')
return value
def reject(value):
raise ValueError('Constante JSON inválida: ' + value)
value = json.loads(source, object_pairs_hook=pairs, parse_int=number, parse_float=number, parse_constant=reject)
count = 0
def walk(value, depth=0):
nonlocal count
count += 1
if count > 100000 or depth > 100:
raise ValueError('Limite de 100 níveis ou 100 mil nós JSON')
if isinstance(value, dict):
for child in value.values():
walk(child, depth + 1)
elif isinstance(value, list):
for child in value:
walk(child, depth + 1)
walk(value)
if object_only and (not isinstance(value, dict)):
raise ValueError(label + ': informe objeto JSON')
return value
def portable_headers(source):
source = text(source, 'Cabeçalhos')
data = read(source if source.strip() else '{}', 'Cabeçalhos', True)
seen = set()
for (name, value) in data.items():
if not re.fullmatch("[!#$%&'*+\\-.^_`|~0-9A-Za-z]+", name):
raise ValueError('Nome de cabeçalho inválido')
if name.lower() in seen:
raise ValueError('Cabeçalho repetido')
seen.add(name.lower())
if not isinstance(value, str) or re.search('[^\\t\\x20-\\x7e]', value):
raise ValueError('Cabeçalhos exigem strings ASCII sem quebras de linha')
if len(data) > 100:
raise ValueError('Limite de 100 cabeçalhos')
return data
def output(value):
source = json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False)
source = source.encode('utf-8', errors='backslashreplace').decode('utf-8')
if len(source.encode('utf-16-le')) // 2 > 1000000:
raise ValueError('Limite de 1 milhão na saída')
return source
def text(value, title):
if not isinstance(value, str) or len(value.encode('utf-16-le', errors='surrogatepass')) // 2 > 100000:
raise ValueError(title + ': limite de 100 mil unidades UTF-16')
return value
def generate_headers(values):
data = {}
def add(key, value):
if any((name.lower() == key.lower() for name in data)):
raise ValueError('Cabeçalho repetido entre os campos e o JSON')
data[key] = value
def optional(value, title):
value = text(value, title)
if re.search('[\\x00-\\x1f\\x7f]', value):
raise ValueError('Controles não permitidos')
return value.strip()
(content_type, accept, token) = (optional(values['contentType'], 'Content-Type'), optional(values['accept'], 'Accept'), optional(values['bearerToken'], 'Token'))
if content_type:
add('Content-Type', content_type)
if accept:
add('Accept', accept)
if token:
if not re.fullmatch('[A-Za-z0-9\\-._~+/]+=*', token):
raise ValueError('Token Bearer inválido')
add('Authorization', 'Bearer ' + token)
for (key, value) in portable_headers(values['headers']).items():
add(key, value)
if len(data) > 100 or any((re.search('[^\\t\\x20-\\x7e]', value) for value in data.values())):
raise ValueError('Limite de 100 cabeçalhos com valores ASCII')
def index_key(key):
return bool(re.fullmatch('0|[1-9][0-9]*', key)) and len(key) <= 10 and (int(key) <= 4294967294)
ordered = {key: data[key] for key in sorted((key for key in data if index_key(key)), key=int)}
ordered.update(((key, value) for (key, value) in data.items() if not index_key(key)))
if values['format'] == 'JSON':
return output(ordered)
if values['format'] == 'Texto':
return '\n'.join((key + ': ' + value for (key, value) in ordered.items()))
raise ValueError('Escolha JSON ou Texto')
return generate_headers(values)
return convert(parameters)
raise ValueError("Selecione uma modalidade válida de API.")
<?php
function executar($values) {
$variant = $values["variant"] ?? "rest";
$convertSelected = function () use ($variant, $values) {
if ($variant === "rest") {
$parameters = array_replace(["method" => "GET", "url" => "", "headers" => "{\"Content-Type\":\"application/json\"}", "body" => ""], $values);
$convert = function ($values) {
if (!is_array($values)) throw new InvalidArgumentException("Informe um array associativo com os campos da ferramenta");
$text = function ($value, $label) {
if (!is_string($value)) throw new InvalidArgumentException($label.': informe texto');
if (!function_exists('iconv')) throw new RuntimeException('Requer iconv');
$utf16 = iconv('UTF-8', 'UTF-16LE', $value);
if ($utf16 === false || strlen($utf16) / 2 > 100000) throw new InvalidArgumentException($label.': UTF-8 inválido ou limite de 100 mil caracteres');
return $value;
};
$read = function ($source, $label, $objectOnly = false) use ($text) {
$source = $text($source, $label);
if (trim($source) === '') throw new InvalidArgumentException($label.': informe JSON');
json_decode($source, false, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
$stack = [];
for ($i = 0; $i < strlen($source); $i++) {
$ch = $source[$i];
if ($ch === '{' || $ch === '[') { $stack[] = ['object'=>$ch === '{', 'keys'=>[]]; continue; }
if ($ch === '}' || $ch === ']') { array_pop($stack); continue; }
if ($ch === '"') {
$start = $i; $escaped = false;
while (++$i < strlen($source)) { $c = $source[$i]; if ($escaped) $escaped = false; elseif ($c === '\\') $escaped = true; elseif ($c === '"') break; }
$look = $i + 1; while ($look < strlen($source) && str_contains(" \t\r\n", $source[$look])) $look++;
$index = count($stack) - 1;
if ($index >= 0 && $stack[$index]['object'] && ($source[$look] ?? '') === ':') {
$key = json_decode(substr($source, $start, $i-$start+1), false, 512, JSON_THROW_ON_ERROR);
if (array_key_exists($key, $stack[$index]['keys'])) throw new InvalidArgumentException('Chave duplicada: '.$key);
$stack[$index]['keys'][$key] = true;
}
} elseif ($ch === '-' || ctype_digit($ch)) {
preg_match('/\G-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/', $source, $match, 0, $i);
$token = $match[0]; $value = (float)$token;
$mantissa = explode('e', strtolower($token))[0];
if (!is_finite($value) || ($value == 0 && (str_starts_with($token, '-') || preg_match('/[1-9]/', $mantissa))) || (floor($value) === $value && abs($value) > 9007199254740991)) throw new InvalidArgumentException('Número não preservável; use string');
$i += strlen($token)-1;
}
}
$value = json_decode($source, false, 512, JSON_THROW_ON_ERROR);
$count = 0;
$walk = function ($value, $depth = 0) use (&$walk, &$count) {
if (++$count > 100000 || $depth > 100) throw new InvalidArgumentException('Limite de 100 níveis ou 100 mil nós JSON');
if (is_object($value) || is_array($value)) foreach ($value as $child) $walk($child, $depth+1);
};
$walk($value);
if ($objectOnly && !is_object($value)) throw new InvalidArgumentException($label.': informe objeto JSON');
return $value;
};
$output = function ($value) {
$result = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
$result = preg_replace_callback('/^( +)/m', fn($match)=>str_repeat(' ', strlen($match[1])/2), $result);
if (strlen(iconv('UTF-8','UTF-16LE',$result))/2 > 1000000) throw new InvalidArgumentException('Resultado excede 1 milhão de caracteres');
return $result;
};
$method = function ($value) use ($text) {
$value = trim($text($value, 'Método'));
if (!in_array($value, ['GET','POST','PUT','PATCH','DELETE','HEAD','OPTIONS'], true)) throw new InvalidArgumentException('Método HTTP não suportado');
return $value;
};
$address = function ($value, $mock) use ($text) {
$value = trim($text($value, $mock ? 'Caminho' : 'URL'));
if ($value === '' || preg_match('/[\s\\\\\x00-\x1f\x7f]/u', $value) || str_contains($value, '#') || preg_match('/%(?![0-9a-fA-F]{2})/', $value)) throw new InvalidArgumentException('URL/caminho inválido');
$relative = str_starts_with($value, '/') && !str_starts_with($value, '//');
if ($mock && (!$relative || str_contains($value, '?'))) throw new InvalidArgumentException('Mock exige caminho local sem domínio ou parâmetros');
if (!$relative && !preg_match('~^https?://[^/]~i', $value)) throw new InvalidArgumentException('Use HTTP, HTTPS ou caminho local iniciado por /');
$parsed = parse_url($relative ? 'https://example.invalid'.$value : $value);
if (!$parsed || !in_array($parsed['scheme'] ?? '', ['http','https'], true) || empty($parsed['host']) || isset($parsed['user']) || isset($parsed['pass'])) throw new InvalidArgumentException('URL com credenciais ou protocolo inválido');
return $value;
};
$headers = function ($value) use ($text, $read) {
$source = trim($text($value, 'Cabeçalhos'));
$data = $read($source === '' ? '{}' : $source, 'Cabeçalhos', true);
$seen = [];
foreach (get_object_vars($data) as $key=>$content) {
if (!preg_match("/^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/D", $key)) throw new InvalidArgumentException('Nome de cabeçalho inválido: '.$key);
$lower = strtolower($key);
if (isset($seen[$lower])) throw new InvalidArgumentException('Cabeçalho repetido: '.$key);
$seen[$lower] = true;
if (!is_string($content) || preg_match('/[\x00-\x08\x0a-\x1f\x7f]/', $content)) throw new InvalidArgumentException('Cabeçalho deve ser string sem controles');
}
return $data;
};
$generate_rest = function ($values) use ($method, $text, $address, $headers, $read, $output) {
$verb = $method($values['method'] ?? null);
$body = $text($values['body'] ?? null, 'Corpo');
$data = ['method'=>$verb,'url'=>$address($values['url'] ?? null,false),'headers'=>$headers($values['headers'] ?? null)];
if (trim($body) !== '') {
if (in_array($verb, ['GET','HEAD'], true)) throw new InvalidArgumentException('GET/HEAD exigem corpo vazio');
$data['body'] = $read($body, 'Corpo da requisição');
}
return $output($data);
};
return $generate_rest($values);
};
return $convert($parameters);
}
if ($variant === "curl") {
$parameters = array_replace(["method" => "GET", "url" => "", "headers" => "{}", "body" => ""], $values);
$convert = function ($values) {
$address = function ($value) {
if (!preg_match('~^https?://~i', $value) || preg_match('/[\s\\\\\x00-\x1f\x7f]|%(?![\da-f]{2})/iu', $value)) throw new InvalidArgumentException('URL HTTP/HTTPS inválida');
$parts = parse_url($value);
if (!$parts || empty($parts['host']) || isset($parts['user']) || isset($parts['pass']) || !empty($parts['fragment'])) throw new InvalidArgumentException('URL com credenciais ou fragmento');
if (preg_match('/[{}\[\]]/', preg_replace('~//\[[\da-f:]+\]~i', '//ipv6', $value))) throw new InvalidArgumentException('Globbing de URL não suportado');
return $value;
};
$text = function ($value, $label) {
if (!is_string($value) || !preg_match('//u', $value) || str_contains($value, "\0") || strlen(iconv('UTF-8','UTF-16LE',$value))/2 > 100000) throw new InvalidArgumentException($label.': texto com até 100 mil caracteres, sem NUL ou Unicode inválido');
return $value;
};
$method = function ($value) {
if (!in_array($value, ['GET','POST','PUT','PATCH','DELETE','HEAD','OPTIONS'], true)) throw new InvalidArgumentException('Método HTTP não suportado');
return $value;
};
$read = function ($source, $label, $objectOnly = false) use ($text) {
$source = $text($source, $label);
if (trim($source) === '') throw new InvalidArgumentException($label.': informe JSON');
json_decode($source, false, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
$stack = [];
for ($i = 0; $i < strlen($source); $i++) {
$ch = $source[$i];
if ($ch === '{' || $ch === '[') { $stack[] = ['object'=>$ch === '{', 'keys'=>[]]; continue; }
if ($ch === '}' || $ch === ']') { array_pop($stack); continue; }
if ($ch === '"') {
$start = $i; $escaped = false;
while (++$i < strlen($source)) { $c = $source[$i]; if ($escaped) $escaped = false; elseif ($c === '\\') $escaped = true; elseif ($c === '"') break; }
$look = $i + 1; while ($look < strlen($source) && str_contains(" \t\r\n", $source[$look])) $look++;
$index = count($stack) - 1;
if ($index >= 0 && $stack[$index]['object'] && ($source[$look] ?? '') === ':') {
$key = json_decode(substr($source, $start, $i-$start+1), false, 512, JSON_THROW_ON_ERROR);
if (array_key_exists($key, $stack[$index]['keys'])) throw new InvalidArgumentException('Chave duplicada: '.$key);
$stack[$index]['keys'][$key] = true;
}
} elseif ($ch === '-' || ctype_digit($ch)) {
preg_match('/\G-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/', $source, $match, 0, $i);
$token = $match[0]; $value = (float)$token; $mantissa = explode('e', strtolower($token))[0];
if (!is_finite($value) || ($value == 0 && (str_starts_with($token, '-') || preg_match('/[1-9]/', $mantissa))) || (floor($value) === $value && abs($value) > 9007199254740991)) throw new InvalidArgumentException('Número não preservável; use string');
$i += strlen($token)-1;
}
}
$value = json_decode($source, false, 512, JSON_THROW_ON_ERROR);
$count = 0;
$walk = function ($value, $depth = 0) use (&$walk, &$count) {
if (++$count > 100000 || $depth > 100) throw new InvalidArgumentException('Limite de 100 níveis ou 100 mil nós JSON');
if (is_object($value) || is_array($value)) foreach ($value as $child) $walk($child, $depth+1);
};
$walk($value);
if ($objectOnly && !is_object($value)) throw new InvalidArgumentException($label.': informe objeto JSON');
return $value;
};
$header = function ($name, $value, &$entries) {
if (!is_string($value) || !preg_match("/^[!#$%&'*+.^_`|~\\da-z-]+$/iD", $name) || preg_match('/[\x00-\x08\x0a-\x1f\x7f]/', $value)) throw new InvalidArgumentException('Cabeçalho inválido');
if (trim($value) === '') throw new InvalidArgumentException('Cabeçalho vazio não suportado');
if (preg_match('/[^\t\x20-\x7e]/', $value)) throw new InvalidArgumentException('Valores de cabeçalhos devem ser ASCII');
foreach ($entries as [$key]) if (strtolower($name) === strtolower($key)) throw new InvalidArgumentException('Cabeçalho duplicado: '.$name);
$blocked = ['host','content-length','cookie','set-cookie','connection','transfer-encoding','accept-encoding','origin','referer','user-agent','proxy-authorization','expect','trailer','te','upgrade','via','date','dnt','keep-alive','permissions-policy','access-control-request-method','access-control-request-headers'];
if (in_array(strtolower($name), $blocked, true) || preg_match('/^(sec-|proxy-)/i', $name) || in_array(strtolower($name), ['x-http-method','x-http-method-override','x-method-override'], true) && in_array(strtoupper($value), ['CONNECT','TRACE','TRACK'], true)) throw new InvalidArgumentException('Cabeçalho não portável para Fetch: '.$name);
$entries[] = [$name, $value];
};
$finish = function ($data) {
if (array_key_exists('body',$data) && in_array($data['method'], ['GET','HEAD'],true)) throw new InvalidArgumentException('GET/HEAD com corpo não suportado');
$contentType = false;
foreach ($data['headers'] as [$name]) if (strtolower($name) === 'content-type') $contentType = true;
if (array_key_exists('body',$data) && !$contentType) $data['headers'][] = ['Content-Type','application/x-www-form-urlencoded'];
if (count($data['headers']) > 100) throw new InvalidArgumentException('Limite de 100 cabeçalhos');
return $data;
};
$generate_curl = function ($values) use ($address,$text,$method,$read,$header,$finish) {
$url = $address(trim($text($values['url'] ?? null,'URL'))); $verb = $method($text($values['method'] ?? null,'Método'));
$source = $text($values['headers'] ?? null,'Cabeçalhos'); $entries = [];
$object = $read(trim($source) === '' ? '{}' : $source,'Cabeçalhos',true);
foreach (get_object_vars($object) as $name=>$value) $header((string)$name,$value,$entries);
$body = $text($values['body'] ?? null,'Corpo');
$data = ['method'=>$verb,'url'=>$url,'headers'=>$entries];
if ($body !== '') $data['body'] = $body;
$data = $finish($data);
$quote = fn($value)=>"'".str_replace("'","'\\''",$value)."'";
$args = ['curl','--request',$quote($data['method']),'--url',$quote($data['url'])];
foreach ($data['headers'] as [$name,$value]) array_push($args,'--header',$quote($name.': '.$value));
if (array_key_exists('body',$data)) array_push($args,'--data-raw',$quote($data['body']));
return implode(' ',$args);
};
return $generate_curl($values);
};
return $convert($parameters);
}
if ($variant === "fetch") {
$parameters = array_replace(["command" => ""], $values);
$convert = function ($values) {
$shell_words = function ($source) {
$words = []; $word = ''; $mode = ''; $active = false; $size = strlen($source);
for ($index=0; $index<$size; $index++) {
$char = $source[$index];
if ($mode !== "'" && $char === '\\') {
if (++$index >= $size) throw new InvalidArgumentException('Escape incompleto');
$next = $source[$index];
if ($next === "\n") continue;
if ($mode === '"' && !str_contains('$`"\\', $next)) $word .= '\\';
$word .= $next; $active = true; continue;
}
if ($char === "'" && $mode !== '"' || $char === '"' && $mode !== "'") { $mode = $mode === '' ? $char : ''; $active = true; continue; }
if ($mode !== "'" && str_contains('$`', $char)) throw new InvalidArgumentException('Expansão não suportada na posição '.($index+1));
if ($mode === '' && str_contains(";&|<>()[\\]{}*?~#\r\n", $char)) throw new InvalidArgumentException('Operador/glob/comentário não suportado na posição '.($index+1));
if ($mode === '' && ($char === ' ' || $char === "\t")) {
if ($active) { $words[] = $word; $word = ''; $active = false; }
} else { $word .= $char; $active = true; }
}
if ($mode !== '') throw new InvalidArgumentException('Aspas incompletas');
if ($active) $words[] = $word;
if (count($words)>1000) throw new InvalidArgumentException('Limite de 1000 argumentos');
return $words;
};
$text = function ($value, $label) {
if (!is_string($value) || !preg_match('//u', $value) || str_contains($value, "\0") || strlen(iconv('UTF-8','UTF-16LE',$value))/2 > 100000) throw new InvalidArgumentException($label.': texto com até 100 mil caracteres, sem NUL ou Unicode inválido');
return $value;
};
$method = function ($value) {
if (!in_array($value, ['GET','POST','PUT','PATCH','DELETE','HEAD','OPTIONS'], true)) throw new InvalidArgumentException('Método HTTP não suportado');
return $value;
};
$address = function ($value) {
if (!preg_match('~^https?://~i', $value) || preg_match('/[\s\\\\\x00-\x1f\x7f]|%(?![\da-f]{2})/iu', $value)) throw new InvalidArgumentException('URL HTTP/HTTPS inválida');
$parts = parse_url($value);
if (!$parts || empty($parts['host']) || isset($parts['user']) || isset($parts['pass']) || !empty($parts['fragment'])) throw new InvalidArgumentException('URL com credenciais ou fragmento');
if (preg_match('/[{}\[\]]/', preg_replace('~//\[[\da-f:]+\]~i', '//ipv6', $value))) throw new InvalidArgumentException('Globbing de URL não suportado');
return $value;
};
$header = function ($name, $value, &$entries) {
if (!is_string($value) || !preg_match("/^[!#$%&'*+.^_`|~\\da-z-]+$/iD", $name) || preg_match('/[\x00-\x08\x0a-\x1f\x7f]/', $value)) throw new InvalidArgumentException('Cabeçalho inválido');
if (trim($value) === '') throw new InvalidArgumentException('Cabeçalho vazio não suportado');
if (preg_match('/[^\t\x20-\x7e]/', $value)) throw new InvalidArgumentException('Valores de cabeçalhos devem ser ASCII');
foreach ($entries as [$key]) if (strtolower($name) === strtolower($key)) throw new InvalidArgumentException('Cabeçalho duplicado: '.$name);
$blocked = ['host','content-length','cookie','set-cookie','connection','transfer-encoding','accept-encoding','origin','referer','user-agent','proxy-authorization','expect','trailer','te','upgrade','via','date','dnt','keep-alive','permissions-policy','access-control-request-method','access-control-request-headers'];
if (in_array(strtolower($name), $blocked, true) || preg_match('/^(sec-|proxy-)/i', $name) || in_array(strtolower($name), ['x-http-method','x-http-method-override','x-method-override'], true) && in_array(strtoupper($value), ['CONNECT','TRACE','TRACK'], true)) throw new InvalidArgumentException('Cabeçalho não portável para Fetch: '.$name);
$entries[] = [$name, $value];
};
$finish = function ($data) {
if (array_key_exists('body',$data) && in_array($data['method'], ['GET','HEAD'],true)) throw new InvalidArgumentException('GET/HEAD com corpo não suportado');
$contentType = false;
foreach ($data['headers'] as [$name]) if (strtolower($name) === 'content-type') $contentType = true;
if (array_key_exists('body',$data) && !$contentType) $data['headers'][] = ['Content-Type','application/x-www-form-urlencoded'];
if (count($data['headers']) > 100) throw new InvalidArgumentException('Limite de 100 cabeçalhos');
return $data;
};
$parse_curl = function ($source) use ($shell_words,$text,$method,$address,$header,$finish) {
$words = $shell_words(trim($text($source,'Comando cURL')));
if (array_shift($words) !== 'curl') throw new InvalidArgumentException('A entrada deve começar com curl');
$verb = null; $url = null; $body = null; $entries = [];
$supported = ['-X','--request','-H','--header','--url','-d','--data','--data-raw','--data-binary'];
for ($index=0; $index<count($words); $index++) {
$option = $words[$index]; $inline = null;
if (str_starts_with($option,'--') && str_contains($option,'=')) [$option,$inline] = explode('=',$option,2);
if (in_array($option,$supported,true)) {
$value = $inline ?? ($words[++$index] ?? null);
if ($value === null) throw new InvalidArgumentException('Falta valor de '.$option);
if (in_array($option,['-X','--request'],true)) {
if ($verb !== null) throw new InvalidArgumentException('Método repetido');
$verb = $method($value);
} elseif ($option === '--url') {
if ($url !== null) throw new InvalidArgumentException('Múltiplas URLs');
$url = $address($value);
} elseif (in_array($option,['-H','--header'],true)) {
$at = strpos($value,':');
if ($at === false || $at < 1) throw new InvalidArgumentException('Cabeçalho precisa de Nome: valor');
$header(substr($value,0,$at),ltrim(substr($value,$at+1),"\t "),$entries);
} else {
if ($body !== null) throw new InvalidArgumentException('Múltiplos corpos');
if ($option !== '--data-raw' && str_starts_with($value,'@')) throw new InvalidArgumentException('Arquivo/entrada @ não suportado');
if (in_array($option,['-d','--data'],true) && preg_match('/[\r\n]/',$value)) throw new InvalidArgumentException('Use --data-raw para corpo multilinha');
$body = $value;
}
} elseif (str_starts_with($option,'-')) throw new InvalidArgumentException('Opção cURL não suportada: '.$option);
else {
if ($url !== null) throw new InvalidArgumentException('Argumento extra ou múltiplas URLs');
$url = $address($option);
}
}
if ($url === null) throw new InvalidArgumentException('Informe uma URL HTTP/HTTPS');
$data = ['method'=>$verb ?? ($body !== null ? 'POST':'GET'),'url'=>$url,'headers'=>$entries];
if ($body !== null) $data['body'] = $body;
return $finish($data);
};
$convert_curl = function ($source,$target) use ($parse_curl) {
$data = $parse_curl($source);
$quote = fn($value)=>json_encode($value,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_THROW_ON_ERROR);
$parts = [];
foreach ($data['headers'] as [$name,$value]) $parts[] = '['.$quote($name).']: '.$quote($value);
$headers = '{'.implode(', ',$parts).'}';
$lines = $target === 'axios' ? ["import axios from \"axios\";\n"] : [];
$lines[] = 'async function executar() {';
if ($target === 'fetch') {
array_push($lines,' const response = await fetch('.$quote($data['url']).', {',' method: '.$quote($data['method']).',',' headers: '.$headers.',',' credentials: "omit",',' redirect: "manual",');
if (array_key_exists('body',$data)) $lines[] = ' body: '.$quote($data['body']).',';
array_push($lines,' });',' return response;','}');
} else {
array_push($lines,' const response = await axios({',' url: '.$quote($data['url']).',',' method: '.$quote($data['method']).',',' headers: '.$headers.',',' withCredentials: false,',' maxRedirects: 0,',' validateStatus: () => true,',' transformRequest: [(data) => data],',' transformResponse: [(data) => data],',' responseType: "text",');
if (array_key_exists('body',$data)) $lines[] = ' data: '.$quote($data['body']).',';
array_push($lines,' });',' return response;','}');
}
return implode("\n",$lines);
};
return $convert_curl($values["command"], 'fetch');
};
return $convert($parameters);
}
if ($variant === "axios") {
$parameters = array_replace(["command" => ""], $values);
$convert = function ($values) {
$shell_words = function ($source) {
$words = []; $word = ''; $mode = ''; $active = false; $size = strlen($source);
for ($index=0; $index<$size; $index++) {
$char = $source[$index];
if ($mode !== "'" && $char === '\\') {
if (++$index >= $size) throw new InvalidArgumentException('Escape incompleto');
$next = $source[$index];
if ($next === "\n") continue;
if ($mode === '"' && !str_contains('$`"\\', $next)) $word .= '\\';
$word .= $next; $active = true; continue;
}
if ($char === "'" && $mode !== '"' || $char === '"' && $mode !== "'") { $mode = $mode === '' ? $char : ''; $active = true; continue; }
if ($mode !== "'" && str_contains('$`', $char)) throw new InvalidArgumentException('Expansão não suportada na posição '.($index+1));
if ($mode === '' && str_contains(";&|<>()[\\]{}*?~#\r\n", $char)) throw new InvalidArgumentException('Operador/glob/comentário não suportado na posição '.($index+1));
if ($mode === '' && ($char === ' ' || $char === "\t")) {
if ($active) { $words[] = $word; $word = ''; $active = false; }
} else { $word .= $char; $active = true; }
}
if ($mode !== '') throw new InvalidArgumentException('Aspas incompletas');
if ($active) $words[] = $word;
if (count($words)>1000) throw new InvalidArgumentException('Limite de 1000 argumentos');
return $words;
};
$text = function ($value, $label) {
if (!is_string($value) || !preg_match('//u', $value) || str_contains($value, "\0") || strlen(iconv('UTF-8','UTF-16LE',$value))/2 > 100000) throw new InvalidArgumentException($label.': texto com até 100 mil caracteres, sem NUL ou Unicode inválido');
return $value;
};
$method = function ($value) {
if (!in_array($value, ['GET','POST','PUT','PATCH','DELETE','HEAD','OPTIONS'], true)) throw new InvalidArgumentException('Método HTTP não suportado');
return $value;
};
$address = function ($value) {
if (!preg_match('~^https?://~i', $value) || preg_match('/[\s\\\\\x00-\x1f\x7f]|%(?![\da-f]{2})/iu', $value)) throw new InvalidArgumentException('URL HTTP/HTTPS inválida');
$parts = parse_url($value);
if (!$parts || empty($parts['host']) || isset($parts['user']) || isset($parts['pass']) || !empty($parts['fragment'])) throw new InvalidArgumentException('URL com credenciais ou fragmento');
if (preg_match('/[{}\[\]]/', preg_replace('~//\[[\da-f:]+\]~i', '//ipv6', $value))) throw new InvalidArgumentException('Globbing de URL não suportado');
return $value;
};
$header = function ($name, $value, &$entries) {
if (!is_string($value) || !preg_match("/^[!#$%&'*+.^_`|~\\da-z-]+$/iD", $name) || preg_match('/[\x00-\x08\x0a-\x1f\x7f]/', $value)) throw new InvalidArgumentException('Cabeçalho inválido');
if (trim($value) === '') throw new InvalidArgumentException('Cabeçalho vazio não suportado');
if (preg_match('/[^\t\x20-\x7e]/', $value)) throw new InvalidArgumentException('Valores de cabeçalhos devem ser ASCII');
foreach ($entries as [$key]) if (strtolower($name) === strtolower($key)) throw new InvalidArgumentException('Cabeçalho duplicado: '.$name);
$blocked = ['host','content-length','cookie','set-cookie','connection','transfer-encoding','accept-encoding','origin','referer','user-agent','proxy-authorization','expect','trailer','te','upgrade','via','date','dnt','keep-alive','permissions-policy','access-control-request-method','access-control-request-headers'];
if (in_array(strtolower($name), $blocked, true) || preg_match('/^(sec-|proxy-)/i', $name) || in_array(strtolower($name), ['x-http-method','x-http-method-override','x-method-override'], true) && in_array(strtoupper($value), ['CONNECT','TRACE','TRACK'], true)) throw new InvalidArgumentException('Cabeçalho não portável para Fetch: '.$name);
$entries[] = [$name, $value];
};
$finish = function ($data) {
if (array_key_exists('body',$data) && in_array($data['method'], ['GET','HEAD'],true)) throw new InvalidArgumentException('GET/HEAD com corpo não suportado');
$contentType = false;
foreach ($data['headers'] as [$name]) if (strtolower($name) === 'content-type') $contentType = true;
if (array_key_exists('body',$data) && !$contentType) $data['headers'][] = ['Content-Type','application/x-www-form-urlencoded'];
if (count($data['headers']) > 100) throw new InvalidArgumentException('Limite de 100 cabeçalhos');
return $data;
};
$parse_curl = function ($source) use ($shell_words,$text,$method,$address,$header,$finish) {
$words = $shell_words(trim($text($source,'Comando cURL')));
if (array_shift($words) !== 'curl') throw new InvalidArgumentException('A entrada deve começar com curl');
$verb = null; $url = null; $body = null; $entries = [];
$supported = ['-X','--request','-H','--header','--url','-d','--data','--data-raw','--data-binary'];
for ($index=0; $index<count($words); $index++) {
$option = $words[$index]; $inline = null;
if (str_starts_with($option,'--') && str_contains($option,'=')) [$option,$inline] = explode('=',$option,2);
if (in_array($option,$supported,true)) {
$value = $inline ?? ($words[++$index] ?? null);
if ($value === null) throw new InvalidArgumentException('Falta valor de '.$option);
if (in_array($option,['-X','--request'],true)) {
if ($verb !== null) throw new InvalidArgumentException('Método repetido');
$verb = $method($value);
} elseif ($option === '--url') {
if ($url !== null) throw new InvalidArgumentException('Múltiplas URLs');
$url = $address($value);
} elseif (in_array($option,['-H','--header'],true)) {
$at = strpos($value,':');
if ($at === false || $at < 1) throw new InvalidArgumentException('Cabeçalho precisa de Nome: valor');
$header(substr($value,0,$at),ltrim(substr($value,$at+1),"\t "),$entries);
} else {
if ($body !== null) throw new InvalidArgumentException('Múltiplos corpos');
if ($option !== '--data-raw' && str_starts_with($value,'@')) throw new InvalidArgumentException('Arquivo/entrada @ não suportado');
if (in_array($option,['-d','--data'],true) && preg_match('/[\r\n]/',$value)) throw new InvalidArgumentException('Use --data-raw para corpo multilinha');
$body = $value;
}
} elseif (str_starts_with($option,'-')) throw new InvalidArgumentException('Opção cURL não suportada: '.$option);
else {
if ($url !== null) throw new InvalidArgumentException('Argumento extra ou múltiplas URLs');
$url = $address($option);
}
}
if ($url === null) throw new InvalidArgumentException('Informe uma URL HTTP/HTTPS');
$data = ['method'=>$verb ?? ($body !== null ? 'POST':'GET'),'url'=>$url,'headers'=>$entries];
if ($body !== null) $data['body'] = $body;
return $finish($data);
};
$convert_curl = function ($source,$target) use ($parse_curl) {
$data = $parse_curl($source);
$quote = fn($value)=>json_encode($value,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_THROW_ON_ERROR);
$parts = [];
foreach ($data['headers'] as [$name,$value]) $parts[] = '['.$quote($name).']: '.$quote($value);
$headers = '{'.implode(', ',$parts).'}';
$lines = $target === 'axios' ? ["import axios from \"axios\";\n"] : [];
$lines[] = 'async function executar() {';
if ($target === 'fetch') {
array_push($lines,' const response = await fetch('.$quote($data['url']).', {',' method: '.$quote($data['method']).',',' headers: '.$headers.',',' credentials: "omit",',' redirect: "manual",');
if (array_key_exists('body',$data)) $lines[] = ' body: '.$quote($data['body']).',';
array_push($lines,' });',' return response;','}');
} else {
array_push($lines,' const response = await axios({',' url: '.$quote($data['url']).',',' method: '.$quote($data['method']).',',' headers: '.$headers.',',' withCredentials: false,',' maxRedirects: 0,',' validateStatus: () => true,',' transformRequest: [(data) => data],',' transformResponse: [(data) => data],',' responseType: "text",');
if (array_key_exists('body',$data)) $lines[] = ' data: '.$quote($data['body']).',';
array_push($lines,' });',' return response;','}');
}
return implode("\n",$lines);
};
return $convert_curl($values["command"], 'axios');
};
return $convert($parameters);
}
if ($variant === "headers") {
$parameters = array_replace(["contentType" => "application/json", "accept" => "application/json", "bearerToken" => "", "headers" => "{}", "format" => "JSON"], $values);
$convert = function ($values) {
$text = function ($value,$title) {
if (!is_string($value) || !preg_match('//u',$value) || strlen(iconv('UTF-8','UTF-16LE',$value))/2 > 100000) throw new InvalidArgumentException($title.': texto UTF-8 válido, até 100 mil unidades UTF-16');
return $value;
};
$read = function ($source, $label, $objectOnly = false) use ($text) {
$source = $text($source, $label);
if (trim($source) === '') throw new InvalidArgumentException($label.': informe JSON');
json_decode($source, false, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
$stack = [];
for ($i = 0; $i < strlen($source); $i++) {
$ch = $source[$i];
if ($ch === '{' || $ch === '[') { $stack[] = ['object'=>$ch === '{', 'keys'=>[]]; continue; }
if ($ch === '}' || $ch === ']') { array_pop($stack); continue; }
if ($ch === '"') {
$start = $i; $escaped = false;
while (++$i < strlen($source)) { $c = $source[$i]; if ($escaped) $escaped = false; elseif ($c === '\\') $escaped = true; elseif ($c === '"') break; }
$look = $i + 1; while ($look < strlen($source) && str_contains(" \t\r\n", $source[$look])) $look++;
$index = count($stack) - 1;
if ($index >= 0 && $stack[$index]['object'] && ($source[$look] ?? '') === ':') {
$key = json_decode(substr($source, $start, $i-$start+1), false, 512, JSON_THROW_ON_ERROR);
if (array_key_exists($key, $stack[$index]['keys'])) throw new InvalidArgumentException('Chave duplicada: '.$key);
$stack[$index]['keys'][$key] = true;
}
} elseif ($ch === '-' || ctype_digit($ch)) {
preg_match('/\G-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/', $source, $match, 0, $i);
$token = $match[0]; $value = (float)$token; $mantissa = explode('e', strtolower($token))[0];
if (!is_finite($value) || ($value == 0 && (str_starts_with($token, '-') || preg_match('/[1-9]/', $mantissa))) || (floor($value) === $value && abs($value) > 9007199254740991)) throw new InvalidArgumentException('Número não preservável; use string');
$i += strlen($token)-1;
}
}
$value = json_decode($source, false, 512, JSON_THROW_ON_ERROR);
$count = 0;
$walk = function ($value, $depth = 0) use (&$walk, &$count) {
if (++$count > 100000 || $depth > 100) throw new InvalidArgumentException('Limite de 100 níveis ou 100 mil nós JSON');
if (is_object($value) || is_array($value)) foreach ($value as $child) $walk($child, $depth+1);
};
$walk($value);
if ($objectOnly && !is_object($value)) throw new InvalidArgumentException($label.': informe objeto JSON');
return $value;
};
$portable_headers = function ($source) use ($read,$text) {
$source = $text($source,'Cabeçalhos');
$data = $read(trim($source)==='' ? '{}' : $source,'Cabeçalhos',true); $seen = [];
foreach (get_object_vars($data) as $name=>$value) {
$name = (string)$name;
if (!preg_match("/^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/D",$name)) throw new InvalidArgumentException('Nome de cabeçalho inválido');
$lower = strtolower($name);
if (isset($seen[$lower])) throw new InvalidArgumentException('Cabeçalho repetido');
$seen[$lower] = true;
if (!is_string($value) || preg_match('/[^\t\x20-\x7e]/',$value)) throw new InvalidArgumentException('Cabeçalhos exigem strings ASCII sem quebras de linha');
}
if (count($seen)>100) throw new InvalidArgumentException('Limite de 100 cabeçalhos');
return $data;
};
$output = function ($value) {
$source = json_encode($value,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
$source = preg_replace_callback('/^( +)/m',fn($m)=>str_repeat(' ',strlen($m[1])/2),$source);
if (strlen(iconv('UTF-8','UTF-16LE',$source))/2>1000000) throw new InvalidArgumentException('Limite de 1 milhão na saída');
return $source;
};
$generate_headers = function ($values) use ($text,$portable_headers,$output) {
$data = new stdClass();
$add = function ($key,$value) use ($data) {
foreach (get_object_vars($data) as $name=>$unused) if (strtolower((string)$name)===strtolower($key)) throw new InvalidArgumentException('Cabeçalho repetido entre os campos e o JSON');
$data->{$key} = $value;
};
$optional = function ($value,$title) use ($text) {
$value = $text($value,$title);
if (preg_match('/[\x00-\x1f\x7f]/',$value)) throw new InvalidArgumentException('Controles não permitidos');
return trim($value);
};
$contentType = $optional($values['contentType'],'Content-Type'); $accept = $optional($values['accept'],'Accept'); $token = $optional($values['bearerToken'],'Token');
if ($contentType!=='') $add('Content-Type',$contentType);
if ($accept!=='') $add('Accept',$accept);
if ($token!=='') {
if (!preg_match('/^[A-Za-z0-9\-._~+\/]+=*$/D',$token)) throw new InvalidArgumentException('Token Bearer inválido');
$add('Authorization','Bearer '.$token);
}
foreach (get_object_vars($portable_headers($values['headers'])) as $key=>$value) $add((string)$key,$value);
$entries = get_object_vars($data);
if (count($entries)>100) throw new InvalidArgumentException('Limite de 100 cabeçalhos');
foreach ($entries as $value) if (preg_match('/[^\t\x20-\x7e]/',$value)) throw new InvalidArgumentException('Valores devem ser ASCII');
$isIndex = fn($key)=>preg_match('/^(0|[1-9][0-9]*)$/D',(string)$key) && strlen((string)$key)<=10 && (int)$key<=4294967294;
uksort($entries,fn($a,$b)=>$isIndex($a) && $isIndex($b) ? (int)$a <=> (int)$b : ($isIndex($a) ? -1 : ($isIndex($b) ? 1 : 0)));
$ordered = new stdClass(); foreach ($entries as $key=>$value) $ordered->{(string)$key} = $value;
if ($values['format']==='JSON') return $output($ordered);
if ($values['format']==='Texto') { $lines=[]; foreach ($entries as $key=>$value) $lines[]=$key.': '.$value; return implode("\n",$lines); }
throw new InvalidArgumentException('Escolha JSON ou Texto');
};
return $generate_headers($values);
};
return $convert($parameters);
}
throw new InvalidArgumentException("Selecione uma modalidade válida de API.");
};
return $convertSelected();
}