JavaScript Python PHP
import { SaxesParser } from 'saxes';
async function executar(values) {
async function generateFrontendQr(v) {
const mode = feChoice(v.mode, ['Texto', 'URL', 'Wi-Fi']);
let text = feText(v.input);
if (mode === 'URL')
text = feUrl(text);
if (mode === 'Wi-Fi') {
const ssid = feText(v.ssid), password = feText(v.password), security = feChoice(v.security, ['WPA', 'aberta']);
feChoice(v.hidden, ['Sim', 'Não']);
if (!ssid || new TextEncoder().encode(ssid).length > 32)
throw new Error('SSID: use de 1 a 32 bytes UTF-8.');
if (security === 'WPA' && !/^(?:[\x20-\x7e]{8,63}|[\da-fA-F]{64})$/.test(password))
throw new Error('Senha WPA: use 8–63 caracteres ASCII imprimíveis ou 64 dígitos HEX.');
if (security === 'aberta' && password)
throw new Error('Rede aberta não aceita senha. Limpe o campo.');
const esc = (s) => s.replace(/[\\;,:\"]/g, '\\$&');
text = `WIFI:T:${security === 'WPA' ? 'WPA' : 'nopass'};S:${esc(ssid)};${security === 'WPA' ? 'P:' + esc(password) + ';' : ''}H:${v.hidden === 'Sim' ? 'true' : 'false'};;`;
}
if (!text || new TextEncoder().encode(text).length > 1500)
throw new Error('Use conteúdo não vazio com até 1500 bytes UTF-8.');
const { qrcode, drawingSVG } = await import('@bwip-js/generic');
// BWIPP QR modules are two drawing points: padding 8 equals four modules.
const options = { bcid: 'qrcode', text, eclevel: 'M', scale: 4, padding: 8, backgroundcolor: 'FFFFFF', parse: false, parsefnc: false };
const svg = feBarcodeSize(qrcode(options, drawingSVG()));
return { text: svg, images: [{ label: 'QR Code', svg }], meta: { title: 'Conteúdo codificado', description: text, url: '' } };
}
function feText(value, max = 100000) {
if (typeof value !== 'string' || value.length > max)
throw new Error(`Use texto com até ${max} 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 feChoice(value, choices) {
if (!choices.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
function feUrl(value) {
feText(value, 2048);
let parsed;
try {
parsed = new URL(value);
}
catch {
throw new Error('Informe uma URL HTTP/HTTPS absoluta válida.');
}
if (!/^https?:\/\//i.test(value) || !['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password || /[\s\\]/u.test(value))
throw new Error('Use HTTP/HTTPS, sem credenciais, espaços ou barras invertidas.');
return value;
}
function feBarcodeSize(svg) {
let width = 0, height = 0;
const parser = new SaxesParser();
parser.on('opentag', tag => {
if (tag.name !== 'svg')
return;
const box = String(tag.attributes.viewBox).split(/\s+/).map(Number);
width = box[2];
height = box[3];
});
parser.write(svg).close();
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 8192 || height > 8192)
throw new Error('Código excede as dimensões de imagem suportadas.');
return svg.replace('<svg ', `<svg width="${width}" height="${height}" `);
}
for (const value of Object.values(values)) if (typeof value !== "string" || value.length > 100000) throw new Error("Use até 100 mil caracteres por campo.");
return await generateFrontendQr(values);
}
import json
import subprocess
def executar(values):
# Requer Node.js 22+ e os pacotes npm indicados abaixo; toda a lógica está visível.
source = r'''
import { SaxesParser } from 'saxes';
async function executar(values) {
async function generateFrontendQr(v) {
const mode = feChoice(v.mode, ['Texto', 'URL', 'Wi-Fi']);
let text = feText(v.input);
if (mode === 'URL')
text = feUrl(text);
if (mode === 'Wi-Fi') {
const ssid = feText(v.ssid), password = feText(v.password), security = feChoice(v.security, ['WPA', 'aberta']);
feChoice(v.hidden, ['Sim', 'Não']);
if (!ssid || new TextEncoder().encode(ssid).length > 32)
throw new Error('SSID: use de 1 a 32 bytes UTF-8.');
if (security === 'WPA' && !/^(?:[\x20-\x7e]{8,63}|[\da-fA-F]{64})$/.test(password))
throw new Error('Senha WPA: use 8–63 caracteres ASCII imprimíveis ou 64 dígitos HEX.');
if (security === 'aberta' && password)
throw new Error('Rede aberta não aceita senha. Limpe o campo.');
const esc = (s) => s.replace(/[\\;,:\"]/g, '\\$&');
text = `WIFI:T:${security === 'WPA' ? 'WPA' : 'nopass'};S:${esc(ssid)};${security === 'WPA' ? 'P:' + esc(password) + ';' : ''}H:${v.hidden === 'Sim' ? 'true' : 'false'};;`;
}
if (!text || new TextEncoder().encode(text).length > 1500)
throw new Error('Use conteúdo não vazio com até 1500 bytes UTF-8.');
const { qrcode, drawingSVG } = await import('@bwip-js/generic');
// BWIPP QR modules are two drawing points: padding 8 equals four modules.
const options = { bcid: 'qrcode', text, eclevel: 'M', scale: 4, padding: 8, backgroundcolor: 'FFFFFF', parse: false, parsefnc: false };
const svg = feBarcodeSize(qrcode(options, drawingSVG()));
return { text: svg, images: [{ label: 'QR Code', svg }], meta: { title: 'Conteúdo codificado', description: text, url: '' } };
}
function feText(value, max = 100000) {
if (typeof value !== 'string' || value.length > max)
throw new Error(`Use texto com até ${max} 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 feChoice(value, choices) {
if (!choices.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
function feUrl(value) {
feText(value, 2048);
let parsed;
try {
parsed = new URL(value);
}
catch {
throw new Error('Informe uma URL HTTP/HTTPS absoluta válida.');
}
if (!/^https?:\/\//i.test(value) || !['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password || /[\s\\]/u.test(value))
throw new Error('Use HTTP/HTTPS, sem credenciais, espaços ou barras invertidas.');
return value;
}
function feBarcodeSize(svg) {
let width = 0, height = 0;
const parser = new SaxesParser();
parser.on('opentag', tag => {
if (tag.name !== 'svg')
return;
const box = String(tag.attributes.viewBox).split(/\s+/).map(Number);
width = box[2];
height = box[3];
});
parser.write(svg).close();
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 8192 || height > 8192)
throw new Error('Código excede as dimensões de imagem suportadas.');
return svg.replace('<svg ', `<svg width="${width}" height="${height}" `);
}
for (const value of Object.values(values)) if (typeof value !== "string" || value.length > 100000) throw new Error("Use até 100 mil caracteres por campo.");
return await generateFrontendQr(values);
}
let payload = "";
for await (const chunk of process.stdin) payload += chunk;
try { const input = JSON.parse(payload); const result = await executar(input.values, input.image); process.stdout.write(JSON.stringify({ok: true, result}, (_, value) => value instanceof Uint8Array ? Array.from(value) : value)); }
catch (error) { process.stdout.write(JSON.stringify({ok: false, error: error.message})); }
'''
payload = json.dumps({"values": values}, ensure_ascii=True)
process = subprocess.run(["node", "--input-type=module", "-e", source], input=payload, 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 indicados abaixo; toda a lógica está visível.
$source = <<<'JAVASCRIPT'
import { SaxesParser } from 'saxes';
async function executar(values) {
async function generateFrontendQr(v) {
const mode = feChoice(v.mode, ['Texto', 'URL', 'Wi-Fi']);
let text = feText(v.input);
if (mode === 'URL')
text = feUrl(text);
if (mode === 'Wi-Fi') {
const ssid = feText(v.ssid), password = feText(v.password), security = feChoice(v.security, ['WPA', 'aberta']);
feChoice(v.hidden, ['Sim', 'Não']);
if (!ssid || new TextEncoder().encode(ssid).length > 32)
throw new Error('SSID: use de 1 a 32 bytes UTF-8.');
if (security === 'WPA' && !/^(?:[\x20-\x7e]{8,63}|[\da-fA-F]{64})$/.test(password))
throw new Error('Senha WPA: use 8–63 caracteres ASCII imprimíveis ou 64 dígitos HEX.');
if (security === 'aberta' && password)
throw new Error('Rede aberta não aceita senha. Limpe o campo.');
const esc = (s) => s.replace(/[\\;,:\"]/g, '\\$&');
text = `WIFI:T:${security === 'WPA' ? 'WPA' : 'nopass'};S:${esc(ssid)};${security === 'WPA' ? 'P:' + esc(password) + ';' : ''}H:${v.hidden === 'Sim' ? 'true' : 'false'};;`;
}
if (!text || new TextEncoder().encode(text).length > 1500)
throw new Error('Use conteúdo não vazio com até 1500 bytes UTF-8.');
const { qrcode, drawingSVG } = await import('@bwip-js/generic');
// BWIPP QR modules are two drawing points: padding 8 equals four modules.
const options = { bcid: 'qrcode', text, eclevel: 'M', scale: 4, padding: 8, backgroundcolor: 'FFFFFF', parse: false, parsefnc: false };
const svg = feBarcodeSize(qrcode(options, drawingSVG()));
return { text: svg, images: [{ label: 'QR Code', svg }], meta: { title: 'Conteúdo codificado', description: text, url: '' } };
}
function feText(value, max = 100000) {
if (typeof value !== 'string' || value.length > max)
throw new Error(`Use texto com até ${max} 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 feChoice(value, choices) {
if (!choices.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
function feUrl(value) {
feText(value, 2048);
let parsed;
try {
parsed = new URL(value);
}
catch {
throw new Error('Informe uma URL HTTP/HTTPS absoluta válida.');
}
if (!/^https?:\/\//i.test(value) || !['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password || /[\s\\]/u.test(value))
throw new Error('Use HTTP/HTTPS, sem credenciais, espaços ou barras invertidas.');
return value;
}
function feBarcodeSize(svg) {
let width = 0, height = 0;
const parser = new SaxesParser();
parser.on('opentag', tag => {
if (tag.name !== 'svg')
return;
const box = String(tag.attributes.viewBox).split(/\s+/).map(Number);
width = box[2];
height = box[3];
});
parser.write(svg).close();
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 8192 || height > 8192)
throw new Error('Código excede as dimensões de imagem suportadas.');
return svg.replace('<svg ', `<svg width="${width}" height="${height}" `);
}
for (const value of Object.values(values)) if (typeof value !== "string" || value.length > 100000) throw new Error("Use até 100 mil caracteres por campo.");
return await generateFrontendQr(values);
}
let payload = "";
for await (const chunk of process.stdin) payload += chunk;
try { const input = JSON.parse(payload); const result = await executar(input.values, input.image); process.stdout.write(JSON.stringify({ok: true, result}, (_, value) => value instanceof Uint8Array ? Array.from(value) : value)); }
catch (error) { process.stdout.write(JSON.stringify({ok: false, error: error.message})); }
JAVASCRIPT;
$payload = json_encode(["values" => $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)) {
$written = fwrite($pipes[0], substr($payload, $offset));
if ($written === false || $written === 0) { proc_terminate($process); foreach ($pipes as $pipe) fclose($pipe); proc_close($process); throw new RuntimeException("Falha ao enviar a entrada."); }
$offset += $written;
}
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); $stderr = stream_get_contents($pipes[2]); fclose($pipes[2]); $status = proc_close($process);
if ($timeout || $status !== 0) { throw new RuntimeException("Falha técnica 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"];
}