/* Copyright 2026 Renchao Wu. Apache-2.0. */ import{parseRequest,makeReport,reportCsv}from'./core.mjs';const $=id=>document.getElementById(id),DEFAULT={method:'GET',base_status:200,resource:{length:'10',etag:'"resource-v1"',last_modified:'Sun, 06 Nov 1994 08:49:37 GMT',date_is_strong:true},range:'bytes=0-4,3-8',if_range:null};let epoch=0,examples=[],report=null,localBytes=null,localLabel=null,readingFile=false; function status(message,error=false){$('status').textContent=message;$('status').className=error?'error':'';} function text(q){$('request').value=JSON.stringify(q,null,2);$('request').scrollTop=0;$('request').scrollLeft=0;} function invalidate(){epoch++;if(readingFile){readingFile=false;localBytes=null;localLabel=null;$('file').value='';$('useLength').disabled=true;$('fileStatus').textContent='Local file read superseded by a newer action. Choose the file again.';}report=null;$('result').hidden=true;$('download').disabled=true;$('csv').disabled=true;for(let id of['binding','statusValue','selectedValue','uniqueValue','overlapValue','planDetails','actualDetails','provenance','memberSummary','memberCount'])$(id).textContent='';for(let id of['trace','memberRows','partRows','unionRows'])$(id).replaceChildren();} function clearBytes(){readingFile=false;localBytes=null;localLabel=null;$('file').value='';$('fileStatus').textContent='No local bytes bound. Resource length is asserted metadata.';$('useLength').disabled=true;} function bind(bytes,label){localBytes=new Uint8Array(bytes);localLabel=label;$('fileStatus').textContent=`Local bytes ready: ${label}; ${bytes.length} observed bytes. No timestamp or ETag was inferred. Use this length explicitly if needed.`;$('useLength').disabled=false;} const show=v=>v===null||v===undefined?'unavailable':String(v); function rows(id,data){let body=$(id);body.replaceChildren();for(let row of data){let tr=document.createElement('tr');for(let v of row){let td=document.createElement('td');td.textContent=show(v);tr.append(td);}body.append(tr);}} function members(){if(!report)return;let a=report.range_analysis,f=$('memberFilter').value,list=a.members.filter(r=>f==='all'||f==='satisfiable'&&r.satisfiable===true||f==='unsatisfiable'&&r.status==='valid'&&r.satisfiable===false||f==='malformed'&&r.status.startsWith('malformed')||f==='empty'&&r.status==='ignored-empty');rows('memberRows',list.map(r=>[r.ordinal,JSON.stringify(r.raw),r.kind,r.status,r.first,r.last,r.suffix,r.satisfiable,r.interval?.first,r.interval?.exclusive_end,r.interval?.length]));$('memberCount').textContent=`Showing ${list.length} of ${a.members.length} inspected member records. Full original header and every inspected record remain in JSON.`;} function render(){let p=report.plan,a=report.range_analysis,c=report.if_range;$('binding').textContent=`${report.request.method}; asserted representation length ${report.request.resource.length} bytes. ${report.scope.payload_observed?'Actual local bytes are bound and their length matches.':'Metadata-only plan; no actual file has been checked.'}`;$('statusValue').textContent=p.status===null?'outside profile':String(p.status);$('selectedValue').textContent=p.selected_payload_bytes;$('uniqueValue').textContent=p.unique_payload_bytes;$('overlapValue').textContent=p.overlap_payload_bytes;$('planDetails').textContent=`Reason: ${p.reason}. Kind: ${p.kind}. Top-level Content-Range: ${show(p.content_range)}. Planned Content-Length: ${show(p.planned_content_length)}. If-Range: ${c.status}${c.comparison?'; '+c.comparison:''}. Actual wire-body length is unknown.`;$('actualDetails').textContent=report.actual_payload?`Observed file SHA-256 ${report.actual_payload.whole_sha256}; ${report.actual_payload.whole_observed_byte_length} bytes. Slice hashes below refer to actual local bytes; previews stop after 32 bytes.`:'No observed file or slice hashes. The supplied length and validators are assertions.';$('provenance').textContent=`Request snapshot SHA-256 ${report.provenance.request_snapshot_sha256}; contract ${report.provenance.contract_sha256}. Snapshot digest is not a hash of the raw JSON text.`;for(let line of report.decision_trace){let li=document.createElement('li');li.textContent=line;$('trace').append(li);}$('memberSummary').textContent=`Analysis: ${a.status}; complete within this profile: ${a.complete}. Original list-token count: ${show(a.raw_token_count)}; empty inspected: ${show(a.empty_member_count)}; nonempty inspected: ${show(a.nonempty_member_count)}; semantic satisfiable count for a complete valid range: ${show(a.semantic_satisfiable_members)}. Incomplete or malformed analysis never claims a full satisfiable-member count.`;members();rows('partRows',p.selected_intervals.map(part=>{let s=report.actual_payload?.slices.find(s=>s.part_ordinal===part.part_ordinal);return[part.part_ordinal,part.member_ordinal,part.first,part.last,part.exclusive_end,part.length,part.content_range,s?.sha256??'not observed',s?s.preview_first32_hex+(s.preview_truncated?'…':''):'not observed'];}));rows('unionRows',p.diagnostic_union_intervals.map(u=>[u.first,u.last,u.exclusive_end,u.length]));$('result').hidden=false;$('download').disabled=false;$('csv').disabled=false;} async function run(){invalidate();let generation=epoch;status('Computing local range plan…');try{let q=parseRequest($('request').value),result=await makeReport(q,localBytes);if(epoch!==generation)return;report=result;render();status(report.plan.status===null?'Outside this processing profile. Full diagnostic report is available.':'Range plan ready. No target-server request was made.');}catch(e){if(epoch!==generation)return;invalidate();status(`Request rejected: ${e.message}`,true);}} async function loadExample(){invalidate();let generation=epoch,example=examples.find(e=>e.id===$('example').value);if(!example){status('Choose an available example.',true);return;}clearBytes();status('Loading the selected original example…');try{let bytes=null;if(example.payload!==null){if(!/^fixtures\/payloads\/(empty|utf8-crlf|all-bytes)\.bin$/.test(example.payload))throw Error('Unexpected local example asset');let response=await fetch(example.payload);if(!response.ok)throw Error(`HTTP ${response.status}`);let raw=await response.arrayBuffer();if(raw.byteLength>1048576)throw Error('Example exceeds local file cap');bytes=new Uint8Array(raw);let digest=new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),hex=[...digest].map(x=>x.toString(16).padStart(2,'0')).join('');if(hex!==example.payload_sha256)throw Error('Original sample digest mismatch');}if(epoch!==generation)return;text(example.request);if(bytes!==null)bind(bytes,'original example '+example.id);$('memberFilter').value='all';await run();}catch(e){if(epoch!==generation)return;invalidate();status(`Example unavailable: ${e.message}`,true);}} function save(name,content,type){let a=document.createElement('a'),url=URL.createObjectURL(new Blob([content],{type}));a.href=url;a.download=name;document.body.append(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);} $('request').addEventListener('input',()=>{invalidate();status('Edited request. Compute the current JSON when ready.');});$('request').addEventListener('keydown',e=>{if(e.ctrlKey&&e.key==='Enter'){e.preventDefault();run();}});$('example').addEventListener('change',()=>{invalidate();status('Example selected. Load example to replace the current request.');});$('loadExample').addEventListener('click',loadExample);$('run').addEventListener('click',run);$('restore').addEventListener('click',()=>{invalidate();clearBytes();text(DEFAULT);$('memberFilter').value='all';if(examples.length)$('example').value='overlap';run();});$('clear').addEventListener('click',()=>{invalidate();clearBytes();$('request').value='';status('Cleared. No bound bytes, report or exports.');});$('file').addEventListener('change',async()=>{invalidate();let generation=epoch,file=$('file').files[0];localBytes=null;localLabel=null;$('useLength').disabled=true;if(!file){$('fileStatus').textContent='No local bytes bound. Resource length is asserted metadata.';status('No file chosen.');return;}readingFile=true;$('fileStatus').textContent='Reading local bytes…';status('Reading the selected file locally…');try{if(file.size>1048576)throw Error('Local file exceeds 1 MiB');let raw=await file.arrayBuffer();if(epoch!==generation)return;if(raw.byteLength>1048576)throw Error('Observed file exceeds 1 MiB');readingFile=false;bind(new Uint8Array(raw),file.name);status('Local bytes ready. Use their length explicitly, then compute.');}catch(e){if(epoch!==generation)return;clearBytes();status(`File rejected: ${e.message}`,true);}});$('useLength').addEventListener('click',()=>{invalidate();try{if(localBytes===null)throw Error('No local bytes ready');let q=parseRequest($('request').value);q.resource.length=String(localBytes.byteLength);text(q);status('Observed local file length prepared in JSON. Compute to inspect slices.');}catch(e){status(`Cannot prepare length: ${e.message}`,true);}});$('memberFilter').addEventListener('change',members);$('download').addEventListener('click',()=>{if(report)save('http-range-report.json',JSON.stringify(report,null,2)+'\n','application/json');});$('csv').addEventListener('click',()=>{if(report)save('http-range-parts.csv',reportCsv(report),'text/csv');});text(DEFAULT);for(let id of['request','run','restore','clear','file'])$(id).disabled=false;let startup=epoch; try{let response=await fetch('examples.json');if(!response.ok)throw Error(`HTTP ${response.status}`);let data=await response.json();if(data.schema!=='http-range-desk-examples-v1'||!Array.isArray(data.examples)||data.examples.length!==8)throw Error('Example inventory shape');examples=data.examples;for(let e of examples){parseRequest(JSON.stringify(e.request));let o=document.createElement('option');o.value=e.id;o.textContent=e.title;$('example').append(o);}$('example').value='overlap';$('example').disabled=false;$('loadExample').disabled=false;$('resourceStatus').textContent='Original example inventory ready. It is separate from the current request and any local file.';if(epoch===startup)run();}catch(e){$('resourceStatus').textContent=`Original example inventory unavailable: ${e.message}. Direct JSON planning remains available.`;$('resourceStatus').className='error';}