import {Client,closeClient} from './client.js'; import {cloudConfigured, cloudClient} from '../../frontend/src/cloud.js'; import {runBatch} from './batch_jobs.mjs'; import {activeWorkspace} from '../../frontend/src/workspace.mjs'; let workspace; export function sessionKey(){ if(workspace)return workspace; try{workspace=localStorage.getItem('defectrag-private-workspace')}catch{} if(!/^[a-f0-9]{64}$/.test(workspace||'')){ workspace=Array.from(crypto.getRandomValues(new Uint8Array(32)),x=>x.toString(16).padStart(2,'0')).join(''); try{localStorage.setItem('defectrag-private-workspace',workspace)}catch{} } return workspace; } // API downloads use the current authenticated scope, not an older CSV capability. export const spaceUrl=path=>path; async function credentials(){ if(!cloudConfigured())return ''; const client=await cloudClient(); const {data,error}=await client.auth.getSession(); if(error)throw new Error('Account session could not refresh. Reconnect or sign in again.'); if(data.session?.expires_at&&data.session.expires_at*1000new Promise((resolve,reject)=>{ const reader=new FileReader();reader.onload=()=>resolve(String(reader.result).split(',')[1]); reader.onerror=()=>reject(new Error('Image could not be read'));reader.readAsDataURL(file); }); export async function spaceFetch(path,options={}){ const workspace=activeWorkspace(); const endpoint=new URL(path,location.origin).pathname; try{ const publicRead=(!options.method||options.method==='GET')&&(/^\/api\/(health|models|evaluation|samples|gallery)(\/|$)/.test(endpoint)||endpoint==='/api/benchmark/official'); const token=publicRead?'':await credentials(); let data; if(options.method==='POST'&&['/api/inspect','/api/batch'].includes(endpoint)){ const body=options.body,category=body.get('category'),batch=body.get('batch')||''; const files=endpoint==='/api/batch'?body.getAll('files'):[body.get('file')]; if(!files.length||files.length>20||(endpoint==='/api/batch'&&!batch.trim()))throw new Error('Choose 1–20 images and a batch label.'); const {records,errors}=await runBatch(files,async file=>{ if(file.size>10*1024*1024)throw new Error('Image limit is 10 MB'); return await queued('/inspect',{image_b64:await encode(file),filename:file.name,category,batch,request_id:body.get('request_id')||''},token,workspace); }); if(endpoint==='/api/inspect'){ if(errors.length)throw new Error(errors[0].message); data=records[0]; }else data={records,errors,batch}; }else if(options.method==='POST'&&endpoint==='/api/assistant'){ data=await queued('/assistant',JSON.parse(options.body),token,workspace); }else{ const headers=new Headers(options.headers||{}); headers.set('X-DefectRAG-Session',sessionKey()); headers.set('X-DefectRAG-Workspace',workspace); if(token)headers.set('Authorization','Bearer '+token); const response=await fetch(path,{...options,headers}); return response; } return Response.json({data}); }catch(error){ const message=error.message||'Model request failed'; const invalid=/image limit|invalid image|choose 1|supported category|batch label|32px|25 MP|aspect ratio/i.test(message); return Response.json({error:{message}},{status:invalid?422:503}); } }