JavaScript Python PHP
async function executar(values) {
function generateInfraEnvExample(v) {
const mode = infraChoice(v.mode, ['Vazio', 'Marcador', 'Exemplos por nome']), parsed = parseInfraEnv(v.input);
const replacement = (key) => mode === 'Vazio' ? '' : mode === 'Marcador' ? 'CHANGE_ME' : /(?:^|_)PORT$/.test(key) ? '3000' : /(?:URL|URI|ORIGIN)$/.test(key) ? 'https://example.com' : /EMAIL$/.test(key) ? 'usuario@example.com' : /(?:ENABLED|DISABLED|DEBUG)$/.test(key) ? 'false' : 'CHANGE_ME';
const text = parsed.parts.map(part => part.key ? part.prefix + encodeInfraEnvValue(replacement(part.key)) + part.suffix : part.raw).join('');
return { text, files: [{ name: '.env.example', content: text }], notes: ['Todos os valores foram substituídos. Comentários são mantidos e podem conter dados sensíveis: revise-os antes de compartilhar. Exemplos não são credenciais nem configuração pronta.'] };
}
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;
}
function parseInfraEnv(input) {
const source = infraText(input).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n'), values = Object.create(null), parts = [];
let position = 0;
const fail = (message, offset = position) => { const prefix = source.slice(0, offset), line = prefix.split('\n').length, column = offset - prefix.lastIndexOf('\n'); throw new Error(`ENV: ${message} (linha ${line}, coluna ${column}).`); };
while (position < source.length) {
const start = position;
while (/[\t ]/.test(source[position] || '\0'))
position++;
if (source[position] === '#' || source[position] === '\n' || position === source.length) {
while (position < source.length && source[position] !== '\n')
position++;
if (source[position] === '\n')
position++;
parts.push({ raw: source.slice(start, position) });
continue;
}
if (source.slice(position).startsWith('export ') || source.slice(position).startsWith('export\t')) {
position += 6;
while (/[\t ]/.test(source[position] || '\0'))
position++;
}
const match = source.slice(position).match(/^[A-Za-z_][A-Za-z0-9_]*/);
if (!match)
fail('nome de variável inválido');
const key = match[0];
position += key.length;
while (/[\t ]/.test(source[position] || '\0'))
position++;
if (source[position] !== '=')
fail('esperado = após o nome');
position++;
while (/[\t ]/.test(source[position] || '\0'))
position++;
const valueStart = position;
let value = '', valueEnd = position;
const quote = source[position];
if (quote === '"' || quote === "'" || quote === '`') {
position++;
const content = position;
while (position < source.length && source[position] !== quote)
position++;
if (position === source.length)
fail('aspas não fechadas', valueStart);
value = source.slice(content, position);
position++;
valueEnd = position;
if (quote === '"')
value = value.replace(/\\n/g, '\n').replace(/\\r/g, '\r');
while (/[\t ]/.test(source[position] || '\0'))
position++;
if (position < source.length && source[position] !== '#' && source[position] !== '\n')
fail('conteúdo extra após as aspas; escapes do delimitador não são suportados');
}
else {
while (position < source.length && source[position] !== '\n' && source[position] !== '#')
position++;
valueEnd = position;
while (valueEnd > valueStart && /[\t ]/.test(source[valueEnd - 1]))
valueEnd--;
value = source.slice(valueStart, valueEnd);
}
while (position < source.length && source[position] !== '\n')
position++;
if (source[position] === '\n')
position++;
if (Object.hasOwn(values, key))
fail('variável duplicada: ' + key, start);
if (Object.keys(values).length >= 200)
fail('limite de 200 variáveis', start);
values[key] = value;
parts.push({ raw: source.slice(start, position), key, value, prefix: source.slice(start, valueStart), suffix: source.slice(valueEnd, position) });
}
return { values, parts };
}
function encodeInfraEnvValue(value) {
infraText(value);
if (value === '')
return '';
const candidates = [];
if (!/[#\r\n]/.test(value) && value.trim() === value && !/^["'`]/.test(value))
candidates.push(value);
if (!value.includes("'") && !value.includes('\r'))
candidates.push("'" + value + "'");
if (!value.includes('`') && !value.includes('\r'))
candidates.push('`' + value + '`');
if (!value.includes('"') && !/\\[nr]/.test(value))
candidates.push('"' + value.replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '"');
for (const candidate of candidates)
if (parseInfraEnv('VALUE=' + candidate).values.VALUE === value)
return candidate;
throw new Error('O valor combina aspas/escapes sem representação fiel no subconjunto ENV. Mantenha-o em JSON ou ajuste conscientemente a configuração; nenhum caractere foi descartado.');
}
const keys = ['minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];
for (const value of Object.values(values)) infraText(value);
const output = await generateInfraEnvExample(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
import re
def executar(values):
def text(value, limit=100000):
if not isinstance(value, str) or len(value.encode('utf-16-le')) // 2 > limit or re.search(r'[\x00-\x08\x0b\x0c\x0e-\x1f\ufffe\uffff\ud800-\udfff]', value):
raise ValueError('Texto excede o limite ou contém caracteres inválidos.')
return value
def choice(value, options):
if value not in options:
raise ValueError('Opção não suportada.')
return value
def read_env(source):
source = text(source).removeprefix('\ufeff').replace('\r\n', '\n').replace('\r', '\n')
position, result, parts = 0, {}, []
def fail(message):
line = source[:position].count('\n') + 1
column = position - source.rfind('\n', 0, position)
raise ValueError(f'ENV: {message} (linha {line}, coluna {column}).')
while position < len(source):
start = position
while position < len(source) and source[position] in ' \t': position += 1
if position == len(source) or source[position] in '#\n':
while position < len(source) and source[position] != '\n': position += 1
if position < len(source): position += 1
parts.append({'raw': source[start:position]})
continue
if source[position:].startswith(('export ', 'export\t')):
position += 6
while position < len(source) and source[position] in ' \t': position += 1
match = re.match(r'[A-Za-z_][A-Za-z0-9_]*', source[position:])
if not match: fail('nome de variável inválido')
key = match[0]
position += len(key)
while position < len(source) and source[position] in ' \t': position += 1
if position >= len(source) or source[position] != '=': fail('esperado =')
position += 1
while position < len(source) and source[position] in ' \t': position += 1
value_start = position
if position < len(source) and source[position] in "'\"`":
quote = source[position]
position += 1
content = position
while position < len(source) and source[position] != quote: position += 1
if position == len(source): fail('aspas não fechadas')
value = source[content:position]
position += 1
value_end = position
if quote == '"': value = value.replace('\\n', '\n').replace('\\r', '\r')
while position < len(source) and source[position] in ' \t': position += 1
if position < len(source) and source[position] not in '#\n': fail('conteúdo extra após aspas')
else:
while position < len(source) and source[position] not in '#\n': position += 1
value_end = position
while value_end > value_start and source[value_end - 1] in ' \t': value_end -= 1
value = source[value_start:value_end]
while position < len(source) and source[position] != '\n': position += 1
if position < len(source): position += 1
if key in result: fail('variável duplicada: ' + key)
if len(result) >= 200: fail('limite de 200 variáveis')
result[key] = value
parts.append({'key': key, 'prefix': source[start:value_start], 'suffix': source[value_end:position]})
return result, parts
def encode_env(value):
text(value)
if value == '': return ''
candidates = []
if not re.search(r'[#\r\n]', value) and value.strip() == value and value[0] not in "'\"`": candidates.append(value)
if "'" not in value and '\r' not in value: candidates.append("'" + value + "'")
if '`' not in value and '\r' not in value: candidates.append('`' + value + '`')
if '"' not in value and not re.search(r'\\[nr]', value): candidates.append('"' + value.replace('\n', '\\n').replace('\r', '\\r') + '"')
for candidate in candidates:
if read_env('VALUE=' + candidate)[0]['VALUE'] == value: return candidate
raise ValueError('Valor sem representação fiel no subconjunto ENV.')
for value in values.values(): text(value)
mode = choice(values['mode'], ['Vazio', 'Marcador', 'Exemplos por nome'])
_, parts = read_env(values['input'])
def replacement(key):
if mode == 'Vazio': return ''
if mode == 'Marcador': return 'CHANGE_ME'
if re.search(r'(?:^|_)PORT$', key): return '3000'
if re.search(r'(?:URL|URI|ORIGIN)$', key): return 'https://example.com'
if key.endswith('EMAIL'): return 'usuario@example.com'
if re.search(r'(?:ENABLED|DISABLED|DEBUG)$', key): return 'false'
return 'CHANGE_ME'
output = ''.join(part['prefix'] + encode_env(replacement(part['key'])) + part['suffix'] if 'key' in part else part['raw'] for part in parts)
return {'text': output, 'files': [{'name': '.env.example', 'content': output}], 'notes': ['Todos os valores foram substituídos. Comentários são mantidos e podem conter dados sensíveis: revise-os antes de compartilhar. Exemplos não são credenciais nem configuração pronta.']}
<?php
function executar(array $values): array {
$text = static function ($value, $limit = 100000) { if (!is_string($value) || !preg_match('//u', $value) || strlen(iconv('UTF-8', 'UTF-16LE', $value)) / 2 > $limit || preg_match('/[\x00-\x08\x0b\x0c\x0e-\x1f\x{fffe}\x{ffff}]/u', $value)) throw new InvalidArgumentException('Texto excede o limite ou contém caracteres inválidos.'); return $value; };
$choice = static function ($value, $options) { if (!in_array($value, $options, true)) throw new InvalidArgumentException('Opção não suportada.'); return $value; };
$readEnv = static function ($source) use ($text) {
$source = preg_replace('/^\xEF\xBB\xBF/', '', $text($source)); $source = str_replace(["\r\n", "\r"], "\n", $source); $p = 0; $size = strlen($source); $values = []; $parts = [];
$fail = static function ($message) use (&$p, $source) { throw new InvalidArgumentException('ENV: ' . $message . ' (linha ' . (substr_count(substr($source, 0, $p), "\n") + 1) . ').'); };
while ($p < $size) {
$start = $p; while ($p < $size && str_contains(" \t", $source[$p])) $p++;
if ($p === $size || $source[$p] === '#' || $source[$p] === "\n") { while ($p < $size && $source[$p] !== "\n") $p++; if ($p < $size) $p++; $parts[] = ['raw' => substr($source, $start, $p - $start)]; continue; }
if (str_starts_with(substr($source, $p), 'export ') || str_starts_with(substr($source, $p), "export\t")) { $p += 6; while ($p < $size && str_contains(" \t", $source[$p])) $p++; }
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*/', substr($source, $p), $match)) $fail('nome inválido'); $key = $match[0]; $p += strlen($key);
while ($p < $size && str_contains(" \t", $source[$p])) $p++; if ($p === $size || $source[$p] !== '=') $fail('esperado ='); $p++; while ($p < $size && str_contains(" \t", $source[$p])) $p++; $valueStart = $p;
if ($p < $size && str_contains("'\"`", $source[$p])) { $quote = $source[$p++]; $content = $p; while ($p < $size && $source[$p] !== $quote) $p++; if ($p === $size) $fail('aspas não fechadas'); $value = substr($source, $content, $p - $content); $p++; $valueEnd = $p; if ($quote === '"') $value = str_replace(['\\n', '\\r'], ["\n", "\r"], $value); while ($p < $size && str_contains(" \t", $source[$p])) $p++; if ($p < $size && $source[$p] !== '#' && $source[$p] !== "\n") $fail('conteúdo extra após aspas'); }
else { while ($p < $size && $source[$p] !== '#' && $source[$p] !== "\n") $p++; $valueEnd = $p; while ($valueEnd > $valueStart && str_contains(" \t", $source[$valueEnd - 1])) $valueEnd--; $value = substr($source, $valueStart, $valueEnd - $valueStart); }
while ($p < $size && $source[$p] !== "\n") $p++; if ($p < $size) $p++; if (array_key_exists($key, $values)) $fail('variável duplicada: ' . $key); if (count($values) >= 200) $fail('limite de 200 variáveis'); $values[$key] = $value; $parts[] = ['key' => $key, 'prefix' => substr($source, $start, $valueStart - $start), 'suffix' => substr($source, $valueEnd, $p - $valueEnd)];
}
return [$values, $parts];
};
$encodeEnv = static function ($value) use ($text, $readEnv) {
$text($value); if ($value === '') return ''; $candidates = [];
if (!preg_match('/[#\r\n]/', $value) && trim($value) === $value && !str_contains("'\"`", $value[0])) $candidates[] = $value;
if (!str_contains($value, "'") && !str_contains($value, "\r")) $candidates[] = "'" . $value . "'";
if (!str_contains($value, '`') && !str_contains($value, "\r")) $candidates[] = '`' . $value . '`';
if (!str_contains($value, '"') && !preg_match('/\\\\[nr]/', $value)) $candidates[] = '"' . str_replace(["\n", "\r"], ['\\n', '\\r'], $value) . '"';
foreach ($candidates as $candidate) if ($readEnv('VALUE=' . $candidate)[0]['VALUE'] === $value) return $candidate;
throw new InvalidArgumentException('Valor sem representação fiel no subconjunto ENV.');
};
foreach ($values as $value) $text($value);
$mode = $choice($values['mode'], ['Vazio', 'Marcador', 'Exemplos por nome']); [, $parts] = $readEnv($values['input']); $output = '';
foreach ($parts as $part) { if (!isset($part['key'])) { $output .= $part['raw']; continue; } $key = $part['key']; $replacement = $mode === 'Vazio' ? '' : ($mode === 'Marcador' ? 'CHANGE_ME' : (preg_match('/(?:^|_)PORT$/D', $key) ? '3000' : (preg_match('/(?:URL|URI|ORIGIN)$/D', $key) ? 'https://example.com' : (str_ends_with($key, 'EMAIL') ? 'usuario@example.com' : (preg_match('/(?:ENABLED|DISABLED|DEBUG)$/D', $key) ? 'false' : 'CHANGE_ME'))))); $output .= $part['prefix'] . $encodeEnv($replacement) . $part['suffix']; }
return ['text' => $output, 'files' => [['name' => '.env.example', 'content' => $output]], 'notes' => ['Todos os valores foram substituídos. Comentários são mantidos e podem conter dados sensíveis: revise-os antes de compartilhar. Exemplos não são credenciais nem configuração pronta.']];
}