JavaScript Python PHP
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 generateProjectDocumentation(v) {
const mode = productivityChoice(v.mode, ['README', 'Documentação técnica']), name = productivityLabel(v.name, 'Projeto');
let text = '# ' + productivityMd(name) + (mode === 'README' ? '\n' : ' — Documentação técnica\n');
text += productivitySection('Apresentação', v.summary, false, true);
if (mode === 'README') {
for (const [title, key, language] of [['Instalação', 'installation', 'sh'], ['Uso', 'usage', 'text']]) {
const value = productivityText(v[key], title);
if (value.trim())
text += '\n## ' + title + '\n\n' + productivityFence(value, language);
}
text += productivitySection('Arquitetura', v.architecture) + productivitySection('Contribuição', v.contributing);
}
else {
text += productivitySection('Arquitetura', v.architecture, false, true) + productivitySection('Interfaces e integrações', v.interfaces) + productivitySection('Decisões técnicas', v.decisions, true) + productivitySection('Operação e manutenção', v.maintenance);
}
return { text, filename: mode === 'README' ? 'README.md' : 'documentacao-tecnica.md' };
}
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 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 productivityMd(value) {
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/[\\`*_{}[\]()#+.!|~-]/g, '\\$&');
}
function productivitySection(title, value, list = false, required = false) {
if (list) {
const lines = productivityLines(value, title, required);
return lines.length ? '\n## ' + title + '\n\n' + lines.map(line => '- ' + productivityMd(line)).join('\n') + '\n' : '';
}
const content = productivityText(value, title).trim();
if (required && !content)
throw new Error('Preencha ' + title + '.');
return content ? '\n## ' + title + '\n\n' + productivityMd(content) + '\n' : '';
}
function productivityFence(value, language) {
const fence = '`'.repeat(Math.max(3, ...Array.from(value.matchAll(/`+/g), match => match[0].length + 1)));
return fence + language + '\n' + value + (value.endsWith('\n') ? '' : '\n') + fence + '\n';
}
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;
}
for (const value of Object.values(values)) productivityText(value);
return productivityOutput(generateProjectDocumentation(values));
}
import re
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 md(value):
value=value.replace('&','&').replace('<','<').replace('>','>')
return re.sub(r'[\\`*_{}[\]()#+.!|~-]',lambda m:'\\'+m[0],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 section(title, value='', listing=False, required=False):
if listing:
items=lines(value,title,required)
return '\n## '+title+'\n\n'+'\n'.join('- '+md(item) for item in items)+'\n' if items else ''
content=trim(text(value,title))
if required and not content: raise ValueError('Preencha '+title+'.')
return '\n## '+title+'\n\n'+md(content)+'\n' if content else ''
def fence(value, language):
border='`'*max([3]+[len(x)+1 for x in re.findall(r'`+',value)])
return border+language+'\n'+value+('' if value.endswith('\n') else '\n')+border+'\n'
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}
for value in values.values(): text(value)
mode=choice(values.get('mode'),['README','Documentação técnica']); name=label(values.get('name',''),'Projeto')
out='# '+md(name)+('\n' if mode=='README' else ' — Documentação técnica\n')
out+=section('Apresentação',values.get('summary',''),required=True)
if mode=='README':
for title,key,language in [('Instalação','installation','sh'),('Uso','usage','text')]:
value=text(values.get(key,''),title)
if trim(value): out+='\n## '+title+'\n\n'+fence(value,language)
out+=section('Arquitetura',values.get('architecture',''))+section('Contribuição',values.get('contributing',''))
else:
out+=section('Arquitetura',values.get('architecture',''),required=True)+section('Interfaces e integrações',values.get('interfaces',''))+section('Decisões técnicas',values.get('decisions',''),True)+section('Operação e manutenção',values.get('maintenance',''))
return finish(out,'README.md' if mode=='README' else 'documentacao-tecnica.md')
<?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);
};
$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;
};
$md = function ($value) {
$value=str_replace(['&','<','>'],['&','<','>'],$value);
return preg_replace_callback('/[\\\\`*_{}\[\]()#+.!|~\-]/',fn($m)=>'\\'.$m[0],$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;
};
$section = function ($title,$value='',$listing=false,$required=false) use ($lines,$md,$text,$trimText) {
if ($listing) { $items=$lines($value,$title,$required); return $items ? "\n## ".$title."\n\n".implode("\n",array_map(fn($x)=>'- '.$md($x),$items))."\n" : ''; }
$content=$trimText($text($value,$title));
if ($required && $content==='') throw new InvalidArgumentException('Preencha '.$title.'.');
return $content!=='' ? "\n## ".$title."\n\n".$md($content)."\n" : '';
};
$fence = function ($value,$language) {
preg_match_all('/`+/',$value,$matches); $length=3; foreach ($matches[0] as $match) $length=max($length,strlen($match)+1); $border=str_repeat('`',$length);
return $border.$language."\n".$value.(str_ends_with($value,"\n") ? '' : "\n").$border."\n";
};
$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];
};
foreach ($values as $value) $text($value);
$mode=$choice($values['mode'],['README','Documentação técnica']); $name=$label($values['name'] ?? '','Projeto');
$out='# '.$md($name).($mode==='README' ? "\n" : " — Documentação técnica\n");
$out.=$section('Apresentação',$values['summary'] ?? '',false,true);
if ($mode==='README') {
foreach ([['Instalação','installation','sh'],['Uso','usage','text']] as [$title,$key,$language]) { $content=$text($values[$key] ?? '',$title); if ($trimText($content)!=='') $out.="\n## ".$title."\n\n".$fence($content,$language); }
$out.=$section('Arquitetura',$values['architecture'] ?? '').$section('Contribuição',$values['contributing'] ?? '');
} else $out.=$section('Arquitetura',$values['architecture'] ?? '',false,true).$section('Interfaces e integrações',$values['interfaces'] ?? '').$section('Decisões técnicas',$values['decisions'] ?? '',true).$section('Operação e manutenção',$values['maintenance'] ?? '');
return $finish($out,$mode==='README' ? 'README.md' : 'documentacao-tecnica.md');
}