JavaScript Python PHP
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
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 generateSitemapRobots(v) {
const mode = productivityChoice(v.mode, ['Sitemap XML', 'robots.txt']);
if (mode === 'Sitemap XML') {
const seen = new Set(), origins = new Set();
const escape = (value) => value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
const entries = productivityArray(v.input, 'URLs', 1000).map(item => {
const entry = productivityObject(item, 'URL', ['url', 'lastmod']), url = productivityUrl(entry.url), lastmod = productivityDate(entry.lastmod);
if (seen.has(url))
throw new Error('URL duplicada: ' + url);
seen.add(url);
origins.add(new URL(url).origin);
return ' <url>\n <loc>' + escape(url) + '</loc>\n' + (lastmod ? ' <lastmod>' + lastmod + '</lastmod>\n' : '') + ' </url>';
});
if (origins.size !== 1)
throw new Error('Use URLs de uma única origem (protocolo, domínio e porta).');
return { text: '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n' + entries.join('\n') + '\n</urlset>\n', filename: 'sitemap.xml' };
}
const seen = new Set();
const groups = productivityArray(v.input, 'Grupos robots', 100).map(item => {
const group = productivityObject(item, 'Grupo', ['agent', 'allow', 'disallow']), agent = productivityLabel(group.agent, 'User-agent');
if (!/^(?:\*|[A-Za-z0-9_.-]+)$/.test(agent) || seen.has(agent.toLowerCase()))
throw new Error('User-agent inválido ou repetido; use * isolado ou um token por grupo, como Googlebot.');
seen.add(agent.toLowerCase());
const lines = ['User-agent: ' + agent];
for (const [key, directive] of [['allow', 'Allow'], ['disallow', 'Disallow']]) {
if (group[key] === undefined)
continue;
const paths = group[key];
if (!Array.isArray(paths) || paths.length > 500)
throw new Error(key + ': use lista de até 500 caminhos.');
for (const value of paths) {
const path = productivityText(value, directive);
if (typeof value !== 'string' || path.length > 2047 || path && !path.startsWith('/') || /[\s#\\]|%(?![\da-f]{2})/i.test(path))
throw new Error(directive + ': use caminho iniciado por / ou string vazia, sem espaços, comentários ou escapes inválidos.');
lines.push(directive + ': ' + path);
}
}
if (lines.length === 1)
throw new Error('Cada grupo exige ao menos uma regra Allow/Disallow (string vazia é permitida).');
return lines.join('\n');
});
const sitemaps = productivityLines(v.sitemaps, 'Sitemaps').map(url => 'Sitemap: ' + productivityUrl(url));
if (new Set(sitemaps).size !== sitemaps.length)
throw new Error('Sitemap repetido.');
return { text: groups.join('\n\n') + (sitemaps.length ? '\n\n' + sitemaps.join('\n') : '') + '\n', filename: 'robots.txt' };
}
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 productivityLines(value, label, required = false) {
const lines = productivityText(value, label).split('\n').map(line => line.trim()).filter(Boolean);
if (lines.length > 500 || required && !lines.length)
throw new Error(label + ': informe de ' + (required ? '1' : '0') + ' a 500 linhas não vazias.');
return lines;
}
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 productivityDate(value) {
const date = productivityLabel(value, 'Data', true);
if (!date)
return '';
if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || date.startsWith('0000') || !Number.isFinite(Date.parse(date + 'T00:00:00Z')) || new Date(date + 'T00:00:00Z').toISOString().slice(0, 10) !== date)
throw new Error('Data inválida: use YYYY-MM-DD e um dia real do calendário.');
return date;
}
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 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 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 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 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(generateSitemapRobots(values));
}
import re
import json
import math
import datetime
from urllib.parse import urlsplit
def executar(values):
def text(value='', label='Campo'):
if not isinstance(value,str) or len(value.encode('utf-16-le',errors='surrogatepass'))//2 > 100000: raise ValueError(label+': informe texto de até 100 mil unidades UTF-16.')
if re.search(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff]',value): raise ValueError(label+': controles ou Unicode inválido.')
return value.replace('\r\n','\n').replace('\r','\n')
def trim(value):
return value.strip('\t\n\r \v\f\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff')
def label(value, title, optional=False):
content=trim(text(value,title))
if (not content and not optional) or len(content.encode('utf-16-le'))//2>200 or re.search(r'[\n\t\u2028\u2029]',content): raise ValueError(title+': use uma linha de 1–200 caracteres.')
return content
def choice(value, options):
if value not in options: raise ValueError('Escolha uma opção válida.')
return value
def lines(value, title, required=False):
result=[trim(line) for line in text(value,title).split('\n') if trim(line)]
if len(result)>500 or required and not result: raise ValueError(title+': informe até 500 linhas não vazias.')
return result
def obj(value, title, keys=None):
if not isinstance(value,dict): raise ValueError(title+': use um objeto JSON.')
if keys is not None and any(key not in keys for key in value): raise ValueError(title+': campo não suportado.')
return value
def array_input(source,title,limit=500):
value=read(source,title)
if not isinstance(value,list) or not value or len(value)>limit: raise ValueError(title+': lista JSON não vazia fora do limite.')
return value
def date(value=''):
content=label(value,'Data',True)
if not content: return ''
if not re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}',content): raise ValueError('Data inválida: use YYYY-MM-DD.')
datetime.date.fromisoformat(content)
return content
def url(value):
content=trim(text(value,'URL'))
if len(content)>2047 or not re.match(r'^https?://[^/]',content,re.I) or re.search(r'[^\x21-\x7e]|[\\<>"`{}|^]|%(?![\da-fA-F]{2})',content) or '#' in content: raise ValueError('URL HTTP/HTTPS ASCII inválida.')
parsed=urlsplit(content)
if not parsed.hostname or parsed.username is not None or parsed.password is not None or parsed.port is not None and not 0<=parsed.port<=65535: raise ValueError('URL com credenciais ou porta inválida.')
return content
def finish(content, filename):
if len(content.encode('utf-16-le'))//2>1000000: raise ValueError('Saída excede 1 milhão de unidades UTF-16.')
return {'text':content,'filename':filename}
def read(source, label, object_only=False):
text(source, label)
if not source.strip(): raise ValueError(label + ': informe JSON')
def pairs(items):
result = {}
for key, value in items:
if key in result: raise ValueError('Chave duplicada: ' + key)
result[key] = value
return result
def number(token):
if '.' not in token and 'e' not in token.lower() and len(token.lstrip('-')) > 16: raise ValueError('Inteiro fora do intervalo seguro; use string')
value = float(token) if '.' in token or 'e' in token.lower() else int(token)
if not math.isfinite(value): raise ValueError('Número não finito')
if value == 0 and (token.startswith('-') or re.search('[1-9]', token.lower().split('e')[0])): raise ValueError('Zero negativo ou underflow')
if value % 1 == 0 and abs(value) > 9007199254740991: raise ValueError('Inteiro fora do intervalo seguro; use string')
return value
def reject(value): raise ValueError('Constante JSON inválida: ' + value)
value = json.loads(source, object_pairs_hook=pairs, parse_int=number, parse_float=number, parse_constant=reject)
count = 0
def walk(value, depth=0):
nonlocal count
count += 1
if count > 100000 or depth > 100: raise ValueError('Limite de 100 níveis ou 100 mil nós JSON')
if isinstance(value, dict):
for child in value.values(): walk(child, depth + 1)
elif isinstance(value, list):
for child in value: walk(child, depth + 1)
walk(value)
if object_only and not isinstance(value, dict): raise ValueError(label + ': informe objeto JSON')
return value
for value in values.values(): text(value)
mode=choice(values.get('mode'),['Sitemap XML','robots.txt'])
if mode=='Sitemap XML':
seen=set(); origins=set(); entries=[]
def escape(value): return value.replace('&','&').replace('<','<').replace('>','>').replace('"','"').replace("'",''')
for item in array_input(values.get('input',''),'URLs',1000):
entry=obj(item,'URL',['url','lastmod']); location=url(entry.get('url','')); when=date(entry.get('lastmod',''))
if location in seen: raise ValueError('URL duplicada.')
seen.add(location); parsed=urlsplit(location); origins.add((parsed.scheme.lower(),parsed.hostname.lower(),parsed.port or (443 if parsed.scheme.lower()=='https' else 80)))
entries.append(' <url>\n <loc>'+escape(location)+'</loc>\n'+(' <lastmod>'+when+'</lastmod>\n' if when else '')+' </url>')
if len(origins)!=1: raise ValueError('Use URLs de uma única origem.')
return finish('<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+'\n'.join(entries)+'\n</urlset>\n','sitemap.xml')
seen=set(); groups=[]
for item in array_input(values.get('input',''),'Grupos robots',100):
group=obj(item,'Grupo',['agent','allow','disallow']); agent=label(group.get('agent',''),'User-agent')
if not re.fullmatch(r'(?:\*|[A-Za-z0-9_.-]+)',agent) or agent.lower() in seen: raise ValueError('User-agent inválido ou repetido.')
seen.add(agent.lower()); result=['User-agent: '+agent]
for key,directive in [('allow','Allow'),('disallow','Disallow')]:
if key not in group: continue
paths=group[key]
if not isinstance(paths,list) or len(paths)>500: raise ValueError('Lista de caminhos inválida.')
for value in paths:
path=text(value,directive)
if len(path.encode('utf-16-le'))//2>2047 or path and not path.startswith('/') or re.search(r'[\s#\\]|%(?![\da-fA-F]{2})',path): raise ValueError('Caminho inválido.')
result.append(directive+': '+path)
if len(result)==1: raise ValueError('Grupo exige ao menos uma regra.')
groups.append('\n'.join(result))
sitemaps=['Sitemap: '+url(item) for item in lines(values.get('sitemaps',''),'Sitemaps')]
if len(set(sitemaps))!=len(sitemaps): raise ValueError('Sitemap repetido.')
return finish('\n\n'.join(groups)+('\n\n'+'\n'.join(sitemaps) if sitemaps else '')+'\n','robots.txt')
<?php
function executar(array $values): array {
$text = function ($value = '', $label = 'Campo') {
if (!is_string($value) || !preg_match('//u', $value) || strlen(iconv('UTF-8','UTF-16LE',$value))/2 > 100000) throw new InvalidArgumentException($label.': texto de até 100 mil unidades UTF-16.');
if (preg_match('/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/', $value)) throw new InvalidArgumentException($label.': caracteres de controle.');
return str_replace(["\r\n","\r"],"\n",$value);
};
$read = function ($source, $label, $objectOnly = false) use ($text) {
$source = $text($source, $label);
if (trim($source) === '') throw new InvalidArgumentException($label.': informe JSON');
json_decode($source, false, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
$stack = [];
for ($i = 0; $i < strlen($source); $i++) {
$ch = $source[$i];
if ($ch === '{' || $ch === '[') { $stack[] = ['object'=>$ch === '{', 'keys'=>[]]; continue; }
if ($ch === '}' || $ch === ']') { array_pop($stack); continue; }
if ($ch === '"') {
$start = $i; $escaped = false;
while (++$i < strlen($source)) { $c = $source[$i]; if ($escaped) $escaped = false; elseif ($c === '\\') $escaped = true; elseif ($c === '"') break; }
$look = $i + 1; while ($look < strlen($source) && str_contains(" \t\r\n", $source[$look])) $look++;
$index = count($stack) - 1;
if ($index >= 0 && $stack[$index]['object'] && ($source[$look] ?? '') === ':') {
$key = json_decode(substr($source, $start, $i-$start+1), false, 512, JSON_THROW_ON_ERROR);
if (array_key_exists($key, $stack[$index]['keys'])) throw new InvalidArgumentException('Chave duplicada: '.$key);
$stack[$index]['keys'][$key] = true;
}
} elseif ($ch === '-' || ctype_digit($ch)) {
preg_match('/\G-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/', $source, $match, 0, $i);
$token = $match[0]; $value = (float)$token; $mantissa = explode('e', strtolower($token))[0];
if (!is_finite($value) || ($value == 0 && (str_starts_with($token, '-') || preg_match('/[1-9]/', $mantissa))) || (floor($value) === $value && abs($value) > 9007199254740991)) throw new InvalidArgumentException('Número não preservável; use string');
$i += strlen($token)-1;
}
}
$value = json_decode($source, false, 512, JSON_THROW_ON_ERROR);
$count = 0;
$walk = function ($value, $depth = 0) use (&$walk, &$count) {
if (++$count > 100000 || $depth > 100) throw new InvalidArgumentException('Limite de 100 níveis ou 100 mil nós JSON');
if (is_object($value) || is_array($value)) foreach ($value as $child) $walk($child, $depth+1);
};
$walk($value);
if ($objectOnly && !is_object($value)) throw new InvalidArgumentException($label.': informe objeto JSON');
return $value;
};
$trimText = fn($value)=>preg_replace('/^[\s\x{FEFF}]+|[\s\x{FEFF}]+$/u','',$value);
$label = function ($value,$title,$optional=false) use ($text,$trimText) {
$content=$trimText($text($value,$title));
if (($content==='' && !$optional) || strlen(iconv('UTF-8','UTF-16LE',$content))/2>200 || preg_match('/[\n\t\x{2028}\x{2029}]/u',$content)) throw new InvalidArgumentException($title.': use uma linha de 1–200 caracteres.');
return $content;
};
$choice = function ($value,$options) {
if (!in_array($value,$options,true)) throw new InvalidArgumentException('Escolha uma opção válida.');
return $value;
};
$lines = function ($value,$title,$required=false) use ($text,$trimText) {
$result=array_values(array_filter(array_map($trimText,explode("\n",$text($value,$title))),fn($x)=>$x!==''));
if (count($result)>500 || ($required && !$result)) throw new InvalidArgumentException($title.': informe até 500 linhas não vazias.');
return $result;
};
$obj = function ($value,$title,$keys=null) {
if (!is_object($value)) throw new InvalidArgumentException($title.': use objeto JSON.');
if ($keys!==null) foreach (get_object_vars($value) as $key=>$unused) if (!in_array((string)$key,$keys,true)) throw new InvalidArgumentException($title.': campo não suportado: '.$key);
return $value;
};
$arrayInput = function ($source,$title,$limit=500) use ($read) {
$value=$read($source,$title);
if (!is_array($value) || !$value || count($value)>$limit) throw new InvalidArgumentException($title.': lista JSON não vazia fora do limite.');
return $value;
};
$date = function ($value='') use ($label) {
$content=$label($value,'Data',true); if ($content==='') return '';
if (!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/D',$content) || !checkdate((int)substr($content,5,2),(int)substr($content,8,2),(int)substr($content,0,4))) throw new InvalidArgumentException('Data inválida: use YYYY-MM-DD e um dia real.');
return $content;
};
$url = function ($value) use ($text,$trimText) {
$content=$trimText($text($value,'URL'));
if (strlen($content)>2047 || !preg_match('~^https?://[^/]~i',$content) || preg_match('/[^\x21-\x7e]|[\\\\<>"`{}|^]|%(?![\da-f]{2})/i',$content) || str_contains($content,'#')) throw new InvalidArgumentException('URL HTTP/HTTPS ASCII inválida.');
$parsed=parse_url($content);
if (!$parsed || empty($parsed['host']) || isset($parsed['user']) || isset($parsed['pass'])) throw new InvalidArgumentException('URL com credenciais ou porta inválida.');
return $content;
};
$finish = function ($content,$filename) {
if (strlen(iconv('UTF-8','UTF-16LE',$content))/2>1000000) throw new InvalidArgumentException('Saída excede 1 milhão de unidades UTF-16.');
return ['text'=>$content,'filename'=>$filename];
};
$get = fn($object,$key)=>property_exists($object,$key) ? $object->{$key} : '';
foreach ($values as $value) $text($value);
$mode=$choice($values['mode'],['Sitemap XML','robots.txt']);
if ($mode==='Sitemap XML') {
$seen=[]; $origins=[]; $entries=[];
$escape=fn($value)=>str_replace(['&','<','>','"',"'"],['&','<','>','"','''],$value);
foreach ($arrayInput($values['input'] ?? '','URLs',1000) as $item) {
$entry=$obj($item,'URL',['url','lastmod']); $location=$url($get($entry,'url')); $when=$date($get($entry,'lastmod'));
if (isset($seen[$location])) throw new InvalidArgumentException('URL duplicada.');
$seen[$location]=true; $parsed=parse_url($location); $scheme=strtolower($parsed['scheme']); $origins[$scheme.'://'.strtolower($parsed['host']).':'.($parsed['port'] ?? ($scheme==='https' ? 443 : 80))]=true;
$entries[]=" <url>\n <loc>".$escape($location)."</loc>\n".($when!=='' ? ' <lastmod>'.$when."</lastmod>\n" : '').' </url>';
}
if (count($origins)!==1) throw new InvalidArgumentException('Use URLs de uma única origem.');
return $finish('<?xml version="1.0" encoding="UTF-8"?>'."\n".'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n".implode("\n",$entries)."\n</urlset>\n",'sitemap.xml');
}
$seen=[]; $groups=[];
foreach ($arrayInput($values['input'] ?? '','Grupos robots',100) as $item) {
$group=$obj($item,'Grupo',['agent','allow','disallow']); $agent=$label($get($group,'agent'),'User-agent');
if (!preg_match('/^(?:\*|[A-Za-z0-9_.-]+)$/D',$agent) || isset($seen[strtolower($agent)])) throw new InvalidArgumentException('User-agent inválido ou repetido.');
$seen[strtolower($agent)]=true; $result=['User-agent: '.$agent];
foreach ([['allow','Allow'],['disallow','Disallow']] as [$key,$directive]) {
if (!property_exists($group,$key)) continue;
$paths=$group->{$key}; if (!is_array($paths) || count($paths)>500) throw new InvalidArgumentException('Lista de caminhos inválida.');
foreach ($paths as $value) { $path=$text($value,$directive); if (strlen(iconv('UTF-8','UTF-16LE',$path))/2>2047 || ($path!=='' && !str_starts_with($path,'/')) || preg_match('/[\s#\\\\]|%(?![\da-f]{2})/iu',$path)) throw new InvalidArgumentException('Caminho inválido.'); $result[]=$directive.': '.$path; }
}
if (count($result)===1) throw new InvalidArgumentException('Grupo exige ao menos uma regra.');
$groups[]=implode("\n",$result);
}
$sitemaps=array_map(fn($item)=>'Sitemap: '.$url($item),$lines($values['sitemaps'] ?? '','Sitemaps'));
if (count(array_unique($sitemaps))!==count($sitemaps)) throw new InvalidArgumentException('Sitemap repetido.');
return $finish(implode("\n\n",$groups).($sitemaps ? "\n\n".implode("\n",$sitemaps) : '')."\n",'robots.txt');
}