JavaScript Python PHP
import { Temporal } from "@js-temporal/polyfill";
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument, stringify } from "yaml";
async function executar(values) {
async function formatInfraConfiguration(v) {
const input = infraText(v.input), format = infraChoice(v.format, ['YAML', 'TOML']), mode = infraChoice(v.mode, ['Validar', 'Formatar']);
if (!input.trim())
throw new Error('Informe um documento ' + format + '.');
if (format === 'TOML') {
const toml = await import('smol-toml');
// smol-toml uses the global Temporal API for its strict date implementation.
// Parsing/stringifying is synchronous and the previous global is restored.
const host = globalThis, previous = host.Temporal;
try {
host.Temporal = Temporal;
const data = toml.parse(input, { integersAsBigInt: true, useLegacyDate: false, unsafeKeyBehaviour: 'keep' });
let nodes = 0;
const walk = (value, depth = 0) => {
if (++nodes > 50000 || depth > 64)
throw new Error('TOML excede 50 mil nós ou 64 níveis.');
if (typeof value === 'bigint' && (value < BigInt('-9223372036854775808') || value > BigInt('9223372036854775807')))
throw new Error('Inteiro TOML fora do intervalo de 64 bits com sinal.');
if (mode === 'Formatar' && typeof value === 'number' && Object.is(value, -0))
throw new Error('A formatação não preserva o sinal do float -0.0. Use Validar para conferir esse documento sem alterar o valor.');
if (typeof value === 'string' && /[\uD800-\uDFFF]/u.test(value))
throw new Error('String TOML contém Unicode inválido.');
if (Array.isArray(value))
value.forEach(x => walk(x, depth + 1));
else if (value && typeof value === 'object' && [Object.prototype, null].includes(Object.getPrototypeOf(value)))
Object.values(value).forEach(x => walk(x, depth + 1));
};
walk(data);
return { text: mode === 'Validar' ? 'TOML válido (1.1, sem validação das regras da aplicação).' : toml.stringify(data, { numbersAsFloat: true, strictTemporal: true }), notes: ['TOML: comentários e apresentação original não são preservados. Inteiros permanecem exatos; floats usam a precisão IEEE 754 definida pelo parser.'] };
}
catch (cause) {
throw new Error('TOML inválido: ' + (cause instanceof Error ? cause.message : 'erro de sintaxe ou data'));
}
finally {
if (previous === undefined)
delete host.Temporal;
else
host.Temporal = previous;
}
}
const lines = new LineCounter(), doc = parseDocument(input, { version: '1.2', schema: 'core', uniqueKeys: true, intAsBigInt: true, lineCounter: lines, resolveKnownTags: false, prettyErrors: true });
const issue = doc.errors[0] ?? doc.warnings[0];
if (issue)
throw new Error('YAML inválido: ' + issue.message);
if (doc.directives?.yaml.version !== '1.2')
throw new Error('Somente YAML 1.2 é suportado.');
let count = 0;
const walk = (node, depth = 0) => {
if (++count > 50000 || depth > 64)
throw new Error('YAML excede 50 mil nós ou 64 níveis.');
if (!node)
return;
if (isAlias(node))
throw new Error('Aliases YAML não são aceitos nesta ferramenta.');
if (typeof node === 'object' && 'tag' in node && node.tag && !['tag:yaml.org,2002:str', 'tag:yaml.org,2002:bool', 'tag:yaml.org,2002:null', 'tag:yaml.org,2002:int', 'tag:yaml.org,2002:float', 'tag:yaml.org,2002:map', 'tag:yaml.org,2002:seq'].includes(String(node.tag)))
throw new Error('Tags YAML personalizadas não são aceitas.');
if (isMap(node))
for (const pair of node.items) {
if (!isScalar(pair.key) || typeof pair.key.value !== 'string')
throw new Error('Use chaves YAML de texto.');
if (pair.key.value === '<<' && pair.key.type === 'PLAIN')
throw new Error('Merge YAML não é suportado.');
walk(pair.key, depth + 1);
walk(pair.value, depth + 1);
}
if (isSeq(node))
node.items.forEach(item => walk(item, depth + 1));
};
walk(doc.contents);
if (!doc.contents)
throw new Error('Informe um valor YAML; use null para um valor nulo.');
if (mode === 'Validar')
return { text: 'YAML válido (1.2, sem validação das regras da aplicação).' };
const prettier = await import('prettier/standalone'), plugin = await import('prettier/plugins/yaml');
return { text: await prettier.format(input, { parser: 'yaml', plugins: [plugin], tabWidth: 2, endOfLine: 'lf', embeddedLanguageFormatting: 'off' }) };
}
function infraText(value, limit = 100000) {
if (typeof value !== 'string' || value.length > limit)
throw new Error(`Use texto com até ${limit} caracteres.`);
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/u.test(value) || /[\uD800-\uDFFF]/u.test(value))
throw new Error('Há caracteres de controle ou Unicode inválidos na entrada.');
return value;
}
function infraChoice(value, options) {
if (!options.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
for (const value of Object.values(values)) infraText(value);
const output = await formatInfraConfiguration(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
import json
import subprocess
def executar(values):
# Requer Node.js 22+ e os pacotes npm abaixo; a implementação completa está visível.
source = r'''
import { Temporal } from "@js-temporal/polyfill";
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument, stringify } from "yaml";
async function executar(values) {
async function formatInfraConfiguration(v) {
const input = infraText(v.input), format = infraChoice(v.format, ['YAML', 'TOML']), mode = infraChoice(v.mode, ['Validar', 'Formatar']);
if (!input.trim())
throw new Error('Informe um documento ' + format + '.');
if (format === 'TOML') {
const toml = await import('smol-toml');
// smol-toml uses the global Temporal API for its strict date implementation.
// Parsing/stringifying is synchronous and the previous global is restored.
const host = globalThis, previous = host.Temporal;
try {
host.Temporal = Temporal;
const data = toml.parse(input, { integersAsBigInt: true, useLegacyDate: false, unsafeKeyBehaviour: 'keep' });
let nodes = 0;
const walk = (value, depth = 0) => {
if (++nodes > 50000 || depth > 64)
throw new Error('TOML excede 50 mil nós ou 64 níveis.');
if (typeof value === 'bigint' && (value < BigInt('-9223372036854775808') || value > BigInt('9223372036854775807')))
throw new Error('Inteiro TOML fora do intervalo de 64 bits com sinal.');
if (mode === 'Formatar' && typeof value === 'number' && Object.is(value, -0))
throw new Error('A formatação não preserva o sinal do float -0.0. Use Validar para conferir esse documento sem alterar o valor.');
if (typeof value === 'string' && /[\uD800-\uDFFF]/u.test(value))
throw new Error('String TOML contém Unicode inválido.');
if (Array.isArray(value))
value.forEach(x => walk(x, depth + 1));
else if (value && typeof value === 'object' && [Object.prototype, null].includes(Object.getPrototypeOf(value)))
Object.values(value).forEach(x => walk(x, depth + 1));
};
walk(data);
return { text: mode === 'Validar' ? 'TOML válido (1.1, sem validação das regras da aplicação).' : toml.stringify(data, { numbersAsFloat: true, strictTemporal: true }), notes: ['TOML: comentários e apresentação original não são preservados. Inteiros permanecem exatos; floats usam a precisão IEEE 754 definida pelo parser.'] };
}
catch (cause) {
throw new Error('TOML inválido: ' + (cause instanceof Error ? cause.message : 'erro de sintaxe ou data'));
}
finally {
if (previous === undefined)
delete host.Temporal;
else
host.Temporal = previous;
}
}
const lines = new LineCounter(), doc = parseDocument(input, { version: '1.2', schema: 'core', uniqueKeys: true, intAsBigInt: true, lineCounter: lines, resolveKnownTags: false, prettyErrors: true });
const issue = doc.errors[0] ?? doc.warnings[0];
if (issue)
throw new Error('YAML inválido: ' + issue.message);
if (doc.directives?.yaml.version !== '1.2')
throw new Error('Somente YAML 1.2 é suportado.');
let count = 0;
const walk = (node, depth = 0) => {
if (++count > 50000 || depth > 64)
throw new Error('YAML excede 50 mil nós ou 64 níveis.');
if (!node)
return;
if (isAlias(node))
throw new Error('Aliases YAML não são aceitos nesta ferramenta.');
if (typeof node === 'object' && 'tag' in node && node.tag && !['tag:yaml.org,2002:str', 'tag:yaml.org,2002:bool', 'tag:yaml.org,2002:null', 'tag:yaml.org,2002:int', 'tag:yaml.org,2002:float', 'tag:yaml.org,2002:map', 'tag:yaml.org,2002:seq'].includes(String(node.tag)))
throw new Error('Tags YAML personalizadas não são aceitas.');
if (isMap(node))
for (const pair of node.items) {
if (!isScalar(pair.key) || typeof pair.key.value !== 'string')
throw new Error('Use chaves YAML de texto.');
if (pair.key.value === '<<' && pair.key.type === 'PLAIN')
throw new Error('Merge YAML não é suportado.');
walk(pair.key, depth + 1);
walk(pair.value, depth + 1);
}
if (isSeq(node))
node.items.forEach(item => walk(item, depth + 1));
};
walk(doc.contents);
if (!doc.contents)
throw new Error('Informe um valor YAML; use null para um valor nulo.');
if (mode === 'Validar')
return { text: 'YAML válido (1.2, sem validação das regras da aplicação).' };
const prettier = await import('prettier/standalone'), plugin = await import('prettier/plugins/yaml');
return { text: await prettier.format(input, { parser: 'yaml', plugins: [plugin], tabWidth: 2, endOfLine: 'lf', embeddedLanguageFormatting: 'off' }) };
}
function infraText(value, limit = 100000) {
if (typeof value !== 'string' || value.length > limit)
throw new Error(`Use texto com até ${limit} caracteres.`);
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/u.test(value) || /[\uD800-\uDFFF]/u.test(value))
throw new Error('Há caracteres de controle ou Unicode inválidos na entrada.');
return value;
}
function infraChoice(value, options) {
if (!options.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
for (const value of Object.values(values)) infraText(value);
const output = await formatInfraConfiguration(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
let input=""; for await (const chunk of process.stdin) input+=chunk; try { process.stdout.write(JSON.stringify({ok:true,result:await 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 {
// Requer Node.js 22+ e os pacotes npm abaixo; a implementação completa está visível.
$source = <<<'JAVASCRIPT'
import { Temporal } from "@js-temporal/polyfill";
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument, stringify } from "yaml";
async function executar(values) {
async function formatInfraConfiguration(v) {
const input = infraText(v.input), format = infraChoice(v.format, ['YAML', 'TOML']), mode = infraChoice(v.mode, ['Validar', 'Formatar']);
if (!input.trim())
throw new Error('Informe um documento ' + format + '.');
if (format === 'TOML') {
const toml = await import('smol-toml');
// smol-toml uses the global Temporal API for its strict date implementation.
// Parsing/stringifying is synchronous and the previous global is restored.
const host = globalThis, previous = host.Temporal;
try {
host.Temporal = Temporal;
const data = toml.parse(input, { integersAsBigInt: true, useLegacyDate: false, unsafeKeyBehaviour: 'keep' });
let nodes = 0;
const walk = (value, depth = 0) => {
if (++nodes > 50000 || depth > 64)
throw new Error('TOML excede 50 mil nós ou 64 níveis.');
if (typeof value === 'bigint' && (value < BigInt('-9223372036854775808') || value > BigInt('9223372036854775807')))
throw new Error('Inteiro TOML fora do intervalo de 64 bits com sinal.');
if (mode === 'Formatar' && typeof value === 'number' && Object.is(value, -0))
throw new Error('A formatação não preserva o sinal do float -0.0. Use Validar para conferir esse documento sem alterar o valor.');
if (typeof value === 'string' && /[\uD800-\uDFFF]/u.test(value))
throw new Error('String TOML contém Unicode inválido.');
if (Array.isArray(value))
value.forEach(x => walk(x, depth + 1));
else if (value && typeof value === 'object' && [Object.prototype, null].includes(Object.getPrototypeOf(value)))
Object.values(value).forEach(x => walk(x, depth + 1));
};
walk(data);
return { text: mode === 'Validar' ? 'TOML válido (1.1, sem validação das regras da aplicação).' : toml.stringify(data, { numbersAsFloat: true, strictTemporal: true }), notes: ['TOML: comentários e apresentação original não são preservados. Inteiros permanecem exatos; floats usam a precisão IEEE 754 definida pelo parser.'] };
}
catch (cause) {
throw new Error('TOML inválido: ' + (cause instanceof Error ? cause.message : 'erro de sintaxe ou data'));
}
finally {
if (previous === undefined)
delete host.Temporal;
else
host.Temporal = previous;
}
}
const lines = new LineCounter(), doc = parseDocument(input, { version: '1.2', schema: 'core', uniqueKeys: true, intAsBigInt: true, lineCounter: lines, resolveKnownTags: false, prettyErrors: true });
const issue = doc.errors[0] ?? doc.warnings[0];
if (issue)
throw new Error('YAML inválido: ' + issue.message);
if (doc.directives?.yaml.version !== '1.2')
throw new Error('Somente YAML 1.2 é suportado.');
let count = 0;
const walk = (node, depth = 0) => {
if (++count > 50000 || depth > 64)
throw new Error('YAML excede 50 mil nós ou 64 níveis.');
if (!node)
return;
if (isAlias(node))
throw new Error('Aliases YAML não são aceitos nesta ferramenta.');
if (typeof node === 'object' && 'tag' in node && node.tag && !['tag:yaml.org,2002:str', 'tag:yaml.org,2002:bool', 'tag:yaml.org,2002:null', 'tag:yaml.org,2002:int', 'tag:yaml.org,2002:float', 'tag:yaml.org,2002:map', 'tag:yaml.org,2002:seq'].includes(String(node.tag)))
throw new Error('Tags YAML personalizadas não são aceitas.');
if (isMap(node))
for (const pair of node.items) {
if (!isScalar(pair.key) || typeof pair.key.value !== 'string')
throw new Error('Use chaves YAML de texto.');
if (pair.key.value === '<<' && pair.key.type === 'PLAIN')
throw new Error('Merge YAML não é suportado.');
walk(pair.key, depth + 1);
walk(pair.value, depth + 1);
}
if (isSeq(node))
node.items.forEach(item => walk(item, depth + 1));
};
walk(doc.contents);
if (!doc.contents)
throw new Error('Informe um valor YAML; use null para um valor nulo.');
if (mode === 'Validar')
return { text: 'YAML válido (1.2, sem validação das regras da aplicação).' };
const prettier = await import('prettier/standalone'), plugin = await import('prettier/plugins/yaml');
return { text: await prettier.format(input, { parser: 'yaml', plugins: [plugin], tabWidth: 2, endOfLine: 'lf', embeddedLanguageFormatting: 'off' }) };
}
function infraText(value, limit = 100000) {
if (typeof value !== 'string' || value.length > limit)
throw new Error(`Use texto com até ${limit} caracteres.`);
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/u.test(value) || /[\uD800-\uDFFF]/u.test(value))
throw new Error('Há caracteres de controle ou Unicode inválidos na entrada.');
return value;
}
function infraChoice(value, options) {
if (!options.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
for (const value of Object.values(values)) infraText(value);
const output = await formatInfraConfiguration(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
let input=""; for await (const chunk of process.stdin) input+=chunk; try { process.stdout.write(JSON.stringify({ok:true,result:await executar(JSON.parse(input))})); } catch (error) { process.stdout.write(JSON.stringify({ok:false,error:error.message})); }
JAVASCRIPT;
$payload = 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($payload)) { $n = fwrite($pipes[0], substr($payload, $offset)); if ($n === false || $n === 0) { proc_terminate($process); foreach ($pipes as $pipe) fclose($pipe); proc_close($process); throw new RuntimeException("Falha ao enviar a entrada."); } $offset += $n; }
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("Falha técnica ou timeout no Node.js; confira as dependências npm.");
$response = json_decode($output, true, 512, JSON_THROW_ON_ERROR); if (!$response["ok"]) throw new InvalidArgumentException($response["error"]);
return $response["result"];
}