File size: 1,876 Bytes
5ca3c16
5fd201e
 
 
 
 
 
fc92530
5fd201e
 
 
 
 
 
 
fc92530
5fd201e
fc92530
 
 
5ca3c16
fc92530
5ca3c16
fc92530
5fd201e
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import {watchPreview} from '/preview-site/lifecycle.js';
const status=document.getElementById('status'),query=new URLSearchParams(location.search),fragment=new URLSearchParams(location.hash.slice(1)),nonce=fragment.get('bridge');
const proof=Array.from(crypto.getRandomValues(new Uint8Array(32)),b=>b.toString(16).padStart(2,'0')).join('');
globalThis.zkPopupProof={nonce,proof};
history.replaceState(null,'',location.pathname+location.search);
const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms));
async function start(){
 let lease=query.get('lease');
 if(nonce){
  let login;const deadline=Date.now()+30000;
  do{
   const r=await fetch('/space/preview-login',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify({nonce,proof})});
   if(r.status===202){await pause(250);continue;}
   if(!r.ok)throw Error();login=await r.json();break;
  }while(Date.now()<deadline);
  if(!login)throw Error();lease=login.lease;
 }
 if(!/^[a-f0-9]{32}$/.test(lease||''))throw Error();
 const prefix='/preview-site/'+lease+'/api/';
 const s=await(await fetch(prefix+'session',{credentials:'same-origin'})).json();if(!s.authenticated)throw Error();
 await watchPreview(lease,s.csrf,prefix+'preview/client');
 const opened=await fetch(prefix+'preview?preview_id='+lease,{credentials:'same-origin'});if(!opened.ok)throw Error();
 let state=await opened.json();const deadline=Date.now()+900000;
 while(state.status==='starting'&&Date.now()<deadline){await pause(1500);const r=await fetch(prefix+'preview?preview_id='+lease,{credentials:'same-origin'});if(!r.ok)throw Error();state=await r.json();}
 if(state.status!=='ready'||state.id!==lease)throw Error();location.replace('/preview-site/?lease='+encodeURIComponent(lease));
}
start().catch(()=>{status.textContent='应用打开未完成,请从当前工作台的工程重试。';});