JavaScript Python PHP
function executar(values) {
function lgText(value) { if (typeof value !== 'string' || value.length > 100000 || !value.isWellFormed())
throw new Error('Use texto Unicode válido de até 100 mil caracteres por campo.'); return value; }
function generateLogicCases(v) {
const name = v.name, type = lgChoice(v, 'type', ['Inteiro', 'Texto']), required = lgYes(v, 'required');
if (!name || [...name].length > 64 || /[\u0000-\u001f]/.test(name))
throw new Error('Nome do campo: 1–64 caracteres, sem controles.');
const min = lgInt(v, 'min', type === 'Texto' ? 0 : -1000000000, type === 'Texto' ? 100000 : 1000000000), max = lgInt(v, 'max', min, type === 'Texto' ? 100000 : 1000000000);
const candidates = [['Propriedade ausente', undefined, true], ['Nulo', null], ['Vazio', ''], ['Booleano', false], ['Objeto', {}], ['Lista', []]];
for (const n of [...new Set([min - 1, min, Math.floor((min + max) / 2), max, max + 1])])
if (type === 'Inteiro' || n >= 0)
candidates.push([`Limite ${n}`, type === 'Texto' ? 'a'.repeat(n) : n]);
if (type === 'Inteiro')
candidates.push(['Número textual', String(min)], ['Decimal', min + 0.5]);
else
candidates.push(['Unicode (2 pontos de código)', 'á😀'], ['Número', 0], ['Espaços preservados', ' ']);
return lgJson({ rule: { name, type, min, max, required, coercion: false }, cases: candidates.map(([label, value, missing]) => {
const empty = missing || value === null || value === '', valid = empty ? !required : type === 'Inteiro' ? typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max : typeof value === 'string' && [...value].length >= min && [...value].length <= max;
return { label, input: missing ? {} : Object.fromEntries([[name, value]]), expectedValid: Boolean(valid), reason: empty ? required ? 'Campo obrigatório ausente, nulo ou vazio.' : 'Campo opcional aceita ausência, null e vazio.' : valid ? 'Tipo e limites atendidos.' : 'Tipo ou limites não atendidos.' };
}) });
}
function required(values, key) { if (!values[key])
throw new Error(`Preencha o campo ${key}.`); return values[key]; }
function lgInt(v, key, min, max) { const raw = v[key], n = Number(raw); if (!/^-?\d+$/.test(raw ?? '') || !Number.isSafeInteger(n) || n < min || n > max)
throw new Error(`${key}: informe um inteiro de ${min} a ${max}.`); return n; }
function lgChoice(v, key, choices) { if (!choices.includes(v[key]))
throw new Error(`Opção inválida: ${key}.`); return v[key]; }
function lgYes(v, key) { return lgChoice(v, key, ['Sim', 'Não']) === 'Sim'; }
function lgJson(value, compact = false) { const text = JSON.stringify(value, null, compact ? undefined : 2); if (text.length > 1000000)
throw new Error('Resultado excede 1 milhão de caracteres. Reduza os limites.'); return { text, file: 'resultado.json' }; }
for (const value of Object.values(values)) lgText(value);
return generateLogicCases(values);
}
import json
import re
def executar(values):
def integer(key, low, high):
raw = values.get(key, '')
if not re.fullmatch(r'-?[0-9]+', raw) or not low <= int(raw) <= high:
raise ValueError(f'{key}: informe um inteiro de {low} a {high}.')
return int(raw)
def choice(key, options):
if values.get(key) not in options:
raise ValueError('Opção inválida: ' + key)
return values[key]
def yes(key):
return choice(key, ['Sim', 'Não']) == 'Sim'
def output(value, compact=False):
text = json.dumps(value, ensure_ascii=False, indent=None if compact else 2, separators=(',', ':') if compact else (',', ': '), allow_nan=False)
if len(text.encode('utf-16-le')) // 2 > 1000000:
raise ValueError('Resultado excede 1 milhão de caracteres. Reduza os limites.')
return {'text': text, 'file': 'resultado.json'}
for value in values.values():
if not isinstance(value, str) or len(value.encode('utf-16-le')) // 2 > 100000:
raise ValueError('Use texto Unicode válido de até 100 mil caracteres por campo.')
value.encode('utf-8')
name, kind, required = values['name'], choice('type', ['Inteiro', 'Texto']), yes('required')
if not 1 <= len(name) <= 64 or re.search(r'[\x00-\x1f]', name):
raise ValueError('Nome do campo: 1–64 caracteres, sem controles.')
low = integer('min', 0 if kind == 'Texto' else -1000000000, 100000 if kind == 'Texto' else 1000000000)
high = integer('max', low, 100000 if kind == 'Texto' else 1000000000)
candidates = [('Propriedade ausente', None, True), ('Nulo', None, False), ('Vazio', '', False), ('Booleano', False, False), ('Objeto', {}, False), ('Lista', [], False)]
for n in dict.fromkeys([low - 1, low, (low + high) // 2, high, high + 1]):
if kind == 'Inteiro' or n >= 0:
candidates.append((f'Limite {n}', 'a' * n if kind == 'Texto' else n, False))
candidates += [('Número textual', str(low), False), ('Decimal', low + 0.5, False)] if kind == 'Inteiro' else [('Unicode (2 pontos de código)', 'á😀', False), ('Número', 0, False), ('Espaços preservados', ' ', False)]
cases = []
for label, value, missing in candidates:
empty = missing or value is None or value == ''
valid = not required if empty else (type(value) is int and low <= value <= high) if kind == 'Inteiro' else (isinstance(value, str) and low <= len(value) <= high)
reason = ('Campo obrigatório ausente, nulo ou vazio.' if required else 'Campo opcional aceita ausência, null e vazio.') if empty else 'Tipo e limites atendidos.' if valid else 'Tipo ou limites não atendidos.'
cases.append({'label': label, 'input': {} if missing else {name: value}, 'expectedValid': valid, 'reason': reason})
return output({'rule': {'name': name, 'type': kind, 'min': low, 'max': high, 'required': required, 'coercion': False}, 'cases': cases})
<?php
function executar(array $values): array {
// PHP 8.1+ de 64 bits, JSON, PCRE e iconv.
$chars = static function (string $text): array {
$result = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
if ($result === false) throw new InvalidArgumentException('Use Unicode válido.');
return $result;
};
$integer = static function (string $key, int $low, int $high) use ($values): int {
$raw = $values[$key] ?? '';
if (!preg_match('/^-?[0-9]+$/D', $raw) || strlen(ltrim($raw, '-0')) > 10 || (int)$raw < $low || (int)$raw > $high) throw new InvalidArgumentException("$key: informe um inteiro de $low a $high.");
return (int)$raw;
};
$choice = static function (string $key, array $options) use ($values): string {
if (!in_array($values[$key] ?? null, $options, true)) throw new InvalidArgumentException('Opção inválida: ' . $key);
return $values[$key];
};
$yes = static fn(string $key): bool => $choice($key, ['Sim', 'Não']) === 'Sim';
$output = static function ($value, bool $compact = false): array {
$flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS | JSON_THROW_ON_ERROR;
$text = json_encode($value, $flags | ($compact ? 0 : JSON_PRETTY_PRINT));
if (!$compact) $text = preg_replace_callback('/^ +/m', static fn($m) => str_repeat(' ', intdiv(strlen($m[0]), 2)), $text);
if (strlen(iconv('UTF-8', 'UTF-16LE', $text)) / 2 > 1000000) throw new InvalidArgumentException('Resultado excede 1 milhão de caracteres. Reduza os limites.');
return ['text' => $text, 'file' => 'resultado.json'];
};
foreach ($values as $value) {
if (!is_string($value) || preg_match('//u', $value) !== 1 || strlen(iconv('UTF-8', 'UTF-16LE', $value)) / 2 > 100000) throw new InvalidArgumentException('Use texto Unicode válido de até 100 mil caracteres por campo.');
}
$name = $values['name'];
$kind = $choice('type', ['Inteiro', 'Texto']);
$required = $yes('required');
if (count($chars($name)) < 1 || count($chars($name)) > 64 || preg_match('/[\x00-\x1f]/', $name)) throw new InvalidArgumentException('Nome do campo: 1–64 caracteres, sem controles.');
$low = $integer('min', $kind === 'Texto' ? 0 : -1000000000, $kind === 'Texto' ? 100000 : 1000000000);
$high = $integer('max', $low, $kind === 'Texto' ? 100000 : 1000000000);
$candidates = [['Propriedade ausente', null, true], ['Nulo', null], ['Vazio', ''], ['Booleano', false], ['Objeto', new stdClass()], ['Lista', []]];
foreach (array_unique([$low - 1, $low, (int)floor(($low + $high) / 2), $high, $high + 1]) as $n) if ($kind === 'Inteiro' || $n >= 0) $candidates[] = ['Limite ' . $n, $kind === 'Texto' ? str_repeat('a', $n) : $n];
$candidates = array_merge($candidates, $kind === 'Inteiro' ? [['Número textual', (string)$low], ['Decimal', $low + 0.5]] : [['Unicode (2 pontos de código)', 'á😀'], ['Número', 0], ['Espaços preservados', ' ']]);
$cases = [];
foreach ($candidates as $candidate) {
[$label, $value] = $candidate;
$missing = $candidate[2] ?? false;
$empty = $missing || $value === null || $value === '';
$valid = $empty ? !$required : ($kind === 'Inteiro' ? is_int($value) && $value >= $low && $value <= $high : is_string($value) && count($chars($value)) >= $low && count($chars($value)) <= $high);
$reason = $empty ? ($required ? 'Campo obrigatório ausente, nulo ou vazio.' : 'Campo opcional aceita ausência, null e vazio.') : ($valid ? 'Tipo e limites atendidos.' : 'Tipo ou limites não atendidos.');
$cases[] = ['label' => $label, 'input' => $missing ? new stdClass() : (object)[$name => $value], 'expectedValid' => $valid, 'reason' => $reason];
}
return $output(['rule' => ['name' => $name, 'type' => $kind, 'min' => $low, 'max' => $high, 'required' => $required, 'coercion' => false], 'cases' => $cases]);
}