Files
dtf-system/tests/artwork_browser_test.mjs
Cauê Faleiros 083441583a
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 8m24s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m14s
feat: each product's metres are summed and rounded once, and the 1 m minimum is once per order (Marcus, 2026-12-03)
Marcus: "o pedido mínimo de um metro deve ser somente para o primeiro
metro, após isso deve se somar a metragem de cada arquivo", "Soma tudo e
arredonda uma vez só", and for different products "Pode ser sim": each
product apart at its price, the minimum for the whole order. Order #246
(three ready sheets of 3,74, 0,24 and 0,22 m) was 5,80 m with 1 m per item;
it is now 4,20 m.

pricing.bill_order replaces the per-item minimum and bill_splits: per
product the exact lengths (a ready sheet without its gaps) are rounded once
with the 8 mm grace, the minimum's difference goes to the first item's
product, and each product's total is shared back to its items in 10 cm
steps (each its length rounded down, the missing steps to the largest
fractions, the minimum to the product's first item), for Tiny's 10 cm SKUs
and the cards. A share of 0 m adds no Tiny line. The print file's guard
allows an item one 10 cm step under its length. The Site cart shares the
same way (cobrarPedido), split sheets round once, the buy box says the
items of a product are summed and rounded once, and the Montador's
estimate rounds its sum once. Contract: output/revisao/contrato-minimo-pedido.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 12:46:40 -03:00

665 lines
46 KiB
JavaScript

// Isolated upload/editor regression: no API, database, storage, or Docker services.
// Run: node local/artwork_browser_test.mjs
// Optional: ARTWORK_FILE=/absolute/path/to/image.jpg to also inspect a real image.
import assert from 'node:assert/strict';
import {spawn} from 'node:child_process';
import {createServer} from 'node:http';
import {createHash} from 'node:crypto';
import {mkdtemp, readFile, writeFile, mkdir} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {resolve} from 'node:path';
const html=await readFile('web/index.html','utf8');
const hashes=[...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)]
.filter(m=>! /\bsrc\s*=/i.test(m[1]))
.map(m=>"'sha256-"+createHash('sha256').update(m[2]).digest('base64')+"'");
function pdfFixture({pages=1,media='[0 0 720 360]',crop='',rotate=0,unit=1}={}){
const objects=[
'<< /Type /Catalog /Pages 2 0 R >>',
'<< /Type /Pages /Kids ['+Array.from({length:pages},(_,i)=>i+3+' 0 R').join(' ')+
'] /Count '+pages+' /MediaBox '+media+' >>',
...Array.from({length:pages},()=> '<< /Type /Page /Parent 2 0 R'+
(crop?' /CropBox '+crop:'')+(rotate?' /Rotate '+rotate:'')+
(unit!==1?' /UserUnit '+unit:'')+' >>')
];
const chunks=['%PDF-1.6\n%\xE2\xE3\xCF\xD3\n'], offsets=[0];
let length=Buffer.byteLength(chunks[0],'latin1');
for(let i=0;i<objects.length;i++){
offsets.push(length);
const part=(i+1)+' 0 obj\n'+objects[i]+'\nendobj\n';
chunks.push(part);length+=Buffer.byteLength(part,'latin1');
}
const xref=length;
chunks.push('xref\n0 '+(objects.length+1)+'\n0000000000 65535 f \n');
for(const offset of offsets.slice(1))chunks.push(String(offset).padStart(10,'0')+' 00000 n \n');
chunks.push('trailer\n<< /Size '+(objects.length+1)+
' /Root 1 0 R >>\nstartxref\n'+xref+'\n%%EOF\n');
return Buffer.from(chunks.join(''),'latin1');
}
const pdfData=options=>JSON.stringify(pdfFixture(options).toString('base64'));
const server=createServer(async(req,res)=>{
if(req.url.startsWith('/api/')){
res.setHeader('Content-Type','application/json');
res.end(JSON.stringify(req.url==='/api/session'?{cart_scope:'isolated-artwork-test'}:{customer:null}));
return;
}
if(req.url==='/'){
res.setHeader('Content-Type','text/html');
res.setHeader('Content-Security-Policy',`default-src 'self'; script-src 'self' ${hashes.join(' ')}; script-src-attr 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; object-src 'none'`);
res.end(html);return;
}
// Serve any script the page asks for, resolved inside web/, rather than
// a hardcoded list: the Site's behaviour is split across several files and a
// list would silently 404 the next one added.
if(/^\/[\w.-]+\.js$/.test(req.url) || /^\/vendor\/pdf\.(worker\.)?min\.js$/.test(req.url)){
try{
const body=await readFile(resolve('web'+req.url));
res.setHeader('Content-Type','text/javascript');res.end(body);return;
}catch{ res.writeHead(404);res.end();return; }
}
res.writeHead(404);res.end();
});
await new Promise(r=>server.listen(0,'127.0.0.1',r));
const profile=await mkdtemp(tmpdir()+'/dtf-artwork-');
const chrome=spawn(process.env.CHROME_BIN||'/usr/bin/google-chrome-stable',[
'--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check',
...(process.env.CHROME_NO_SANDBOX==='1'?['--no-sandbox']:[]),
'--remote-debugging-port=0','--user-data-dir='+profile,'about:blank'
],{stdio:['ignore','ignore','pipe']});
let stderr='',ws,next=0;
chrome.stderr.on('data',b=>stderr+=b);
const pending=new Map(),errors=[];
const pause=ms=>new Promise(r=>setTimeout(r,ms));
async function waitFor(fn,label){
const end=Date.now()+15000;
while(Date.now()<end){if(await fn())return;await pause(50);}
throw new Error('Timeout: '+label);
}
function call(method,params={}){
return new Promise((resolve,reject)=>{const id=++next;pending.set(id,{resolve,reject});ws.send(JSON.stringify({id,method,params}));});
}
async function evaluate(expression){
const r=await call('Runtime.evaluate',{expression,awaitPromise:true,returnByValue:true});
if(r.exceptionDetails)throw new Error(JSON.stringify(r.exceptionDetails));
return r.result.value;
}
const click=selector=>evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`);
async function fill(selector,value){
await evaluate(`(()=>{const el=document.querySelector(${JSON.stringify(selector)});el.value=${JSON.stringify(String(value))};el.dispatchEvent(new Event('input',{bubbles:true}));})()`);
}
async function packed(count){
await waitFor(()=>evaluate(`window.lastLayout?.pos.length===${count} && !!document.querySelector('#vArea canvas') && Math.abs(metros-window.lastLayout.altura/100)<0.0001`),'packed canvas and matching metres');
return evaluate(`({height:lastLayout.altura, pos:lastLayout.pos, metres:metros, billed:cobrar(metros), mode:modo, heading:$('montcabTit').textContent})`);
}
async function screenshot(name){
// Finish editing as a customer does when leaving the field, refreshing the
// item's quality/details as well as the already-live canvas.
await evaluate(`$('lista').querySelector('[data-cm]')?.dispatchEvent(new Event('change',{bubbles:true}))`);
await waitFor(()=>evaluate(`!!$('vArea').querySelector('canvas') && Math.abs(metros-montagemCm/100)<0.0001`),'screenshot layout');
await evaluate(`$('foco').scrollIntoView({behavior:'instant',block:'start'})`);
const r=await call('Page.captureScreenshot',{format:'png'});
await mkdir('output/local',{recursive:true});
await writeFile('output/local/'+name+'.png',Buffer.from(r.data,'base64'));
}
try{
let port;
await waitFor(async()=>{try{port=Number((await readFile(profile+'/DevToolsActivePort','utf8')).split('\n')[0]);return true;}catch{return false;}},'Chrome startup');
// Chrome writes DevToolsActivePort a moment before it accepts connections
// (CI run 416): a refused connection is tried again for a few seconds.
let tab;
for(let attempt=0;!tab;attempt++){
try{tab=await(await fetch(`http://127.0.0.1:${port}/json/new?about:blank`,{method:'PUT'})).json();}
catch(error){if(attempt>=50||error?.cause?.code!=='ECONNREFUSED')throw error;await pause(200);}
}
ws=new WebSocket(tab.webSocketDebuggerUrl);
await new Promise((r,j)=>{ws.onopen=r;ws.onerror=j;});
ws.onmessage=event=>{
const m=JSON.parse(event.data);
if(m.id){const p=pending.get(m.id);pending.delete(m.id);m.error?p.reject(m.error):p.resolve(m.result);}
else if(m.method==='Runtime.exceptionThrown')errors.push(m.params.exceptionDetails);
};
await call('Runtime.enable');await call('Page.enable');
await call('Emulation.setDeviceMetricsOverride',{width:1440,height:1100,deviceScaleFactor:1,mobile:false});
await call('Page.navigate',{url:`http://127.0.0.1:${server.address().port}/`});
await waitFor(()=>evaluate(`typeof sel==='function' && typeof pintaEntrega==='function'`),'Site scripts');
await evaluate('window.siteVideosReady');
assert.equal(await evaluate(`document.querySelectorAll('#videosGrid .videoCard').length`),0);
assert.equal(await evaluate(`document.querySelector('#videos').hidden`),true);
await evaluate(`VIDEOS[0].src='/preview.mp4';videosSection()`);
await evaluate(`document.querySelector('#videosGrid .videoCard').focus()`);
await click('#videosGrid .videoCard');
assert.deepEqual(await evaluate(`({dialog:document.querySelector('.videoModal').getAttribute('role'),
focus:document.activeElement.className,open:!document.querySelector('.videoModal').hidden})`),
{dialog:'dialog',focus:'vmClose',open:true});
await call('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});
assert.equal(await evaluate(`document.querySelector('.videoModal').hidden &&
document.activeElement.classList.contains('videoCard')`),true);
// A home card plays muted and in loop only while it is on screen (Rodada 5,
// D7). Chrome here decodes no video, so the test records what the page asks
// of the card's player: play when it enters the screen, pause when it leaves.
await evaluate(`(()=>{window.cardCalls=[];const P=HTMLMediaElement.prototype;
window.realPlay=P.play;window.realPause=P.pause;
P.play=function(){if(this.closest('.videoCard'))cardCalls.push('play');return Promise.resolve();};
P.pause=function(){if(this.closest('.videoCard'))cardCalls.push('pause');};
VIDEOS[0].src='/preview.mp4';videosSection();})()`);
assert.deepEqual(await evaluate(`(()=>{const v=document.querySelector('#videosGrid .videoCard video');return {muted:v.muted,loop:v.loop,inline:v.playsInline};})()`),
{muted:true,loop:true,inline:true});
await evaluate(`window.scrollTo({top:document.querySelector('#videosGrid .videoCard').getBoundingClientRect().top+scrollY-200,behavior:'instant'})`);
await waitFor(()=>evaluate(`cardCalls.at(-1)==='play'`),'home video card plays on screen');
await evaluate(`window.scrollTo({top:0,behavior:'instant'})`);
await waitFor(()=>evaluate(`cardCalls.at(-1)==='pause'`),'home video card pauses off screen');
await evaluate(`HTMLMediaElement.prototype.play=realPlay;HTMLMediaElement.prototype.pause=realPause`);
await evaluate(`VIDEOS[0].src=null;videosSection()`);
// Observe the actual engine, without replacing its placement or rendering.
await evaluate(`(()=>{
const original=encaixar;
encaixar=(pieces,width,...rest)=>{const result=original(pieces,width,...rest);
if(pieces.some(p=>p.a))window.lastLayout={altura:result.altura,pos:result.pos.map(p=>({x:p.x,y:p.y,w:p.w,h:p.h,rot:p.rot}))};
return result;};
window.sendImage=async(type='image/png',drop=false)=>{
const c=document.createElement('canvas');c.width=200;c.height=400;
const ctx=c.getContext('2d');ctx.fillStyle='white';ctx.fillRect(0,0,200,400);
ctx.fillStyle='#222';ctx.fillRect(85,20,20,360);ctx.fillRect(25,100,140,20);
ctx.fillStyle='#e65c00';ctx.fillRect(130,280,45,80);
const blob=await new Promise(r=>c.toBlob(r,type));
const file=new File([blob],type==='image/jpeg'?'artwork.jpg':'artwork.png',{type});
const dt=new DataTransfer();dt.items.add(file);
if(drop)$('zona').dispatchEvent(new DragEvent('drop',{dataTransfer:dt,bubbles:true,cancelable:true}));
else{$('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true}));}
};
// A genuine mounted sheet spans the film width with printable resolution,
// on a transparent background; or with a solid one, or a residue dot. The
// pHYs chunk makes its real width known, as a sheet exported at 300 DPI.
window.comDpi=async(blob,ppm=11811)=>{
const b=new Uint8Array(await blob.arrayBuffer());
const crc=c=>{let x=0xffffffff;for(const v of c){x^=v;for(let k=0;k<8;k++)x=x&1?0xedb88320^(x>>>1):x>>>1;}return (x^0xffffffff)>>>0;};
let i=8;
while(i+8<=b.length){
const len=((b[i]<<24)>>>0)+(b[i+1]<<16)+(b[i+2]<<8)+b[i+3];
const tipo=String.fromCharCode(...b.slice(i+4,i+8));
if(tipo==='IDAT'){
const ch=new Uint8Array(21), dv=new DataView(ch.buffer);
dv.setUint32(0,9);ch.set([0x70,0x48,0x59,0x73],4);
dv.setUint32(8,ppm);dv.setUint32(12,ppm);ch[16]=1;
dv.setUint32(17,crc(ch.subarray(4,17)));
const out=new Uint8Array(b.length+21);
out.set(b.subarray(0,i),0);out.set(ch,i);out.set(b.subarray(i),i+21);
return new Blob([out],{type:'image/png'});
}
i+=12+len;
}
return blob;
};
window.sendSheet=async({fundo=false,ponto=false}={})=>{
const cm=larguraFilme(), px=Math.ceil(cm/2.54*300);
const c=document.createElement('canvas');c.width=px;c.height=Math.round(px*0.6);
const ctx=c.getContext('2d');
if(fundo){ctx.fillStyle='white';ctx.fillRect(0,0,c.width,c.height);}
ctx.fillStyle='#222';ctx.fillRect(40,40,px/4,px/4);
if(ponto)ctx.fillRect(Math.round(px*0.8),Math.round(c.height/2),4,4);
const blob=await window.comDpi(await new Promise(r=>c.toBlob(r,'image/png')));
const dt=new DataTransfer();dt.items.add(new File([blob],'folha-montada.png',{type:'image/png'}));
$('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true}));
};
window.pickTipo=t=>document.querySelector('#tipoEnvio .cam[data-tipo="'+t+'"]').click();
})()`);
// Reproduce the reported entry path, with no navigation workaround.
// Navigation links must reach the chooser, never preselect a product.
assert.equal(await evaluate(`document.querySelectorAll('[data-modo-cta]').length`),0);
// One price per product (Dropstar, 2026-10-23), the same in the top chip, the
// home example, the product cards and the price table; nothing on the page
// still prices by the grade.
assert.deepEqual(await evaluate(`(()=>{const de=m=>[...document.querySelectorAll('[data-preco="'+m+'"]')].map(e=>e.textContent);
return {file:de('file'),avulsa:de('avulsa'),uvfile:de('uvfile'),uv:de('uv'),
stale:/14,90|conforme a nota|desconto|escada|menor preço da tabela/i.test(document.body.textContent)};})()`),
{file:['R$ 19,90','R$ 19,90','R$ 19,90','R$ 19,90'],avulsa:['R$ 21,90','R$ 21,90'],
uvfile:['R$ 79,90','R$ 79,90'],uv:['R$ 89,90','R$ 89,90'],stale:false});
// Item 9: the thinnest stroke at 300 DPI as Dropstar measures it, an odd
// width being 2d - 1, and ink specks under 30 px left out (2026-10-30).
assert.deepEqual(await evaluate(`(async()=>{
const medir=async(...rects)=>{const c=document.createElement('canvas');c.width=900;c.height=700;
const g=c.getContext('2d');g.fillStyle='#000';for(const r of rects)g.fillRect(...r);
return analisarMapa(await mapaDaImagem(await createImageBitmap(c),900/300*2.54)).traco;};
const linhas=w=>[[50,50,800,w],[50,400,800,40]];
const ciscos=Array.from({length:300},(_,i)=>[60+(i%30)*25,200+Math.floor(i/30)*15,3,3]);
return [(await medir(...linhas(2))).px,(await medir(...linhas(5))).px,(await medir(...linhas(6))).px,
(await medir(...linhas(20))).classe,(await medir(...linhas(20),...ciscos)).classe];})()`),[2,5,6,'C3','C3']);
await click('[data-modo="file"]');
// A ready sheet with two source files stores the finest stroke's position
// on the combined film, not its position within the second file.
assert.deepEqual(await evaluate(`(()=>{
const old=folhas,oldLayout=montagemLayout;
folhas=[{an:{traco:{px:9,classe:'C2',proofYFraction:0.2}}},
{an:{traco:{px:3,classe:'C1',proofYFraction:0.5}}}];
montagemLayout=null;
try{return tracoDoItem(null,{height_cm:100,placements:[
{source_index:0,y_cm:0,length_cm:50,rotation_degrees:0},
{source_index:1,y_cm:50,length_cm:50,rotation_degrees:0}]});}
finally{folhas=old;montagemLayout=oldLayout;}
})()`),{strokePx:3,strokeClass:'C1',strokeChoice:null,
proofSourceIndex:1,proofYFraction:0.75});
// Opening a product paints on the next frame; on a busy runner the check
// must wait for it rather than race it.
await waitFor(()=>evaluate(`!$('tipoEnvio').hidden`),'by-metre product open');
// By-metre opens declaring a mounted sheet; switching is explicit and priced.
assert.deepEqual(await evaluate(`({shown:!$('tipoEnvio').hidden,
on:[...document.querySelectorAll('#tipoEnvio .cam.on')].map(b=>b.dataset.tipo)})`),
{shown:true,on:['folha']});
await evaluate(`(()=>{const f=new File(['x'],'oversize.cdr');Object.defineProperty(f,'size',{value:4294967296+1});return sel([f]);})()`);
assert.equal(await evaluate(`folhas.length===0 && $('recusa').textContent.includes('4 GB')`),true,
'files beyond the 4 GB upload limit are rejected before browser analysis');
// A PNG above the browser's ~32k-pixel height limit cannot be checked here:
// it is refused with a clear message instead of being accepted as 0 DPI.
await evaluate(`(()=>{const h=new Uint8Array(54);h.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0,0,0,13,0x49,0x48,0x44,0x52]);
const v=new DataView(h.buffer);v.setUint32(16,6732);v.setUint32(20,35433);h.set([8,6,0,0,0],24);
v.setUint32(33,9);h.set([0x70,0x48,0x59,0x73],37);v.setUint32(41,11811);v.setUint32(45,11811);h[49]=1;
const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:900*1048576});return sel([f]);})()`);
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].measurementError`),'tall sheet refused');
assert.equal(await evaluate(`folhas[0].measurementError.includes('PNG alto')`),true);
await evaluate(`folhas=[];pintaFolha()`);
// A ready textile sheet whose real width is known (PNG pHYs >= 200 DPI, or a
// PDF page) must be 57 cm wide: otherwise it leaves the list and a dialog
// names it. A hand-made PNG header with a pHYs chunk, read by its header.
await evaluate(`window.pngLargura=async(w,ppm,h=10339,nome='folha-larga.png')=>{
const comDpi=ppm!=null, b=new Uint8Array(comDpi?54:33);
b.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A]);
const v=new DataView(b.buffer);
v.setUint32(8,13);b.set([0x49,0x48,0x44,0x52],12);
v.setUint32(16,w);v.setUint32(20,h);b.set([8,6,0,0,0],24);
if(comDpi){v.setUint32(33,9);b.set([0x70,0x48,0x59,0x73],37);
v.setUint32(41,ppm);v.setUint32(45,ppm);b[49]=1;}
const f=new File([b],nome,{type:'image/png'});
Object.defineProperty(f,'size',{value:900*1048576});
return sel([f]);}`);
// S1/S2: 35,8 cm at 300 DPI enters at its real size and asks for confirmation.
await evaluate(`pngLargura(4227,11811)`);
await waitFor(()=>evaluate(`folhas.length===1 && $('tamanhoDlg').open`),'narrow sheet opens the size dialog');
assert.equal(await evaluate(`$('tamanhoTit').textContent`),'folha-larga.png');
const tamanhoTxt=await evaluate(`$('tamanhoTxt').textContent`);
assert.match(tamanhoTxt,/35,8 cm/);
assert.match(tamanhoTxt,/0,88 m/);
assert.match(tamanhoTxt,/R\$ 21,90\/m/);
assert.equal(await evaluate(`$('tamanhoOk').textContent`),'Imprimir no tamanho real');
// While unconfirmed, "Adicionar ao carrinho" says so and adds nothing.
assert.deepEqual(await evaluate(`(()=>{const antes=pedido.length;$('qOk').disabled=false;$('qOk').click();
return {added:pedido.length-antes,msg:$('qmsg').textContent.includes('Confirme o tamanho')};})()`),
{added:0,msg:true});
await click('#tamanhoOk');
await waitFor(()=>evaluate(`!$('tamanhoDlg').open && folhas[0]?.confirmado===true`),'narrow sheet confirmed');
assert.ok(Math.abs(await evaluate(`folhas[0].med.larg`)-35.79)<0.02);
assert.equal(await evaluate(`$('larguraDlg').open`),false);
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.size_confirmed===true`),
'confirmed size goes to the cart source');
await evaluate(`folhas=[];pintaFolha()`);
// S3: "Enviar outro arquivo" takes the sheet out of the list.
await evaluate(`pngLargura(4227,11811)`);
await waitFor(()=>evaluate(`folhas.length===1 && $('tamanhoDlg').open`),'narrow sheet opens again');
await click('#tamanhoOutro');
await waitFor(()=>evaluate(`folhas.length===0 && !$('tamanhoDlg').open`),'send another removes the sheet');
// S6: 61,0 cm does not fit the film: it leaves and the width dialog names it.
await evaluate(`pngLargura(7200,11811,10339,'folha-larga.png')`);
await waitFor(()=>evaluate(`folhas.length===0 && $('larguraDlg').open`),'too-wide sheet opens the width dialog');
assert.deepEqual(await evaluate(`({itens:$('larguraLista').children.length,
texto:$('larguraLista').textContent,titulo:$('larguraTit').textContent})`),
{itens:1,texto:'folha-larga.png: tem 61,0 cm e não cabe em 57 cm.',
titulo:'A folha não cabe no filme de 57 cm'});
await click('#larguraOk');
await waitFor(()=>evaluate(`!$('larguraDlg').open && $('larguraLista').children.length===0`),
'width dialog closes and clears the list');
// S5: 6732 px at 300 DPI is 57 cm within tolerance: no dialog, real width.
await evaluate(`pngLargura(6732,11811)`);
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].med && !$('tamanhoDlg').open && !$('larguraDlg').open`),
'57 cm sheet accepted');
assert.ok(Math.abs(await evaluate(`folhas[0].med.larg`)-56.998)<0.01);
assert.equal(await evaluate(`!!folhas[0].confirmado`),false);
await evaluate(`folhas=[];pintaFolha()`);
// S7: without pHYs the width is unknown, so it assumes the film and asks.
await evaluate(`pngLargura(6732,null,10339,'folha-sem-dpi.png')`);
await waitFor(()=>evaluate(`folhas.length===1 && $('tamanhoDlg').open`),'unknown width opens the size dialog');
assert.equal(await evaluate(`$('tamanhoTit').textContent`),'folha-sem-dpi.png');
assert.match(await evaluate(`$('tamanhoTxt').textContent`),
/57 cm de largura e 87,5 cm de altura \(300 DPI\)/);
await click('#tamanhoOk');
await waitFor(()=>evaluate(`folhas[0]?.confirmado===true && !$('tamanhoDlg').open`),'unknown width confirmed');
await evaluate(`folhas=[];pintaFolha()`);
// S8: unknown width with less than 200 DPI is refused by resolution.
await evaluate(`pngLargura(2154,null,10339,'folha-baixa.png')`);
await waitFor(()=>evaluate(`folhas.length===0 && $('avisoTipo').textContent.includes('abaixo do mínimo de 200')`),
'unknown width under 200 DPI is refused');
assert.match(await evaluate(`$('avisoTipo').textContent`),/artes avulsas/);
// S13: several sheets needing a dialog are answered one at a time, in order.
await evaluate(`pngLargura(4227,11811,10339,'folha-a.png')`);
await waitFor(()=>evaluate(`$('tamanhoDlg').open && $('tamanhoTit').textContent==='folha-a.png'`),'first sheet in order');
await evaluate(`pngLargura(4300,11811,10339,'folha-b.png')`);
await waitFor(()=>evaluate(`folhas.length===2`),'second sheet queued');
await click('#tamanhoOk');
await waitFor(()=>evaluate(`$('tamanhoDlg').open && $('tamanhoTit').textContent==='folha-b.png'`),'second sheet next');
await click('#tamanhoOk');
await waitFor(()=>evaluate(`!$('tamanhoDlg').open && folhas.length===2 && folhas.every(x=>x.confirmado)`),
'each sheet answered on its own');
await evaluate(`folhas=[];pintaFolha()`);
await evaluate(`pickTipo('avulsa')`);
assert.equal(await evaluate('modo'),'avulsa');
// JPG has no transparency: refused in loose artwork as in a sheet (Dropstar,
// 2026-10-23), with the reason, before anything is read.
await evaluate(`sel([new File(['x'],'arte.jpg',{type:'image/jpeg'})])`);
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('JPG não entra')`),true);
// The content decides, not the name (D-13): a JPG called ".png" is refused as a JPG.
await evaluate(`sel([new File([new Uint8Array([0xFF,0xD8,0xFF,0xE0])],'disfarce.png',{type:'image/png'})])`);
assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('disfarce.png é JPG')`),true);
// A large WebP artwork cannot be read in parts: it is measured from its
// header and placed as a full box, with its grade, instead of refused.
await evaluate(`(()=>{const h=new Uint8Array(30);h.set([0x52,0x49,0x46,0x46,0,0,0,0,0x57,0x45,0x42,0x50,0x56,0x50,0x38,0x58]);
h.set([0x39,0x09,0x00,0x39,0x09,0x00],24);
const f=new File([h],'arte-grande.webp');Object.defineProperty(f,'size',{value:400*1048576});return sel([f]);})()`);
await waitFor(()=>evaluate(`artes.length===1 && artes[0].semPrevia===true`),'large WebP artwork measured from its header');
await fill('[data-cm]',20);
await waitFor(()=>evaluate(`!!itemAtual?.production?.sources?.length`),'large WebP artwork packed');
assert.deepEqual(await evaluate(`({dpi:Math.round(dpiDe(artes[0])),src:!!artes[0].src,
measurement:itemAtual.production.sources[0].measurement,note:$('lista').textContent.includes('Sem prévia')})`),
{dpi:300,src:false,measurement:'file',note:true});
await evaluate(`artes=[];pintaArtes()`);
await evaluate('sendImage()');
await waitFor(()=>evaluate(`artes.length===1 && !!artes[0].src`),'PNG artwork model');
assert.deepEqual(await evaluate(`({mode:modo,sheets:folhas.length,width:artes[0].cm,quantity:artes[0].q})`),{mode:'avulsa',sheets:0,width:0,quantity:1});
await fill('[data-cm]',20);await fill('[data-q]',6);
let layout=await packed(6);
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.copies===6`),'per-file production record');
assert.deepEqual(await evaluate(`({version:itemAtual.production.version,source:itemAtual.production.sources[0]})`),
{version:3,source:{kind:'artwork',width_cm:20,length_cm:40,copies:6,
rotation_degrees:0,mirrored:false,measurement:'file'}});
assert.equal(await evaluate('itemAtual.production.placements.length'),6);
// 5 mm margins top and bottom, between rows, at the edges and between pieces.
assert.equal(await evaluate('itemAtual.production.height_cm'),122);
assert.deepEqual(await evaluate('itemAtual.production.placements.map(p=>[p.source_index,p.copy_index,p.x_cm,p.y_cm])'),
[[0,0,0.5,0.5],[0,1,21,0.5],[0,2,0.5,41],[0,3,21,41],[0,4,0.5,81.5],[0,5,21,81.5]]);
assert.equal(layout.heading,'Montagem ao vivo');assert.equal(layout.height,122);
assert.equal(layout.billed,1.3);
assert.deepEqual(layout.pos.map(p=>[p.x,p.y]),[[0.5,0.5],[21,0.5],[0.5,41],[21,41],[0.5,81.5],[21,81.5]]);
assert.ok(layout.pos.every(p=>p.h/p.w===2 && p.x+p.w<=57));
await screenshot('artwork-packed');
await fill('[data-cm]',15);
await waitFor(()=>evaluate('lastLayout?.altura===61.5 && metros===0.615'),'width updates without blur');
await fill('[data-q]',9);layout=await packed(9);assert.equal(layout.height,92);
await click('[data-giro]');
await waitFor(()=>evaluate('lastLayout?.altura===24.5 && metros===0.245'),'rotation updates packing');
// A textile transfer is pressed face down: mirrored, it prints backwards on
// the garment. Textile has no mirror button (Dropstar, 2026-10-21).
assert.equal(await evaluate(`!!document.querySelector('[data-esp]')`),false,'textile has no mirror button');
assert.equal(await evaluate('metros'),0.245);
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.mirrored===false`),'transforms in production record');
assert.deepEqual(await evaluate(`({rotation:itemAtual.production.sources[0].rotation_degrees,copies:itemAtual.production.sources[0].copies})`),
{rotation:90,copies:9});
await waitFor(()=>evaluate(`itemAtual?.qualityStatus==='rejected'`),'low resolution refusal');
assert.equal(await evaluate('cartPodeEnviar()'),false);
await fill('[data-cm]',3);
await waitFor(()=>evaluate(`itemAtual?.qualityStatus==='ok'`),'rotated DPI uses image height');
assert.equal(await evaluate('Math.round(dpiDe(artes[0]))'),339);
await click('[data-giro]');
await waitFor(()=>evaluate(`itemAtual?.qualityStatus==='warning'`),'unrotated resolution warning');
assert.equal(await evaluate('Math.round(dpiDe(artes[0]))'),169);
assert.equal(await evaluate('cartPodeEnviar()'),false);
await click('#cienteOk');
assert.equal(await evaluate('cartPodeEnviar()'),true);
await fill('[data-q]',8);
assert.equal(await evaluate('itemAtual===null'),true,'editing invalidates the old cart immediately');
await waitFor(()=>evaluate(`itemAtual?.qualityStatus==='warning'`),'edited warning');
assert.equal(await evaluate('cartPodeEnviar()'),false,'acknowledgement does not survive an edit');
await fill('[data-cm]',58);
await waitFor(()=>evaluate(`itemAtual===null && artes[0].cm===58`),'oversized width rejected');
assert.equal(await evaluate('cartPodeEnviar()'),false);
assert.equal(await evaluate(`(()=>{try{encaixar([{w:58,h:10,img:null}],57);return false}catch(error){return error instanceof RangeError}})()`),true,
'packing engine must not shrink an oversized source');
// Dropstar's order 1 (2026-10-21): six 28,2 x 29,14 cm pieces. Two fit across
// 57 cm only with 2 mm at each edge and between them: aligned columns, 5 mm
// rows and margins, 89,42 cm instead of the 97,14 cm the grid gave.
assert.deepEqual(await evaluate(`(()=>{const a={};
const r=encaixar(Array.from({length:6},(_,i)=>({w:28.2,h:29.14,img:null,a,copyIndex:i})),57);
return {altura:+r.altura.toFixed(2),folga:+r.folga.toFixed(3),
xs:[...new Set(r.pos.map(p=>+p.x.toFixed(2)))],ys:[...new Set(r.pos.map(p=>+p.y.toFixed(2)))]};})()`),
{altura:89.42,folga:0.2,xs:[0.2,28.6],ys:[0.5,30.14,59.78]});
// UV, 27 cm: two 13,2 cm pieces still share a row, 2 mm apart.
assert.equal(await evaluate(`(()=>{const a={};const r=encaixar([{w:13.2,h:10,img:null,a},{w:13.2,h:10,img:null,a}],27);
return new Set(r.pos.map(p=>p.y)).size===1 && Math.abs(r.folga-0.6/3)<1e-9})()`),true);
// A long piece stands up when that shortens the sheet: 30 x 10 cm, eight copies,
// five to a row turned instead of one to a row as sent.
assert.deepEqual(await evaluate(`(()=>{const a={};const r=encaixar(Array.from({length:8},()=>({w:30,h:10,img:null,a})),57);
return {rot:[...new Set(r.pos.map(p=>p.rot))],altura:+r.altura.toFixed(2)}})()`),
{rot:[90],altura:61.5});
// Any piece that is not square is tried both ways (Dropstar, 2026-10-23):
// 19,5 x 18,5 cm fits 2 to a row standing and 3 lying down.
assert.deepEqual(await evaluate(`(()=>{const a={};const r=encaixar(Array.from({length:6},()=>({w:19.5,h:18.5,img:null,a})),57);
return {rot:[...new Set(r.pos.map(p=>p.rot))],altura:+r.altura.toFixed(2)}})()`),
{rot:[90],altura:40.5});
await click('[data-rm]');
assert.equal(await evaluate(`artes.length===0 && itemAtual===null && !cartPodeEnviar()`),true,
'removed artwork cannot remain in the cart');
// A transparent asymmetric image exposes masks that ignore user transforms.
// Its top-left quarter becomes bottom-right after a mirror and 90° turn.
assert.equal(await evaluate(`(()=>{
const image=document.createElement('canvas');image.width=100;image.height=200;
image.getContext('2d').fillRect(0,0,50,100);
const result=encaixar([{w:20,h:10,img:image,a:{giro:90,esp:true},travado:true}],57);
const m=result.pos[0].m;
return !m.bits[2*m.cw+2] && !m.bits[2*m.cw+30] && !!m.bits[15*m.cw+30];
})()`),true);
// A real finished sheet keeps its own width and by-metre price. Its 19 cm
// without ink at the bottom are cut, but for 0,5 cm (Marcus, 2026-11-18);
// the 0,7 cm at the top stay, under the 1 cm the cut starts at.
await click('#bVoltar');await click('[data-modo="file"]');
await evaluate('sendSheet()');
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].previewSrc && folhas[0].med.alt>34 && folhas[0].corte?.topo===0 &&
folhas[0].corte.fim>18 && Math.abs(metros-(folhas[0].med.alt-folhas[0].corte.fim)/100)<0.0001`),'ready-sheet image, trimmed');
assert.equal(await evaluate(`$('lista').textContent.includes('cm vazios do fim do arquivo. Cobrado: 1,00 m.')`),true);
// On its way at once, with its own row under the uploader (Dropstar,
// 2026-10-29). There is no storage here, so it fails, and says so with a
// way to try again; tests/browser_test.mjs sends it for real.
await waitFor(()=>evaluate(`!!dtfEnvio.estado(folhas[0].f)`),'the sheet starts uploading at once');
await waitFor(()=>evaluate(`$('envios').textContent.includes('Não foi possível enviar folha-montada.png') &&
!!$('envios').querySelector('[data-envio]')`),'a failed upload says so under the uploader');
assert.deepEqual(await evaluate(`({mode:modo,art:artes.length,title:$('montcabTit').textContent,rate:precoMetro()})`),{mode:'file',art:0,title:'Sua folha',rate:19.9});
// One price per product (Dropstar, 2026-10-23): the sheet is still graded
// internally, but the customer's screen no longer shows the /100 score.
await waitFor(()=>evaluate('itemAtual?.nota>0'),'graded ready sheet');
assert.deepEqual(await evaluate(`({unit:itemAtual.unit,total:itemAtual.total,hidden:!document.getElementById('cNota'),
metre:$('cMetro').textContent,ladder:!!document.getElementById('cEscada'),
discount:/desconto/i.test($('carrLin').textContent+$('resLin').textContent+$('compra').textContent)})`),
{unit:19.9,total:19.9,hidden:true,metre:'R$ 19,90',ladder:false,discount:false});
assert.deepEqual(await evaluate(`({folha:$('tipoFolhaPreco').textContent,avulsa:$('tipoAvulsaPreco').textContent})`),
{folha:'R$ 19,90 /m',avulsa:'R$ 21,90 /m'});
assert.equal(await evaluate(`document.querySelectorAll('[data-cm]').length`),0);
// With a sheet loaded the declaration is locked; it cannot flip under the customer.
assert.equal(await evaluate(`document.querySelector('#tipoEnvio .cam[data-tipo="avulsa"]').disabled`),true);
await evaluate(`(()=>{const el=$('lista').querySelector('[data-repf]');el.value=2;el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
// Two copies and the 8 mm between them (Marcus, 2026-11-26).
await waitFor(()=>evaluate('Math.abs(metros-(2*folhas[0].m+0.008))<0.0001 && folhas[0].m<0.2'),'ready-sheet repetitions');
assert.equal(await evaluate(`document.querySelectorAll('.folhaPrevia').length`),1);
await evaluate(`(()=>{folhas.push({f:new File(['manual'],'manual.cdr'),med:null,rep:1,m:1,an:null});pintaFolha();})()`);
await waitFor(()=>evaluate(`itemAtual?.nota===0 && itemAtual?.unit===PRECO[modo]+TAXA_MANUAL`),'mixed analyzed and manual sheets: the price plus the manual charge');
// Residue and a solid background stop the order before payment (Dropstar,
// 2026-10-21). A residue is ink under 2 mm on both sides, measured in real
// millimetres: the same dot, wherever it falls on the 1 mm grid, gets the
// same verdict, from 0,5 to 4 mm.
assert.deepEqual(await evaluate(`(async()=>{
const medir=async(mm,dx,dy)=>{const c=document.createElement('canvas');c.width=5700;c.height=600;
const ctx=c.getContext('2d');ctx.fillStyle='#000';ctx.fillRect(100,100,3000,300);
const lado=Math.round(mm*10);ctx.fillRect(4000+dx,300+dy,lado,lado);
return analisarMapa(await mapaDaImagem(c,57)).residuos;};
const out={};
for(const mm of [0.5,1.5,1.9,2.1,4])out[mm]=[await medir(mm,0,0),await medir(mm,5,0),await medir(mm,0,5),await medir(mm,5,5)];
return out;})()`),
{'0.5':[1,1,1,1],'1.5':[1,1,1,1],'1.9':[1,1,1,1],'2.1':[0,0,0,0],'4':[0,0,0,0]});
// A large PNG is read as a stream; every pixel goes into the same ink map.
assert.deepEqual(await evaluate(`(async()=>{
const c=document.createElement('canvas');c.width=5700;c.height=600;
const ctx=c.getContext('2d');ctx.fillStyle='#000';ctx.fillRect(100,100,3000,300);ctx.fillRect(4005,305,12,12);
const blob=await new Promise(r=>c.toBlob(r,'image/png'));
const lido=await previaPngGrande(new File([blob],'folha.png'),600,null,57);
const a=analisarMapa(lido.mapa), b=analisarMapa(await mapaDaImagem(c,57));
return {stream:[a.residuos,a.artes,a.fundoChapado,a.pontos[0].mm],direct:[b.residuos,b.artes,b.fundoChapado,b.pontos[0].mm]};})()`),
{stream:[1,1,false,1.2],direct:[1,1,false,1.2]});
await click('#bVoltar');await click('[data-modo="file"]');
await evaluate('sendSheet({ponto:true})');
await waitFor(()=>evaluate(`folhas.length===1 && folhas[0].pct==null && folhas[0].an?.residuos===1`),'residue found');
await waitFor(()=>evaluate(`$('aoVivo').textContent.includes('ponto de recorte') && itemAtual===null`),'residue stops the order');
assert.equal(await evaluate(`$('lista').textContent.includes('Sobrou 1 ponto de recorte na sua folha')`),true);
await waitFor(()=>evaluate(`folhas[0].previewSrc.startsWith('data:image/webp')`),'residue circled on the preview');
// A ready sheet now offers the same acceptance as loose art (Dropstar,
// 2026-11-05): the dots may be part of the art; the customer can take them.
assert.deepEqual(await evaluate(`({box:!!document.querySelector('[data-residuo]'),
text:$('lista').textContent.includes('Quero imprimir assim'),stopped:itemAtual===null})`),{box:true,text:true,stopped:true});
await evaluate(`(()=>{const el=document.querySelector('[data-residuo]');el.checked=true;
el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await waitFor(()=>evaluate('itemAtual!==null'),'accepted residue lets the sheet through');
await evaluate(`folhas=[];pintaFolha()`);
await evaluate('sendSheet({fundo:true})');
await waitFor(()=>evaluate(`folhas[0]?.an?.fundoChapado===true && itemAtual===null && $('aoVivo').textContent.includes('fundo transparente')`),'solid background stops the order');
assert.equal(await evaluate(`$('lista').textContent.includes('O fundo da sua folha não é transparente')`),true);
await evaluate(`folhas=[];pintaFolha()`);
// An image too small to span the film is refused, never silently repriced.
await click('#bVoltar');await click('[data-modo="file"]');
await evaluate('sendImage()');
await waitFor(()=>evaluate(`!!document.getElementById('usarAvulsa')`),'ready-sheet refusal');
assert.deepEqual(await evaluate(`({mode:modo,sheets:folhas.length,art:artes.length})`),{mode:'file',sheets:0,art:0});
await click('#usarAvulsa');
await waitFor(()=>evaluate(`modo==='avulsa' && artes.length===1`),'one-click recovery into loose artwork');
// Keep manual ready-sheet uploads intact.
await click('#bVoltar');await click('[data-modo="file"]');
await evaluate(`sel([new File(['sheet'],'sheet.cdr')])`);
await waitFor(()=>evaluate(`!!$('lista').querySelector('[data-comp]')`),'manual ready sheet');
await evaluate(`(()=>{const el=$('lista').querySelector('[data-comp]');el.value=1.01;el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await waitFor(()=>evaluate('itemAtual?.total===21.89'),'unchanged manual pricing');
await evaluate(`folhas[0].semAnalise='<img src=x onerror=alert(1)>';pintaFolha()`);
assert.equal(await evaluate(`!$('lista').querySelector('img') && $('lista').textContent.includes('<img src=x')`),true,
'PDF parser errors are text, never executable markup');
// Parsed geometry honors inherited MediaBox, CropBox, rotation and UserUnit.
// Extra pages and unreadable PDFs must never fall through to manual pricing.
const pdfFile=(data,name='sheet.pdf')=>`new File([Uint8Array.from(atob(${data}),c=>c.charCodeAt(0))],${JSON.stringify(name)},{type:'application/pdf'})`;
// A 50,8 cm page on the 57 cm film: real size, asking for confirmation.
const rotated=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 720 1440]',crop:'[0 0 360 720]',rotate:90,unit:2}))})`);
assert.deepEqual(rotated,{larg:50.8,alt:25.4,fonte:'página do PDF · UserUnit 2',confirmar:'estreita'});
const rendered=await evaluate(`rasterizarPdf(${pdfFile(pdfData({media:'[0 0 720 1440]',crop:'[0 0 360 720]',rotate:90,unit:2}))},50.8,25.4).then(r=>({ok:!!r.tela,error:r.erro||null}))`);
assert.deepEqual(rendered,{ok:true,error:null});
// A PDF sheet gets the same ink map, rendered in strips: a blank page is all transparent.
const mapped=await evaluate(`rasterizarPdf(${pdfFile(pdfData())},25.4,12.7,true).then(r=>{const a=analisarMapa(r.mapa);
return {fundo:a.fundoChapado,residuos:a.residuos,largura:r.mapa.wPx}})`);
assert.deepEqual(mapped,{fundo:false,residuos:0,largura:1270});
const multi=await evaluate(`medirFolha(${pdfFile(pdfData({pages:2}))})`);
assert.equal(multi.rejected,true);assert.match(multi.reason,/2 páginas/);
const beyondSpec=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 20000 720]'}))})`);
assert.equal(beyondSpec.rejected,true);assert.match(beyondSpec.reason,/508 cm/);
const broken=await evaluate(`medirFolha(new File(['broken'],'broken.pdf',{type:'application/pdf'}))`);
assert.equal(broken.rejected,true);
// A PDF page is a known real width too: 30 cm enters narrow with confirmation,
// 57 cm enters as the film, and 60 cm does not fit.
const pdfWide=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 850.394 360]'}))})`);
assert.equal(pdfWide.confirmar,'estreita');
assert.ok(Math.abs(pdfWide.larg-30)<0.01);
const pdfTooWide=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 1700.787 360]'}))})`);
assert.equal(!!pdfTooWide.largaDemais,true);
assert.ok(Math.abs(pdfTooWide.largaDemais.cm-60)<0.01);
const pdfOk=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 1615.748 360]'}))})`);
assert.ok(Math.abs(pdfOk.larg-57)<0.01);
assert.equal(pdfOk.confirmar,undefined);
await click('#bVoltar');await click('[data-modo="file"]');
await evaluate(`sel([${pdfFile(pdfData({pages:2}),'two-pages.pdf')}])`);
await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].measurementError`),'multipage PDF refusal');
assert.equal(await evaluate(`avaliar().pronto`),false);
assert.equal(await evaluate(`cartPodeEnviar()`),false);
assert.match(await evaluate(`$('lista').textContent`),/não pode ser orçado/);
// A ".cdr" that is a PDF (D-13) is renamed and measured as a PDF, not handled by hand.
await click('#bVoltar');await click('[data-modo="file"]');
// A 57 cm page: the ready-sheet width rule passes it, so this checks only the renaming.
await evaluate(`sel([${pdfFile(pdfData({media:'[0 0 1615.748 360]'}),'folha.cdr')}])`);
// Measured, and its ink check finished: a check still running repaints the list after the mode below changes.
await waitFor(()=>evaluate(`folhas.length===1 && !!(folhas[0].med || folhas[0].measurementError) && folhas[0].pct==null`),'renamed PDF measured');
assert.deepEqual(await evaluate(`({name:folhas[0].f.name,measured:!!folhas[0].med,manual:folhaManual()})`),
{name:'folha.pdf',measured:true,manual:false});
await click('#bVoltar');await click('[data-modo="avulsa"]');
await evaluate(`sel([new File(['not an image'],'broken.png',{type:'image/png'})])`);
await waitFor(()=>evaluate('artes.length===1 && artes[0].decodeError===true'),'failed image decode');
await fill('[data-cm]',20);
await waitFor(()=>evaluate('itemAtual===null && !cartPodeEnviar()'),'undecodable image cannot be quoted');
// PNG drag/drop follows exactly the same artwork path; UV stays UV. Reaching it
// from a by-metre product is one declared click, and it is reversible.
for(const [mode,expected] of [['file','avulsa'],['avulsa','avulsa'],['uvfile','uv'],['uv','uv']]){
await click('#bVoltar');await click('[data-modo="'+mode+'"]');
if(await evaluate(`ehFolha()`))await evaluate(`pickTipo('avulsa')`);
await evaluate(`sendImage('image/png',true)`);
await waitFor(()=>evaluate('artes.length===1 && !!artes[0].src'),'PNG drop');
assert.equal(await evaluate('modo'),expected);
await fill('[data-cm]',10);await fill('[data-q]',4);await packed(4);
}
// UV keeps the mirror until Dropstar decides; it changes the pixels and the record.
const beforeMirror=await evaluate(`$('vArea').querySelector('canvas').toDataURL()`);
await click('[data-esp]');
await waitFor(()=>evaluate(`$('vArea').querySelector('canvas').toDataURL()!==${JSON.stringify(beforeMirror)}`),'mirror updates pixels');
await waitFor(()=>evaluate(`itemAtual?.production?.sources[0]?.mirrored===true`),'UV mirror in production record');
await click('[data-esp]');
// An older image load must not overwrite a newer edit, even before debounce.
// The packing loads each artwork's image through imagemDaArte.
await evaluate(`(()=>{window.realLoad=imagemDaArte;window.delayed=[];
imagemDaArte=a=>new Promise(resolve=>delayed.push(()=>realLoad(a).then(resolve)));
})()`);
await fill('[data-q]',5);
await waitFor(()=>evaluate('delayed.length===1'),'delayed preview');
await fill('[data-q]',7);
await evaluate(`imagemDaArte=realLoad;delayed[0]()`);
await packed(7);
const timeoutCleanup=await evaluate(`(async()=>{
const realLoader=carregarPdfJs, realTimer=setTimeout, realWorker=temWorker;
let destroyed=false, fail;
carregarPdfJs=async()=>({getDocument:()=>({
promise:new Promise((_,reject)=>{fail=reject}),
destroy:()=>{destroyed=true;fail(new Error('cancelled'));return Promise.resolve()}
})});
temWorker=true;
window.setTimeout=(fn,ms)=>realTimer(fn,ms===30000?1:ms);
try{
const result=await rasterizarPdf({arrayBuffer:async()=>new ArrayBuffer(1)},10,10);
return {timedOut:result.erro==='demorou demais neste navegador',destroyed};
}finally{carregarPdfJs=realLoader;window.setTimeout=realTimer;temWorker=realWorker;}
})()`);
assert.deepEqual(timeoutCleanup,{timedOut:true,destroyed:true});
// One rounding per product and the 1 m minimum once per order (Marcus,
// 2026-12-03): the same shares as app/core/pricing.py bill_order.
assert.deepEqual(await evaluate(`cobrarPedido([{modo:'file',exato:3.7364},{modo:'file',exato:0.2447},{modo:'file',exato:0.2164}])`),[3.7,0.3,0.2]);
assert.deepEqual(await evaluate(`cobrarPedido([{modo:'file',exato:0.25},{modo:'avulsa',exato:0.31}])`),[0.6,0.4]);
assert.deepEqual(await evaluate(`cobrarPedido([{modo:'file',exato:0.3}])`),[1]);
assert.deepEqual(await evaluate(`cobrarPedido([{modo:'file',exato:2.004},{modo:'file',exato:3.004}])`),[2,3]);
// Proof pop-up (Marcus, 2026-12-02): only above 10 m, not mandatory; closing
// it is going on without a proof, and the cart summary follows the answer.
assert.deepEqual(await evaluate(`[pedidoLongo([{cob:10}]),pedidoLongo([{cob:6},{cob:4.5}])]`),[false,true]);
assert.equal(await evaluate(`perguntaProva()`),false);
assert.equal(await evaluate(`$('provaDlg').open`),false);
await evaluate(`window.provaLongo=pedidoLongo; pedidoLongo=()=>true; window.provaResp=perguntaProva(); 1`);
await waitFor(()=>evaluate(`$('provaDlg').open && document.activeElement.id==='provaSim'`),'proof pop-up opens');
assert.equal(await evaluate(`perguntaProva()`),null);
await click('#provaSim');
assert.equal(await evaluate(`window.provaResp`),true);
assert.equal(await evaluate(`querProva && $('resLin').textContent.includes('Prova antes de imprimir')`),true);
await evaluate(`window.provaResp=perguntaProva(); 1`);
await click('#provaNao');
assert.equal(await evaluate(`window.provaResp`),false);
assert.equal(await evaluate(`$('resLin').textContent.includes('Prova antes de imprimir')`),false);
await evaluate(`window.provaResp=perguntaProva(); $('provaDlg').close(); 1`);
assert.equal(await evaluate(`window.provaResp`),false);
await evaluate(`pedidoLongo=window.provaLongo; 1`);
// Inspect the supplied local artwork, when requested, using the real file input.
if(process.env.ARTWORK_FILE){
await click('#bVoltar');await click('[data-modo="file"]');
const doc=await call('DOM.getDocument');
const input=await call('DOM.querySelector',{nodeId:doc.root.nodeId,selector:'#inp'});
await call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve(process.env.ARTWORK_FILE)]});
await waitFor(()=>evaluate('artes.length===1 && !!artes[0].src'),'supplied artwork');
await fill('[data-cm]',20);await fill('[data-q]',6);layout=await packed(6);
assert.ok(new Set(layout.pos.map(p=>p.x)).size>1);
assert.ok(new Set(layout.pos.map(p=>p.y)).size>1);
await screenshot('artwork-supplied');
console.log('Supplied image:',JSON.stringify(layout));
}
assert.deepEqual(errors,[]);
console.log('PASS: PNG upload and drop, JPG refused, packed copies, 5 mm gaps, aspect ratio, live width/quantity/rotation/mirror, metres, ready-sheet pricing/repeats, residue and solid background stop the order, UV, proof pop-up above 10 m, one rounding per product, stale renders, strict inline CSP.');
}catch(error){console.error(error);if(stderr)console.error(stderr.slice(-1200));process.exitCode=1;}
finally{ws?.close();chrome.kill();server.closeAllConnections();await new Promise(r=>server.close(r));}