JavaScript Python PHP
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
function executar(values) {
function simulateWebhook(values) {
const url = address(values.url, false);
if (!/^https?:\/\//i.test(url))
throw new Error('O webhook exige uma URL HTTP/HTTPS absoluta; ela não será acessada.');
const status = integer(values.status, 'Status simulado', 200, 599);
const request = { method: 'POST', url, headers: portableHeaders(values.headers), body: json(values.body, 'Corpo do evento') };
return result({ request, simulation: { responseStatus: status, delivered: status >= 200 && status < 300 } });
}
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 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 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 integer(input, label, min, max) {
const value = text(input, label).trim();
if (!/^(?:0|[1-9]\d*)$/.test(value) || value.length > 5 || Number(value) < min || Number(value) > max)
throw new Error(label + ': inteiro de ' + min + ' a ' + max + ', sem decimais ou notação científica.');
return Number(value);
}
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 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 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 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 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;
}
return simulateWebhook(values);
}
import json
import math
import re
from urllib.parse import urlsplit
def executar(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 integer(value, title, minimum, maximum):
value = text(value, title).strip()
if not re.fullmatch('(?:0|[1-9][0-9]*)', value) or len(value) > 5 or (not minimum <= int(value) <= maximum):
raise ValueError(title + ': inteiro fora do intervalo permitido')
return int(value)
def simulate_webhook(values):
url = text(values['url'], 'URL').strip()
if not re.match('^https?://[^/]', url, re.I) or re.search('[\\s\\\\\\x00-\\x1f\\x7f]|%(?![\\da-fA-F]{2})', url) or '#' in url:
raise ValueError('Informe URL HTTP/HTTPS absoluta sem fragmento ou controles')
parsed = urlsplit(url)
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username is not None or (parsed.password is not None) or (parsed.port is not None and parsed.port > 65535):
raise ValueError('URL inválida ou com credenciais')
status = integer(values['status'], 'Status simulado', 200, 599)
request = {'method': 'POST', 'url': url, 'headers': portable_headers(values['headers']), 'body': read(values['body'], 'Corpo do evento')}
return output({'request': request, 'simulation': {'responseStatus': status, 'delivered': 200 <= status < 300}})
return simulate_webhook(values)
<?php
function executar($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;
};
$integer = function ($value,$title,$min,$max) use ($text) {
$value = trim($text($value,$title));
if (!preg_match('/^(?:0|[1-9][0-9]*)$/D',$value) || strlen($value)>5 || (int)$value<$min || (int)$value>$max) throw new InvalidArgumentException($title.': inteiro fora do intervalo');
return (int)$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;
};
$simulate_webhook = function ($values) use ($text,$integer,$portable_headers,$read,$output) {
$url = trim($text($values['url'],'URL'));
if (!preg_match('~^https?://[^/]~i',$url) || preg_match('/[\s\\\\\x00-\x1f\x7f]|%(?![\da-f]{2})/iu',$url) || str_contains($url,'#')) throw new InvalidArgumentException('Informe URL HTTP/HTTPS absoluta sem fragmento ou controles');
$parts = parse_url($url);
if (!$parts || !in_array(strtolower($parts['scheme'] ?? ''),['http','https'],true) || empty($parts['host']) || isset($parts['user']) || isset($parts['pass'])) throw new InvalidArgumentException('URL inválida ou com credenciais');
$status = $integer($values['status'],'Status simulado',200,599);
$request = ['method'=>'POST','url'=>$url,'headers'=>$portable_headers($values['headers']),'body'=>$read($values['body'],'Corpo do evento')];
return $output(['request'=>$request,'simulation'=>['responseStatus'=>$status,'delivered'=>$status>=200 && $status<300]]);
};
return $simulate_webhook($values);
}