90 lines
6.1 KiB
JavaScript
90 lines
6.1 KiB
JavaScript
import {memoryProfile} from './feed-gecko-profile.mjs';
|
|
const api = '/_/api/v1/extension/organizer.feeds/browser/';
|
|
const status = document.getElementById('status'), canvas = document.getElementById('screen');
|
|
let engine, started = false, ready = false, stopped = false, navigating = false, poll, resizeTimer;
|
|
let history = [], position = 0;
|
|
const startup = new AbortController();
|
|
let deadline, finding=false;
|
|
const ja = parent.document.documentElement.lang.startsWith('ja');
|
|
const text = (en,jp) => ja ? jp : en;
|
|
function report(message) { status.textContent=message; status.hidden=!message; }
|
|
function url(value) { try { const u=new URL(value); return ['https:','http:'].includes(u.protocol)&&!u.username&&!u.password&&u.href.length<=8192 ? u.href : ''; } catch {return '';} }
|
|
function send(data) { parent.postMessage({type:'pageswiki-gecko',...data},location.origin); }
|
|
function navigationState() { send({href:history[position],back:position>0,forward:position<history.length-1}); }
|
|
async function pageState() {
|
|
const uri=String(await engine.evalChrome('String(document.documentURI)'));
|
|
const failed=/^about:(neterror|certerror)(?:\?|$)/.test(uri);
|
|
// The minimal upstream GRE omits error-page localization/modules. Never
|
|
// expose a broken certificate override UI; use our own inert explanation.
|
|
canvas.hidden=failed;
|
|
report(failed?text('The page could not be loaded securely or the connection failed. Certificate errors cannot be bypassed here. Use ↗ to inspect it in your browser.','安全な接続を確立できないか、通信に失敗しました。証明書エラーはここでは無視できません。↗からブラウザで確認してください。'):'');
|
|
return !failed;
|
|
}
|
|
async function navigate(command) {
|
|
if(!ready||stopped||navigating)return;
|
|
const next=position+(command==='back'?-1:command==='forward'?1:0);
|
|
if(next<0||next>=history.length)return;
|
|
navigating=true;position=next;
|
|
try {
|
|
// Minimal upstream GRE omits SessionStoreFunctions: native history.back()
|
|
// fails. Keep a bounded viewer-local URL history and re-load the chosen URL.
|
|
await engine.load(history[position]);
|
|
await pageState();
|
|
const current=url(await engine.evalChrome('String(location.href)'));
|
|
if(current)history[position]=current;
|
|
navigationState();
|
|
} catch { report(text('Navigation failed. Use ↗ to open the original.','移動できませんでした。↗から原文を開いてください。')); }
|
|
finally {navigating=false;}
|
|
}
|
|
function stop() { stopped=true;ready=false;startup.abort();clearTimeout(deadline);clearTimeout(poll);clearTimeout(resizeTimer);engine?.destroy(); }
|
|
function fail() {
|
|
if(stopped)return;
|
|
stop();
|
|
// Upstream destroy() only detaches input; the parent must discard the iframe
|
|
// to release the WASM heap, workers and socket, including a stuck init().
|
|
send({failed:true});
|
|
}
|
|
async function find(query, backwards) {
|
|
if(!ready||stopped||finding||navigating||typeof query!=='string'||!query.trim()||query.length>256)return;
|
|
finding=true;
|
|
try {
|
|
const found=await engine.evalChrome(`String(window.find(${JSON.stringify(query)},false,${backwards===true},true,false,false,false))`);
|
|
if(!stopped)send({findResult:found==='true',query});
|
|
} catch {if(!stopped)send({findError:true});}
|
|
finally {finding=false;}
|
|
}
|
|
async function start(href) {
|
|
started=true;
|
|
if(!crossOriginIsolated || typeof SharedArrayBuffer==='undefined') {fail();return;}
|
|
report(text('Starting Gecko…','Geckoを起動中…'));
|
|
const timer=setTimeout(()=>{if(!ready&&!stopped)report(text('Startup is taking longer than expected. Close the viewer to stop, or use ↗.','起動に時間がかかっています。閉じると停止します。↗から原文も開けます。'));},45000);
|
|
deadline=setTimeout(fail,120000);
|
|
try {
|
|
const {Gecko}=await import(api+'assets/v0.0.1/gecko.js'); if(stopped)return;
|
|
const font=await fetch(api+'distribution/v0.0.1/NotoSansCJKjp-Regular.otf',{credentials:'same-origin',signal:startup.signal});
|
|
if(!font.ok)throw Error('Bundled font unavailable');
|
|
const data=new Uint8Array(await font.arrayBuffer());if(stopped)return;
|
|
if(data.byteLength!==16467736)throw Error('Bundled font size mismatch');
|
|
const profile=memoryProfile();await profile.mkdir('fonts');await profile.writeFile('fonts/NotoSansCJKjp-Regular.otf',data);
|
|
const socket=new URL(api+'wisp/',location.href);socket.protocol=location.protocol==='https:'?'wss:':'ws:';
|
|
engine=new Gecko({canvas,wasm:{url:api+'assets/v0.0.1/gecko.wasm.zst',compressed:true},wispUrl:socket.href,profile,width:Math.min(innerWidth,1920),height:Math.min(innerHeight,1080),env:{GECKO_NOWASMJIT:'1'},print:()=>{},printErr:()=>{}});
|
|
await engine.init();if(stopped)return;
|
|
await engine.load(href);if(stopped)return;
|
|
history=[url(await engine.evalChrome('String(location.href)'))||href];position=0;
|
|
ready=true;clearTimeout(deadline);await pageState();canvas.focus();send({ready:true});
|
|
navigationState();
|
|
const update=async()=>{if(stopped)return;try{if(!navigating){await pageState();const href=url(await engine.evalChrome('String(location.href)'));if(href&&!navigating&&href!==history[position]){history=history.slice(0,position+1);history.push(href);if(history.length>64)history.shift();position=history.length-1;navigationState();}}}catch{/* Keep the last validated URL. */}if(!stopped)poll=setTimeout(update,2000);};update();
|
|
} catch {fail();}
|
|
finally {clearTimeout(timer);}
|
|
}
|
|
addEventListener('message',event=>{
|
|
if(event.source!==parent||event.origin!==location.origin||event.data?.type!=='pageswiki-gecko')return;
|
|
if(!started){const href=url(event.data.href);if(href)start(href);return;}
|
|
if(['back','forward','reload'].includes(event.data.command))navigate(event.data.command);
|
|
if(event.data.command==='find')find(event.data.query,event.data.backwards);
|
|
});
|
|
addEventListener('resize',()=>{clearTimeout(resizeTimer);resizeTimer=setTimeout(()=>{if(ready&&!stopped)engine.resize(Math.min(innerWidth,1920),Math.min(innerHeight,1080)).catch(()=>{});},150);});
|
|
addEventListener('keydown',e=>{if(e.key==='Escape'){e.preventDefault();send({close:true});}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='f'){e.preventDefault();e.stopImmediatePropagation();send({find:true});}},true);
|
|
addEventListener('pagehide',stop);
|
|
send({listening:true});
|