diff --git a/dist/inform7/parchment-for-inform7.zip b/dist/inform7/parchment-for-inform7.zip index 0fd06e5a..f6a38c07 100644 Binary files a/dist/inform7/parchment-for-inform7.zip and b/dist/inform7/parchment-for-inform7.zip differ diff --git a/dist/web/main.js b/dist/web/main.js index 6f3fbd65..033e5ea9 100644 --- a/dist/web/main.js +++ b/dist/web/main.js @@ -1,17 +1,17 @@ -var $u=Object.defineProperty;var ju=(a,e)=>{for(var r in e)$u(a,r,{get:e[r],enumerable:!0})};function Ar(a){for(var e=1;e"u")){_=Ar({},e,_),typeof _.expires=="number"&&(_.expires=new Date(Date.now()+_.expires*864e5)),_.expires&&(_.expires=_.expires.toUTCString()),f=encodeURIComponent(f).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var p="";for(var y in _)_[y]&&(p+="; "+y,_[y]!==!0&&(p+="="+_[y].split(";")[0]));return document.cookie=f+"="+a.write(u,f)+p}}function i(f){if(!(typeof document>"u"||arguments.length&&!f)){for(var u=document.cookie?document.cookie.split("; "):[],_={},p=0;p{let i=a;return typeof e=="string"||Array.isArray(e)?i=a.toLocaleString(e,r):(e===!0||r!==void 0)&&(i=a.toLocaleString(void 0,r)),i};function an(a,e){if(!Number.isFinite(a))throw new TypeError(`Expected a finite number, got ${typeof a}: ${a}`);e={bits:!1,binary:!1,space:!0,...e};let r=e.bits?e.binary?Hu:Nu:e.binary?qu:zu,i=e.space?" ":"";if(e.signed&&a===0)return` 0${i}${r[0]}`;let f=a<0,u=f?"-":e.signed?"+":"";f&&(a=-a);let _;if(e.minimumFractionDigits!==void 0&&(_={minimumFractionDigits:e.minimumFractionDigits}),e.maximumFractionDigits!==void 0&&(_={maximumFractionDigits:e.maximumFractionDigits,..._}),a<1){let b=Ko(a,e.locale,_);return u+b+i+r[0]}let p=Math.min(Math.floor(e.binary?Math.log(a)/Math.log(1024):Math.log10(a)/3),r.length-1);a/=(e.binary?1024:1e3)**p,_||(a=a.toPrecision(3));let y=Ko(Number(a),e.locale,_),x=r[p];return u+y+i+x}var Vu=typeof global=="object"&&global&&global.Object===Object&&global,Gr=Vu;var Ku=typeof self=="object"&&self&&self.Object===Object&&self,Yu=Gr||Ku||Function("return this")(),Y=Yu;var Ju=Y.Symbol,ue=Ju;var Yo=Object.prototype,Qu=Yo.hasOwnProperty,Xu=Yo.toString,rr=ue?ue.toStringTag:void 0;function Zu(a){var e=Qu.call(a,rr),r=a[rr];try{a[rr]=void 0;var i=!0}catch{}var f=Xu.call(a);return i&&(e?a[rr]=r:delete a[rr]),f}var Jo=Zu;var ec=Object.prototype,tc=ec.toString;function rc(a){return tc.call(a)}var Qo=rc;var ic="[object Null]",nc="[object Undefined]",Xo=ue?ue.toStringTag:void 0;function oc(a){return a==null?a===void 0?nc:ic:Xo&&Xo in Object(a)?Jo(a):Qo(a)}var ye=oc;function ac(a){return a!=null&&typeof a=="object"}var ce=ac;var sc="[object Symbol]";function lc(a){return typeof a=="symbol"||ce(a)&&ye(a)==sc}var Cr=lc;function fc(a,e){for(var r=-1,i=a==null?0:a.length,f=Array(i);++r-1&&a%1==0&&a-1&&a%1==0&&a<=r_}var Wr=i_;function n_(a){return a!=null&&Wr(a.length)&&!Er(a)}var Br=n_;var o_=Object.prototype;function a_(a){var e=a&&a.constructor,r=typeof e=="function"&&e.prototype||o_;return a===r}var mt=a_;function s_(a,e){for(var r=-1,i=Array(a);++r-1}var Pa=Sd;function Td(a,e){var r=this.__data__,i=qe(r,a);return i<0?(++this.size,r.push([a,e])):r[i][1]=e,this}var $a=Td;function kt(a){var e=-1,r=a==null?0:a.length;for(this.clear();++e=e||oe<0||A&&pe>=u}function P(){var j=Yr();if(re(j))return Fe(j);p=setTimeout(P,Q(j))}function Fe(j){return p=void 0,E&&i?J(j):(i=f=void 0,_)}function Oe(){p!==void 0&&clearTimeout(p),x=0,i=y=f=p=void 0}function De(){return p===void 0?_:Fe(Yr())}function de(){var j=Yr(),oe=re(j);if(i=arguments,f=this,y=j,oe){if(p===void 0)return V(y);if(A)return clearTimeout(p),p=setTimeout(P,e),J(y)}return p===void 0&&(p=setTimeout(P,e)),_}return de.cancel=Oe,de.flush=De,de}var at=R7;var F7="Expected a function";function O7(a,e,r){var i=!0,f=!0;if(typeof a!="function")throw new TypeError(F7);return ne(r)&&(i="leading"in r?!!r.leading:i,f="trailing"in r?!!r.trailing:f),at(a,e,{leading:i,maxWait:e,trailing:f})}var st=O7;var D7={"&":"&","<":"<",">":">",""":'"',"'":"'"},W7=Ya(D7),Ps=W7;var $s=/&(?:amp|lt|gt|quot|#39);/g,B7=RegExp($s.source);function M7(a){return a=Ka(a),a&&B7.test(a)?a.replace($s,Ps):a}var dn=M7;var le=class extends DataView{constructor(e,r,i){e instanceof Uint8Array?super(e.buffer,e.byteOffset,e.byteLength):super(e,r,i)}getFourCC(e){return String.fromCharCode(this.getUint8(e),this.getUint8(e+1),this.getUint8(e+2),this.getUint8(e+3))}getUint8Subarray(e,r){return new Uint8Array(this.buffer,this.byteOffset+(e||0),r)}setFourCC(e,r){this.setUint8(e,r.charCodeAt(0)),this.setUint8(e+1,r.charCodeAt(1)),this.setUint8(e+2,r.charCodeAt(2)),this.setUint8(e+3,r.charCodeAt(3))}setUint8Array(e,r){this.getUint8Subarray(e,r.length).set(r)}};function js(a){let e=new Uint8Array(a.length*4),r=new DataView(e.buffer);for(let i=0;if)throw new Error("IFF chunk out of range");this.chunks.push({data:r.getUint8Subarray(i+8,u),offset:i,type:r.getFourCC(i)}),i+=8+u,i%2&&i++}}write(){let e=12;for(let f of this.chunks)e+=8+f.data.length,e%2&&e++;let r=new le(new ArrayBuffer(e));r.setFourCC(0,"FORM"),r.setUint32(4,e-8),r.setFourCC(8,this.type);let i=12;for(let f of this.chunks)r.setFourCC(i,f.type),r.setUint32(i+4,f.data.length),r.setUint8Array(i+8,f.data),i+=8+f.data.length,i%2&&i++;return r.getUint8Subarray()}};var qs={Data:"data",Exec:"exec",Pict:"pict","Snd ":"sound"},Ns="????",Ct=class{constructor(e){this.classname="Blorb";this.chunks={};this.is_inited=!1;this.metadata={};e&&this.init(e)}init(e,r){if(!this.is_inited){if(e instanceof Uint8Array){let i=new ar;if(i.parse(e),i.type!=="IFRS")throw new Error("Not a Blorb file");if(i.chunks[0].type!=="RIdx")throw new Error("Malformed blorb: chunk 1 is not RIdx");for(let f of i.chunks)switch(f.type){case"Dbug":{this.debugdata=f.data;break}case"Fspc":{let u=new le(f.data);this.coverimagenum=u.getUint32(0);break}case"IFmd":{let u=or.decode(f.data),_=/(.+)<\/bibliographic>/is.exec(u),p=/<(\w+)>(.+)<\/\1>/gi,y=//g,x=/\s+/g;if(_){let b;for(;b=p.exec(_[1]);){let A=b[1].toLowerCase(),E=b[2].replace(x," ");A==="description"&&(E=E.replace(y,` -`)),this.metadata[A]=dn(E)}}break}case"RDes":{let u=new le(f.data),_=4;for(;_J.offset===x)[0];if(!b)throw new Error(`No Blorb chunk at offset ${x}`);let A=b.type,E={blorbtype:A,content:A==="FORM"?e.subarray(b.offset,b.offset+8+b.data.length):b.data,usage:qs[p]};p==="Pict"&&(A==="JPEG"?E.type="jpeg":A==="PNG "?E.type="png":E.type=Ns),p==="Data"&&(E.binary=A==="BINA"||A==="FORM"),this.chunks[`${E.usage}:${y}`]=E}break}}}else if(r?.format==="infomap")for(let i in e){if(!Number.isInteger(+i))continue;let f=Object.assign({},e[i]);delete f.image,f.height&&f.width&&(f.imagesize={height:f.height,width:f.width},delete f.height,delete f.width),f.type=f.url.endsWith(".png")?"png":"jpeg",f.usage="pict",this.chunks[`pict:${i}`]=f}else if(!(Array.isArray(e)&&e.length===0))throw new Error("Unsupported Blorb.init data format");this.is_inited=!0}}getlibrary(){return null}get_chunk(e,r){return this.chunks[`${e}:${r}`]||null}get_cover_pict(){return this.coverimagenum??null}get_data_chunk(e){let r=this.chunks[`data:${e}`];return r?.content?{binary:r.binary,data:r.content}:null}get_debug_info(){return this.debugdata}get_exec_data(e){let r=this.chunks["exec:0"];return!r?.content||e&&r.blorbtype!==e?null:r.content}get_image_info(e){let r=this.chunks[`pict:${e}`];if(!r)return null;!r.imagesize&&r.content&&(r.type==="jpeg"?r.imagesize=U7(r.content):r.type==="png"&&(r.imagesize=P7(r.content)));let i=Object.assign({image:e},r);return i.imagesize&&(i.height=i.imagesize.height,i.width=i.imagesize.width),i}get_image_url(e){let r=this.chunks[`pict:${e}`];return r?r.url?r.url:r.type!==Ns&&r.content?(r.url=URL.createObjectURL(new Blob([r.content],{type:`image/${r.type}`})),r.url):null:null}get_metadata(e){return this.metadata[e]}inited(){return this.is_inited}};function U7(a){let e=new le(a),r=0;for(;r=208&&i<=217)continue;let f=e.getUint16(r);if(i>=192&&i<=207&&i!==200)return f<7?void 0:{height:e.getUint16(r+3),width:e.getUint16(r+5)};r+=f}}function P7(a){let e=new le(a);if(e.getFourCC(0)!=="\x89PNG")return;let r=8;for(;reo,evtype_CharInput:()=>Qn,evtype_Hyperlink:()=>ro,evtype_LineInput:()=>Xn,evtype_MouseInput:()=>Zn,evtype_None:()=>li,evtype_Redraw:()=>to,evtype_SoundNotify:()=>V7,evtype_Timer:()=>fi,evtype_VolumeNotify:()=>K7,filemode_Read:()=>te,filemode_ReadWrite:()=>Se,filemode_Write:()=>be,filemode_WriteAppend:()=>di,fileusage_BinaryMode:()=>f1,fileusage_Data:()=>a1,fileusage_InputRecord:()=>l1,fileusage_SavedGame:()=>_i,fileusage_TextMode:()=>ao,fileusage_Transcript:()=>s1,fileusage_TypeMask:()=>Bt,gestalt_CharInput:()=>bn,gestalt_CharOutput:()=>kn,gestalt_CharOutput_ApproxPrint:()=>j7,gestalt_CharOutput_CannotPrint:()=>$7,gestalt_CharOutput_ExactPrint:()=>xn,gestalt_DateTime:()=>Wn,gestalt_DrawImage:()=>An,gestalt_GarglkText:()=>Un,gestalt_Graphics:()=>Tn,gestalt_GraphicsCharInput:()=>Mn,gestalt_GraphicsTransparency:()=>En,gestalt_HyperlinkInput:()=>Cn,gestalt_Hyperlinks:()=>Gn,gestalt_LineInput:()=>wn,gestalt_LineInputEcho:()=>Fn,gestalt_LineTerminatorKey:()=>Dn,gestalt_LineTerminators:()=>On,gestalt_MouseInput:()=>vn,gestalt_ResourceStream:()=>Bn,gestalt_Sound:()=>L7,gestalt_Sound2:()=>H7,gestalt_SoundMusic:()=>N7,gestalt_SoundNotify:()=>q7,gestalt_SoundVolume:()=>z7,gestalt_Timer:()=>Sn,gestalt_Unicode:()=>In,gestalt_UnicodeNorm:()=>Rn,gestalt_Version:()=>yn,imagealign_InlineCenter:()=>m1,imagealign_InlineDown:()=>h1,imagealign_InlineUp:()=>p1,imagealign_MarginLeft:()=>g1,imagealign_MarginRight:()=>y1,keycode_Delete:()=>qn,keycode_Down:()=>Ln,keycode_End:()=>Yn,keycode_Escape:()=>Et,keycode_Func1:()=>It,keycode_Func10:()=>ai,keycode_Func11:()=>si,keycode_Func12:()=>lt,keycode_Func2:()=>Xr,keycode_Func3:()=>Zr,keycode_Func4:()=>ei,keycode_Func5:()=>ti,keycode_Func6:()=>ri,keycode_Func7:()=>ii,keycode_Func8:()=>ni,keycode_Func9:()=>oi,keycode_Home:()=>Kn,keycode_Left:()=>lr,keycode_MAXVAL:()=>Jn,keycode_PageDown:()=>Vn,keycode_PageUp:()=>Hn,keycode_Return:()=>zn,keycode_Right:()=>$n,keycode_Tab:()=>Nn,keycode_Unknown:()=>Pn,keycode_Up:()=>jn,seekmode_Current:()=>lo,seekmode_End:()=>ut,seekmode_Start:()=>so,style_Alert:()=>e1,style_BlockQuote:()=>r1,style_Emphasized:()=>J7,style_Header:()=>X7,style_Input:()=>i1,style_NUMSTYLES:()=>ui,style_Normal:()=>Y7,style_Note:()=>t1,style_Preformatted:()=>Q7,style_Subheader:()=>Z7,style_User1:()=>n1,style_User2:()=>o1,stylehint_BackColor:()=>go,stylehint_Indentation:()=>fo,stylehint_Justification:()=>cr,stylehint_NUMHINTS:()=>bo,stylehint_Oblique:()=>po,stylehint_ParaIndentation:()=>uo,stylehint_Proportional:()=>ho,stylehint_ReverseColor:()=>yo,stylehint_Size:()=>co,stylehint_TextColor:()=>mo,stylehint_Weight:()=>_o,stylehint_just_Centered:()=>_1,stylehint_just_LeftFlush:()=>u1,stylehint_just_LeftRight:()=>c1,stylehint_just_RightFlush:()=>d1,winmethod_Above:()=>Ot,winmethod_Below:()=>io,winmethod_Border:()=>no,winmethod_BorderMask:()=>ft,winmethod_DirMask:()=>Dt,winmethod_DivisionMask:()=>Wt,winmethod_Fixed:()=>Je,winmethod_Left:()=>Ye,winmethod_NoBorder:()=>oo,winmethod_Proportional:()=>ci,winmethod_Right:()=>Ft,wintype_AllTypes:()=>fr,wintype_Blank:()=>Rt,wintype_Graphics:()=>Ke,wintype_Pair:()=>ur,wintype_TextBuffer:()=>ve,wintype_TextGrid:()=>Ie,zcolor_Current:()=>hi,zcolor_Default:()=>pi});var yn=0,bn=1,wn=2,kn=3,$7=0,j7=1,xn=2,vn=4,Sn=5,Tn=6,An=7,L7=8,z7=9,q7=10,Gn=11,Cn=12,N7=13,En=14,In=15,Rn=16,Fn=17,On=18,Dn=19,Wn=20,H7=21,Bn=22,Mn=23,Un=4352,Pn=4294967295,lr=4294967294,$n=4294967293,jn=4294967292,Ln=4294967291,zn=4294967290,qn=4294967289,Et=4294967288,Nn=4294967287,Hn=4294967286,Vn=4294967285,Kn=4294967284,Yn=4294967283,It=4294967279,Xr=4294967278,Zr=4294967277,ei=4294967276,ti=4294967275,ri=4294967274,ii=4294967273,ni=4294967272,oi=4294967271,ai=4294967270,si=4294967269,lt=4294967268,Jn=28,li=0,fi=1,Qn=2,Xn=3,Zn=4,eo=5,to=6,V7=7,ro=8,K7=9,Y7=0,J7=1,Q7=2,X7=3,Z7=4,e1=5,t1=6,r1=7,i1=8,n1=9,o1=10,ui=11,fr=0,ur=1,Rt=2,ve=3,Ie=4,Ke=5,Ye=0,Ft=1,Ot=2,io=3,Dt=15,Je=16,ci=32,Wt=240,no=0,oo=256,ft=256,a1=0,_i=1,s1=2,l1=3,Bt=15,ao=256,f1=0,be=1,te=2,Se=3,di=5,so=0,lo=1,ut=2,fo=0,uo=1,cr=2,co=3,_o=4,po=5,ho=6,mo=7,go=8,yo=9,bo=10,u1=0,c1=1,_1=2,d1=3,p1=1,h1=2,m1=3,g1=4,y1=5,pi=-1,hi=-2;var mi=class{constructor(e,r,i){this.binary=r,this.buf=e,this.fref=i,this.uni=Gt(e)}convert(){if(this.uni){if(this.binary)return js(this.buf);{let e=String.fromCodePoint(...this.buf);return zs.encode(e)}}else return this.buf.slice()}},gi=class{constructor(e){this.cache={};this.classname="CachingDialogWrapper";this.streaming=!1;this.write=at(()=>{for(let e in this.cache){let r=this.cache[e];if(this.Dialog.streaming){let i=this.Dialog.file_fopen(1,r.fref);i.fwrite(r.convert()),i.fclose()}else this.Dialog.file_write(r.fref,r.convert())}this.cache={}},0);this.Dialog=e}init(e){}file_ref_exists(e){return!!this.cache[e.filename]||this.Dialog.file_ref_exists(e)}file_read(e){if(this.cache[e.filename])return this.cache[e.filename].convert();if(this.Dialog.streaming){let r=this.Dialog.file_fopen(2,e);if(!r)return null;r.fseek(0,2);let i=r.ftell(),f=new Uint8Array(i);return r.fseek(0,0),r.fread(f),r.fclose(),f}else return this.Dialog.file_read(e)}file_remove_ref(e){this.cache[e.filename]&&delete this.cache[e.filename],this.Dialog.file_remove_ref(e)}file_write(e,r){throw new Error("CachingDialogWrapper.write_file should be called instead")}inited(){return!0}write_file(e,r){return this.cache[e.filename]=r,this.write(),!0}autosave_read(e){return this.Dialog.autosave_read(e)}autosave_write(e,r){this.Dialog.autosave_write(e,r)}file_clean_fixed_name(e,r){return this.Dialog.file_clean_fixed_name(e,r)}file_construct_ref(e,r,i){return this.Dialog.file_construct_ref(e,r,i)}file_construct_temp_ref(e){return this.Dialog.file_construct_temp_ref(e)}getlibrary(e){return this.Dialog.getlibrary(e)}open(e,r,i,f){this.Dialog.open(e,r,i,f)}};function _r(a,e,r){let i=Math.min(r,e.length);for(let f=0;fQe?Xe:u}else r.set(this.buf.subarray(this.pos,this.pos+i));return this.pos+=i,this.read_count+=i,i}get_char(r){if(this.posQe?Xe:i}return-1}get_line(r){let i=Math.min(r.length-1,this.len-this.pos);if(i<0)return 0;let f=!Gt(r)&&this.uni,u=0;for(;uQe?Xe:_,_===10)break}return r[u]=Ks,this.read_count+=u,u}get_position(){return this.pos}put_buffer(r,i){let f=r.length;this.write_count+=f,this.pos+f>this.len&&this.expandable&&this.expand(f);let u=Math.min(f,this.len-this.pos);if(u!==0){if(i&&!this.uni)for(let _=0;_Qe?Xe:p}else Array.isArray(r)&&(r=(i?Uint32Array:Uint8Array).from(r)),this.buf.set(r.subarray(0,u),this.pos);this.pos+=u,this.write()}}put_char(r){this.write_count++,this.pos===this.len&&this.expandable&&this.expand(1),this.posQe?Xe:r,this.write())}put_string(r){this.put_buffer(Uint32Array.from(r,i=>i.codePointAt(0)),!0)}set_position(r,i){r===1?this.pos+=i:r===2?this.pos=this.len+i:this.pos=i,this.pos<0&&(this.pos=0),this.pos>this.len&&(this.pos=this.len)}write(){}},ki=class extends Ze{constructor(e,r,i,f){super(r,i,f),this.expandable=!0,this.fref=e}expand(e){let r=this.pos+e;this.len=r;let i=this.buf.length;if(r>i){i+=Math.max(r-i,100);let f=this.buf;this.buf=new(this.uni?Uint32Array:Uint8Array)(i),this.buf.set(f)}}write(){this.fref.write(this.buf.subarray(0,this.len))}},xi=class extends pr{constructor(){super(...arguments);this.type="null"}put_buffer(r,i){this.write_count+=r.length}put_char(r){this.write_count++}put_string(r,i){this.write_count+=[...r].length}},vi=class extends pr{constructor(r){super(1,0);this.type="window";this.win=r}put_buffer(r,i){if(this.win.input.type==="line")throw new Error("Window has pending line request");this.write_count+=r.length,this.win.put_string(String.fromCodePoint(...r)),this.win.echostr?.put_buffer(r,i)}put_char(r){if(this.win.input.type==="line")throw new Error("Window has pending line request");this.write_count++,this.win.put_string(String.fromCodePoint(r)),this.win.echostr?.put_char(r)}put_string(r,i){if(this.win.input.type==="line")throw new Error("Window has pending line request");this.write_count+=[...r].length,this.win.put_string(r,i),this.win.echostr?.put_string(r,i)}set_css(r,i){this.win.set_css(r,i),this.win.echostr?.type==="window"&&this.win.echostr.set_css(r,i)}set_hyperlink(r){this.win.set_hyperlink(r),this.win.echostr?.type==="window"&&this.win.echostr.set_hyperlink(r)}set_style(r){this.win.set_style(r),this.win.echostr?.type==="window"&&this.win.echostr.set_style(r)}};var Ut=class{constructor(e){this.box={bottom:0,left:0,right:0,top:0};this.disprock=0;this.echostr=null;this.input={id:0};this.next=null;this.parent=null;this.prev=null;this.rock=e,this.str=new vi(this)}clear(){}put_string(e,r){}set_css(e,r){}set_hyperlink(e){}set_style(e){}update(){if(this.type==="blank"||this.type==="pair")return{content:null,input:null,size:null};let e={id:this.input.id};Mt(this.input,e,"hyperlink"),Mt(this.input,e,"mouse");let r=this.box;return{content:null,input:e,size:{height:r.bottom-r.top,id:this.disprock,left:r.left,rock:this.rock,top:r.top,type:this.type,width:r.right-r.left}}}},Si=class extends Ut{constructor(){super(...arguments);this.type="blank";this.typenum=2}},Ti=class extends Ut{constructor(r,i){super(r);this.cleared=!0;this.request_echo_line_input=!0;this.stylehints=nr(i)}update(){let r=super.update();Object.keys(this.stylehints).length&&(r.size.styles=this.stylehints);let i=this.input,f=r.input;return i.type&&(Mt(i,f,"gen"),Mt(i,f,"type"),i.type==="line"&&(f.maxlen=this.line_input_buf.length,Mt(i,f,"initial"),Mt(i,f,"terminators"))),delete i.initial,r}},Ai=class extends Ti{constructor(r,i){super(r,i);this.echo_line_input=!0;this.last_textrun=fe(Ii,!0);this.type="buffer";this.typenum=3;this.last_textrun=fe(Ii,!0),this.content=[{content:[this.last_textrun]}],this.last_par=this.content[0]}clear(){this.cleared=!0,this.clear_content()}clear_content(){this.last_textrun=fe(this.last_textrun,!1),this.content=[{append:!0,content:[this.last_textrun]}],this.last_par=this.content[0]}clone_textrun(r,i){(i||this.last_textrun.text!=="")&&(this.last_textrun=fe(this.last_textrun,r),this.last_par.content.push(this.last_textrun))}put_image(r){r.hyperlink=this.last_textrun.hyperlink,this.last_par.content.push(r),this.clone_textrun(!1,!0)}put_string(r,i){let f=this.last_textrun.style;i&&this.set_style(i);for(let[u,_]of r.split(` +var ju=Object.defineProperty;var Lu=(o,e)=>{for(var r in e)ju(o,r,{get:e[r],enumerable:!0})};function Ar(o){for(var e=1;e"u")){_=Ar({},e,_),typeof _.expires=="number"&&(_.expires=new Date(Date.now()+_.expires*864e5)),_.expires&&(_.expires=_.expires.toUTCString()),f=encodeURIComponent(f).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var p="";for(var y in _)_[y]&&(p+="; "+y,_[y]!==!0&&(p+="="+_[y].split(";")[0]));return document.cookie=f+"="+o.write(u,f)+p}}function i(f){if(!(typeof document>"u"||arguments.length&&!f)){for(var u=document.cookie?document.cookie.split("; "):[],_={},p=0;p{let i=o;return typeof e=="string"||Array.isArray(e)?i=o.toLocaleString(e,r):(e===!0||r!==void 0)&&(i=o.toLocaleString(void 0,r)),i};function an(o,e){if(!Number.isFinite(o))throw new TypeError(`Expected a finite number, got ${typeof o}: ${o}`);e={bits:!1,binary:!1,space:!0,...e};let r=e.bits?e.binary?Vu:Hu:e.binary?Nu:qu,i=e.space?" ":"";if(e.signed&&o===0)return` 0${i}${r[0]}`;let f=o<0,u=f?"-":e.signed?"+":"";f&&(o=-o);let _;if(e.minimumFractionDigits!==void 0&&(_={minimumFractionDigits:e.minimumFractionDigits}),e.maximumFractionDigits!==void 0&&(_={maximumFractionDigits:e.maximumFractionDigits,..._}),o<1){let b=Ko(o,e.locale,_);return u+b+i+r[0]}let p=Math.min(Math.floor(e.binary?Math.log(o)/Math.log(1024):Math.log10(o)/3),r.length-1);o/=(e.binary?1024:1e3)**p,_||(o=o.toPrecision(3));let y=Ko(Number(o),e.locale,_),x=r[p];return u+y+i+x}var Ku=typeof global=="object"&&global&&global.Object===Object&&global,Gr=Ku;var Yu=typeof self=="object"&&self&&self.Object===Object&&self,Ju=Gr||Yu||Function("return this")(),Y=Ju;var Qu=Y.Symbol,ue=Qu;var Yo=Object.prototype,Xu=Yo.hasOwnProperty,Zu=Yo.toString,rr=ue?ue.toStringTag:void 0;function ec(o){var e=Xu.call(o,rr),r=o[rr];try{o[rr]=void 0;var i=!0}catch{}var f=Zu.call(o);return i&&(e?o[rr]=r:delete o[rr]),f}var Jo=ec;var tc=Object.prototype,rc=tc.toString;function ic(o){return rc.call(o)}var Qo=ic;var nc="[object Null]",oc="[object Undefined]",Xo=ue?ue.toStringTag:void 0;function ac(o){return o==null?o===void 0?oc:nc:Xo&&Xo in Object(o)?Jo(o):Qo(o)}var ye=ac;function sc(o){return o!=null&&typeof o=="object"}var ce=sc;var lc="[object Symbol]";function fc(o){return typeof o=="symbol"||ce(o)&&ye(o)==lc}var Cr=fc;function uc(o,e){for(var r=-1,i=o==null?0:o.length,f=Array(i);++r-1&&o%1==0&&o-1&&o%1==0&&o<=i_}var Wr=n_;function o_(o){return o!=null&&Wr(o.length)&&!Er(o)}var Br=o_;var a_=Object.prototype;function s_(o){var e=o&&o.constructor,r=typeof e=="function"&&e.prototype||a_;return o===r}var mt=s_;function l_(o,e){for(var r=-1,i=Array(o);++r-1}var Pa=Td;function Ad(o,e){var r=this.__data__,i=qe(r,o);return i<0?(++this.size,r.push([o,e])):r[i][1]=e,this}var $a=Ad;function kt(o){var e=-1,r=o==null?0:o.length;for(this.clear();++e=e||oe<0||A&&pe>=u}function P(){var j=Yr();if(re(j))return Fe(j);p=setTimeout(P,Q(j))}function Fe(j){return p=void 0,E&&i?J(j):(i=f=void 0,_)}function Oe(){p!==void 0&&clearTimeout(p),x=0,i=y=f=p=void 0}function De(){return p===void 0?_:Fe(Yr())}function de(){var j=Yr(),oe=re(j);if(i=arguments,f=this,y=j,oe){if(p===void 0)return V(y);if(A)return clearTimeout(p),p=setTimeout(P,e),J(y)}return p===void 0&&(p=setTimeout(P,e)),_}return de.cancel=Oe,de.flush=De,de}var at=F7;var O7="Expected a function";function D7(o,e,r){var i=!0,f=!0;if(typeof o!="function")throw new TypeError(O7);return ne(r)&&(i="leading"in r?!!r.leading:i,f="trailing"in r?!!r.trailing:f),at(o,e,{leading:i,maxWait:e,trailing:f})}var st=D7;var W7={"&":"&","<":"<",">":">",""":'"',"'":"'"},B7=Ya(W7),Ps=B7;var $s=/&(?:amp|lt|gt|quot|#39);/g,M7=RegExp($s.source);function U7(o){return o=Ka(o),o&&M7.test(o)?o.replace($s,Ps):o}var dn=U7;var le=class extends DataView{constructor(e,r,i){e instanceof Uint8Array?super(e.buffer,e.byteOffset,e.byteLength):super(e,r,i)}getFourCC(e){return String.fromCharCode(this.getUint8(e),this.getUint8(e+1),this.getUint8(e+2),this.getUint8(e+3))}getUint8Subarray(e,r){return new Uint8Array(this.buffer,this.byteOffset+(e||0),r)}setFourCC(e,r){this.setUint8(e,r.charCodeAt(0)),this.setUint8(e+1,r.charCodeAt(1)),this.setUint8(e+2,r.charCodeAt(2)),this.setUint8(e+3,r.charCodeAt(3))}setUint8Array(e,r){this.getUint8Subarray(e,r.length).set(r)}};function js(o){let e=new Uint8Array(o.length*4),r=new DataView(e.buffer);for(let i=0;if)throw new Error("IFF chunk out of range");this.chunks.push({data:r.getUint8Subarray(i+8,u),offset:i,type:r.getFourCC(i)}),i+=8+u,i%2&&i++}}write(){let e=12;for(let f of this.chunks)e+=8+f.data.length,e%2&&e++;let r=new le(new ArrayBuffer(e));r.setFourCC(0,"FORM"),r.setUint32(4,e-8),r.setFourCC(8,this.type);let i=12;for(let f of this.chunks)r.setFourCC(i,f.type),r.setUint32(i+4,f.data.length),r.setUint8Array(i+8,f.data),i+=8+f.data.length,i%2&&i++;return r.getUint8Subarray()}};var qs={Data:"data",Exec:"exec",Pict:"pict","Snd ":"sound"},Ns="????",Ct=class{constructor(e){this.classname="Blorb";this.chunks={};this.is_inited=!1;this.metadata={};e&&this.init(e)}init(e,r){if(!this.is_inited){if(e instanceof Uint8Array){let i=new ar;if(i.parse(e),i.type!=="IFRS")throw new Error("Not a Blorb file");if(i.chunks[0].type!=="RIdx")throw new Error("Malformed blorb: chunk 1 is not RIdx");for(let f of i.chunks)switch(f.type){case"Dbug":{this.debugdata=f.data;break}case"Fspc":{let u=new le(f.data);this.coverimagenum=u.getUint32(0);break}case"IFmd":{let u=or.decode(f.data),_=/(.+)<\/bibliographic>/is.exec(u),p=/<(\w+)>(.+)<\/\1>/gi,y=//g,x=/\s+/g;if(_){let b;for(;b=p.exec(_[1]);){let A=b[1].toLowerCase(),E=b[2].replace(x," ");A==="description"&&(E=E.replace(y,` +`)),this.metadata[A]=dn(E)}}break}case"RDes":{let u=new le(f.data),_=4;for(;_J.offset===x)[0];if(!b)throw new Error(`No Blorb chunk at offset ${x}`);let A=b.type,E={blorbtype:A,content:A==="FORM"?e.subarray(b.offset,b.offset+8+b.data.length):b.data,usage:qs[p]};p==="Pict"&&(A==="JPEG"?E.type="jpeg":A==="PNG "?E.type="png":E.type=Ns),p==="Data"&&(E.binary=A==="BINA"||A==="FORM"),this.chunks[`${E.usage}:${y}`]=E}break}}}else if(r?.format==="infomap")for(let i in e){if(!Number.isInteger(+i))continue;let f=Object.assign({},e[i]);delete f.image,f.height&&f.width&&(f.imagesize={height:f.height,width:f.width},delete f.height,delete f.width),f.type=f.url.endsWith(".png")?"png":"jpeg",f.usage="pict",this.chunks[`pict:${i}`]=f}else if(!(Array.isArray(e)&&e.length===0))throw new Error("Unsupported Blorb.init data format");this.is_inited=!0}}getlibrary(){return null}get_chunk(e,r){return this.chunks[`${e}:${r}`]||null}get_cover_pict(){return this.coverimagenum??null}get_data_chunk(e){let r=this.chunks[`data:${e}`];return r?.content?{binary:r.binary,data:r.content}:null}get_debug_info(){return this.debugdata}get_exec_data(e){let r=this.chunks["exec:0"];return!r?.content||e&&r.blorbtype!==e?null:r.content}get_image_info(e){let r=this.chunks[`pict:${e}`];if(!r)return null;!r.imagesize&&r.content&&(r.type==="jpeg"?r.imagesize=P7(r.content):r.type==="png"&&(r.imagesize=$7(r.content)));let i=Object.assign({image:e},r);return i.imagesize&&(i.height=i.imagesize.height,i.width=i.imagesize.width),i}get_image_url(e){let r=this.chunks[`pict:${e}`];return r?r.url?r.url:r.type!==Ns&&r.content?(r.url=URL.createObjectURL(new Blob([r.content],{type:`image/${r.type}`})),r.url):null:null}get_metadata(e){return this.metadata[e]}inited(){return this.is_inited}};function P7(o){let e=new le(o),r=0;for(;r=208&&i<=217)continue;let f=e.getUint16(r);if(i>=192&&i<=207&&i!==200)return f<7?void 0:{height:e.getUint16(r+3),width:e.getUint16(r+5)};r+=f}}function $7(o){let e=new le(o);if(e.getFourCC(0)!=="\x89PNG")return;let r=8;for(;reo,evtype_CharInput:()=>Qn,evtype_Hyperlink:()=>ro,evtype_LineInput:()=>Xn,evtype_MouseInput:()=>Zn,evtype_None:()=>li,evtype_Redraw:()=>to,evtype_SoundNotify:()=>K7,evtype_Timer:()=>fi,evtype_VolumeNotify:()=>Y7,filemode_Read:()=>te,filemode_ReadWrite:()=>Se,filemode_Write:()=>be,filemode_WriteAppend:()=>di,fileusage_BinaryMode:()=>u1,fileusage_Data:()=>s1,fileusage_InputRecord:()=>f1,fileusage_SavedGame:()=>_i,fileusage_TextMode:()=>ao,fileusage_Transcript:()=>l1,fileusage_TypeMask:()=>Bt,gestalt_CharInput:()=>bn,gestalt_CharOutput:()=>kn,gestalt_CharOutput_ApproxPrint:()=>L7,gestalt_CharOutput_CannotPrint:()=>j7,gestalt_CharOutput_ExactPrint:()=>xn,gestalt_DateTime:()=>Wn,gestalt_DrawImage:()=>An,gestalt_GarglkText:()=>Un,gestalt_Graphics:()=>Tn,gestalt_GraphicsCharInput:()=>Mn,gestalt_GraphicsTransparency:()=>En,gestalt_HyperlinkInput:()=>Cn,gestalt_Hyperlinks:()=>Gn,gestalt_LineInput:()=>wn,gestalt_LineInputEcho:()=>Fn,gestalt_LineTerminatorKey:()=>Dn,gestalt_LineTerminators:()=>On,gestalt_MouseInput:()=>vn,gestalt_ResourceStream:()=>Bn,gestalt_Sound:()=>z7,gestalt_Sound2:()=>V7,gestalt_SoundMusic:()=>H7,gestalt_SoundNotify:()=>N7,gestalt_SoundVolume:()=>q7,gestalt_Timer:()=>Sn,gestalt_Unicode:()=>In,gestalt_UnicodeNorm:()=>Rn,gestalt_Version:()=>yn,imagealign_InlineCenter:()=>g1,imagealign_InlineDown:()=>m1,imagealign_InlineUp:()=>h1,imagealign_MarginLeft:()=>y1,imagealign_MarginRight:()=>b1,keycode_Delete:()=>qn,keycode_Down:()=>Ln,keycode_End:()=>Yn,keycode_Escape:()=>Et,keycode_Func1:()=>It,keycode_Func10:()=>ai,keycode_Func11:()=>si,keycode_Func12:()=>lt,keycode_Func2:()=>Xr,keycode_Func3:()=>Zr,keycode_Func4:()=>ei,keycode_Func5:()=>ti,keycode_Func6:()=>ri,keycode_Func7:()=>ii,keycode_Func8:()=>ni,keycode_Func9:()=>oi,keycode_Home:()=>Kn,keycode_Left:()=>lr,keycode_MAXVAL:()=>Jn,keycode_PageDown:()=>Vn,keycode_PageUp:()=>Hn,keycode_Return:()=>zn,keycode_Right:()=>$n,keycode_Tab:()=>Nn,keycode_Unknown:()=>Pn,keycode_Up:()=>jn,seekmode_Current:()=>lo,seekmode_End:()=>ut,seekmode_Start:()=>so,style_Alert:()=>t1,style_BlockQuote:()=>i1,style_Emphasized:()=>Q7,style_Header:()=>Z7,style_Input:()=>n1,style_NUMSTYLES:()=>ui,style_Normal:()=>J7,style_Note:()=>r1,style_Preformatted:()=>X7,style_Subheader:()=>e1,style_User1:()=>o1,style_User2:()=>a1,stylehint_BackColor:()=>go,stylehint_Indentation:()=>fo,stylehint_Justification:()=>cr,stylehint_NUMHINTS:()=>bo,stylehint_Oblique:()=>po,stylehint_ParaIndentation:()=>uo,stylehint_Proportional:()=>ho,stylehint_ReverseColor:()=>yo,stylehint_Size:()=>co,stylehint_TextColor:()=>mo,stylehint_Weight:()=>_o,stylehint_just_Centered:()=>d1,stylehint_just_LeftFlush:()=>c1,stylehint_just_LeftRight:()=>_1,stylehint_just_RightFlush:()=>p1,winmethod_Above:()=>Ot,winmethod_Below:()=>io,winmethod_Border:()=>no,winmethod_BorderMask:()=>ft,winmethod_DirMask:()=>Dt,winmethod_DivisionMask:()=>Wt,winmethod_Fixed:()=>Je,winmethod_Left:()=>Ye,winmethod_NoBorder:()=>oo,winmethod_Proportional:()=>ci,winmethod_Right:()=>Ft,wintype_AllTypes:()=>fr,wintype_Blank:()=>Rt,wintype_Graphics:()=>Ke,wintype_Pair:()=>ur,wintype_TextBuffer:()=>ve,wintype_TextGrid:()=>Ie,zcolor_Current:()=>hi,zcolor_Default:()=>pi});var yn=0,bn=1,wn=2,kn=3,j7=0,L7=1,xn=2,vn=4,Sn=5,Tn=6,An=7,z7=8,q7=9,N7=10,Gn=11,Cn=12,H7=13,En=14,In=15,Rn=16,Fn=17,On=18,Dn=19,Wn=20,V7=21,Bn=22,Mn=23,Un=4352,Pn=4294967295,lr=4294967294,$n=4294967293,jn=4294967292,Ln=4294967291,zn=4294967290,qn=4294967289,Et=4294967288,Nn=4294967287,Hn=4294967286,Vn=4294967285,Kn=4294967284,Yn=4294967283,It=4294967279,Xr=4294967278,Zr=4294967277,ei=4294967276,ti=4294967275,ri=4294967274,ii=4294967273,ni=4294967272,oi=4294967271,ai=4294967270,si=4294967269,lt=4294967268,Jn=28,li=0,fi=1,Qn=2,Xn=3,Zn=4,eo=5,to=6,K7=7,ro=8,Y7=9,J7=0,Q7=1,X7=2,Z7=3,e1=4,t1=5,r1=6,i1=7,n1=8,o1=9,a1=10,ui=11,fr=0,ur=1,Rt=2,ve=3,Ie=4,Ke=5,Ye=0,Ft=1,Ot=2,io=3,Dt=15,Je=16,ci=32,Wt=240,no=0,oo=256,ft=256,s1=0,_i=1,l1=2,f1=3,Bt=15,ao=256,u1=0,be=1,te=2,Se=3,di=5,so=0,lo=1,ut=2,fo=0,uo=1,cr=2,co=3,_o=4,po=5,ho=6,mo=7,go=8,yo=9,bo=10,c1=0,_1=1,d1=2,p1=3,h1=1,m1=2,g1=3,y1=4,b1=5,pi=-1,hi=-2;var mi=class{constructor(e,r,i){this.binary=r,this.buf=e,this.fref=i,this.uni=Gt(e)}convert(){if(this.uni){if(this.binary)return js(this.buf);{let e=String.fromCodePoint(...this.buf);return zs.encode(e)}}else return this.buf.slice()}},gi=class{constructor(e){this.cache={};this.classname="CachingDialogWrapper";this.streaming=!1;this.write=at(()=>{for(let e in this.cache){let r=this.cache[e];if(this.Dialog.streaming){let i=this.Dialog.file_fopen(1,r.fref);i.fwrite(r.convert()),i.fclose()}else this.Dialog.file_write(r.fref,r.convert())}this.cache={}},0);this.Dialog=e}init(e){}file_ref_exists(e){return!!this.cache[e.filename]||this.Dialog.file_ref_exists(e)}file_read(e){if(this.cache[e.filename])return this.cache[e.filename].convert();if(this.Dialog.streaming){let r=this.Dialog.file_fopen(2,e);if(!r)return null;r.fseek(0,2);let i=r.ftell(),f=new Uint8Array(i);return r.fseek(0,0),r.fread(f),r.fclose(),f}else return this.Dialog.file_read(e)}file_remove_ref(e){this.cache[e.filename]&&delete this.cache[e.filename],this.Dialog.file_remove_ref(e)}file_write(e,r){throw new Error("CachingDialogWrapper.write_file should be called instead")}inited(){return!0}write_file(e,r){return this.cache[e.filename]=r,this.write(),!0}autosave_read(e){return this.Dialog.autosave_read(e)}autosave_write(e,r){this.Dialog.autosave_write(e,r)}file_clean_fixed_name(e,r){return this.Dialog.file_clean_fixed_name(e,r)}file_construct_ref(e,r,i){return this.Dialog.file_construct_ref(e,r,i)}file_construct_temp_ref(e){return this.Dialog.file_construct_temp_ref(e)}getlibrary(e){return this.Dialog.getlibrary(e)}open(e,r,i,f){this.Dialog.open(e,r,i,f)}};function _r(o,e,r){let i=Math.min(r,e.length);for(let f=0;fQe?Xe:u}else r.set(this.buf.subarray(this.pos,this.pos+i));return this.pos+=i,this.read_count+=i,i}get_char(r){if(this.posQe?Xe:i}return-1}get_line(r){let i=Math.min(r.length-1,this.len-this.pos);if(i<0)return 0;let f=!Gt(r)&&this.uni,u=0;for(;uQe?Xe:_,_===10)break}return r[u]=Ks,this.read_count+=u,u}get_position(){return this.pos}put_buffer(r,i){let f=r.length;this.write_count+=f,this.pos+f>this.len&&this.expandable&&this.expand(f);let u=Math.min(f,this.len-this.pos);if(u!==0){if(i&&!this.uni)for(let _=0;_Qe?Xe:p}else Array.isArray(r)&&(r=(i?Uint32Array:Uint8Array).from(r)),this.buf.set(r.subarray(0,u),this.pos);this.pos+=u,this.write()}}put_char(r){this.write_count++,this.pos===this.len&&this.expandable&&this.expand(1),this.posQe?Xe:r,this.write())}put_string(r){this.put_buffer(Uint32Array.from(r,i=>i.codePointAt(0)),!0)}set_position(r,i){r===1?this.pos+=i:r===2?this.pos=this.len+i:this.pos=i,this.pos<0&&(this.pos=0),this.pos>this.len&&(this.pos=this.len)}write(){}},ki=class extends Ze{constructor(e,r,i,f){super(r,i,f),this.expandable=!0,this.fref=e}expand(e){let r=this.pos+e;this.len=r;let i=this.buf.length;if(r>i){i+=Math.max(r-i,100);let f=this.buf;this.buf=new(this.uni?Uint32Array:Uint8Array)(i),this.buf.set(f)}}write(){this.fref.write(this.buf.subarray(0,this.len))}},xi=class extends pr{constructor(){super(...arguments);this.type="null"}put_buffer(r,i){this.write_count+=r.length}put_char(r){this.write_count++}put_string(r,i){this.write_count+=[...r].length}},vi=class extends pr{constructor(r){super(1,0);this.type="window";this.win=r}put_buffer(r,i){if(this.win.input.type==="line")throw new Error("Window has pending line request");this.write_count+=r.length,this.win.put_string(String.fromCodePoint(...r)),this.win.echostr?.put_buffer(r,i)}put_char(r){if(this.win.input.type==="line")throw new Error("Window has pending line request");this.write_count++,this.win.put_string(String.fromCodePoint(r)),this.win.echostr?.put_char(r)}put_string(r,i){if(this.win.input.type==="line")throw new Error("Window has pending line request");this.write_count+=[...r].length,this.win.put_string(r,i),this.win.echostr?.put_string(r,i)}set_css(r,i){this.win.set_css(r,i),this.win.echostr?.type==="window"&&this.win.echostr.set_css(r,i)}set_hyperlink(r){this.win.set_hyperlink(r),this.win.echostr?.type==="window"&&this.win.echostr.set_hyperlink(r)}set_style(r){this.win.set_style(r),this.win.echostr?.type==="window"&&this.win.echostr.set_style(r)}};var Ut=class{constructor(e){this.box={bottom:0,left:0,right:0,top:0};this.disprock=0;this.echostr=null;this.input={id:0};this.next=null;this.parent=null;this.prev=null;this.rock=e,this.str=new vi(this)}clear(){}put_string(e,r){}set_css(e,r){}set_hyperlink(e){}set_style(e){}update(){if(this.type==="blank"||this.type==="pair")return{content:null,input:null,size:null};let e={id:this.input.id};Mt(this.input,e,"hyperlink"),Mt(this.input,e,"mouse");let r=this.box;return{content:null,input:e,size:{height:r.bottom-r.top,id:this.disprock,left:r.left,rock:this.rock,top:r.top,type:this.type,width:r.right-r.left}}}},Si=class extends Ut{constructor(){super(...arguments);this.type="blank";this.typenum=2}},Ti=class extends Ut{constructor(r,i){super(r);this.cleared=!0;this.request_echo_line_input=!0;this.stylehints=nr(i)}update(){let r=super.update();Object.keys(this.stylehints).length&&(r.size.styles=this.stylehints);let i=this.input,f=r.input;return i.type&&(Mt(i,f,"gen"),Mt(i,f,"type"),i.type==="line"&&(f.maxlen=this.line_input_buf.length,Mt(i,f,"initial"),Mt(i,f,"terminators"))),delete i.initial,r}},Ai=class extends Ti{constructor(r,i){super(r,i);this.echo_line_input=!0;this.last_textrun=fe(Ii,!0);this.type="buffer";this.typenum=3;this.last_textrun=fe(Ii,!0),this.content=[{content:[this.last_textrun]}],this.last_par=this.content[0]}clear(){this.cleared=!0,this.clear_content()}clear_content(){this.last_textrun=fe(this.last_textrun,!1),this.content=[{append:!0,content:[this.last_textrun]}],this.last_par=this.content[0]}clone_textrun(r,i){(i||this.last_textrun.text!=="")&&(this.last_textrun=fe(this.last_textrun,r),this.last_par.content.push(this.last_textrun))}put_image(r){r.hyperlink=this.last_textrun.hyperlink,this.last_par.content.push(r),this.clone_textrun(!1,!0)}put_string(r,i){let f=this.last_textrun.style;i&&this.set_style(i);for(let[u,_]of r.split(` `).entries())u!==0&&(this.last_textrun=fe(this.last_textrun,!1),this.last_par={content:[this.last_textrun]},this.content.push(this.last_par)),this.last_textrun.text+=_;i&&this.set_style(f)}set_css(r,i){this.last_textrun.css_styles[r]!==i&&(this.clone_textrun(!0),i===void 0?delete this.last_textrun.css_styles[r]:this.last_textrun.css_styles[r]=i)}set_flow_break(){this.last_par.flowbreak=!0}set_hyperlink(r){r===0&&(r=void 0),r!==this.last_textrun.hyperlink&&(this.clone_textrun(!1),r?this.last_textrun.hyperlink=r:delete this.last_textrun.hyperlink)}set_style(r){r!==this.last_textrun.style&&(this.clone_textrun(!1),this.last_textrun.style=r)}update(){let r=super.update();this.last_textrun=fe(this.last_textrun,!1);let i=this.content;for(let f of i)f.content=Zs(f.content.filter(u=>"special"in u||u.text));return(this.cleared||i.length>1||i[0].content.length)&&(r.content={id:this.disprock,text:i.map(f=>f.append||f.flowbreak||f.content.length?f:{})},this.cleared&&(r.content.clear=!0,this.cleared=!1)),this.clear_content(),r}},Gi=class extends Ut{constructor(){super(...arguments);this.draw=[];this.height=0;this.type="graphics";this.typenum=5;this.width=0}clear(){this.draw=this.draw.filter(r=>r.special==="setcolor").slice(-1),this.draw.push({special:"fill"})}update(){let r=super.update();return this.draw.length&&(r.content={draw:this.draw,id:this.disprock},this.draw=[]),r.size.graphheight=this.height,r.size.graphwidth=this.width,r}},Ci=class extends Ti{constructor(){super(...arguments);this.current_styles=fe(Ii,!0);this.height=0;this.lines=[];this.type="grid";this.typenum=4;this.width=0;this.x=0;this.y=0}clear(){this.cleared=!0;let r=this.height;this.update_size(0,this.width),this.update_size(r,this.width),this.x=this.y=0}fit_cursor(){if(this.x>=this.width&&(this.x=0,this.y++),this.y>=this.height)return!0}put_string(r,i){let f=this.current_styles.style;i&&this.set_style(i);for(let u of r){if(this.fit_cursor())break;if(u===` -`){this.x=0,this.y++;continue}let _=this.lines[this.y];_.changed=!0,_.content[this.x++]=fe(this.current_styles,!1,u)}i&&this.set_style(f)}set_css(r,i){this.current_styles.css_styles[r]!==i&&(this.current_styles=fe(this.current_styles,!0),i===void 0?delete this.current_styles.css_styles[r]:this.current_styles.css_styles[r]=i)}set_hyperlink(r){r?this.current_styles.hyperlink=r:delete this.current_styles.hyperlink}set_style(r){this.current_styles.style=r}update_size(r,i){let f=this.height,u=this.width;this.height=r,this.width=i;let _=fe(Ii,!0," ");if(f>r)this.lines.length=r;else if(r>f)for(let y=f;yi.changed)&&(r.content={id:this.disprock,lines:this.lines.flatMap((i,f)=>i.changed?(i.changed=!1,{content:Zs(i.content.reduce((u,_)=>{if(!u.length)return[fe(_,!1,_.text)];let p=u[u.length-1];return _.css_styles===p.css_styles&&_.hyperlink===p.hyperlink&&_.style===p.style?p.text+=_.text:u.push(fe(_,!1,_.text)),u},[])),line:f}):[])},this.cleared&&(r.content.clear=!0,this.cleared=!1)),this.input.type){let i=r.input;this.fit_cursor()?(i.xpos=this.width-1,i.ypos=this.height-1):(i.xpos=this.x,i.ypos=this.y)}return r.size.gridheight=this.height,r.size.gridwidth=this.width,r}},Ei=class extends Ut{constructor(r,i,f){super(0);this.child1=null;this.child2=null;this.type="pair";this.typenum=1;this.border=(i&256)===256,this.dir=i&15,this.fixed=(i&240)===16,this.key=r,this.size=f,this.backward=this.dir===0||this.dir===2,this.vertical=this.dir===0||this.dir===1}},Ii={css_styles:{},style:"normal",text:""};function Zs(a){return a.map(e=>("special"in e||Object.keys(e.css_styles).length||delete e.css_styles,e))}function fe(a,e,r=""){return Object.assign({},a,{css_styles:e?Object.assign({},a.css_styles):a.css_styles,text:r})}function Mt(a,e,r){a[r]&&(e[r]=a[r])}var Oi=class{constructor(){this.value=0}get_value(){return this.value}set_value(e){this.value=e}},Di=class{constructor(){this.fields=[]}get_field(e){return this.fields[e]}get_fields(){return this.fields}push_field(e){this.fields.push(e)}set_field(e,r){this.fields[e]=r}},gr=class{constructor(){this.Dialog=null;this.GlkOte=null;this.VM=null;this.disprock_counter=1;this.do_autosave=!1;this.exited=!1;this.first_fref=null;this.gen=0;this.metrics=sr;this.current_stream=null;this.first_stream=null;this.stylehints={buffer:{},grid:{}};this.support=[];this.timer={interval:0,last_interval:0,started:0};this.version=Qr;this.first_window=null;this.root_window=null;this.windows_changed=!1;this.Const=wo;this.DidNotReturn=dr;this.RefBox=Oi;this.RefStruct=Di}init(e){if(this.before_select_hook=e.before_select_hook,this.Blorb=e.Blorb,e.Dialog)this.Dialog=new gi(e.Dialog);else throw new Error("No reference to Dialog");if(this.do_autosave=!!e.do_vm_autosave,this.GiDispa=e.GiDispa,this.gestalt_hook=e.glk_gestalt_hook,e.GlkOte)this.GlkOte=e.GlkOte;else throw new Error("No reference to GlkOte");if(e.vm)this.VM=e.vm;else throw new Error("No reference to VM");this.before_select_hook?.(),this.GiDispa?.init({io:this,vm:this.VM});let r=e;r.accept=this.accept.bind(this),this.GlkOte.init(r)}call_may_not_return(e){return e===1||e===192||e===98}fatal_error(e){if(this.exited=!0,!this.GlkOte){console.error("Fatal error: "+e);return}this.GlkOte.error(e),this.GlkOte.update({type:"update",disable:!0,gen:this.gen})}getlibrary(e){switch(e){case"Blorb":return this.Blorb||null;case"Dialog":return this.Dialog;case"GiDispa":return this.GiDispa||null;case"GlkOte":return this.GlkOte;case"VM":return this.VM;default:return null}}inited(){return!!(this.GlkOte&&this.VM)}restore_allstate(e){throw new Error("Autosaves not yet supported")}save_allstate(){throw new Error("Autosaves not yet supported")}update(){let e={gen:this.gen,type:"update"};this.exited&&(e.disable=!0);let r=[],i=[],f=[];for(let _=this.first_window;_;_=_.next){let p=_.update();if(p.content&&r.push(p.content),p.input){let y=p.input;(y.hyperlink||y.mouse||y.type)&&i.push(y)}this.windows_changed&&p.size&&f.push(p.size)}r.length&&(e.content=r),i.length&&(e.input=i),f.length&&(e.windows=f),this.windows_changed=!1,this.special&&(e.specialinput=this.special,delete this.special);let u=this.timer;u.last_interval!==u.interval&&(e.timer=u.interval||null,u.last_interval=u.interval),this.GlkOte.update(nr(e)),this.before_select_hook?.()}byte_array_to_string(e){return String.fromCodePoint(...e)}glk_put_jstring(e,r){this.glk_put_jstring_stream(this.current_stream,e)}glk_put_jstring_stream(e,r,i){if(!e)throw new Error("Invalid Stream");e.put_string(r)}uni_array_to_string(e){return String.fromCodePoint(...e)}glk_buffer_canon_decompose_uni(e,r){return hr(e,r,i=>i.normalize("NFD"))}glk_buffer_canon_normalize_uni(e,r){return hr(e,r,i=>i.normalize("NFC"))}glk_buffer_to_lower_case_uni(e,r){return hr(e,r,i=>i.toLowerCase())}glk_buffer_to_title_case_uni(e,r,i){return hr(e,r,f=>f.reduce((u,_,p)=>{let y={\u00DF:"Ss",\u01C4:"\u01C5",\u01C5:"\u01C5",\u01C6:"\u01C5",\u01C7:"\u01C8",\u01C8:"\u01C8",\u01C9:"\u01C8",\u01CA:"\u01CB",\u01CB:"\u01CB",\u01CC:"\u01CB",\u01F1:"\u01F2",\u01F2:"\u01F2",\u01F3:"\u01F2",\u0587:"\u0535\u0582",\u1FB2:"\u1FBA\u0345",\u1FB3:"\u1FBC",\u1FB4:"\u0386\u0345",\u1FB7:"\u0391\u0342\u0345",\u1FBC:"\u1FBC",\u1FC2:"\u1FCA\u0345",\u1FC3:"\u1FCC",\u1FC4:"\u0389\u0345",\u1FC7:"\u0397\u0342\u0345",\u1FCC:"\u1FCC",\u1FF2:"\u1FFA\u0345",\u1FF3:"\u1FFC",\u1FF4:"\u038F\u0345",\u1FF7:"\u03A9\u0342\u0345",\u1FFC:"\u1FFC",\uFB00:"Ff",\uFB01:"Fi",\uFB02:"Fl",\uFB03:"Ffi",\uFB04:"Ffl",\uFB05:"St",\uFB06:"St",\uFB13:"\u0544\u0576",\uFB14:"\u0544\u0565",\uFB15:"\u0544\u056B",\uFB16:"\u054E\u0576",\uFB17:"\u0544\u056D"},x=["\u1F88\u1F89\u1F8A\u1F8B\u1F8C\u1F8D\u1F8E\u1F8F","\u1F98\u1F99\u1F9A\u1F9B\u1F9C\u1F9D\u1F9E\u1F9F","\u1FA8\u1FA9\u1FAA\u1FAB\u1FAC\u1FAD\u1FAE\u1FAF"],b=String.fromCodePoint(_);return p===0?y[b]?b=y[b]:_>=8064&&_<8112?b=x[(_-8064)/16|0][_%8]:b=b.toUpperCase():i&&(b=b.toLowerCase()),u+b},""),!0)}glk_buffer_to_upper_case_uni(e,r){return hr(e,r,i=>i.toUpperCase())}glk_cancel_char_event(e){if(!e)throw new Error("Invalid Window");delete e.input.type}glk_cancel_hyperlink_event(e){if(!e)throw new Error("Invalid Window");(e.type==="buffer"||e.type==="grid")&&delete e.input.hyperlink}glk_cancel_line_event(e,r){if(!e)throw new Error("Invalid Window");if(e.input.type!=="line"){r&&Ri(r);return}this.handle_line_input(e,this.partial_inputs?.[e.disprock]??"",r)}glk_cancel_mouse_event(e){if(!e)throw new Error("Invalid Window");(e.type==="graphics"||e.type==="grid")&&delete e.input.mouse}glk_char_to_lower(e){return e>=65&&e<=90||e>=192&&e<=222&&e!==215?e+32:e}glk_char_to_upper(e){return e>=97&&e<=122||e>=224&&e<=254&&e!==247?e-32:e}glk_current_simple_time(e){return Math.floor(Date.now()/(e*1e3))}glk_current_time(e){vo(Date.now(),e)}glk_date_to_simple_time_local(e,r){return Math.floor(tl(e)/(r*1e3))}glk_date_to_simple_time_utc(e,r){return Math.floor(rl(e)/(r*1e3))}glk_date_to_time_local(e,r){vo(tl(e),r)}glk_date_to_time_utc(e,r){vo(rl(e),r)}glk_exit(){return this.exited=!0,dr}glk_fileref_create_by_name(e,r,i){let f=this.Dialog.file_clean_fixed_name(r,e&15);return this.create_fileref(f,i,e)}glk_fileref_create_by_prompt(e,r,i){let f=Ys[r]??"read",u=e&15,_=bi[u]??"data";return this.special={filemode:f,filetype:_,type:"fileref_prompt"},u===1&&(this.special.gameid=this.VM.get_signature()),this.special_data={rock:i,usage:e},dr}glk_fileref_create_from_fileref(e,r,i){if(!r)throw new Error("Invalid Fileref");return this.create_fileref(r.filename,i,e)}glk_fileref_create_temp(e,r){let i=bi[e&15],f=this.Dialog.file_construct_temp_ref(i);return this.create_fileref(f.filename,r,e,f)}glk_fileref_delete_file(e){if(!e)throw new Error("Invalid Fileref");e.delete_file()}glk_fileref_destroy(e){if(!e)throw new Error("Invalid Fileref");this.GiDispa?.class_unregister("fileref",e);let r=e.prev,i=e.next;e.prev=null,e.next=null,r?r.next=i:this.first_fref=i,i&&(i.prev=r)}glk_fileref_does_file_exist(e){if(!e)throw new Error("Invalid Fileref");return e.exists()}glk_fileref_get_rock(e){if(!e)throw new Error("Invalid Fileref");return e.rock}glk_fileref_iterate(e,r){let i=e?e.next:this.first_fref;return r&&r.set_value(i?i.rock:0),i}glk_gestalt(e,r){return this.glk_gestalt_ext(e,r,null)}glk_gestalt_ext(e,r,i){let f=this.gestalt_hook?.(e,r,i);if(f)return f;switch(e){case 0:return 1797;case 1:return r<=4294967294&&r>=4294967268?1:r>=4294967296-28||r>1114111||r>=0&&r<32||r>=127&&r<160?0:1;case 2:return r>1114111||r>=0&&r<32||r>=127&&r<160?0:1;case 3:return i&&(i[0]=1),2;case 19:return+(r===4294967288||r>=4294967268&&r<=4294967279);case 7:return+((r===5||r===3)&&this.support.includes("graphics"));case 4352:return+this.support.includes("garglktext");case 6:case 23:case 14:return+this.support.includes("graphics");case 11:return+this.support.includes("hyperlinks");case 12:return+((r===3||r===4)&&this.support.includes("hyperlinks"));case 4:return+((r===5||r===4)&&this.support.includes("graphics"));case 5:return+this.support.includes("timer");case 20:case 17:case 18:case 22:case 15:case 16:return 1;default:return 0}}glk_get_buffer_stream(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return Array.isArray(r)?Fi(r,Uint8Array,i=>e.get_buffer(i)):e.get_buffer(r)}glk_get_buffer_stream_uni(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return Array.isArray(r)?Fi(r,Uint32Array,i=>e.get_buffer(i)):e.get_buffer(r)}glk_get_char_stream(e){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return e.get_char(!1)}glk_get_char_stream_uni(e){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return e.get_char(!0)}glk_get_line_stream(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return Array.isArray(r)?Fi(r,Uint8Array,i=>e.get_line(i)+1)-1:e.get_line(r)}glk_get_line_stream_uni(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return Array.isArray(r)?Fi(r,Uint32Array,i=>e.get_line(i)+1)-1:e.get_line(r)}glk_image_draw(e,r,i,f){let u=this.Blorb?.get_image_info(r);return u?(this.draw_image(e,u,u.height||0,i,f,u.width||0),1):0}glk_image_draw_scaled(e,r,i,f,u,_){let p=this.Blorb?.get_image_info(r);return p?(this.draw_image(e,p,_||0,i,f,u||0),1):0}glk_image_get_info(e,r,i){let f=this.Blorb?.get_image_info(e);return i&&i.set_value(f?.height||0),r&&r.set_value(f?.width||0),f?1:0}glk_put_buffer(e){this.glk_put_buffer_stream(this.current_stream,e)}glk_put_buffer_stream(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode===2)throw new Error("Cannot write to read-only stream");e.put_buffer(r,!1)}glk_put_buffer_stream_uni(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode===2)throw new Error("Cannot write to read-only stream");e.put_buffer(r,!0)}glk_put_buffer_uni(e){this.glk_put_buffer_stream_uni(this.current_stream,e)}glk_put_char(e){this.glk_put_char_stream(this.current_stream,e)}glk_put_char_stream(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode===2)throw new Error("Cannot write to read-only stream");e.put_char(r)}glk_put_char_stream_uni(e,r){this.glk_put_char_stream(e,r)}glk_put_char_uni(e){this.glk_put_char_stream(this.current_stream,e)}glk_put_string(e){this.glk_put_string_stream(this.current_stream,e)}glk_put_string_stream(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode===2)throw new Error("Cannot write to read-only stream");e.put_string(r)}glk_put_string_stream_uni(e,r){this.glk_put_string_stream(e,r)}glk_put_string_uni(e){this.glk_put_string_stream(this.current_stream,e)}glk_request_char_event(e){this.request_char_event(e,!1)}glk_request_char_event_uni(e){this.request_char_event(e,!0)}glk_request_hyperlink_event(e){if(!e)throw new Error("Invalid Window");(e.type==="buffer"||e.type==="grid")&&(e.input.hyperlink=!0)}glk_request_line_event(e,r,i){this.request_line_event(e,r,!1,i)}glk_request_line_event_uni(e,r,i){this.request_line_event(e,r,!0,i)}glk_request_mouse_event(e){if(!e)throw new Error("Invalid Window");(e.type==="graphics"||e.type==="grid")&&(e.input.mouse=!0)}glk_request_timer_events(e){this.timer.interval=e,this.timer.started=e?Date.now():0}glk_schannel_create(e){return null}glk_schannel_create_ext(e,r){return null}glk_schannel_destroy(e){throw new Error("Invalid Schannel")}glk_schannel_get_rock(e){throw new Error("Invalid Schannel")}glk_schannel_iterate(e,r){return r&&r.set_value(0),null}glk_schannel_pause(e){throw new Error("Invalid Schannel")}glk_schannel_play(e,r){throw new Error("Invalid Schannel")}glk_schannel_play_ext(e,r,i,f){throw new Error("Invalid Schannel")}glk_schannel_play_multi(e,r,i){throw new Error("Invalid Schannel")}glk_schannel_set_volume(e,r){throw new Error("Invalid Schannel")}glk_schannel_set_volume_ext(e,r,i,f){throw new Error("Invalid Schannel")}glk_schannel_stop(e){throw new Error("Invalid Schannel")}glk_schannel_unpause(e){throw new Error("Invalid Schannel")}glk_select(e){return this.selectref=e,dr}glk_select_poll(e){Ri(e);let r=this.timer;if(r.interval){let i=Date.now();i-r.started>r.interval&&(r.last_interval=0,r.started=i,e.set_field(0,1))}}glk_set_echo_line_event(e,r){if(!e)throw new Error("Invalid Window");e.type==="buffer"&&(e.echo_line_input=!!r)}glk_set_hyperlink(e){this.glk_set_hyperlink_stream(this.current_stream,e)}glk_set_hyperlink_stream(e,r){if(!e)throw new Error("Invalid Stream");e.type==="window"&&e.set_hyperlink(r)}glk_set_style(e){this.glk_set_style_stream(this.current_stream,e)}glk_set_style_stream(e,r){if(!e)throw new Error("Invalid Stream");e.type==="window"&&((r<0||r>11)&&(r=0),e.set_style(wi[r]))}glk_set_terminators_line_event(e,r){if(!e)throw new Error("Invalid Window");let i=[];if(r)for(let f of r)xo[f]&&i.push(xo[f]);i.length?e.input.terminators=i:delete e.input.terminators}glk_set_window(e){this.current_stream=e?e.str:null}glk_sound_load_hint(e,r){}glk_stream_close(e,r){if(!e)throw new Error("Invalid Stream");e.close(r),this.unregister_stream(e)}glk_stream_get_current(){return this.current_stream}glk_stream_get_position(e){if(!e)throw new Error("Invalid Stream");return e.get_position()}glk_stream_get_rock(e){if(!e)throw new Error("Invalid Stream");return e.rock}glk_stream_iterate(e,r){let i=e?e.next:this.first_stream;return r&&r.set_value(i?i.rock:0),i}glk_stream_open_file(e,r,i){return this.create_file_stream(e,r,i,!1)}glk_stream_open_file_uni(e,r,i){return this.create_file_stream(e,r,i,!0)}glk_stream_open_memory(e,r,i){return this.create_memory_stream(e,r,i,Uint8Array)}glk_stream_open_memory_uni(e,r,i){return this.create_memory_stream(e,r,i,Uint32Array)}glk_stream_open_resource(e,r){return this.create_resource_stream(e,r,!1)}glk_stream_open_resource_uni(e,r){return this.create_resource_stream(e,r,!0)}glk_stream_set_current(e){this.current_stream=e}glk_stream_set_position(e,r,i){if(!e)throw new Error("Invalid Stream");e.set_position(i,r)}glk_style_distinguish(e,r,i){return 0}glk_style_measure(e,r,i,f){return f&&f.set_value(0),0}glk_stylehint_clear(e,r,i){let f=`.Style_${wi[r]}${i<=2?"_par":""}`;function u(_){_[f]&&(delete _[f][ko[i]],Object.keys(_[f]).length||delete _[f])}(e===0||e===3)&&u(this.stylehints.buffer),(e===0||e===4)&&u(this.stylehints.grid)}glk_stylehint_set(e,r,i,f){if(r<0||r>=11||i<0||i>=10)return;if(e===0){this.glk_stylehint_set(3,r,i,f),this.glk_stylehint_set(4,r,i,f);return}if(e===2||e===5||e===1)return;let u=e===3?this.stylehints.buffer:this.stylehints.grid,_=`.Style_${wi[r]}${i<=2?"_par":""}`,p=["left","justify","center","right"],y=["lighter","normal","bold"],x;(i===0||i===1)&&(x=f+"em"),i===2&&(x=p[f]),i===3&&(x=1+f*.1+"em"),i===4&&(x=y[f+1]),i===5&&(x=f?"italic":"normal"),i===6&&(x=f?0:1),(i===7||i===8)&&(x=mr(f)),i===9&&(x=f),x!==void 0&&(u[_]||(u[_]={}),u[_][ko[i]]=x)}glk_tick(){}glk_simple_time_to_date_local(e,r,i){nl(e*1e3*r,i)}glk_simple_time_to_date_utc(e,r,i){ol(e*1e3*r,i)}glk_time_to_date_local(e,r){nl(al(e),r)}glk_time_to_date_utc(e,r){ol(al(e),r)}glk_window_clear(e){if(!e)throw new Error("Invalid Window");if(e.input.type==="line")throw new Error("Window has pending line input");e.clear()}glk_window_close(e,r){if(!e)throw new Error("Invalid Window");if(e.str.close(r),e===this.root_window)this.root_window=null,this.remove_window(e,!0);else{let i=e.parent,f=i.child1===e?i.child2:i.child1,u=i.parent;u?(u.child1===i?u.child1=f:u.child2=f,f.parent=u):(this.root_window=f,f.parent=null),this.remove_window(e,!0),this.remove_window(i,!1),this.rearrange_window(f,i.box)}}glk_window_erase_rect(e,r,i,f,u){if(!e)throw new Error("Invalid Window");if(e.type!=="graphics")throw new Error("Invalid Window: not a graphics window");e.draw.push({height:u,special:"fill",width:f,x:r,y:i})}glk_window_fill_rect(e,r,i,f,u,_){if(!e)throw new Error("Invalid Window");if(e.type!=="graphics")throw new Error("Invalid Window: not a graphics window");e.draw.push({color:mr(r),height:_,special:"fill",width:u,x:i,y:f})}glk_window_flow_break(e){if(!e)throw new Error("Invalid Window");e.type==="buffer"&&e.set_flow_break()}glk_window_get_arrangement(e,r,i,f){if(!e)throw new Error("Invalid Window");if(e.type!=="pair")throw new Error("Invalid Window: not a pair window");f&&f?.set_value(e.key),r&&r?.set_value(e.dir|(e.fixed?16:32)|(e.border?0:256)),i&&i?.set_value(e.size)}glk_window_get_echo_stream(e){if(!e)throw new Error("Invalid Window");return e.echostr}glk_window_get_parent(e){if(!e)throw new Error("Invalid Window");return e.parent}glk_window_get_rock(e){if(!e)throw new Error("Invalid Window");return e.rock}glk_window_get_root(){return this.root_window}glk_window_get_sibling(e){if(!e)throw new Error("Invalid Window");let r=e.parent;return r?r.child1===e?r.child2:r.child1:null}glk_window_get_size(e,r,i){if(!e)throw new Error("Invalid Window");let f=this.metrics,u=0,_=0;switch(e.type){case"buffer":u=Pt((e.box.bottom-e.box.top-f.buffermarginy)/f.buffercharheight),_=Pt((e.box.right-e.box.left-f.buffermarginx)/f.buffercharwidth);break;case"graphics":case"grid":u=e.height,_=e.width;break}i&&i?.set_value(u),r&&r?.set_value(_)}glk_window_get_stream(e){if(!e)throw new Error("Invalid Window");return e.str}glk_window_get_type(e){if(!e)throw new Error("Invalid Window");return e.typenum}glk_window_iterate(e,r){let i=e?e.next:this.first_window;return r&&r?.set_value(i?i.rock:0),i}glk_window_move_cursor(e,r,i){if(!e)throw new Error("Invalid Window");if(e.type!=="grid")throw new Error("Invalid Window: not a grid window");e.x=Math.max(0,r),e.y=Math.max(0,i)}glk_window_open(e,r,i,f,u){if(this.root_window){if(!e)throw new Error("Invalid splitwin");if(e.type==="pair")throw new Error("Invalid splitwin: must not be a pair window");let p=r&240,y=r&15;if(p!==16&&p!==32)throw new Error("Invalid method: must be fixed or proportional");if(p===16&&e.type==="blank")throw new Error("Invalid method: blank windows cannot be only be split proportionally");if(y!==2&&y!==3&&y!==0&&y!==1)throw new Error("Invalid method: bad direction")}else if(e)throw new Error("Invalid splitwin: must be null for first window");let _;switch(f){case 2:_=new Si(u);break;case 5:_=new Gi(u);break;case 3:_=new Ai(u,this.stylehints.buffer);break;case 4:_=new Ci(u,this.stylehints.grid);break;default:throw new Error("Invalid wintype")}if(this.register_window(_),e){let p=new Ei(_,r,i);this.register_window(p),p.child1=e,p.child2=_;let y=e.parent;e.parent=p,_.parent=p,p.parent=y,y?y.child1===e?y.child1=p:y.child2=p:this.root_window=p,this.rearrange_window(p,e.box)}else this.root_window=_,this.rearrange_window(_,{bottom:this.metrics.height,left:0,right:this.metrics.width,top:0});return _}glk_window_set_arrangement(e,r,i,f){if(!e)throw new Error("Invalid Window");if(e.type!=="pair")throw new Error("Invalid Window: not a pair window");if(f){if(f.type==="pair")throw new Error("Invalid keywin: cannot be a pair window");let x=f;for(;(x=x?.parent)&&x!==e;);if(!x)throw new Error("keywin must be a descendent")}let u=r&15,_=u===0||u===1;if(f||(f=e.key),_&&!e.vertical)throw new Error("Invalid method: split must stay horizontal");if(!_&&e.vertical)throw new Error("Invalid method: split must stay vertical");let p=(r&240)===16;if(f.type==="blank"&&p)throw new Error("Invalid method: blank windows cannot be only be split proportionally");let y=u===0||u===2;if(y!==e.backward){let x=e.child1;e.child1=e.child2,e.child2=x}e.backward=y,e.border=(r&256)===256,e.dir=u,e.fixed=p,e.key=f,e.size=i,e.vertical=_,this.rearrange_window(e,e.box)}glk_window_set_background_color(e,r){if(!e)throw new Error("Invalid Window");if(e.type!=="graphics")throw new Error("Invalid Window: not a graphics window");e.draw.push({color:mr(r),special:"setcolor"})}glk_window_set_echo_stream(e,r){if(!e)throw new Error("Invalid Window");e.echostr=r}garglk_set_reversevideo(e){this.garglk_set_reversevideo_stream(this.current_stream,e)}garglk_set_reversevideo_stream(e,r){if(!e)throw new Error("Invalid Stream");e.type==="window"&&e.set_css("reverse",r?1:void 0)}garglk_set_zcolors(e,r){this.garglk_set_zcolors_stream(this.current_stream,e,r)}garglk_set_zcolors_stream(e,r,i){if(!e)throw new Error("Invalid Stream");e.type==="window"&&(r!==-2&&e.set_css("color",r===-1?void 0:mr(r)),i!==-2&&e.set_css("background-color",i===-1?void 0:mr(i)))}accept(e){if(this.exited)return this.GlkOte.log("GlkApi has exited");if(e.gen!==this.gen)return this.GlkOte.log(`Input event has wrong generation number: expected ${this.gen}, received ${e.gen}`);if(this.gen++,!this.selectref&&e.type!=="init"&&e.type!=="specialresponse")return;this.partial_inputs=e.partial;let r=0,i=null,f=0,u=0,_;if("window"in e)for(i=this.first_window;i&&i.disprock!==e.window;i=i.next);switch(e.type){case"init":this.metrics=il(e.metrics),this.support=e.support,this.VM.start();return;case"arrange":this.metrics=il(e.metrics),this.root_window&&this.rearrange_window(this.root_window,{bottom:this.metrics.height,left:0,right:this.metrics.width,top:0}),r=5;break;case"char":if(i?.input.type!=="char")return;delete i.input.type,r=2,e.value.length===1?(f=e.value.codePointAt(0),!i.uni_input&&f>Qe&&(f=Xe)):f=Qs[e.value]??4294967295;break;case"hyperlink":if(!i?.input.hyperlink)return;delete i.input.hyperlink,r=8,f=e.value;break;case"line":if(i?.input.type!=="line")return;this.handle_line_input(i,e.value,this.selectref,e.terminator),this.GiDispa?.prepare_resume(this.selectref),delete this.selectref;break;case"mouse":if(!i?.input.mouse)return;delete i.input.mouse,r=4,f=e.x,u=e.y;break;case"redraw":r=6;break;case"specialresponse":{if(e.response!=="fileref_prompt")throw new Error("Unknown type of specialresponse event");let p=e.value;if(typeof p=="string")throw new Error("AsyncGlk no longer supports bare-string filenames from Dialog");p&&(_=this.create_fileref(p.filename,this.special_data.rock,this.special_data.usage,p));break}case"timer":r=1,this.timer.started=Date.now();break;default:throw new Error(`Event type ${e.type} not supported by AsyncGlk`)}this.selectref&&(Ri(this.selectref,r,i,f,u),this.GiDispa?.prepare_resume(this.selectref),delete this.selectref),this.VM.resume(_)}create_fileref(e,r,i,f){if(!f){let _=i&15,p=_===1?this.VM.get_signature():void 0;f=this.Dialog.file_construct_ref(e,bi[_]??"xxx",p)}let u=new yi(this.Dialog,e,f,r,i);return u.next=this.first_fref,this.first_fref=u,u.next&&(u.next.prev=u),this.GiDispa?.class_register("fileref",u),u}create_file_stream(e,r,i,f){if(!e)throw new Error("Invalid Fileref");if(r!==1&&r!==2&&r!==3&&r!==5)throw new Error("Invalid filemode");if(r===2&&!e.exists())return null;let u=null;r!==1&&(u=e.read()),u||(u=new Uint8Array(0),e.write(u));let _=el(u,e.binary,r,i,f,e);return r===5&&_.set_position(2,0),this.register_stream(_),_}create_memory_stream(e,r,i,f){if(r!==2&&r!==1&&r!==3)throw new Error("Illegal filemode");let u;if(e){let _=()=>this.GiDispa?.unretain_array(e);if(Array.isArray(e)){let p=f.from(e);r===2?u=new Ze(p,r,i,_):u=new Ze(p,r,i,()=>{_r(p,e,e.length),_()})}else u=new Ze(e,r,i,_);this.GiDispa?.retain_array(e)}else u=new xi(r,i);return this.register_stream(u),u}create_resource_stream(e,r,i){if(!this.Blorb)return null;let f=this.Blorb.get_data_chunk(e);if(!f)return null;let u=el(f.data,f.binary,2,r,i);return this.register_stream(u),u}draw_image(e,r,i,f,u,_){let p={alttext:r.alttext,height:i,image:r.image,special:"image",url:r.url,width:_};switch(e.type){case"buffer":return p.alignment=Js[f]??"inlineup",e.put_image(p),1;case"graphics":return p.x=f,p.y=u,e.draw.push(p),1}return 0}handle_line_input(e,r,i,f){e.request_echo_line_input&&(e.put_string(r+` +`){this.x=0,this.y++;continue}let _=this.lines[this.y];_.changed=!0,_.content[this.x++]=fe(this.current_styles,!1,u)}i&&this.set_style(f)}set_css(r,i){this.current_styles.css_styles[r]!==i&&(this.current_styles=fe(this.current_styles,!0),i===void 0?delete this.current_styles.css_styles[r]:this.current_styles.css_styles[r]=i)}set_hyperlink(r){r?this.current_styles.hyperlink=r:delete this.current_styles.hyperlink}set_style(r){this.current_styles.style=r}update_size(r,i){let f=this.height,u=this.width;this.height=r,this.width=i;let _=fe(Ii,!0," ");if(f>r)this.lines.length=r;else if(r>f)for(let y=f;yi.changed)&&(r.content={id:this.disprock,lines:this.lines.flatMap((i,f)=>i.changed?(i.changed=!1,{content:Zs(i.content.reduce((u,_)=>{if(!u.length)return[fe(_,!1,_.text)];let p=u[u.length-1];return _.css_styles===p.css_styles&&_.hyperlink===p.hyperlink&&_.style===p.style?p.text+=_.text:u.push(fe(_,!1,_.text)),u},[])),line:f}):[])},this.cleared&&(r.content.clear=!0,this.cleared=!1)),this.input.type){let i=r.input;this.fit_cursor()?(i.xpos=this.width-1,i.ypos=this.height-1):(i.xpos=this.x,i.ypos=this.y)}return r.size.gridheight=this.height,r.size.gridwidth=this.width,r}},Ei=class extends Ut{constructor(r,i,f){super(0);this.child1=null;this.child2=null;this.type="pair";this.typenum=1;this.border=(i&256)===256,this.dir=i&15,this.fixed=(i&240)===16,this.key=r,this.size=f,this.backward=this.dir===0||this.dir===2,this.vertical=this.dir===0||this.dir===1}},Ii={css_styles:{},style:"normal",text:""};function Zs(o){return o.map(e=>("special"in e||Object.keys(e.css_styles).length||delete e.css_styles,e))}function fe(o,e,r=""){return Object.assign({},o,{css_styles:e?Object.assign({},o.css_styles):o.css_styles,text:r})}function Mt(o,e,r){o[r]&&(e[r]=o[r])}var Oi=class{constructor(){this.value=0}get_value(){return this.value}set_value(e){this.value=e}},Di=class{constructor(){this.fields=[]}get_field(e){return this.fields[e]}get_fields(){return this.fields}push_field(e){this.fields.push(e)}set_field(e,r){this.fields[e]=r}},gr=class{constructor(){this.Dialog=null;this.GlkOte=null;this.VM=null;this.disprock_counter=1;this.do_autosave=!1;this.exited=!1;this.first_fref=null;this.gen=0;this.metrics=sr;this.current_stream=null;this.first_stream=null;this.stylehints={buffer:{},grid:{}};this.support=[];this.timer={interval:0,last_interval:0,started:0};this.version=Qr;this.first_window=null;this.root_window=null;this.windows_changed=!1;this.Const=wo;this.DidNotReturn=dr;this.RefBox=Oi;this.RefStruct=Di}init(e){if(this.before_select_hook=e.before_select_hook,this.Blorb=e.Blorb,e.Dialog)this.Dialog=new gi(e.Dialog);else throw new Error("No reference to Dialog");if(this.do_autosave=!!e.do_vm_autosave,this.GiDispa=e.GiDispa,this.gestalt_hook=e.glk_gestalt_hook,e.GlkOte)this.GlkOte=e.GlkOte;else throw new Error("No reference to GlkOte");if(e.vm)this.VM=e.vm;else throw new Error("No reference to VM");this.before_select_hook?.(),this.GiDispa?.init({io:this,vm:this.VM});let r=e;r.accept=this.accept.bind(this),this.GlkOte.init(r)}call_may_not_return(e){return e===1||e===192||e===98}fatal_error(e){if(this.exited=!0,!this.GlkOte){console.error("Fatal error: "+e);return}this.GlkOte.error(e),this.GlkOte.update({type:"update",disable:!0,gen:this.gen})}getlibrary(e){switch(e){case"Blorb":return this.Blorb||null;case"Dialog":return this.Dialog;case"GiDispa":return this.GiDispa||null;case"GlkOte":return this.GlkOte;case"VM":return this.VM;default:return null}}inited(){return!!(this.GlkOte&&this.VM)}restore_allstate(e){throw new Error("Autosaves not yet supported")}save_allstate(){throw new Error("Autosaves not yet supported")}update(){let e={gen:this.gen,type:"update"};this.exited&&(e.disable=!0);let r=[],i=[],f=[];for(let _=this.first_window;_;_=_.next){let p=_.update();if(p.content&&r.push(p.content),p.input){let y=p.input;(y.hyperlink||y.mouse||y.type)&&i.push(y)}this.windows_changed&&p.size&&f.push(p.size)}r.length&&(e.content=r),i.length&&(e.input=i),f.length&&(e.windows=f),this.windows_changed=!1,this.special&&(e.specialinput=this.special,delete this.special);let u=this.timer;u.last_interval!==u.interval&&(e.timer=u.interval||null,u.last_interval=u.interval),this.GlkOte.update(nr(e)),this.before_select_hook?.()}byte_array_to_string(e){return String.fromCodePoint(...e)}glk_put_jstring(e,r){this.glk_put_jstring_stream(this.current_stream,e)}glk_put_jstring_stream(e,r,i){if(!e)throw new Error("Invalid Stream");e.put_string(r)}uni_array_to_string(e){return String.fromCodePoint(...e)}glk_buffer_canon_decompose_uni(e,r){return hr(e,r,i=>i.normalize("NFD"))}glk_buffer_canon_normalize_uni(e,r){return hr(e,r,i=>i.normalize("NFC"))}glk_buffer_to_lower_case_uni(e,r){return hr(e,r,i=>i.toLowerCase())}glk_buffer_to_title_case_uni(e,r,i){return hr(e,r,f=>f.reduce((u,_,p)=>{let y={\u00DF:"Ss",\u01C4:"\u01C5",\u01C5:"\u01C5",\u01C6:"\u01C5",\u01C7:"\u01C8",\u01C8:"\u01C8",\u01C9:"\u01C8",\u01CA:"\u01CB",\u01CB:"\u01CB",\u01CC:"\u01CB",\u01F1:"\u01F2",\u01F2:"\u01F2",\u01F3:"\u01F2",\u0587:"\u0535\u0582",\u1FB2:"\u1FBA\u0345",\u1FB3:"\u1FBC",\u1FB4:"\u0386\u0345",\u1FB7:"\u0391\u0342\u0345",\u1FBC:"\u1FBC",\u1FC2:"\u1FCA\u0345",\u1FC3:"\u1FCC",\u1FC4:"\u0389\u0345",\u1FC7:"\u0397\u0342\u0345",\u1FCC:"\u1FCC",\u1FF2:"\u1FFA\u0345",\u1FF3:"\u1FFC",\u1FF4:"\u038F\u0345",\u1FF7:"\u03A9\u0342\u0345",\u1FFC:"\u1FFC",\uFB00:"Ff",\uFB01:"Fi",\uFB02:"Fl",\uFB03:"Ffi",\uFB04:"Ffl",\uFB05:"St",\uFB06:"St",\uFB13:"\u0544\u0576",\uFB14:"\u0544\u0565",\uFB15:"\u0544\u056B",\uFB16:"\u054E\u0576",\uFB17:"\u0544\u056D"},x=["\u1F88\u1F89\u1F8A\u1F8B\u1F8C\u1F8D\u1F8E\u1F8F","\u1F98\u1F99\u1F9A\u1F9B\u1F9C\u1F9D\u1F9E\u1F9F","\u1FA8\u1FA9\u1FAA\u1FAB\u1FAC\u1FAD\u1FAE\u1FAF"],b=String.fromCodePoint(_);return p===0?y[b]?b=y[b]:_>=8064&&_<8112?b=x[(_-8064)/16|0][_%8]:b=b.toUpperCase():i&&(b=b.toLowerCase()),u+b},""),!0)}glk_buffer_to_upper_case_uni(e,r){return hr(e,r,i=>i.toUpperCase())}glk_cancel_char_event(e){if(!e)throw new Error("Invalid Window");delete e.input.type}glk_cancel_hyperlink_event(e){if(!e)throw new Error("Invalid Window");(e.type==="buffer"||e.type==="grid")&&delete e.input.hyperlink}glk_cancel_line_event(e,r){if(!e)throw new Error("Invalid Window");if(e.input.type!=="line"){r&&Ri(r);return}this.handle_line_input(e,this.partial_inputs?.[e.disprock]??"",r)}glk_cancel_mouse_event(e){if(!e)throw new Error("Invalid Window");(e.type==="graphics"||e.type==="grid")&&delete e.input.mouse}glk_char_to_lower(e){return e>=65&&e<=90||e>=192&&e<=222&&e!==215?e+32:e}glk_char_to_upper(e){return e>=97&&e<=122||e>=224&&e<=254&&e!==247?e-32:e}glk_current_simple_time(e){return Math.floor(Date.now()/(e*1e3))}glk_current_time(e){vo(Date.now(),e)}glk_date_to_simple_time_local(e,r){return Math.floor(tl(e)/(r*1e3))}glk_date_to_simple_time_utc(e,r){return Math.floor(rl(e)/(r*1e3))}glk_date_to_time_local(e,r){vo(tl(e),r)}glk_date_to_time_utc(e,r){vo(rl(e),r)}glk_exit(){return this.exited=!0,dr}glk_fileref_create_by_name(e,r,i){let f=this.Dialog.file_clean_fixed_name(r,e&15);return this.create_fileref(f,i,e)}glk_fileref_create_by_prompt(e,r,i){let f=Ys[r]??"read",u=e&15,_=bi[u]??"data";return this.special={filemode:f,filetype:_,type:"fileref_prompt"},u===1&&(this.special.gameid=this.VM.get_signature()),this.special_data={rock:i,usage:e},dr}glk_fileref_create_from_fileref(e,r,i){if(!r)throw new Error("Invalid Fileref");return this.create_fileref(r.filename,i,e)}glk_fileref_create_temp(e,r){let i=bi[e&15],f=this.Dialog.file_construct_temp_ref(i);return this.create_fileref(f.filename,r,e,f)}glk_fileref_delete_file(e){if(!e)throw new Error("Invalid Fileref");e.delete_file()}glk_fileref_destroy(e){if(!e)throw new Error("Invalid Fileref");this.GiDispa?.class_unregister("fileref",e);let r=e.prev,i=e.next;e.prev=null,e.next=null,r?r.next=i:this.first_fref=i,i&&(i.prev=r)}glk_fileref_does_file_exist(e){if(!e)throw new Error("Invalid Fileref");return e.exists()}glk_fileref_get_rock(e){if(!e)throw new Error("Invalid Fileref");return e.rock}glk_fileref_iterate(e,r){let i=e?e.next:this.first_fref;return r&&r.set_value(i?i.rock:0),i}glk_gestalt(e,r){return this.glk_gestalt_ext(e,r,null)}glk_gestalt_ext(e,r,i){let f=this.gestalt_hook?.(e,r,i);if(f)return f;switch(e){case 0:return 1797;case 1:return r<=4294967294&&r>=4294967268?1:r>=4294967296-28||r>1114111||r>=0&&r<32||r>=127&&r<160?0:1;case 2:return r>1114111||r>=0&&r<32||r>=127&&r<160?0:1;case 3:return i&&(i[0]=1),2;case 19:return+(r===4294967288||r>=4294967268&&r<=4294967279);case 7:return+((r===5||r===3)&&this.support.includes("graphics"));case 4352:return+this.support.includes("garglktext");case 6:case 23:case 14:return+this.support.includes("graphics");case 11:return+this.support.includes("hyperlinks");case 12:return+((r===3||r===4)&&this.support.includes("hyperlinks"));case 4:return+((r===5||r===4)&&this.support.includes("graphics"));case 5:return+this.support.includes("timer");case 20:case 17:case 18:case 22:case 15:case 16:return 1;default:return 0}}glk_get_buffer_stream(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return Array.isArray(r)?Fi(r,Uint8Array,i=>e.get_buffer(i)):e.get_buffer(r)}glk_get_buffer_stream_uni(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return Array.isArray(r)?Fi(r,Uint32Array,i=>e.get_buffer(i)):e.get_buffer(r)}glk_get_char_stream(e){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return e.get_char(!1)}glk_get_char_stream_uni(e){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return e.get_char(!0)}glk_get_line_stream(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return Array.isArray(r)?Fi(r,Uint8Array,i=>e.get_line(i)+1)-1:e.get_line(r)}glk_get_line_stream_uni(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode!==2&&e.fmode!==3)throw new Error("Cannot read from write-only stream");return Array.isArray(r)?Fi(r,Uint32Array,i=>e.get_line(i)+1)-1:e.get_line(r)}glk_image_draw(e,r,i,f){let u=this.Blorb?.get_image_info(r);return u?(this.draw_image(e,u,u.height||0,i,f,u.width||0),1):0}glk_image_draw_scaled(e,r,i,f,u,_){let p=this.Blorb?.get_image_info(r);return p?(this.draw_image(e,p,_||0,i,f,u||0),1):0}glk_image_get_info(e,r,i){let f=this.Blorb?.get_image_info(e);return i&&i.set_value(f?.height||0),r&&r.set_value(f?.width||0),f?1:0}glk_put_buffer(e){this.glk_put_buffer_stream(this.current_stream,e)}glk_put_buffer_stream(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode===2)throw new Error("Cannot write to read-only stream");e.put_buffer(r,!1)}glk_put_buffer_stream_uni(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode===2)throw new Error("Cannot write to read-only stream");e.put_buffer(r,!0)}glk_put_buffer_uni(e){this.glk_put_buffer_stream_uni(this.current_stream,e)}glk_put_char(e){this.glk_put_char_stream(this.current_stream,e)}glk_put_char_stream(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode===2)throw new Error("Cannot write to read-only stream");e.put_char(r)}glk_put_char_stream_uni(e,r){this.glk_put_char_stream(e,r)}glk_put_char_uni(e){this.glk_put_char_stream(this.current_stream,e)}glk_put_string(e){this.glk_put_string_stream(this.current_stream,e)}glk_put_string_stream(e,r){if(!e)throw new Error("Invalid Stream");if(e.fmode===2)throw new Error("Cannot write to read-only stream");e.put_string(r)}glk_put_string_stream_uni(e,r){this.glk_put_string_stream(e,r)}glk_put_string_uni(e){this.glk_put_string_stream(this.current_stream,e)}glk_request_char_event(e){this.request_char_event(e,!1)}glk_request_char_event_uni(e){this.request_char_event(e,!0)}glk_request_hyperlink_event(e){if(!e)throw new Error("Invalid Window");(e.type==="buffer"||e.type==="grid")&&(e.input.hyperlink=!0)}glk_request_line_event(e,r,i){this.request_line_event(e,r,!1,i)}glk_request_line_event_uni(e,r,i){this.request_line_event(e,r,!0,i)}glk_request_mouse_event(e){if(!e)throw new Error("Invalid Window");(e.type==="graphics"||e.type==="grid")&&(e.input.mouse=!0)}glk_request_timer_events(e){this.timer.interval=e,this.timer.started=e?Date.now():0}glk_schannel_create(e){return null}glk_schannel_create_ext(e,r){return null}glk_schannel_destroy(e){throw new Error("Invalid Schannel")}glk_schannel_get_rock(e){throw new Error("Invalid Schannel")}glk_schannel_iterate(e,r){return r&&r.set_value(0),null}glk_schannel_pause(e){throw new Error("Invalid Schannel")}glk_schannel_play(e,r){throw new Error("Invalid Schannel")}glk_schannel_play_ext(e,r,i,f){throw new Error("Invalid Schannel")}glk_schannel_play_multi(e,r,i){throw new Error("Invalid Schannel")}glk_schannel_set_volume(e,r){throw new Error("Invalid Schannel")}glk_schannel_set_volume_ext(e,r,i,f){throw new Error("Invalid Schannel")}glk_schannel_stop(e){throw new Error("Invalid Schannel")}glk_schannel_unpause(e){throw new Error("Invalid Schannel")}glk_select(e){return this.selectref=e,dr}glk_select_poll(e){Ri(e);let r=this.timer;if(r.interval){let i=Date.now();i-r.started>r.interval&&(r.last_interval=0,r.started=i,e.set_field(0,1))}}glk_set_echo_line_event(e,r){if(!e)throw new Error("Invalid Window");e.type==="buffer"&&(e.echo_line_input=!!r)}glk_set_hyperlink(e){this.glk_set_hyperlink_stream(this.current_stream,e)}glk_set_hyperlink_stream(e,r){if(!e)throw new Error("Invalid Stream");e.type==="window"&&e.set_hyperlink(r)}glk_set_style(e){this.glk_set_style_stream(this.current_stream,e)}glk_set_style_stream(e,r){if(!e)throw new Error("Invalid Stream");e.type==="window"&&((r<0||r>11)&&(r=0),e.set_style(wi[r]))}glk_set_terminators_line_event(e,r){if(!e)throw new Error("Invalid Window");let i=[];if(r)for(let f of r)xo[f]&&i.push(xo[f]);i.length?e.input.terminators=i:delete e.input.terminators}glk_set_window(e){this.current_stream=e?e.str:null}glk_sound_load_hint(e,r){}glk_stream_close(e,r){if(!e)throw new Error("Invalid Stream");e.close(r),this.unregister_stream(e)}glk_stream_get_current(){return this.current_stream}glk_stream_get_position(e){if(!e)throw new Error("Invalid Stream");return e.get_position()}glk_stream_get_rock(e){if(!e)throw new Error("Invalid Stream");return e.rock}glk_stream_iterate(e,r){let i=e?e.next:this.first_stream;return r&&r.set_value(i?i.rock:0),i}glk_stream_open_file(e,r,i){return this.create_file_stream(e,r,i,!1)}glk_stream_open_file_uni(e,r,i){return this.create_file_stream(e,r,i,!0)}glk_stream_open_memory(e,r,i){return this.create_memory_stream(e,r,i,Uint8Array)}glk_stream_open_memory_uni(e,r,i){return this.create_memory_stream(e,r,i,Uint32Array)}glk_stream_open_resource(e,r){return this.create_resource_stream(e,r,!1)}glk_stream_open_resource_uni(e,r){return this.create_resource_stream(e,r,!0)}glk_stream_set_current(e){this.current_stream=e}glk_stream_set_position(e,r,i){if(!e)throw new Error("Invalid Stream");e.set_position(i,r)}glk_style_distinguish(e,r,i){return 0}glk_style_measure(e,r,i,f){return f&&f.set_value(0),0}glk_stylehint_clear(e,r,i){let f=`.Style_${wi[r]}${i<=2?"_par":""}`;function u(_){_[f]&&(delete _[f][ko[i]],Object.keys(_[f]).length||delete _[f])}(e===0||e===3)&&u(this.stylehints.buffer),(e===0||e===4)&&u(this.stylehints.grid)}glk_stylehint_set(e,r,i,f){if(r<0||r>=11||i<0||i>=10)return;if(e===0){this.glk_stylehint_set(3,r,i,f),this.glk_stylehint_set(4,r,i,f);return}if(e===2||e===5||e===1)return;let u=e===3?this.stylehints.buffer:this.stylehints.grid,_=`.Style_${wi[r]}${i<=2?"_par":""}`,p=["left","justify","center","right"],y=["lighter","normal","bold"],x;(i===0||i===1)&&(x=f+"em"),i===2&&(x=p[f]),i===3&&(x=1+f*.1+"em"),i===4&&(x=y[f+1]),i===5&&(x=f?"italic":"normal"),i===6&&(x=f?0:1),(i===7||i===8)&&(x=mr(f)),i===9&&(x=f),x!==void 0&&(u[_]||(u[_]={}),u[_][ko[i]]=x)}glk_tick(){}glk_simple_time_to_date_local(e,r,i){nl(e*1e3*r,i)}glk_simple_time_to_date_utc(e,r,i){ol(e*1e3*r,i)}glk_time_to_date_local(e,r){nl(al(e),r)}glk_time_to_date_utc(e,r){ol(al(e),r)}glk_window_clear(e){if(!e)throw new Error("Invalid Window");if(e.input.type==="line")throw new Error("Window has pending line input");e.clear()}glk_window_close(e,r){if(!e)throw new Error("Invalid Window");if(e.str.close(r),e===this.root_window)this.root_window=null,this.remove_window(e,!0);else{let i=e.parent,f=i.child1===e?i.child2:i.child1,u=i.parent;u?(u.child1===i?u.child1=f:u.child2=f,f.parent=u):(this.root_window=f,f.parent=null),this.remove_window(e,!0),this.remove_window(i,!1),this.rearrange_window(f,i.box)}}glk_window_erase_rect(e,r,i,f,u){if(!e)throw new Error("Invalid Window");if(e.type!=="graphics")throw new Error("Invalid Window: not a graphics window");e.draw.push({height:u,special:"fill",width:f,x:r,y:i})}glk_window_fill_rect(e,r,i,f,u,_){if(!e)throw new Error("Invalid Window");if(e.type!=="graphics")throw new Error("Invalid Window: not a graphics window");e.draw.push({color:mr(r),height:_,special:"fill",width:u,x:i,y:f})}glk_window_flow_break(e){if(!e)throw new Error("Invalid Window");e.type==="buffer"&&e.set_flow_break()}glk_window_get_arrangement(e,r,i,f){if(!e)throw new Error("Invalid Window");if(e.type!=="pair")throw new Error("Invalid Window: not a pair window");f&&f?.set_value(e.key),r&&r?.set_value(e.dir|(e.fixed?16:32)|(e.border?0:256)),i&&i?.set_value(e.size)}glk_window_get_echo_stream(e){if(!e)throw new Error("Invalid Window");return e.echostr}glk_window_get_parent(e){if(!e)throw new Error("Invalid Window");return e.parent}glk_window_get_rock(e){if(!e)throw new Error("Invalid Window");return e.rock}glk_window_get_root(){return this.root_window}glk_window_get_sibling(e){if(!e)throw new Error("Invalid Window");let r=e.parent;return r?r.child1===e?r.child2:r.child1:null}glk_window_get_size(e,r,i){if(!e)throw new Error("Invalid Window");let f=this.metrics,u=0,_=0;switch(e.type){case"buffer":u=Pt((e.box.bottom-e.box.top-f.buffermarginy)/f.buffercharheight),_=Pt((e.box.right-e.box.left-f.buffermarginx)/f.buffercharwidth);break;case"graphics":case"grid":u=e.height,_=e.width;break}i&&i?.set_value(u),r&&r?.set_value(_)}glk_window_get_stream(e){if(!e)throw new Error("Invalid Window");return e.str}glk_window_get_type(e){if(!e)throw new Error("Invalid Window");return e.typenum}glk_window_iterate(e,r){let i=e?e.next:this.first_window;return r&&r?.set_value(i?i.rock:0),i}glk_window_move_cursor(e,r,i){if(!e)throw new Error("Invalid Window");if(e.type!=="grid")throw new Error("Invalid Window: not a grid window");e.x=Math.max(0,r),e.y=Math.max(0,i)}glk_window_open(e,r,i,f,u){if(this.root_window){if(!e)throw new Error("Invalid splitwin");if(e.type==="pair")throw new Error("Invalid splitwin: must not be a pair window");let p=r&240,y=r&15;if(p!==16&&p!==32)throw new Error("Invalid method: must be fixed or proportional");if(p===16&&e.type==="blank")throw new Error("Invalid method: blank windows cannot be only be split proportionally");if(y!==2&&y!==3&&y!==0&&y!==1)throw new Error("Invalid method: bad direction")}else if(e)throw new Error("Invalid splitwin: must be null for first window");let _;switch(f){case 2:_=new Si(u);break;case 5:_=new Gi(u);break;case 3:_=new Ai(u,this.stylehints.buffer);break;case 4:_=new Ci(u,this.stylehints.grid);break;default:throw new Error("Invalid wintype")}if(this.register_window(_),e){let p=new Ei(_,r,i);this.register_window(p),p.child1=e,p.child2=_;let y=e.parent;e.parent=p,_.parent=p,p.parent=y,y?y.child1===e?y.child1=p:y.child2=p:this.root_window=p,this.rearrange_window(p,e.box)}else this.root_window=_,this.rearrange_window(_,{bottom:this.metrics.height,left:0,right:this.metrics.width,top:0});return _}glk_window_set_arrangement(e,r,i,f){if(!e)throw new Error("Invalid Window");if(e.type!=="pair")throw new Error("Invalid Window: not a pair window");if(f){if(f.type==="pair")throw new Error("Invalid keywin: cannot be a pair window");let x=f;for(;(x=x?.parent)&&x!==e;);if(!x)throw new Error("keywin must be a descendent")}let u=r&15,_=u===0||u===1;if(f||(f=e.key),_&&!e.vertical)throw new Error("Invalid method: split must stay horizontal");if(!_&&e.vertical)throw new Error("Invalid method: split must stay vertical");let p=(r&240)===16;if(f.type==="blank"&&p)throw new Error("Invalid method: blank windows cannot be only be split proportionally");let y=u===0||u===2;if(y!==e.backward){let x=e.child1;e.child1=e.child2,e.child2=x}e.backward=y,e.border=(r&256)===256,e.dir=u,e.fixed=p,e.key=f,e.size=i,e.vertical=_,this.rearrange_window(e,e.box)}glk_window_set_background_color(e,r){if(!e)throw new Error("Invalid Window");if(e.type!=="graphics")throw new Error("Invalid Window: not a graphics window");e.draw.push({color:mr(r),special:"setcolor"})}glk_window_set_echo_stream(e,r){if(!e)throw new Error("Invalid Window");e.echostr=r}garglk_set_reversevideo(e){this.garglk_set_reversevideo_stream(this.current_stream,e)}garglk_set_reversevideo_stream(e,r){if(!e)throw new Error("Invalid Stream");e.type==="window"&&e.set_css("reverse",r?1:void 0)}garglk_set_zcolors(e,r){this.garglk_set_zcolors_stream(this.current_stream,e,r)}garglk_set_zcolors_stream(e,r,i){if(!e)throw new Error("Invalid Stream");e.type==="window"&&(r!==-2&&e.set_css("color",r===-1?void 0:mr(r)),i!==-2&&e.set_css("background-color",i===-1?void 0:mr(i)))}accept(e){if(this.exited)return this.GlkOte.log("GlkApi has exited");if(e.gen!==this.gen)return this.GlkOte.log(`Input event has wrong generation number: expected ${this.gen}, received ${e.gen}`);if(this.gen++,!this.selectref&&e.type!=="init"&&e.type!=="specialresponse")return;this.partial_inputs=e.partial;let r=0,i=null,f=0,u=0,_;if("window"in e)for(i=this.first_window;i&&i.disprock!==e.window;i=i.next);switch(e.type){case"init":this.metrics=il(e.metrics),this.support=e.support,this.VM.start();return;case"arrange":this.metrics=il(e.metrics),this.root_window&&this.rearrange_window(this.root_window,{bottom:this.metrics.height,left:0,right:this.metrics.width,top:0}),r=5;break;case"char":if(i?.input.type!=="char")return;delete i.input.type,r=2,e.value.length===1?(f=e.value.codePointAt(0),!i.uni_input&&f>Qe&&(f=Xe)):f=Qs[e.value]??4294967295;break;case"hyperlink":if(!i?.input.hyperlink)return;delete i.input.hyperlink,r=8,f=e.value;break;case"line":if(i?.input.type!=="line")return;this.handle_line_input(i,e.value,this.selectref,e.terminator),this.GiDispa?.prepare_resume(this.selectref),delete this.selectref;break;case"mouse":if(!i?.input.mouse)return;delete i.input.mouse,r=4,f=e.x,u=e.y;break;case"redraw":r=6;break;case"specialresponse":{if(e.response!=="fileref_prompt")throw new Error("Unknown type of specialresponse event");let p=e.value;if(typeof p=="string")throw new Error("AsyncGlk no longer supports bare-string filenames from Dialog");p&&(_=this.create_fileref(p.filename,this.special_data.rock,this.special_data.usage,p));break}case"timer":r=1,this.timer.started=Date.now();break;default:throw new Error(`Event type ${e.type} not supported by AsyncGlk`)}this.selectref&&(Ri(this.selectref,r,i,f,u),this.GiDispa?.prepare_resume(this.selectref),delete this.selectref),this.VM.resume(_)}create_fileref(e,r,i,f){if(!f){let _=i&15,p=_===1?this.VM.get_signature():void 0;f=this.Dialog.file_construct_ref(e,bi[_]??"xxx",p)}let u=new yi(this.Dialog,e,f,r,i);return u.next=this.first_fref,this.first_fref=u,u.next&&(u.next.prev=u),this.GiDispa?.class_register("fileref",u),u}create_file_stream(e,r,i,f){if(!e)throw new Error("Invalid Fileref");if(r!==1&&r!==2&&r!==3&&r!==5)throw new Error("Invalid filemode");if(r===2&&!e.exists())return null;let u=null;r!==1&&(u=e.read()),u||(u=new Uint8Array(0),e.write(u));let _=el(u,e.binary,r,i,f,e);return r===5&&_.set_position(2,0),this.register_stream(_),_}create_memory_stream(e,r,i,f){if(r!==2&&r!==1&&r!==3)throw new Error("Illegal filemode");let u;if(e){let _=()=>this.GiDispa?.unretain_array(e);if(Array.isArray(e)){let p=f.from(e);r===2?u=new Ze(p,r,i,_):u=new Ze(p,r,i,()=>{_r(p,e,e.length),_()})}else u=new Ze(e,r,i,_);this.GiDispa?.retain_array(e)}else u=new xi(r,i);return this.register_stream(u),u}create_resource_stream(e,r,i){if(!this.Blorb)return null;let f=this.Blorb.get_data_chunk(e);if(!f)return null;let u=el(f.data,f.binary,2,r,i);return this.register_stream(u),u}draw_image(e,r,i,f,u,_){let p={alttext:r.alttext,height:i,image:r.image,special:"image",url:r.url,width:_};switch(e.type){case"buffer":return p.alignment=Js[f]??"inlineup",e.put_image(p),1;case"graphics":return p.x=f,p.y=u,e.draw.push(p),1}return 0}handle_line_input(e,r,i,f){e.request_echo_line_input&&(e.put_string(r+` `,"input"),e.echostr&&e.echostr.put_string(r+` -`,"input")),r.length>e.line_input_buf.length&&(r=r.slice(0,e.line_input_buf.length)),e.uni_input||(r=r.replace(/[^\x00-\xff]/g,"?"));let u=Uint32Array.from(r,p=>p.codePointAt(0));Array.isArray(e.line_input_buf)?_r(u,e.line_input_buf,r.length):e.line_input_buf?.set(u);let _=Xs[f]??0;i&&Ri(i,3,e,r.length,_),this.GiDispa?.unretain_array(e.line_input_buf),delete e.input.type,delete e.line_input_buf}rearrange_window(e,r){let i=this.metrics;this.windows_changed=!0,e.box=r;let f=r.bottom-r.top,u=r.right-r.left;switch(e.type){case"graphics":{e.height=Pt(f-i.graphicsmarginy),e.width=Pt(u-i.graphicsmarginx);break}case"grid":{let _=Pt((f-i.gridmarginy)/i.gridcharheight),p=Pt((u-i.gridmarginx)/i.gridcharwidth);e.update_size(_,p);break}case"pair":{let _,p,y;e.vertical?(_=r.left,p=r.right,y=i.inspacingx):(_=r.top,p=r.bottom,y=i.inspacingy),e.border||(y=0);let x=p-_,b=0;if(e.fixed){switch(e.key.type){case"buffer":e.vertical?b=e.size*i.buffercharwidth+i.buffermarginx:b=e.size*i.buffercharheight+i.buffermarginy;break;case"graphics":b=e.size+(e.vertical?i.graphicsmarginx:i.graphicsmarginy);break;case"grid":e.vertical?b=e.size*i.gridcharwidth+i.gridmarginx:b=e.size*i.gridcharheight+i.gridmarginy;break}b=Math.ceil(b)}else b=Math.floor(x*e.size/100);e.backward?b=_+b:b=p-b-y,_>=p?b=_:b=Math.min(Math.max(b,_),p-y);let A,E;e.vertical?(A={bottom:r.bottom,left:r.left,right:b,top:r.top},E={bottom:r.bottom,left:b+y,right:r.right,top:r.top}):(A={bottom:b,left:r.left,right:r.right,top:r.top},E={bottom:r.bottom,left:r.left,right:r.right,top:b+y}),this.rearrange_window(e.child1,e.backward?E:A),this.rearrange_window(e.child2,e.backward?A:E);break}}}register_stream(e){e.next=this.first_stream,this.first_stream=e,e.next&&(e.next.prev=e),this.GiDispa?.class_register("stream",e)}register_window(e){this.windows_changed=!0,e.next=this.first_window,this.first_window=e,e.next&&(e.next.prev=e),this.GiDispa?this.GiDispa?.class_register("window",e):e.disprock=this.disprock_counter++,e.input.id=e.disprock,this.register_stream(e.str)}remove_window(e,r){this.windows_changed=!0,this.GiDispa&&"line_input_buf"in e&&e.line_input_buf&&(this.GiDispa.unretain_array(e.line_input_buf),delete e.line_input_buf),e.type==="pair"&&(r&&(this.remove_window(e.child1,!0),this.remove_window(e.child2,!0)),e.child1=null,e.child2=null,e.key=null),this.unregister_stream(e.str),e.echostr=null,e.parent=null,this.GiDispa?.class_unregister("window",e);let i=e.prev,f=e.next;e.prev=null,e.next=null,i?i.next=f:this.first_window=f,f&&(f.prev=i)}request_char_event(e,r){if(!e)throw new Error("Invalid Window");if(e.input.type)throw new Error("Window already has keyboard request");if(e.type==="blank"||e.type==="pair")throw new Error("Window does not support character input");e.input.gen=this.gen,e.input.type="char",e.uni_input=r}request_line_event(e,r,i,f){if(!e)throw new Error("Invalid Window");if(e.input.type)throw new Error("Window already has keyboard request");if(e.type!=="buffer"&&e.type!=="grid")throw new Error("Window does not support line input");e.input.gen=this.gen,f&&(e.input.initial=String.fromCodePoint(...r.slice(0,f))),e.input.type="line",e.line_input_buf=r,e.type==="buffer"&&(e.request_echo_line_input=e.echo_line_input),e.uni_input=i,this.GiDispa?.retain_array(r)}unregister_stream(e){this.current_stream===e&&(this.current_stream=null),this.GiDispa?.class_unregister("stream",e);let r=e.prev,i=e.next;e.prev=null,e.next=null,r?r.next=i:this.first_stream=i,i&&(i.prev=r)}};function hr(a,e,r,i){let f=Array.isArray(a)?a.slice(0,e):a.subarray(0,e),u=i?f:f.reduce((x,b)=>x+String.fromCodePoint(b),""),_=r(u),p=Uint32Array.from(_,x=>x.codePointAt(0)),y=p.length;return Array.isArray(a)?_r(p,a,y):a.set(p.subarray(0,Math.min(a.length,y))),y}function mr(a){return"#"+(a&16777215).toString(16).toUpperCase().padStart(6,"0")}function el(a,e,r,i,f,u){let _;if(f)if(e)_=Ls(a);else{let p=or.decode(a);_=Uint32Array.from(p,y=>y.codePointAt(0))}else _=a;return r===2?new Ze(_,r,i):new ki(u,_,r,i)}function tl(a){return new Date(a.get_field(0),a.get_field(1)-1,a.get_field(2),a.get_field(4),a.get_field(5),a.get_field(6),a.get_field(7)/1e3).getTime()}function rl(a){let e=new Date(0);return e.setUTCFullYear(a.get_field(0)),e.setUTCMonth(a.get_field(1)-1),e.setUTCDate(a.get_field(2)),e.setUTCHours(a.get_field(4)),e.setUTCMinutes(a.get_field(5)),e.setUTCSeconds(a.get_field(6)),e.setUTCMilliseconds(a.get_field(7)/1e3),e.getTime()}function il(a){let e=Object.assign({},sr),r;if(r=a.charheight,r!==void 0&&(e.buffercharheight=r,e.gridcharheight=r),r=a.charwidth,r!==void 0&&(e.buffercharwidth=r,e.gridcharwidth=r),r=a.margin,r!==void 0&&(e.buffermarginx=r,e.buffermarginy=r,e.graphicsmarginx=r,e.graphicsmarginy=r,e.gridmarginx=r,e.gridmarginy=r),r=a.buffermargin,r!==void 0&&(e.buffermarginx=r,e.buffermarginy=r),r=a.graphicsmargin,r!==void 0&&(e.graphicsmarginx=r,e.graphicsmarginy=r),r=a.gridmargin,r!==void 0&&(e.gridmarginx=r,e.gridmarginy=r),r=a.marginx,r!==void 0&&(e.buffermarginx=r,e.graphicsmarginx=r,e.gridmarginx=r),r=a.marginy,r!==void 0&&(e.buffermarginy=r,e.graphicsmarginy=r,e.gridmarginy=r),r=a.spacing,r!==void 0&&(e.inspacingx=r,e.inspacingy=r),r=a.inspacing,r!==void 0&&(e.inspacingx=r,e.inspacingy=r),r=a.spacingx,r!==void 0&&(e.inspacingx=r),r=a.spacingy,r!==void 0&&(e.inspacingy=r),Object.assign(e,a),a.outspacing||e.outspacingx||e.outspacingy)throw new Error("AsyncGlk requires that outspacing metrics be 0");return e}function Pt(a){return Math.max(0,Math.floor(a))}function Ri(a,e=0,r=null,i=0,f=0){a.set_field(0,e),a.set_field(1,r),a.set_field(2,i),a.set_field(3,f)}function nl(a,e){let r=new Date(a);e.set_field(0,r.getFullYear()),e.set_field(1,r.getMonth()+1),e.set_field(2,r.getDate()),e.set_field(3,r.getDay()),e.set_field(4,r.getHours()),e.set_field(5,r.getMinutes()),e.set_field(6,r.getSeconds()),e.set_field(7,r.getMilliseconds()*1e3)}function ol(a,e){let r=new Date(a);e.set_field(0,r.getUTCFullYear()),e.set_field(1,r.getUTCMonth()+1),e.set_field(2,r.getUTCDate()),e.set_field(3,r.getUTCDay()),e.set_field(4,r.getUTCHours()),e.set_field(5,r.getUTCMinutes()),e.set_field(6,r.getUTCSeconds()),e.set_field(7,r.getUTCMilliseconds()*1e3)}function vo(a,e){e.set_field(0,Math.floor(a/4294967296e3)),e.set_field(1,Math.floor(a/1e3)>>>0);let r=Math.floor(a%1e3*1e3);r<0&&(r+=1e6),e.set_field(2,r)}function al(a){return a.get_field(0)*4294967296e3+a.get_field(1)*1e3+a.get_field(2)/1e3}function Fi(a,e,r){let i=new e(a.length),f=r(i);return _r(i,a,f),f}var yr=class{constructor(){this.classname="GlkOte";this.version=Qr;this.accept_func=()=>{};this.autorestoring=!1;this.current_metrics=Object.assign({},sr);this.disabled=!1;this.generation=0;this.is_inited=!1;this.options={};this.timer=null;this.waiting_for_update=!1}async init(e){if(!e)return this.error("no options provided");if(!e.accept)return this.error("an accept function was not given to GlkOte");this.options=e,this.accept_func=e.accept,e.Blorb&&(this.Blorb=e.Blorb),e.Dialog&&(this.Dialog=e.Dialog),this.is_inited=!0,this.send_event({type:"init"})}error(e){throw typeof e=="string"?new Error(e):e}extevent(e){this.send_event({type:"external",value:e})}getdomcontext(){throw new Error("getdomcontext is not applicable to this GlkOte library")}getdomid(e){throw new Error("getdomid is not applicable to this GlkOte library")}getinterface(){return this.options}getlibrary(e){switch(e){case"Blorb":return this.Blorb;case"Dialog":return this.Dialog;default:return null}}inited(){return this.is_inited}log(e){console.log(e)}setdomcontext(e){throw new Error("setdomcontext is not applicable to this GlkOte library")}update(e){try{if(this.autorestoring=!1,this.waiting_for_update=!1,e.type==="error")return this.error(e.message);if(e.type==="pass")return;if(e.type==="retry"){setTimeout(()=>this.send_event({type:"refresh"}),2e3);return}if(e.type!=="update")return this.error(`Unknown update type: ${e.type}`);if(e.gen===this.generation){this.log(`Ignoring repeated generation number: ${e.gen}`);return}this.generation=e.gen,this.disabled&&this.disable(!1),e.input&&this.cancel_inputs(e.input),e.windows&&this.update_windows(e.windows),e.content&&this.update_content(e.content),e.input&&this.update_inputs(e.input),e.timer!==void 0&&(this.timer&&(clearInterval(this.timer),this.timer=null),e.timer&&(this.timer=setInterval(()=>this.ontimer(),e.timer))),e.specialinput&&this.handle_specialinput(e.specialinput),this.disabled=!1,(e.disable||e.specialinput)&&this.disable(!0),e.autorestore&&(this.autorestoring=!0,this.autorestore(e.autorestore)),typeof e.page_margin_bg<"u"&&this.options.set_body_to_page_bg&&this.set_page_bg(e.page_margin_bg),e.disable&&this.exit()}catch(r){this.error(r)}}warning(e){console.warn(e)}autorestore(e){}capabilities(){return["timer"]}exit(){}handle_specialinput(e){if(e.type==="fileref_prompt"){let r=i=>this.send_event({type:"specialresponse",response:"fileref_prompt",value:i});try{this.Dialog?this.Dialog.open(e.filemode!=="read",e.filetype,e.gameid,r):setTimeout(()=>r(null),0)}catch(i){this.log(`Unable to open file dialog: ${i}`),setTimeout(()=>r(null),0)}}else this.error(`Request for unknown special input type: ${e.type}`)}ontimer(){this.disabled||this.send_event({type:"timer"})}save_allstate(){}send_event(e){if(!(this.disabled&&e.type!=="specialresponse")){if(this.waiting_for_update){console.log("Trying to send event when waiting for input",e);return}switch(this.waiting_for_update=!0,e.gen=this.generation,e.type){case"arrange":e.metrics=this.current_metrics;break;case"init":e.metrics=this.current_metrics,e.support=this.capabilities();break;case"specialresponse":e.response="fileref_prompt";break}this.accept_func(e)}}set_page_bg(e){}};function _e(a,e){return $(`<${a}>`,{class:e})}var Wi=class{constructor(e){this.context_element=e.context_element,this.errorcontent_id=e.errorcontent_id,this.errorpane_id=e.errorpane_id,this.gameport_id=e.gameport_id,this.loadingpane_id=e.loadingpane_id,this.prefix=e.prefix,this.windowport_id=e.windowport_id}create(e,r,i){return i??={},typeof i=="string"&&(i={class:i}),i.id=this.prefix+r,$(`<${e}>`,i)}gameport(){return $(`#${this.gameport_id}`,this.context_element)}id(e){return $(`#${this.prefix}${e}`,this.context_element)}windowport(){return $(`#${this.windowport_id}`,this.context_element)}};function $t(){return visualViewport?visualViewport.scale-1>.001:!1}function Te(a){return{height:a.outerHeight(),width:a.outerWidth()}}function w1(a,e){return e.buffercharheight!==a.buffercharheight||e.buffercharwidth!==a.buffercharwidth||e.gridcharheight!==a.gridcharheight||e.gridcharwidth!==a.gridcharwidth||e.height!==a.height||e.width!==a.width}var k1=/(iPad; CPU|iPhone) OS 15_0/i.test(navigator.userAgent),br=class{constructor(e){this.on_gameport_resize=st(async()=>{if(this.glkote.disabled||!this.glkote.inited()){this.on_gameport_resize();return}let e=Object.assign({},this.metrics);await this.measure(),w1(this.metrics,e)&&this.glkote.send_event({type:"arrange"})},200,{leading:!1});this.on_visualViewport_resize=()=>{if($t())return;let e=this.glkote.dom.gameport(),r=document.activeElement?.tagName==="INPUT";k1&&e.toggleClass("ios15fix",r),e.outerHeight(visualViewport.height,!0),window.scrollTo(0,0),this.on_gameport_resize()};this.glkote=e,this.metrics=e.current_metrics,document.readyState==="complete"?this.loaded=Promise.resolve():this.loaded=new Promise(r=>{window.addEventListener("load",r,{once:!0})}),window.ResizeObserver?(this.observer=new ResizeObserver(this.on_gameport_resize),this.observer.observe(this.glkote.dom.gameport()[0])):$(window).on("resize",this.on_gameport_resize),visualViewport&&$(visualViewport).on("resize",this.on_visualViewport_resize)}destroy(){this.observer?this.observer.disconnect():$(window).off("resize",this.on_gameport_resize),visualViewport&&$(visualViewport).off("resize",this.on_visualViewport_resize)}async measure(){let e=this.glkote.dom,r=e.gameport();if(!r.length)throw new Error(`Cannot find gameport element #${e.gameport_id}`);e.id("layouttestpane").remove();let i=e.create("div","layout_test_pane");i.text("This should not be visible");let f=$("
");_e("span","Style_normal").text("12345678").appendTo(f);let u=_e("div","WindowFrame BufferWindow"),_=_e("div","BufferWindowInner").appendTo(u),p=f.clone().addClass("BufferLine").appendTo(_),y=f.clone().addClass("BufferLine").appendTo(_);_e("span","InvisibleCursor").appendTo(y);let x=p.children("span");i.append(u);let b=_e("div","WindowFrame GraphicsWindow"),A=$("",{height:32,width:64}).appendTo(b);i.append(b);let E=_e("div","WindowFrame GridWindow"),J=f.clone().addClass("GridLine").appendTo(E),V=f.clone().addClass("GridLine").appendTo(E),Q=J.children("span");i.append(E),r.append(i),await this.loaded;let re=getComputedStyle(E[0]).getPropertyValue("--glkote-grid-mono-family").split(",")[0].replace(/"/g,"");await document.fonts.load(`14px ${re}`),this.metrics.height=r.height(),this.metrics.width=r.width();let P=Te(u),Fe=Te(x),Oe=Te(p),De=Te(y);this.metrics.buffercharheight=Math.max(1,y.position().top-p.position().top),this.metrics.buffercharwidth=Math.max(1,x.width()/8),this.metrics.buffermarginx=P.width-Fe.width,this.metrics.buffermarginy=P.height-(Oe.height+De.height);let de=Te(b),j=Te(A);this.metrics.graphicsmarginx=de.width-j.width,this.metrics.graphicsmarginy=de.height-j.height;let oe=Te(E),pe=Te(Q),We=Te(J),he=Te(V);this.metrics.gridcharheight=Math.max(1,V.position().top-J.position().top),this.metrics.gridcharwidth=Math.max(1,Q.width()/8),this.metrics.gridmarginx=oe.width-pe.width,this.metrics.gridmarginy=oe.height-(We.height+he.height),i.remove()}};var wr=class{constructor(e,r){this.enabled=!1;this.handler=e=>this.web_handler(e);this.label="";this.session=Date.now()+Math.ceil(Math.random()*1e4).toString(16);this.url="";this.windows=r,e.recording_handler&&(this.enabled=!0,this.handler=e.recording_handler,this.url="(custom handler)"),e.recording_url&&(this.enabled=!0,this.url=e.recording_url),this.label=e.recording_label??"",this.enabled&&console.log(`Transcript recording active: session ${this.session} "${this.label}", destination ${this.url}`)}record_event(e){this.event=e,this.timestamp=Date.now()}record_update(e){if(!e.content)return;let r=this.event,i=r.type,f="";if(i==="char"||i==="line")f=r.value;else if(!(!i||i==="external"||i==="init"||i==="specialresponse"))return;let u="";for(let _ of e.content){let p=this.windows.get(_.id);if(!p||p.type!=="buffer")continue;let y=_.text||[];for(let x of y){x.append||(u+=` -`);let b=x.content;if(b?.length)for(let A=0;A",{"aria-hidden":"true",autocapitalize:"off",class:"Input",data:{window:e},on:{blur:()=>this.onblur(),focus:()=>this.onfocus(),input:r=>this.oninput(r),keydown:r=>this.onkeydown(r),keypress:r=>this.onkeypress(r)},rows:1}).prop("disabled",!0).appendTo(e.frameel)}destroy(){this.el.remove()}onblur(){ll()}onfocus(){this.window.type==="buffer"&&!$t()&&this.window.scroll_to_bottom(),ll()}oninput(e){if(!this.window.inputs?.type)return this.el.trigger("blur"),!1;if(this.window.inputs.type==="char"){let r=e.target.value[0];return this.submit_char(r),r===" "&&this.el.trigger("blur").trigger("focus"),!1}}onkeydown(e){if(!this.window.inputs?.type)return this.el.trigger("blur"),!1;let r=e.which;if(r){if(this.is_line){if(r===hn||r===gn){let i=this.window.manager.history,f;return r===hn&&this.history_index>0?(this.history_index--,f=1):r===gn&&this.history_indexthis.window.height_above_keyboard||this.el[0].focus({preventScroll:!0})}reset(){this.history_index=0,this.el.attr({"aria-hidden":"true",class:"Input"}).css({"background-color":"",color:"",left:Hs,top:"",width:""}).val("");let e=this.window.type==="buffer"?this.window.innerel:this.window.frameel;this.el.parent().is(e)||this.el.appendTo(e)}submit_char(e){this.window.send_text_event({type:"char",value:e})}submit_line(e,r){let i=this.window.manager.history;e&&e!==i[0]&&(i.unshift(e),i.length>sl&&(i.length=sl)),this.window.send_text_event({type:"line",terminator:r,value:e})}update(){this.reset();let e=this.window.inputs;if(!(e.type!=="char"&&e.type!=="line")){if(this.is_line=e.type==="line",this.el.attr({"aria-hidden":"false",maxlength:this.is_line?e.maxlen:1}).prop("disabled",!1).val(e.initial||""),this.is_line){if(this.window.type==="graphics")throw new Error(`Cannot request line input in graphics window ${this.window.id}`);this.el.addClass("LineInput")}switch(this.window.type){case"buffer":(this.window.lastline||this.window.innerel).append(this.el);break;case"grid":{let r=this.window.metrics;this.el.css({left:e.xpos*r.gridcharwidth+r.gridmarginx/2,top:e.ypos*r.gridcharheight+r.gridmarginy/2,width:(e.maxlen||1)*r.gridcharwidth});break}}if(this.window.type!=="graphics"){let r=this.window.last_run_styles;if(r){let i=!!r.reverse;this.el.toggleClass("reverse",i),So(r,i,this.el)}}}}},ll=st(()=>{function a(e){window.scrollTo(0,0),e>0&&setTimeout(a,50,e-1)}a(12)},1e3);function Pi(){return window.getSelection()+""==""}var Mi=class{constructor(e){this.desired=!0;this.blorb=e.blorb,this.dom=e.dom,this.id=e.id,this.manager=e.manager,this.metrics=e.metrics,this.type=e.type,this.frameel=this.dom.create("div",`window${e.id}`,{class:`WindowFrame ${T1[this.type]} WindowRock_${e.rock}`,click:r=>this.onclick(r)}).appendTo(this.dom.windowport()),this.textinput=new Bi(this)}destroy(e){this.textinput.destroy(),e?this.frameel.remove():this.inputs=void 0}measure_height(){}onclick(e){if(this.inputs?.type&&Pi())return this.textinput.el.trigger("focus"),!1}send_text_event(e){this.measure_height(),this.textinput.reset(),this.inputs.type=void 0,this.manager.active_window=this,e.window=this.id,this.manager.send_event(e)}};function So(a,e,r){let i=Object.assign({},a);if(e){let f=i["background-color"],u=i.color;f?i.color=f:delete i.color,u?i["background-color"]=u:delete i["background-color"],delete i.reverse}r.css(i)}function x1(a){let e=[""],r=/\s/,i=!1;for(let f of a){let u=r.test(f);!u&&i&&e.unshift(""),e[0]+=f,i=u}return e.reverse(),e}var Ui=class extends Mi{constructor(e){super(e);let r=i=>this.onlink(i);this.frameel.on("click","a",function(){r(this)}),e.styles&&(this.styles=e.styles,this.add_stylehints())}add_stylehints(){let e=`#window${this.id}`,r={};if(this.styles){for(let[_,p]of Object.entries(this.styles)){let y=`${e} ${_}`.trim(),x=r[y]=Object.assign({},p);if(_){let b=x["background-color"],A=x.color;if(b||A){let E=r[`${y}.reverse`]={};b&&(E.color=b),A&&(E["background-color"]=A)}delete x.monospace,x.reverse&&(delete x["background-color"],delete x.color),delete x.reverse,Object.keys(x).length===0&&delete r[y]}}r[`${e} .Style_input`]&&(r[`${e} .LineInput`]=r[`${e} .Style_input`])}let i=r[`${e} .Style_normal`],f=this.bg||i?.["background-color"],u=this.fg||i?.color;(f||u)&&(r[e]||(r[e]={}),r[e]["background-color"]=f||`var(--glkote-${this.type}-bg)`,r[`${e}.reverse`]={"background-color":u||`var(--glkote-${this.type}-reverse-bg)`}),Object.keys(r).length&&(this.frameel.children("style").remove(),this.frameel.prepend(``))}create_text_run(e,r){let i=e.style,f=e.css_styles?.monospace??this.styles?.[`.Style_${i}`]?.monospace,u="";typeof f<"u"&&(i==="preformatted"?f||(u=" proportional"):f&&(u=" monospace"));let _=e.css_styles?.reverse??this.styles?.[`.Style_${i}`]?.reverse,p=_e("span",`Style_${i}${_?" reverse":""}${u}`);e.css_styles&&So(e.css_styles,!!_,p),typeof r>"u"&&(r=!!f||i==="preformatted");let y=r?$(x1(e.text).map(x=>p.clone().text(x)[0])):p.text(e.text);return e.hyperlink?$("",{data:{glklink:e.hyperlink},href:"#"}).append(y):y}onlink(e){let r=$(e).data("glklink");if(r)return this.inputs?.hyperlink&&this.manager.send_event({type:"hyperlink",value:r,window:this.id}),!1}refresh_styles(e,r){let i;typeof e<"u"&&e!==this.bg&&(this.bg=e,i=1),typeof r<"u"&&r!==this.fg&&(this.fg=r,i=1),i&&this.add_stylehints()}},v1={inlinecenter:"ImageInlineCenter",inlinedown:"ImageInlineDown",inlineup:"ImageInlineUp",marginleft:"ImageMarginLeft",marginright:"ImageMarginRight"},To=class extends Ui{constructor(r){super(r);this.type="buffer";this.is_scrolled_down=!0;this.updatescrolltop=0;this.onscroll=()=>{let r=this.frameel[0];this.is_scrolled_down=r.scrollHeight-r.scrollTop-r.clientHeight<1};this.frameel.attr({"aria-live":"polite",role:"log",tabindex:-1}).on("scroll",this.onscroll),this.innerel=_e("div","BufferWindowInner").append(this.textinput.el).appendTo(this.frameel),this.height_above_keyboard=this.frameel.height()}measure_height(){this.height_above_keyboard=this.frameel.height()}onclick(r){if(this.inputs?.type&&Pi()){if(this.lastline&&this.height_above_keyboard){let i=this.lastline[0].getBoundingClientRect();if(i.bottom<0||i.top>document.documentElement.clientHeight)return!1}return this.textinput.el.trigger("focus"),!1}}scroll_to_bottom(r){(!r||this.is_scrolled_down)&&(this.frameel.scrollTop(this.innerel.height()),this.is_scrolled_down=!0)}update(r){if(r.clear&&(this.textinput.reset(),this.innerel.children(".BufferLine").remove(),this.is_scrolled_down=!0,this.lastline=void 0,this.last_run_styles=void 0,this.refresh_styles(r.bg,r.fg)),!r.text)return;this.frameel.attr("aria-busy","true"),this.updatescrolltop=Math.max(0,(this.lastline?.position().top||0)-20);let i=0;for(;i",{alt:b.alttext||`Image ${b.image}`,class:v1[b.alignment||"inlineup"],height:b.height,src:this.blorb&&this.blorb.get_image_url(b.image)||b.url,width:b.width});if(b.hyperlink){$("",{data:{glklink:b.hyperlink},href:"#"}).append(A).appendTo(_);continue}_.append(A);continue}else x=b;p||(p=1,_.addClass(`Style_${x.style}_par`)),_.append(this.create_text_run(x,i===r.text.length?!0:void 0)),this.last_run_styles=x.css_styles}}$t()||this.frameel.scrollTop(this.updatescrolltop),this.frameel.attr("aria-busy","false")}},Ao=class extends Mi{constructor(r){super(r);this.type="graphics";this.fillcolour="";this.framequeue=[];this.height=0;this.image_cache=new Map;this.width=0;this.clear_cache=at(()=>{this.image_cache.clear()},5e3);this.canvas=this.dom.create("canvas",`win${r.id}_canvas`,{data:{window:this}}),this.frameel.append(this.canvas),this.manager.canvasResizeObserver?.observe(this.canvas[0]),this.buffer=this.dom.create("canvas",`win${r.id}_buffer`)}decode_image(r,i){let f=new Image;return f.src=i,f.decode().then(()=>{this.image_cache.set(r,f)}).catch(()=>{})}destroy(r){this.manager.canvasResizeObserver?.unobserve(this.canvas[0]),super.destroy(r)}onclick(r){return this.inputs?.mouse&&r.button===0?(this.inputs.mouse=!1,this.manager.send_event({type:"mouse",window:this.id,x:Math.floor(r.offsetX-this.metrics.graphicsmarginx/2),y:Math.floor(r.offsetY-this.metrics.graphicsmarginy/2)}),!1):super.onclick(r)}set_dimensions(r,i){this.canvas.css({height:r,width:i}),this.height=r,this.width=i;let f=devicePixelRatio;r=r*f,i=i*f,this.buffer.attr({height:r,width:i}),this.canvas.attr({height:r,width:i})}async update(){let r=this.buffer[0].getContext("2d");for(let i=0;i3?"polite":"off"})}},S1={buffer:To,graphics:Ao,grid:Go},T1={buffer:"BufferWindow",graphics:"GraphicsWindow",grid:"GridWindow"},kr=class extends Map{constructor(r){super();this.history=[];this.onkeydown=r=>{if(!this.glkote.disabled&&r.target.nodeName!=="input"&&!(r.target.nodeName==="div"&&$(r.target).is(".BufferWindow:focus"))){let i=[...this.values()],f=i.filter(u=>u.inputs?.type)[0]||i.filter(u=>u.type==="buffer")[0];f&&(f.frameel.trigger("click"),f.textinput.el.is(":focus")?f.textinput.el.trigger(r):f.type==="buffer"&&f.frameel.trigger("focus"))}};if(this.dom=r.dom,this.glkote=r,this.metrics=r.current_metrics,window.ResizeObserver){let i=new ResizeObserver(f=>{typeof f?.[0].devicePixelContentBoxSize?.[0].blockSize<"u"&&(this.canvasResizeObserver=new ResizeObserver(u=>this.oncanvasresize(u))),i.disconnect()});i.observe(document.body)}this.send_event=i=>r.send_event(i),$(document).on("keydown",this.onkeydown),this.dom.gameport().on("click",()=>this.onclick())}destroy(){for(let r of this.values())r.destroy(!1),this.delete(r.id);$(document).off("keydown",this.onkeydown)}cancel_inputs(r){let i={};for(let f of r)i[f.id]=f;for(let f of this.values())!i[f.id]&&f.inputs&&(f.textinput.el.is(":focus")&&(this.active_window=f),f.textinput.el.prop("disabled",!0),delete f.inputs)}oncanvasresize(r){for(let i of r){let f=i.devicePixelContentBoxSize[0],u=f.blockSize,_=f.inlineSize,p=$(i.target).data("window");p.buffer.attr({height:u,width:_}),p.canvas.attr({height:u,width:_})}this.send_event({type:"redraw"})}onclick(){if(!this.glkote.disabled&&Pi()){for(let r of this.values())if(r.inputs?.type){r.frameel.trigger("click");break}}}update(r){for(let f of this.values())f.desired=!1;for(let f of r){let u=f.id,_=f.type,p=this.get(u);if(!p)p=new S1[_]({blorb:this.blorb,dom:this.dom,id:u,manager:this,metrics:this.metrics,rock:f.rock,styles:f.styles,type:_}),this.set(u,p);else if(p.type!==_)throw new Error(`Window ${u} was created with type ${p.type}, but now is described as type ${_}`);if(p.desired=!0,p.type==="graphics"&&(p.height!==f.graphheight||p.width!==f.graphwidth)&&p.set_dimensions(f.graphheight,f.graphwidth),p.type==="grid"){if(f.gridheight>p.height)for(let y=p.height;yi.inputs?.type)[0]?.textinput.refocus())}};var jt=class extends yr{constructor(){super();this.dom=new Wi({context_element:void 0,errorcontent_id:"errorcontent",errorpane_id:"errorpane",gameport_id:"gameport",loadingpane_id:"loadingpane",prefix:"",windowport_id:"windowport"});this.showing_error=!1;this.showing_loading=!0;this.on_document_scroll=st(async()=>{window.scrollTo(0,0)},500,{leading:!1});this.metrics_calculator=new br(this),this.windows=new kr(this)}async init(r){try{if(!r)throw new Error("no options provided");if(typeof jQuery>"u")throw new Error("jQuery is not loaded");r.dom_prefix&&(this.dom.prefix=r.dom_prefix),r.errorcontent&&(this.dom.errorcontent_id=r.errorcontent),r.errorpane&&(this.dom.errorpane_id=r.errorpane),r.gameport&&(this.dom.gameport_id=r.gameport),r.loadingpane&&(this.dom.loadingpane_id=r.loadingpane),r.windowport&&(this.dom.windowport_id=r.windowport),r.Blorb&&(this.windows.blorb=r.Blorb);let i=this.dom.windowport();if(!i.length)throw new Error(`Cannot find windowport element #${this.dom.windowport_id}`);i.empty(),$(document).on("scroll",this.on_document_scroll);let f="initial-scale=1,interactive-widget=resizes-content,minimum-scale=1,width=device-width";if(/iPhone OS/i.test(navigator.userAgent)&&(f+=",maximum-scale=1"),document.head.querySelector('meta[name="viewport"]').content=f,await this.metrics_calculator.measure(),r.recording_url||r.recording_handler)if(r.recording_format&&r.recording_format!=="simple")console.warn('GlkOte: only the "simple" recording_format is supported');else{let u=new URLSearchParams(document.location.search).get("feedback"),_=r.recording_cookie||"transcript_recording_opt_out";u&&u!=="1"||document.cookie.includes(`${_}=1`)?console.log("User has opted out of transcript recording."):this.transcript_recorder=new wr(r,this.windows)}return super.init(r)}catch(i){this.error(i)}}autorestore(r){Array.isArray(r.history)&&(this.windows.history=r.history);for(let i of this.windows.values())i.type==="buffer"&&i.scroll_to_bottom();if(r.graphics_bg)for(let[i,f]of r.graphics_bg)this.windows.get(i).fillcolour=f;r.transcript_recorder_session&&this.transcript_recorder&&(this.transcript_recorder.session=r.transcript_recorder_session,console.log(`Resuming autosaved transcript recording session: ${r.transcript_recorder_session}`)),setTimeout(()=>this.send_event({type:"arrange"}),0)}cancel_inputs(r){this.windows.cancel_inputs(r)}capabilities(){return["garglktext","graphics","graphicswin","hyperlinks","timer"]}disable(r){for(let i of this.windows.values())i.textinput.el.prop("disabled",r||!i.inputs?.type);this.disabled=r}embellish_error(){if(typeof $>"u")return;let r=$(`#${this.dom.errorpane_id}`);if(r.find("#errorclose").length||$("