JavaScript Python PHP
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
import Ajv from "ajv";
import Ajv2020 from "ajv8/dist/2020.js";
import draft04 from "ajv/lib/refs/json-schema-draft-04.json" with { type: "json" };
import swagger2 from "@seriousme/openapi-schema-validator/schemas/v2.0/schema.json" with { type: "json" };
import openapi30 from "@seriousme/openapi-schema-validator/schemas/v3.0/schema.json" with { type: "json" };
import openapi31 from "@seriousme/openapi-schema-validator/schemas/v3.1/schema.json" with { type: "json" };
import openapi32 from "@seriousme/openapi-schema-validator/schemas/v3.2/schema.json" with { type: "json" };
function executar(values) {
function productivityText(value, label = 'Campo') {
if (value === undefined)
return '';
if (typeof value !== 'string' || value.length > 100000)
throw new Error(label + ': informe texto de até 100 mil unidades UTF-16.');
if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\uD800-\uDFFF]/u.test(value))
throw new Error(label + ': caracteres de controle ou Unicode inválido.');
return value.replace(/\r\n?/g, '\n');
}
function productivityOutput(output) {
if (output.text.length > 1000000)
throw new Error('Saída excede 1 milhão de unidades UTF-16.');
return output;
}
function generateApiContract(v) {
const title = productivityLabel(v.title, 'Título'), version = productivityLabel(v.version, 'Versão'), server = productivityUrl(v.server);
const auth = productivityChoice(v.auth, ['Nenhuma', 'Bearer', 'API key']);
const schemas = productivityObject(json(v.schemas || '{}', 'Schemas'), 'Schemas');
const paths = Object.create(null), ids = new Set(), shapes = new Map();
for (const [index, item] of productivityArray(v.input, 'Endpoints', 100).entries()) {
const endpoint = productivityObject(item, 'Endpoint ' + (index + 1), ['path', 'method', 'summary', 'operationId', 'parameters', 'requestBody', 'responses']);
const path = productivityText(endpoint.path, 'Caminho'), method = productivityChoice(endpoint.method, ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE']).toLowerCase();
if (!/^\/(?!\/)/.test(path) || /[\s?#\\]/.test(path))
throw new Error('Endpoint: use caminho absoluto /recurso, sem query, espaços ou fragmento.');
const variables = Array.from(path.matchAll(/\{([^{}]+)\}/g), match => match[1]), shape = path.replace(/\{[^{}]+\}/g, '{}');
if (/[{}]/.test(path.replace(/\{[^{}]+\}/g, '')) || variables.some(name => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) || new Set(variables).size !== variables.length)
throw new Error('Parâmetros de caminho inválidos ou repetidos.');
if (shapes.has(shape) && shapes.get(shape) !== path)
throw new Error('Caminhos equivalentes com nomes de parâmetros diferentes não são aceitos.');
shapes.set(shape, path);
const operationId = productivityLabel(endpoint.operationId, 'operationId');
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(operationId) || ids.has(operationId))
throw new Error('operationId deve ser identificador ASCII único.');
ids.add(operationId);
const parameters = endpoint.parameters ?? [];
if (!Array.isArray(parameters) || parameters.length > 100)
throw new Error('parameters deve ser lista de até 100 parâmetros inline.');
const seen = new Set(), declared = [];
for (const item of parameters) {
const parameter = productivityObject(item, 'Parâmetro'), name = productivityLabel(parameter.name, 'Nome do parâmetro'), location = productivityChoice(parameter.in, ['path', 'query', 'header', 'cookie']);
const identity = location + ':' + (location === 'header' ? name.toLowerCase() : name);
if (seen.has(identity))
throw new Error('Parâmetro duplicado: ' + name);
seen.add(identity);
if (location === 'path') {
if (parameter.required !== true || !variables.includes(name))
throw new Error('Parâmetro path deve existir no caminho e ter required: true.');
declared.push(name);
}
}
if (variables.some(name => !declared.includes(name)))
throw new Error('Declare todos os parâmetros {nome} do caminho em parameters com in: path e required: true.');
const responses = productivityObject(endpoint.responses, 'Respostas');
if (!Object.keys(responses).length)
throw new Error('Informe pelo menos uma resposta por endpoint.');
for (const [status, response] of Object.entries(responses)) {
if (!/^(?:[1-5][0-9]{2}|default)$/.test(status))
throw new Error('Status de resposta: use 100–599 ou default.');
const object = productivityObject(response, 'Resposta');
if (!Object.hasOwn(object, '$ref'))
productivityLabel(object.description, 'Descrição da resposta');
}
if (!Object.hasOwn(paths, path))
paths[path] = Object.create(null);
const operations = paths[path];
if (Object.hasOwn(operations, method))
throw new Error('Método e caminho duplicados: ' + method + ' ' + path);
const operation = { operationId, summary: productivityLabel(endpoint.summary, 'Resumo'), parameters, responses };
if (endpoint.requestBody !== undefined) {
if (['get', 'head', 'trace'].includes(method))
throw new Error('GET/HEAD/TRACE exigem requestBody ausente neste gerador.');
operation.requestBody = endpoint.requestBody;
}
operations[method] = operation;
}
const components = { schemas }, document = { openapi: '3.0.3', info: { title, version }, servers: [{ url: server }], paths, components };
const description = productivityText(v.description, 'Descrição').trim();
if (description)
document.info.description = description;
if (auth !== 'Nenhuma') {
const name = auth === 'Bearer' ? 'bearerAuth' : 'apiKeyAuth', header = auth === 'API key' ? productivityLabel(v.apiKeyHeader, 'Header da API key') : '';
if (header && !/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(header))
throw new Error('Nome de header API key inválido.');
components.securitySchemes = { [name]: auth === 'Bearer' ? { type: 'http', scheme: 'bearer' } : { type: 'apiKey', in: 'header', name: header } };
document.security = [{ [name]: [] }];
}
const text = JSON.stringify(document, null, 2);
if (text.length > 100000)
throw new Error('Contrato excede 100 mil caracteres para validação estrutural.');
const validation = JSON.parse(validateOpenApi(text, 'JSON'));
if (!validation.valid)
throw new Error('Contrato OpenAPI inválido: ' + validation.errors.map((e) => e.path + ': ' + e.message).join('; '));
return { text, filename: 'openapi.json' };
}
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) {
const message = cause && typeof cause === 'object' && 'message' in cause && typeof cause.message === 'string' ? cause.message : 'JSON inválido.';
throw new Error(label + ': ' + message);
}
}
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 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 validateOpenApi(input, format) {
if (!['JSON', 'YAML'].includes(format))
throw new Error('Escolha JSON ou YAML explicitamente.');
if (input.length > 100_000)
throw new Error('Limite de 100 mil caracteres por documento.');
const data = parseJsonCompatible(input, format);
if (!data || Array.isArray(data) || typeof data !== 'object')
throw new Error('O documento OpenAPI deve ser um objeto.');
const rawVersion = data.openapi ?? data.swagger;
const version = data.swagger === '2.0' && data.openapi === undefined ? '2.0' : typeof rawVersion === 'string' ? /^(3\.[012])\.\d+$/.exec(rawVersion)?.[1] : undefined;
if (!version || (data.swagger !== undefined && data.openapi !== undefined))
throw new Error('Versão não suportada: use swagger: "2.0" ou openapi: "3.0.x", "3.1.x" ou "3.2.x". Não converte versões automaticamente.');
const schemas = { '2.0': swagger2, '3.0': openapi30, '3.1': openapi31, '3.2': openapi32 };
const modern = version === '3.1' || version === '3.2';
const ajv = modern ? new Ajv2020({ strict: false, allErrors: true, validateFormats: false, ownProperties: true }) : new Ajv({ schemaId: 'id', meta: false, allErrors: true, format: false, ownProperties: true, jsonPointers: true });
if (!modern)
ajv.addMetaSchema(draft04);
const errors = [];
function issue(path, message) { if (errors.length < 50)
errors.push({ path, message }); }
function visit(node, path, schemaObject = false) {
if (!node || typeof node !== 'object')
return;
if (Array.isArray(node)) {
node.forEach((child, index) => visit(child, path + '/' + index, schemaObject));
return;
}
if (Object.hasOwn(node, '$ref')) {
const ref = node.$ref;
if (typeof ref !== 'string' || !(ref === '#' || ref.startsWith('#/')))
throw new Error(path + ': somente $ref local (# ou #/...) é permitido; recursos externos não são carregados.');
let target = data;
if (ref !== '#') {
let parts;
try {
parts = decodeURIComponent(ref.slice(2)).split('/').map(part => { if (/~(?:[^01]|$)/.test(part))
throw new Error(); return part.replace(/~1/g, '/').replace(/~0/g, '~'); });
}
catch {
throw new Error(path + ': escape inválido em $ref.');
}
for (const part of parts) {
if (!target || typeof target !== 'object' || !Object.hasOwn(target, part))
throw new Error(path + ': referência local não encontrada: ' + ref);
target = target[part];
}
}
if (target === null || Array.isArray(target) || typeof target !== 'object' && typeof target !== 'boolean')
throw new Error(path + ': referência deve apontar para objeto ou schema booleano.');
}
if (Object.hasOwn(node, '$id') || Object.hasOwn(node, '$anchor') || Object.hasOwn(node, '$dynamicRef') || Object.hasOwn(node, '$dynamicAnchor'))
throw new Error(path + ': bases $id, âncoras e referências dinâmicas não são suportadas; use JSON Pointer local.');
if (Object.hasOwn(node, '$schema') && !['https://json-schema.org/draft/2020-12/schema', 'https://spec.openapis.org/oas/3.1/dialect/base', 'https://spec.openapis.org/oas/3.2/dialect/base'].includes(String(node.$schema)))
throw new Error(path + ': dialeto de JSON Schema não suportado.');
const metaInput = modern && schemaObject ? JSON.parse(JSON.stringify(node, (key, value) => key === '$schema' ? 'https://json-schema.org/draft/2020-12/schema' : value)) : node;
if (modern && schemaObject && !ajv.validateSchema(metaInput))
issue(path, 'Schema Object inválido: ' + ajv.errorsText());
for (const [key, child] of Object.entries(node)) {
// These locations contain arbitrary data, not reference/schema instructions.
if ((schemaObject ? ['example', 'examples', 'default', 'enum', 'const'] : ['example', 'value']).includes(key) || key.startsWith('x-'))
continue;
const escaped = key.replace(/~/g, '~0').replace(/\//g, '~1');
const schemaMap = key === 'schemas' && path === '/components' || key === 'definitions' && path === '' || schemaObject && ['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'].includes(key);
const apiMap = !schemaObject && ['paths', 'webhooks', 'responses', 'headers', 'parameters', 'requestBodies', 'securitySchemes', 'callbacks', 'links', 'examples', 'pathItems'].includes(key);
if ((schemaMap || apiMap) && child && typeof child === 'object' && !Array.isArray(child)) {
for (const [name, value] of Object.entries(child))
visit(value, path + '/' + escaped + '/' + name.replace(/~/g, '~0').replace(/\//g, '~1'), schemaMap);
}
else
visit(child, path + '/' + escaped, key === 'schema' || schemaObject && ['allOf', 'anyOf', 'oneOf', 'not', 'if', 'then', 'else', 'items', 'prefixItems', 'contains', 'additionalProperties', 'unevaluatedProperties', 'unevaluatedItems', 'propertyNames'].includes(key));
}
}
if (data.jsonSchemaDialect !== undefined && !['https://json-schema.org/draft/2020-12/schema', 'https://spec.openapis.org/oas/3.1/dialect/base', 'https://spec.openapis.org/oas/3.2/dialect/base'].includes(String(data.jsonSchemaDialect)))
throw new Error('jsonSchemaDialect personalizado não é suportado.');
visit(data, '');
const validate = ajv.compile(schemas[version]);
const valid = validate(data);
if (!valid)
for (const error of validate.errors ?? [])
issue(('instancePath' in error ? String(error.instancePath) : String(error.dataPath)) || '/', error.message || 'Estrutura inválida.');
return JSON.stringify({ valid: Boolean(valid) && !errors.length, version: rawVersion, errors }, null, 2);
}
function productivityLabel(value, label, optional = false) {
const content = productivityText(value, label).trim();
if ((!content && !optional) || content.length > 200 || /[\n\t\u2028\u2029]/.test(content))
throw new Error(label + ': use uma linha de 1–200 caracteres' + (optional ? ' ou deixe vazio.' : '.'));
return content;
}
function productivityChoice(value, options) {
if (typeof value !== 'string' || !options.includes(value))
throw new Error('Escolha uma opção válida: ' + options.join(', ') + '.');
return value;
}
function productivityObject(value, label, keys) {
if (!value || typeof value !== 'object' || Array.isArray(value))
throw new Error(label + ': use um objeto JSON.');
if (keys)
for (const key of Object.keys(value))
if (!keys.includes(key))
throw new Error(label + ': campo não suportado: ' + key + '.');
return value;
}
function productivityArray(input, label, limit = 500) {
const value = json(input, label);
if (!Array.isArray(value) || !value.length || value.length > limit)
throw new Error(label + ': use uma lista JSON não vazia com até ' + limit + ' itens.');
return value;
}
function productivityUrl(value) {
const url = productivityText(value, 'URL').trim();
if (url.length > 2047 || !/^https?:\/\/[^/]/i.test(url) || /[^\x21-\x7e]|[\\<>"`{}|^]|%(?![\da-f]{2})/i.test(url) || url.includes('#'))
throw new Error('URL inválida: use HTTP/HTTPS absoluta, ASCII (Unicode percent-encoded), até 2047 caracteres, sem espaços, fragmento ou credenciais.');
let parsed;
try {
parsed = new URL(url);
}
catch {
throw new Error('URL HTTP/HTTPS inválida.');
}
if (!parsed.hostname || parsed.username || parsed.password)
throw new Error('Não use credenciais na URL.');
return url;
}
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;
}
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
for (const value of Object.values(values)) productivityText(value);
return productivityOutput(generateApiContract(values));
}
import json
import subprocess
def executar(values):
# Node.js 22+ e pacotes npm dos imports abaixo; implementação completa incluída.
source = r'''
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
import Ajv from "ajv";
import Ajv2020 from "ajv8/dist/2020.js";
import draft04 from "ajv/lib/refs/json-schema-draft-04.json" with { type: "json" };
import swagger2 from "@seriousme/openapi-schema-validator/schemas/v2.0/schema.json" with { type: "json" };
import openapi30 from "@seriousme/openapi-schema-validator/schemas/v3.0/schema.json" with { type: "json" };
import openapi31 from "@seriousme/openapi-schema-validator/schemas/v3.1/schema.json" with { type: "json" };
import openapi32 from "@seriousme/openapi-schema-validator/schemas/v3.2/schema.json" with { type: "json" };
function executar(values) {
function productivityText(value, label = 'Campo') {
if (value === undefined)
return '';
if (typeof value !== 'string' || value.length > 100000)
throw new Error(label + ': informe texto de até 100 mil unidades UTF-16.');
if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\uD800-\uDFFF]/u.test(value))
throw new Error(label + ': caracteres de controle ou Unicode inválido.');
return value.replace(/\r\n?/g, '\n');
}
function productivityOutput(output) {
if (output.text.length > 1000000)
throw new Error('Saída excede 1 milhão de unidades UTF-16.');
return output;
}
function generateApiContract(v) {
const title = productivityLabel(v.title, 'Título'), version = productivityLabel(v.version, 'Versão'), server = productivityUrl(v.server);
const auth = productivityChoice(v.auth, ['Nenhuma', 'Bearer', 'API key']);
const schemas = productivityObject(json(v.schemas || '{}', 'Schemas'), 'Schemas');
const paths = Object.create(null), ids = new Set(), shapes = new Map();
for (const [index, item] of productivityArray(v.input, 'Endpoints', 100).entries()) {
const endpoint = productivityObject(item, 'Endpoint ' + (index + 1), ['path', 'method', 'summary', 'operationId', 'parameters', 'requestBody', 'responses']);
const path = productivityText(endpoint.path, 'Caminho'), method = productivityChoice(endpoint.method, ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE']).toLowerCase();
if (!/^\/(?!\/)/.test(path) || /[\s?#\\]/.test(path))
throw new Error('Endpoint: use caminho absoluto /recurso, sem query, espaços ou fragmento.');
const variables = Array.from(path.matchAll(/\{([^{}]+)\}/g), match => match[1]), shape = path.replace(/\{[^{}]+\}/g, '{}');
if (/[{}]/.test(path.replace(/\{[^{}]+\}/g, '')) || variables.some(name => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) || new Set(variables).size !== variables.length)
throw new Error('Parâmetros de caminho inválidos ou repetidos.');
if (shapes.has(shape) && shapes.get(shape) !== path)
throw new Error('Caminhos equivalentes com nomes de parâmetros diferentes não são aceitos.');
shapes.set(shape, path);
const operationId = productivityLabel(endpoint.operationId, 'operationId');
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(operationId) || ids.has(operationId))
throw new Error('operationId deve ser identificador ASCII único.');
ids.add(operationId);
const parameters = endpoint.parameters ?? [];
if (!Array.isArray(parameters) || parameters.length > 100)
throw new Error('parameters deve ser lista de até 100 parâmetros inline.');
const seen = new Set(), declared = [];
for (const item of parameters) {
const parameter = productivityObject(item, 'Parâmetro'), name = productivityLabel(parameter.name, 'Nome do parâmetro'), location = productivityChoice(parameter.in, ['path', 'query', 'header', 'cookie']);
const identity = location + ':' + (location === 'header' ? name.toLowerCase() : name);
if (seen.has(identity))
throw new Error('Parâmetro duplicado: ' + name);
seen.add(identity);
if (location === 'path') {
if (parameter.required !== true || !variables.includes(name))
throw new Error('Parâmetro path deve existir no caminho e ter required: true.');
declared.push(name);
}
}
if (variables.some(name => !declared.includes(name)))
throw new Error('Declare todos os parâmetros {nome} do caminho em parameters com in: path e required: true.');
const responses = productivityObject(endpoint.responses, 'Respostas');
if (!Object.keys(responses).length)
throw new Error('Informe pelo menos uma resposta por endpoint.');
for (const [status, response] of Object.entries(responses)) {
if (!/^(?:[1-5][0-9]{2}|default)$/.test(status))
throw new Error('Status de resposta: use 100–599 ou default.');
const object = productivityObject(response, 'Resposta');
if (!Object.hasOwn(object, '$ref'))
productivityLabel(object.description, 'Descrição da resposta');
}
if (!Object.hasOwn(paths, path))
paths[path] = Object.create(null);
const operations = paths[path];
if (Object.hasOwn(operations, method))
throw new Error('Método e caminho duplicados: ' + method + ' ' + path);
const operation = { operationId, summary: productivityLabel(endpoint.summary, 'Resumo'), parameters, responses };
if (endpoint.requestBody !== undefined) {
if (['get', 'head', 'trace'].includes(method))
throw new Error('GET/HEAD/TRACE exigem requestBody ausente neste gerador.');
operation.requestBody = endpoint.requestBody;
}
operations[method] = operation;
}
const components = { schemas }, document = { openapi: '3.0.3', info: { title, version }, servers: [{ url: server }], paths, components };
const description = productivityText(v.description, 'Descrição').trim();
if (description)
document.info.description = description;
if (auth !== 'Nenhuma') {
const name = auth === 'Bearer' ? 'bearerAuth' : 'apiKeyAuth', header = auth === 'API key' ? productivityLabel(v.apiKeyHeader, 'Header da API key') : '';
if (header && !/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(header))
throw new Error('Nome de header API key inválido.');
components.securitySchemes = { [name]: auth === 'Bearer' ? { type: 'http', scheme: 'bearer' } : { type: 'apiKey', in: 'header', name: header } };
document.security = [{ [name]: [] }];
}
const text = JSON.stringify(document, null, 2);
if (text.length > 100000)
throw new Error('Contrato excede 100 mil caracteres para validação estrutural.');
const validation = JSON.parse(validateOpenApi(text, 'JSON'));
if (!validation.valid)
throw new Error('Contrato OpenAPI inválido: ' + validation.errors.map((e) => e.path + ': ' + e.message).join('; '));
return { text, filename: 'openapi.json' };
}
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) {
const message = cause && typeof cause === 'object' && 'message' in cause && typeof cause.message === 'string' ? cause.message : 'JSON inválido.';
throw new Error(label + ': ' + message);
}
}
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 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 validateOpenApi(input, format) {
if (!['JSON', 'YAML'].includes(format))
throw new Error('Escolha JSON ou YAML explicitamente.');
if (input.length > 100_000)
throw new Error('Limite de 100 mil caracteres por documento.');
const data = parseJsonCompatible(input, format);
if (!data || Array.isArray(data) || typeof data !== 'object')
throw new Error('O documento OpenAPI deve ser um objeto.');
const rawVersion = data.openapi ?? data.swagger;
const version = data.swagger === '2.0' && data.openapi === undefined ? '2.0' : typeof rawVersion === 'string' ? /^(3\.[012])\.\d+$/.exec(rawVersion)?.[1] : undefined;
if (!version || (data.swagger !== undefined && data.openapi !== undefined))
throw new Error('Versão não suportada: use swagger: "2.0" ou openapi: "3.0.x", "3.1.x" ou "3.2.x". Não converte versões automaticamente.');
const schemas = { '2.0': swagger2, '3.0': openapi30, '3.1': openapi31, '3.2': openapi32 };
const modern = version === '3.1' || version === '3.2';
const ajv = modern ? new Ajv2020({ strict: false, allErrors: true, validateFormats: false, ownProperties: true }) : new Ajv({ schemaId: 'id', meta: false, allErrors: true, format: false, ownProperties: true, jsonPointers: true });
if (!modern)
ajv.addMetaSchema(draft04);
const errors = [];
function issue(path, message) { if (errors.length < 50)
errors.push({ path, message }); }
function visit(node, path, schemaObject = false) {
if (!node || typeof node !== 'object')
return;
if (Array.isArray(node)) {
node.forEach((child, index) => visit(child, path + '/' + index, schemaObject));
return;
}
if (Object.hasOwn(node, '$ref')) {
const ref = node.$ref;
if (typeof ref !== 'string' || !(ref === '#' || ref.startsWith('#/')))
throw new Error(path + ': somente $ref local (# ou #/...) é permitido; recursos externos não são carregados.');
let target = data;
if (ref !== '#') {
let parts;
try {
parts = decodeURIComponent(ref.slice(2)).split('/').map(part => { if (/~(?:[^01]|$)/.test(part))
throw new Error(); return part.replace(/~1/g, '/').replace(/~0/g, '~'); });
}
catch {
throw new Error(path + ': escape inválido em $ref.');
}
for (const part of parts) {
if (!target || typeof target !== 'object' || !Object.hasOwn(target, part))
throw new Error(path + ': referência local não encontrada: ' + ref);
target = target[part];
}
}
if (target === null || Array.isArray(target) || typeof target !== 'object' && typeof target !== 'boolean')
throw new Error(path + ': referência deve apontar para objeto ou schema booleano.');
}
if (Object.hasOwn(node, '$id') || Object.hasOwn(node, '$anchor') || Object.hasOwn(node, '$dynamicRef') || Object.hasOwn(node, '$dynamicAnchor'))
throw new Error(path + ': bases $id, âncoras e referências dinâmicas não são suportadas; use JSON Pointer local.');
if (Object.hasOwn(node, '$schema') && !['https://json-schema.org/draft/2020-12/schema', 'https://spec.openapis.org/oas/3.1/dialect/base', 'https://spec.openapis.org/oas/3.2/dialect/base'].includes(String(node.$schema)))
throw new Error(path + ': dialeto de JSON Schema não suportado.');
const metaInput = modern && schemaObject ? JSON.parse(JSON.stringify(node, (key, value) => key === '$schema' ? 'https://json-schema.org/draft/2020-12/schema' : value)) : node;
if (modern && schemaObject && !ajv.validateSchema(metaInput))
issue(path, 'Schema Object inválido: ' + ajv.errorsText());
for (const [key, child] of Object.entries(node)) {
// These locations contain arbitrary data, not reference/schema instructions.
if ((schemaObject ? ['example', 'examples', 'default', 'enum', 'const'] : ['example', 'value']).includes(key) || key.startsWith('x-'))
continue;
const escaped = key.replace(/~/g, '~0').replace(/\//g, '~1');
const schemaMap = key === 'schemas' && path === '/components' || key === 'definitions' && path === '' || schemaObject && ['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'].includes(key);
const apiMap = !schemaObject && ['paths', 'webhooks', 'responses', 'headers', 'parameters', 'requestBodies', 'securitySchemes', 'callbacks', 'links', 'examples', 'pathItems'].includes(key);
if ((schemaMap || apiMap) && child && typeof child === 'object' && !Array.isArray(child)) {
for (const [name, value] of Object.entries(child))
visit(value, path + '/' + escaped + '/' + name.replace(/~/g, '~0').replace(/\//g, '~1'), schemaMap);
}
else
visit(child, path + '/' + escaped, key === 'schema' || schemaObject && ['allOf', 'anyOf', 'oneOf', 'not', 'if', 'then', 'else', 'items', 'prefixItems', 'contains', 'additionalProperties', 'unevaluatedProperties', 'unevaluatedItems', 'propertyNames'].includes(key));
}
}
if (data.jsonSchemaDialect !== undefined && !['https://json-schema.org/draft/2020-12/schema', 'https://spec.openapis.org/oas/3.1/dialect/base', 'https://spec.openapis.org/oas/3.2/dialect/base'].includes(String(data.jsonSchemaDialect)))
throw new Error('jsonSchemaDialect personalizado não é suportado.');
visit(data, '');
const validate = ajv.compile(schemas[version]);
const valid = validate(data);
if (!valid)
for (const error of validate.errors ?? [])
issue(('instancePath' in error ? String(error.instancePath) : String(error.dataPath)) || '/', error.message || 'Estrutura inválida.');
return JSON.stringify({ valid: Boolean(valid) && !errors.length, version: rawVersion, errors }, null, 2);
}
function productivityLabel(value, label, optional = false) {
const content = productivityText(value, label).trim();
if ((!content && !optional) || content.length > 200 || /[\n\t\u2028\u2029]/.test(content))
throw new Error(label + ': use uma linha de 1–200 caracteres' + (optional ? ' ou deixe vazio.' : '.'));
return content;
}
function productivityChoice(value, options) {
if (typeof value !== 'string' || !options.includes(value))
throw new Error('Escolha uma opção válida: ' + options.join(', ') + '.');
return value;
}
function productivityObject(value, label, keys) {
if (!value || typeof value !== 'object' || Array.isArray(value))
throw new Error(label + ': use um objeto JSON.');
if (keys)
for (const key of Object.keys(value))
if (!keys.includes(key))
throw new Error(label + ': campo não suportado: ' + key + '.');
return value;
}
function productivityArray(input, label, limit = 500) {
const value = json(input, label);
if (!Array.isArray(value) || !value.length || value.length > limit)
throw new Error(label + ': use uma lista JSON não vazia com até ' + limit + ' itens.');
return value;
}
function productivityUrl(value) {
const url = productivityText(value, 'URL').trim();
if (url.length > 2047 || !/^https?:\/\/[^/]/i.test(url) || /[^\x21-\x7e]|[\\<>"`{}|^]|%(?![\da-f]{2})/i.test(url) || url.includes('#'))
throw new Error('URL inválida: use HTTP/HTTPS absoluta, ASCII (Unicode percent-encoded), até 2047 caracteres, sem espaços, fragmento ou credenciais.');
let parsed;
try {
parsed = new URL(url);
}
catch {
throw new Error('URL HTTP/HTTPS inválida.');
}
if (!parsed.hostname || parsed.username || parsed.password)
throw new Error('Não use credenciais na URL.');
return url;
}
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;
}
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
for (const value of Object.values(values)) productivityText(value);
return productivityOutput(generateApiContract(values));
}
let input=""; for await (const chunk of process.stdin) input+=chunk; try { process.stdout.write(JSON.stringify({ok:true,result:executar(JSON.parse(input))})); } catch (error) { process.stdout.write(JSON.stringify({ok:false,error:error.message})); }
'''
process = subprocess.run(["node", "--input-type=module", "-e", source], input=json.dumps(values, ensure_ascii=True), capture_output=True, text=True, timeout=15, check=True)
response = json.loads(process.stdout)
if not response["ok"]: raise ValueError(response["error"])
return response["result"]
<?php
function executar(array $values): array {
// Node.js 22+ e pacotes npm dos imports abaixo; implementação completa incluída.
$source = <<<'JAVASCRIPT'
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
import Ajv from "ajv";
import Ajv2020 from "ajv8/dist/2020.js";
import draft04 from "ajv/lib/refs/json-schema-draft-04.json" with { type: "json" };
import swagger2 from "@seriousme/openapi-schema-validator/schemas/v2.0/schema.json" with { type: "json" };
import openapi30 from "@seriousme/openapi-schema-validator/schemas/v3.0/schema.json" with { type: "json" };
import openapi31 from "@seriousme/openapi-schema-validator/schemas/v3.1/schema.json" with { type: "json" };
import openapi32 from "@seriousme/openapi-schema-validator/schemas/v3.2/schema.json" with { type: "json" };
function executar(values) {
function productivityText(value, label = 'Campo') {
if (value === undefined)
return '';
if (typeof value !== 'string' || value.length > 100000)
throw new Error(label + ': informe texto de até 100 mil unidades UTF-16.');
if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\uD800-\uDFFF]/u.test(value))
throw new Error(label + ': caracteres de controle ou Unicode inválido.');
return value.replace(/\r\n?/g, '\n');
}
function productivityOutput(output) {
if (output.text.length > 1000000)
throw new Error('Saída excede 1 milhão de unidades UTF-16.');
return output;
}
function generateApiContract(v) {
const title = productivityLabel(v.title, 'Título'), version = productivityLabel(v.version, 'Versão'), server = productivityUrl(v.server);
const auth = productivityChoice(v.auth, ['Nenhuma', 'Bearer', 'API key']);
const schemas = productivityObject(json(v.schemas || '{}', 'Schemas'), 'Schemas');
const paths = Object.create(null), ids = new Set(), shapes = new Map();
for (const [index, item] of productivityArray(v.input, 'Endpoints', 100).entries()) {
const endpoint = productivityObject(item, 'Endpoint ' + (index + 1), ['path', 'method', 'summary', 'operationId', 'parameters', 'requestBody', 'responses']);
const path = productivityText(endpoint.path, 'Caminho'), method = productivityChoice(endpoint.method, ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE']).toLowerCase();
if (!/^\/(?!\/)/.test(path) || /[\s?#\\]/.test(path))
throw new Error('Endpoint: use caminho absoluto /recurso, sem query, espaços ou fragmento.');
const variables = Array.from(path.matchAll(/\{([^{}]+)\}/g), match => match[1]), shape = path.replace(/\{[^{}]+\}/g, '{}');
if (/[{}]/.test(path.replace(/\{[^{}]+\}/g, '')) || variables.some(name => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) || new Set(variables).size !== variables.length)
throw new Error('Parâmetros de caminho inválidos ou repetidos.');
if (shapes.has(shape) && shapes.get(shape) !== path)
throw new Error('Caminhos equivalentes com nomes de parâmetros diferentes não são aceitos.');
shapes.set(shape, path);
const operationId = productivityLabel(endpoint.operationId, 'operationId');
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(operationId) || ids.has(operationId))
throw new Error('operationId deve ser identificador ASCII único.');
ids.add(operationId);
const parameters = endpoint.parameters ?? [];
if (!Array.isArray(parameters) || parameters.length > 100)
throw new Error('parameters deve ser lista de até 100 parâmetros inline.');
const seen = new Set(), declared = [];
for (const item of parameters) {
const parameter = productivityObject(item, 'Parâmetro'), name = productivityLabel(parameter.name, 'Nome do parâmetro'), location = productivityChoice(parameter.in, ['path', 'query', 'header', 'cookie']);
const identity = location + ':' + (location === 'header' ? name.toLowerCase() : name);
if (seen.has(identity))
throw new Error('Parâmetro duplicado: ' + name);
seen.add(identity);
if (location === 'path') {
if (parameter.required !== true || !variables.includes(name))
throw new Error('Parâmetro path deve existir no caminho e ter required: true.');
declared.push(name);
}
}
if (variables.some(name => !declared.includes(name)))
throw new Error('Declare todos os parâmetros {nome} do caminho em parameters com in: path e required: true.');
const responses = productivityObject(endpoint.responses, 'Respostas');
if (!Object.keys(responses).length)
throw new Error('Informe pelo menos uma resposta por endpoint.');
for (const [status, response] of Object.entries(responses)) {
if (!/^(?:[1-5][0-9]{2}|default)$/.test(status))
throw new Error('Status de resposta: use 100–599 ou default.');
const object = productivityObject(response, 'Resposta');
if (!Object.hasOwn(object, '$ref'))
productivityLabel(object.description, 'Descrição da resposta');
}
if (!Object.hasOwn(paths, path))
paths[path] = Object.create(null);
const operations = paths[path];
if (Object.hasOwn(operations, method))
throw new Error('Método e caminho duplicados: ' + method + ' ' + path);
const operation = { operationId, summary: productivityLabel(endpoint.summary, 'Resumo'), parameters, responses };
if (endpoint.requestBody !== undefined) {
if (['get', 'head', 'trace'].includes(method))
throw new Error('GET/HEAD/TRACE exigem requestBody ausente neste gerador.');
operation.requestBody = endpoint.requestBody;
}
operations[method] = operation;
}
const components = { schemas }, document = { openapi: '3.0.3', info: { title, version }, servers: [{ url: server }], paths, components };
const description = productivityText(v.description, 'Descrição').trim();
if (description)
document.info.description = description;
if (auth !== 'Nenhuma') {
const name = auth === 'Bearer' ? 'bearerAuth' : 'apiKeyAuth', header = auth === 'API key' ? productivityLabel(v.apiKeyHeader, 'Header da API key') : '';
if (header && !/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(header))
throw new Error('Nome de header API key inválido.');
components.securitySchemes = { [name]: auth === 'Bearer' ? { type: 'http', scheme: 'bearer' } : { type: 'apiKey', in: 'header', name: header } };
document.security = [{ [name]: [] }];
}
const text = JSON.stringify(document, null, 2);
if (text.length > 100000)
throw new Error('Contrato excede 100 mil caracteres para validação estrutural.');
const validation = JSON.parse(validateOpenApi(text, 'JSON'));
if (!validation.valid)
throw new Error('Contrato OpenAPI inválido: ' + validation.errors.map((e) => e.path + ': ' + e.message).join('; '));
return { text, filename: 'openapi.json' };
}
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) {
const message = cause && typeof cause === 'object' && 'message' in cause && typeof cause.message === 'string' ? cause.message : 'JSON inválido.';
throw new Error(label + ': ' + message);
}
}
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 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 validateOpenApi(input, format) {
if (!['JSON', 'YAML'].includes(format))
throw new Error('Escolha JSON ou YAML explicitamente.');
if (input.length > 100_000)
throw new Error('Limite de 100 mil caracteres por documento.');
const data = parseJsonCompatible(input, format);
if (!data || Array.isArray(data) || typeof data !== 'object')
throw new Error('O documento OpenAPI deve ser um objeto.');
const rawVersion = data.openapi ?? data.swagger;
const version = data.swagger === '2.0' && data.openapi === undefined ? '2.0' : typeof rawVersion === 'string' ? /^(3\.[012])\.\d+$/.exec(rawVersion)?.[1] : undefined;
if (!version || (data.swagger !== undefined && data.openapi !== undefined))
throw new Error('Versão não suportada: use swagger: "2.0" ou openapi: "3.0.x", "3.1.x" ou "3.2.x". Não converte versões automaticamente.');
const schemas = { '2.0': swagger2, '3.0': openapi30, '3.1': openapi31, '3.2': openapi32 };
const modern = version === '3.1' || version === '3.2';
const ajv = modern ? new Ajv2020({ strict: false, allErrors: true, validateFormats: false, ownProperties: true }) : new Ajv({ schemaId: 'id', meta: false, allErrors: true, format: false, ownProperties: true, jsonPointers: true });
if (!modern)
ajv.addMetaSchema(draft04);
const errors = [];
function issue(path, message) { if (errors.length < 50)
errors.push({ path, message }); }
function visit(node, path, schemaObject = false) {
if (!node || typeof node !== 'object')
return;
if (Array.isArray(node)) {
node.forEach((child, index) => visit(child, path + '/' + index, schemaObject));
return;
}
if (Object.hasOwn(node, '$ref')) {
const ref = node.$ref;
if (typeof ref !== 'string' || !(ref === '#' || ref.startsWith('#/')))
throw new Error(path + ': somente $ref local (# ou #/...) é permitido; recursos externos não são carregados.');
let target = data;
if (ref !== '#') {
let parts;
try {
parts = decodeURIComponent(ref.slice(2)).split('/').map(part => { if (/~(?:[^01]|$)/.test(part))
throw new Error(); return part.replace(/~1/g, '/').replace(/~0/g, '~'); });
}
catch {
throw new Error(path + ': escape inválido em $ref.');
}
for (const part of parts) {
if (!target || typeof target !== 'object' || !Object.hasOwn(target, part))
throw new Error(path + ': referência local não encontrada: ' + ref);
target = target[part];
}
}
if (target === null || Array.isArray(target) || typeof target !== 'object' && typeof target !== 'boolean')
throw new Error(path + ': referência deve apontar para objeto ou schema booleano.');
}
if (Object.hasOwn(node, '$id') || Object.hasOwn(node, '$anchor') || Object.hasOwn(node, '$dynamicRef') || Object.hasOwn(node, '$dynamicAnchor'))
throw new Error(path + ': bases $id, âncoras e referências dinâmicas não são suportadas; use JSON Pointer local.');
if (Object.hasOwn(node, '$schema') && !['https://json-schema.org/draft/2020-12/schema', 'https://spec.openapis.org/oas/3.1/dialect/base', 'https://spec.openapis.org/oas/3.2/dialect/base'].includes(String(node.$schema)))
throw new Error(path + ': dialeto de JSON Schema não suportado.');
const metaInput = modern && schemaObject ? JSON.parse(JSON.stringify(node, (key, value) => key === '$schema' ? 'https://json-schema.org/draft/2020-12/schema' : value)) : node;
if (modern && schemaObject && !ajv.validateSchema(metaInput))
issue(path, 'Schema Object inválido: ' + ajv.errorsText());
for (const [key, child] of Object.entries(node)) {
// These locations contain arbitrary data, not reference/schema instructions.
if ((schemaObject ? ['example', 'examples', 'default', 'enum', 'const'] : ['example', 'value']).includes(key) || key.startsWith('x-'))
continue;
const escaped = key.replace(/~/g, '~0').replace(/\//g, '~1');
const schemaMap = key === 'schemas' && path === '/components' || key === 'definitions' && path === '' || schemaObject && ['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'].includes(key);
const apiMap = !schemaObject && ['paths', 'webhooks', 'responses', 'headers', 'parameters', 'requestBodies', 'securitySchemes', 'callbacks', 'links', 'examples', 'pathItems'].includes(key);
if ((schemaMap || apiMap) && child && typeof child === 'object' && !Array.isArray(child)) {
for (const [name, value] of Object.entries(child))
visit(value, path + '/' + escaped + '/' + name.replace(/~/g, '~0').replace(/\//g, '~1'), schemaMap);
}
else
visit(child, path + '/' + escaped, key === 'schema' || schemaObject && ['allOf', 'anyOf', 'oneOf', 'not', 'if', 'then', 'else', 'items', 'prefixItems', 'contains', 'additionalProperties', 'unevaluatedProperties', 'unevaluatedItems', 'propertyNames'].includes(key));
}
}
if (data.jsonSchemaDialect !== undefined && !['https://json-schema.org/draft/2020-12/schema', 'https://spec.openapis.org/oas/3.1/dialect/base', 'https://spec.openapis.org/oas/3.2/dialect/base'].includes(String(data.jsonSchemaDialect)))
throw new Error('jsonSchemaDialect personalizado não é suportado.');
visit(data, '');
const validate = ajv.compile(schemas[version]);
const valid = validate(data);
if (!valid)
for (const error of validate.errors ?? [])
issue(('instancePath' in error ? String(error.instancePath) : String(error.dataPath)) || '/', error.message || 'Estrutura inválida.');
return JSON.stringify({ valid: Boolean(valid) && !errors.length, version: rawVersion, errors }, null, 2);
}
function productivityLabel(value, label, optional = false) {
const content = productivityText(value, label).trim();
if ((!content && !optional) || content.length > 200 || /[\n\t\u2028\u2029]/.test(content))
throw new Error(label + ': use uma linha de 1–200 caracteres' + (optional ? ' ou deixe vazio.' : '.'));
return content;
}
function productivityChoice(value, options) {
if (typeof value !== 'string' || !options.includes(value))
throw new Error('Escolha uma opção válida: ' + options.join(', ') + '.');
return value;
}
function productivityObject(value, label, keys) {
if (!value || typeof value !== 'object' || Array.isArray(value))
throw new Error(label + ': use um objeto JSON.');
if (keys)
for (const key of Object.keys(value))
if (!keys.includes(key))
throw new Error(label + ': campo não suportado: ' + key + '.');
return value;
}
function productivityArray(input, label, limit = 500) {
const value = json(input, label);
if (!Array.isArray(value) || !value.length || value.length > limit)
throw new Error(label + ': use uma lista JSON não vazia com até ' + limit + ' itens.');
return value;
}
function productivityUrl(value) {
const url = productivityText(value, 'URL').trim();
if (url.length > 2047 || !/^https?:\/\/[^/]/i.test(url) || /[^\x21-\x7e]|[\\<>"`{}|^]|%(?![\da-f]{2})/i.test(url) || url.includes('#'))
throw new Error('URL inválida: use HTTP/HTTPS absoluta, ASCII (Unicode percent-encoded), até 2047 caracteres, sem espaços, fragmento ou credenciais.');
let parsed;
try {
parsed = new URL(url);
}
catch {
throw new Error('URL HTTP/HTTPS inválida.');
}
if (!parsed.hostname || parsed.username || parsed.password)
throw new Error('Não use credenciais na URL.');
return url;
}
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;
}
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
for (const value of Object.values(values)) productivityText(value);
return productivityOutput(generateApiContract(values));
}
let input=""; for await (const chunk of process.stdin) input+=chunk; try { process.stdout.write(JSON.stringify({ok:true,result:executar(JSON.parse(input))})); } catch (error) { process.stdout.write(JSON.stringify({ok:false,error:error.message})); }
JAVASCRIPT;
$input = json_encode($values, JSON_THROW_ON_ERROR);
$process = proc_open(["node", "--input-type=module", "-e", $source], [["pipe", "r"], ["pipe", "w"], ["pipe", "w"]], $pipes);
if (!is_resource($process)) throw new RuntimeException("Não foi possível iniciar Node.js.");
$offset=0; while($offset<strlen($input)) { $size=fwrite($pipes[0],substr($input,$offset)); if($size===false || $size===0) { proc_terminate($process); foreach($pipes as $pipe) fclose($pipe); proc_close($process); throw new RuntimeException("Falha ao enviar entrada."); } $offset+=$size; }
fclose($pipes[0]); stream_set_timeout($pipes[1],15); $output=stream_get_contents($pipes[1]); $timeout=stream_get_meta_data($pipes[1])["timed_out"]; fclose($pipes[1]); if($timeout) proc_terminate($process); stream_get_contents($pipes[2]); fclose($pipes[2]); $status=proc_close($process);
if($timeout || $status!==0) throw new RuntimeException("Erro técnico ou timeout do Node.js; confira os pacotes npm.");
$response=json_decode($output,true,512,JSON_THROW_ON_ERROR); if(!$response["ok"]) throw new InvalidArgumentException($response["error"]);
return $response["result"];
}