JavaScript Python PHP
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument, stringify } from "yaml";
async function executar(values) {
function generateInfraKubernetes(v) {
const name = infraName(v.name, 'Aplicação', 56), namespace = infraName(v.namespace, 'Namespace'), port = infraInteger(v.port, 'Porta da aplicação', 1024, 65535), servicePort = infraInteger(v.servicePort, 'Porta do Service', 1, 65535), replicas = infraInteger(v.replicas, 'Réplicas', 0, 10), uid = infraInteger(v.uid, 'UID', 1, 2147483647);
if (v.image.length > 255 || !/^(?:(?:[a-z0-9][a-z0-9.-]*)(?::[1-9]\d{0,4})?\/)?(?:[a-z0-9]+(?:[._-][a-z0-9]+)*\/)*[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}|@sha256:[a-f0-9]{64})$/.test(v.image))
throw new Error('Imagem inválida: informe repositório OCI com tag ou digest sha256 explícito, sem espaços ou comandos.');
const cpuRequest = infraInteger(v.cpuRequest, 'CPU request', 1, 64000), cpuLimit = infraInteger(v.cpuLimit, 'CPU limit', 1, 64000), memoryRequest = infraInteger(v.memoryRequest, 'Memória request', 1, 262144), memoryLimit = infraInteger(v.memoryLimit, 'Memória limit', 1, 262144);
if (cpuRequest > cpuLimit || memoryRequest > memoryLimit)
throw new Error('Requests de CPU/memória não podem ultrapassar os limits.');
const environment = infraEnvironment(v.environment), configName = name + '-config', labels = { app: name };
const container = { name, image: v.image, imagePullPolicy: v.image.endsWith(':latest') ? 'Always' : 'IfNotPresent', ports: [{ name: 'http', containerPort: port }], envFrom: [{ configMapRef: { name: configName } }], resources: { requests: { cpu: cpuRequest + 'm', memory: memoryRequest + 'Mi' }, limits: { cpu: cpuLimit + 'm', memory: memoryLimit + 'Mi' } }, securityContext: { runAsNonRoot: true, runAsUser: uid, allowPrivilegeEscalation: false, capabilities: { drop: ['ALL'] }, seccompProfile: { type: 'RuntimeDefault' } } };
if (v.healthPath) {
const path = infraHealthPath(v.healthPath);
container.readinessProbe = { httpGet: { path, port: 'http' }, initialDelaySeconds: 5, periodSeconds: 10, timeoutSeconds: 3 };
container.livenessProbe = { httpGet: { path, port: 'http' }, initialDelaySeconds: 30, periodSeconds: 20, timeoutSeconds: 3 };
}
const metadata = { name, namespace, labels }, deployment = { apiVersion: 'apps/v1', kind: 'Deployment', metadata, spec: { replicas, selector: { matchLabels: labels }, template: { metadata: { labels }, spec: { containers: [container] } } } };
const service = { apiVersion: 'v1', kind: 'Service', metadata, spec: { type: 'ClusterIP', selector: labels, ports: [{ name: 'http', port: servicePort, targetPort: 'http', protocol: 'TCP' }] } };
const config = { apiVersion: 'v1', kind: 'ConfigMap', metadata: { name: configName, namespace }, data: environment };
const text = [deployment, service, config].map(infraYaml).join('---\n');
return { text, files: [{ name: 'manifests.yaml', content: text }], notes: ['A imagem informada é responsabilidade do usuário. Namespace, UID, porta e caminho HTTP precisam corresponder ao ambiente real.', 'ConfigMap não protege segredos. Não há criação de namespace, Secret, Ingress, TLS, PVC ou aplicação automática dos manifests. Valide no cluster de destino antes de usar.'] };
}
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 infraInteger(value, label, min, max) {
if (!/^\d{1,10}$/.test(value || '') || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max)
throw new Error(`${label}: use um inteiro de ${min} a ${max}.`);
return Number(value);
}
function infraEnvironment(input) {
const data = parseJsonCompatible(infraText(input), 'JSON');
if (!data || typeof data !== 'object' || Array.isArray(data))
throw new Error('Informe um objeto JSON de strings, sem listas ou valores aninhados.');
if (Object.keys(data).length > 200)
throw new Error('Limite de 200 variáveis.');
const result = Object.create(null);
for (const [key, value] of Object.entries(data)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
throw new Error('Nome de variável inválido: ' + key);
if (typeof value !== 'string')
throw new Error('A variável ' + key + ' precisa ser string, inclusive números, booleanos e valores vazios.');
result[key] = infraText(value);
}
return result;
}
const limits = ['0–59', '0–23', '1–31', '1–12', '0–7; domingo 0/7'];
const keys = ['minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];
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 infraYaml(value) { return stringify(value, { indent: 2, lineWidth: 0, defaultStringType: 'QUOTE_DOUBLE' }); }
function infraName(value, label, max = 63) {
if (typeof value !== 'string' || value.length > max || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value))
throw new Error(`${label}: use um nome DNS minúsculo de 1 a ${max} caracteres, com números ou hífens internos.`);
return value;
}
function infraHealthPath(value) {
if (value.length > 200 || !/^\/[A-Za-z0-9/_.-]*$/.test(value) || value.split('/').includes('..'))
throw new Error('Use um caminho HTTP simples iniciado por /, sem parâmetros, espaços ou segmentos ...');
return value;
}
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)) infraText(value);
const output = await generateInfraKubernetes(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 { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument, stringify } from "yaml";
async function executar(values) {
function generateInfraKubernetes(v) {
const name = infraName(v.name, 'Aplicação', 56), namespace = infraName(v.namespace, 'Namespace'), port = infraInteger(v.port, 'Porta da aplicação', 1024, 65535), servicePort = infraInteger(v.servicePort, 'Porta do Service', 1, 65535), replicas = infraInteger(v.replicas, 'Réplicas', 0, 10), uid = infraInteger(v.uid, 'UID', 1, 2147483647);
if (v.image.length > 255 || !/^(?:(?:[a-z0-9][a-z0-9.-]*)(?::[1-9]\d{0,4})?\/)?(?:[a-z0-9]+(?:[._-][a-z0-9]+)*\/)*[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}|@sha256:[a-f0-9]{64})$/.test(v.image))
throw new Error('Imagem inválida: informe repositório OCI com tag ou digest sha256 explícito, sem espaços ou comandos.');
const cpuRequest = infraInteger(v.cpuRequest, 'CPU request', 1, 64000), cpuLimit = infraInteger(v.cpuLimit, 'CPU limit', 1, 64000), memoryRequest = infraInteger(v.memoryRequest, 'Memória request', 1, 262144), memoryLimit = infraInteger(v.memoryLimit, 'Memória limit', 1, 262144);
if (cpuRequest > cpuLimit || memoryRequest > memoryLimit)
throw new Error('Requests de CPU/memória não podem ultrapassar os limits.');
const environment = infraEnvironment(v.environment), configName = name + '-config', labels = { app: name };
const container = { name, image: v.image, imagePullPolicy: v.image.endsWith(':latest') ? 'Always' : 'IfNotPresent', ports: [{ name: 'http', containerPort: port }], envFrom: [{ configMapRef: { name: configName } }], resources: { requests: { cpu: cpuRequest + 'm', memory: memoryRequest + 'Mi' }, limits: { cpu: cpuLimit + 'm', memory: memoryLimit + 'Mi' } }, securityContext: { runAsNonRoot: true, runAsUser: uid, allowPrivilegeEscalation: false, capabilities: { drop: ['ALL'] }, seccompProfile: { type: 'RuntimeDefault' } } };
if (v.healthPath) {
const path = infraHealthPath(v.healthPath);
container.readinessProbe = { httpGet: { path, port: 'http' }, initialDelaySeconds: 5, periodSeconds: 10, timeoutSeconds: 3 };
container.livenessProbe = { httpGet: { path, port: 'http' }, initialDelaySeconds: 30, periodSeconds: 20, timeoutSeconds: 3 };
}
const metadata = { name, namespace, labels }, deployment = { apiVersion: 'apps/v1', kind: 'Deployment', metadata, spec: { replicas, selector: { matchLabels: labels }, template: { metadata: { labels }, spec: { containers: [container] } } } };
const service = { apiVersion: 'v1', kind: 'Service', metadata, spec: { type: 'ClusterIP', selector: labels, ports: [{ name: 'http', port: servicePort, targetPort: 'http', protocol: 'TCP' }] } };
const config = { apiVersion: 'v1', kind: 'ConfigMap', metadata: { name: configName, namespace }, data: environment };
const text = [deployment, service, config].map(infraYaml).join('---\n');
return { text, files: [{ name: 'manifests.yaml', content: text }], notes: ['A imagem informada é responsabilidade do usuário. Namespace, UID, porta e caminho HTTP precisam corresponder ao ambiente real.', 'ConfigMap não protege segredos. Não há criação de namespace, Secret, Ingress, TLS, PVC ou aplicação automática dos manifests. Valide no cluster de destino antes de usar.'] };
}
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 infraInteger(value, label, min, max) {
if (!/^\d{1,10}$/.test(value || '') || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max)
throw new Error(`${label}: use um inteiro de ${min} a ${max}.`);
return Number(value);
}
function infraEnvironment(input) {
const data = parseJsonCompatible(infraText(input), 'JSON');
if (!data || typeof data !== 'object' || Array.isArray(data))
throw new Error('Informe um objeto JSON de strings, sem listas ou valores aninhados.');
if (Object.keys(data).length > 200)
throw new Error('Limite de 200 variáveis.');
const result = Object.create(null);
for (const [key, value] of Object.entries(data)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
throw new Error('Nome de variável inválido: ' + key);
if (typeof value !== 'string')
throw new Error('A variável ' + key + ' precisa ser string, inclusive números, booleanos e valores vazios.');
result[key] = infraText(value);
}
return result;
}
const limits = ['0–59', '0–23', '1–31', '1–12', '0–7; domingo 0/7'];
const keys = ['minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];
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 infraYaml(value) { return stringify(value, { indent: 2, lineWidth: 0, defaultStringType: 'QUOTE_DOUBLE' }); }
function infraName(value, label, max = 63) {
if (typeof value !== 'string' || value.length > max || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value))
throw new Error(`${label}: use um nome DNS minúsculo de 1 a ${max} caracteres, com números ou hífens internos.`);
return value;
}
function infraHealthPath(value) {
if (value.length > 200 || !/^\/[A-Za-z0-9/_.-]*$/.test(value) || value.split('/').includes('..'))
throw new Error('Use um caminho HTTP simples iniciado por /, sem parâmetros, espaços ou segmentos ...');
return value;
}
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)) infraText(value);
const output = await generateInfraKubernetes(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 { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument, stringify } from "yaml";
async function executar(values) {
function generateInfraKubernetes(v) {
const name = infraName(v.name, 'Aplicação', 56), namespace = infraName(v.namespace, 'Namespace'), port = infraInteger(v.port, 'Porta da aplicação', 1024, 65535), servicePort = infraInteger(v.servicePort, 'Porta do Service', 1, 65535), replicas = infraInteger(v.replicas, 'Réplicas', 0, 10), uid = infraInteger(v.uid, 'UID', 1, 2147483647);
if (v.image.length > 255 || !/^(?:(?:[a-z0-9][a-z0-9.-]*)(?::[1-9]\d{0,4})?\/)?(?:[a-z0-9]+(?:[._-][a-z0-9]+)*\/)*[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}|@sha256:[a-f0-9]{64})$/.test(v.image))
throw new Error('Imagem inválida: informe repositório OCI com tag ou digest sha256 explícito, sem espaços ou comandos.');
const cpuRequest = infraInteger(v.cpuRequest, 'CPU request', 1, 64000), cpuLimit = infraInteger(v.cpuLimit, 'CPU limit', 1, 64000), memoryRequest = infraInteger(v.memoryRequest, 'Memória request', 1, 262144), memoryLimit = infraInteger(v.memoryLimit, 'Memória limit', 1, 262144);
if (cpuRequest > cpuLimit || memoryRequest > memoryLimit)
throw new Error('Requests de CPU/memória não podem ultrapassar os limits.');
const environment = infraEnvironment(v.environment), configName = name + '-config', labels = { app: name };
const container = { name, image: v.image, imagePullPolicy: v.image.endsWith(':latest') ? 'Always' : 'IfNotPresent', ports: [{ name: 'http', containerPort: port }], envFrom: [{ configMapRef: { name: configName } }], resources: { requests: { cpu: cpuRequest + 'm', memory: memoryRequest + 'Mi' }, limits: { cpu: cpuLimit + 'm', memory: memoryLimit + 'Mi' } }, securityContext: { runAsNonRoot: true, runAsUser: uid, allowPrivilegeEscalation: false, capabilities: { drop: ['ALL'] }, seccompProfile: { type: 'RuntimeDefault' } } };
if (v.healthPath) {
const path = infraHealthPath(v.healthPath);
container.readinessProbe = { httpGet: { path, port: 'http' }, initialDelaySeconds: 5, periodSeconds: 10, timeoutSeconds: 3 };
container.livenessProbe = { httpGet: { path, port: 'http' }, initialDelaySeconds: 30, periodSeconds: 20, timeoutSeconds: 3 };
}
const metadata = { name, namespace, labels }, deployment = { apiVersion: 'apps/v1', kind: 'Deployment', metadata, spec: { replicas, selector: { matchLabels: labels }, template: { metadata: { labels }, spec: { containers: [container] } } } };
const service = { apiVersion: 'v1', kind: 'Service', metadata, spec: { type: 'ClusterIP', selector: labels, ports: [{ name: 'http', port: servicePort, targetPort: 'http', protocol: 'TCP' }] } };
const config = { apiVersion: 'v1', kind: 'ConfigMap', metadata: { name: configName, namespace }, data: environment };
const text = [deployment, service, config].map(infraYaml).join('---\n');
return { text, files: [{ name: 'manifests.yaml', content: text }], notes: ['A imagem informada é responsabilidade do usuário. Namespace, UID, porta e caminho HTTP precisam corresponder ao ambiente real.', 'ConfigMap não protege segredos. Não há criação de namespace, Secret, Ingress, TLS, PVC ou aplicação automática dos manifests. Valide no cluster de destino antes de usar.'] };
}
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 infraInteger(value, label, min, max) {
if (!/^\d{1,10}$/.test(value || '') || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max)
throw new Error(`${label}: use um inteiro de ${min} a ${max}.`);
return Number(value);
}
function infraEnvironment(input) {
const data = parseJsonCompatible(infraText(input), 'JSON');
if (!data || typeof data !== 'object' || Array.isArray(data))
throw new Error('Informe um objeto JSON de strings, sem listas ou valores aninhados.');
if (Object.keys(data).length > 200)
throw new Error('Limite de 200 variáveis.');
const result = Object.create(null);
for (const [key, value] of Object.entries(data)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
throw new Error('Nome de variável inválido: ' + key);
if (typeof value !== 'string')
throw new Error('A variável ' + key + ' precisa ser string, inclusive números, booleanos e valores vazios.');
result[key] = infraText(value);
}
return result;
}
const limits = ['0–59', '0–23', '1–31', '1–12', '0–7; domingo 0/7'];
const keys = ['minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];
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 infraYaml(value) { return stringify(value, { indent: 2, lineWidth: 0, defaultStringType: 'QUOTE_DOUBLE' }); }
function infraName(value, label, max = 63) {
if (typeof value !== 'string' || value.length > max || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value))
throw new Error(`${label}: use um nome DNS minúsculo de 1 a ${max} caracteres, com números ou hífens internos.`);
return value;
}
function infraHealthPath(value) {
if (value.length > 200 || !/^\/[A-Za-z0-9/_.-]*$/.test(value) || value.split('/').includes('..'))
throw new Error('Use um caminho HTTP simples iniciado por /, sem parâmetros, espaços ou segmentos ...');
return value;
}
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)) infraText(value);
const output = await generateInfraKubernetes(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"];
}