vertigo 0.13.0

Reactive Real-DOM library with SSR for Rust
Documentation
1
2
"use strict";const e=new TextDecoder("utf-8"),t=new TextEncoder;class n{constructor(e,t){this.getUint8Memory=e,this.pointer=0,this.ptr=Number(t>>32n),this.size=Number(t%2n**32n),this.dataView=new DataView(this.getUint8Memory().buffer,this.ptr,this.size)}getByte(){const e=this.dataView.getUint8(this.pointer);return this.pointer+=1,e}setByte(e){this.dataView.setUint8(this.pointer,e),this.pointer+=1}getU16(){const e=this.dataView.getUint16(this.pointer);return this.pointer+=2,e}setU16(e){this.dataView.setUint16(this.pointer,e),this.pointer+=2}getU32(){const e=this.dataView.getUint32(this.pointer);return this.pointer+=4,e}setU32(e){this.dataView.setUint32(this.pointer,e),this.pointer+=4}getI32(){const e=this.dataView.getInt32(this.pointer);return this.pointer+=4,e}setI32(e){this.dataView.setInt32(this.pointer,e),this.pointer+=4}getU64(){const e=this.dataView.getBigUint64(this.pointer);return this.pointer+=8,e}setU64(e){this.dataView.setBigUint64(this.pointer,e),this.pointer+=8}getI64(){const e=this.dataView.getBigInt64(this.pointer);return this.pointer+=8,e}setI64(e){this.dataView.setBigInt64(this.pointer,e),this.pointer+=8}getF64(){const e=this.dataView.getFloat64(this.pointer);return this.pointer+=8,e}setF64(e){this.dataView.setFloat64(this.pointer,e),this.pointer+=8}getBuffer(){const e=this.getU32(),t=this.getUint8Memory().subarray(this.ptr+this.pointer,this.ptr+this.pointer+e);return this.pointer+=e,t}setBuffer(e){const t=e.length;this.setU32(t);this.getUint8Memory().subarray(this.ptr+this.pointer,this.ptr+this.pointer+t).set(e),this.pointer+=t}getString(){return e.decode(this.getBuffer())}setString(e){const n=t.encode(e);this.setBuffer(n)}getSavedSize(){return this.pointer}}const s=1,o=2,r=3,i=4,a=5,c=6,l=7,h=8,d=9,u=e=>{if(!0===e||!1===e||null==e)return 1;if("string"==typeof e)return 5+(new TextEncoder).encode(e).length;if("number"==typeof e)return 9;if(e instanceof Uint8Array)return 5+e.length;if(Array.isArray(e)){let t=5;for(const n of e)t+=u(n);return t}if("object"==typeof e&&null!==e){let t=3;for(const[n,s]of Object.entries(e))t+=4+(new TextEncoder).encode(n).length,t+=u(s);return t}throw new Error("jsJsonGetSize: Unknown type "+typeof e)},m=e=>{const t=e.getByte();if(t===s)return!0;if(t===o)return!1;if(t===r)return null;if(t!==i){if(t===a)return e.getString();if(t===c)return e.getF64();if(t===l){const t=e.getU32(),n=[];for(let s=0;s<t;s++)n.push(m(e));return n}if(t===h){const t=e.getU16(),n={};for(let s=0;s<t;s++){const t=e.getString(),s=m(e);n[t]=s}return n}if(t===d)return e.getBuffer().slice();throw new Error(`jsJsonDecodeItem: Unknown type id ${t}`)}},f=(e,t)=>{if(!0!==e)if(!1!==e)if(null!==e)if(void 0!==e){if("string"==typeof e)return t.setByte(a),void t.setString(e);if("number"==typeof e)return t.setByte(c),void t.setF64(e);if(e instanceof Uint8Array)return t.setByte(d),void t.setBuffer(e);if(!Array.isArray(e)){if("object"==typeof e&&null!==e){const n=Object.entries(e);t.setByte(h),t.setU16(n.length);for(const[e,s]of n)t.setString(e),f(s,t);return}throw new Error("saveJsJsonToBufferItem: Unknown type "+typeof e)}t.setByte(l),t.setU32(e.length);for(const n of e)f(n,t)}else t.setByte(i);else t.setByte(r);else t.setByte(o);else t.setByte(s)},g=async(e,t)=>{const s=await(async(e,t)=>{if("function"==typeof WebAssembly.instantiateStreaming){const n=fetch(e);try{return await WebAssembly.instantiateStreaming(n,t)}catch(e){console.warn("`WebAssembly.instantiateStreaming` failed. This could happen if your server does not serve wasm with `application/wasm` MIME type, but check the original error too. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e)}}console.info("fetchModule by WebAssembly.instantiate");const n=await fetch(e),s=await n.arrayBuffer();return await WebAssembly.instantiate(s,t)})(e,t);let o=new Uint8Array(1);const r=()=>{if(s.instance.exports.memory instanceof WebAssembly.Memory)return o.buffer!==s.instance.exports.memory.buffer&&(o=new Uint8Array(s.instance.exports.memory.buffer)),o;throw Error("Missing memory")},i=s.instance.exports;return{exports:i,getUint8Memory:r,wasmCommand:e=>{const t=u(e),s=i.vertigo_export_alloc_block(t),o=new n(r,s);f(e,o);let a=i.vertigo_export_wasm_command(s);if(0n===a)return null;const c=new n(r,a),l=m(c);return i.vertigo_export_free_block(a),l}}};class p{constructor(){this.events=new Set}on(e){let t=!0;const n=n=>{t&&e(n)};return this.events.add(n),()=>{t=!1,this.events.delete(n)}}trigger(e){const t=Array.from(this.events.values());for(const n of t)try{n(e)}catch(e){console.error(e)}}get size(){return this.events.size}}class v{constructor(){this.inner=null,this.resolve=e=>{const t=this.inner;this.inner=null,null!==t&&t.resolve(e)},this.reject=e=>{const t=this.inner;this.inner=null,null!==t&&t.reject(e)},this.isFulfilled=()=>null===this.inner;const[e,t]=(()=>{let e=null,t=null;const n=new Promise((n,s)=>{e=n,t=s});if(null===e)throw Error("createPromiseValue - resolve is null");if(null===t)throw Error("createPromiseValue - reject is null");return[{resolve:e,reject:t},n]})();this.inner=e,this.promise=t}}const w=async(e,t)=>{console.info(`${e} wait ${t}ms`),await(async e=>new Promise(t=>{setTimeout(t,e)}))(t),console.info(`${e} go forth`)};class b{constructor(e){this.host=e,this.formatLog=e=>`Socket ${this.host} ==> ${e}`}}class k{constructor(e,t){this.eventMessage=new p,this.close=e,this.send=t}static connect(e,t,n){const s=new v,o=new v,r=new WebSocket(t);let i=!1;console.info(e.formatLog("starting ..."));const a=()=>{i||(console.info(e.formatLog("close")),i=!0,s.resolve(null),o.resolve(),r.close())},c=new k(a,e=>{i||r.send(e)});setTimeout(()=>{!1===s.isFulfilled()&&(console.error(e.formatLog(`timeout (${n}ms)`)),a())},n);return r.addEventListener("open",()=>{console.info(e.formatLog("open")),s.resolve(c)}),r.addEventListener("error",t=>{console.error(e.formatLog("error"),t),a()}),r.addEventListener("close",a),r.addEventListener("message",t=>{if(i)return;const n=t.data;"string"!=typeof n?console.error(e.formatLog("onMessage - expected string"),n):c.eventMessage.trigger(n)}),{socket:s.promise,done:o.promise}}static startSocket(e,t,n,s){let o=!0,r=null;const i=new b(e);return(async()=>{for(;o;){const a=k.connect(i,e,t),c=await a.socket;if(null!==c){if(r=c,s({type:"socket",socket:c}),c.eventMessage.on(e=>{s({type:"message",message:e})}),await a.done,s({type:"close"}),!o)return void console.info(i.formatLog("disconnect (1)"));await w(i.formatLog("reconnect after close"),n)}else await w(i.formatLog("reconnect after error"),n)}console.info(i.formatLog("disconnect (2)"))})().catch(e=>{console.error(e)}),{send:e=>{null===r?console.error("send fail - missing connection",e):r.send(e)},dispose:()=>{o=!1,r?.close()}}}}const y=e=>{try{return JSON.parse(e)}catch{throw console.error("Failed to parse websocket message",e),Error(e)}},C=(e,t,n)=>{e.wasmCommand({Websocket:{callback:t,message:n}})};class E{constructor(e){this.websocket_register_callback=(e,t)=>{const n=this.getWasm();let s=k.startSocket(e,5e3,3e3,e=>{if(!1!==this.controllerList.has(t)){if("socket"===e.type)return this.socket.set(t,e.socket),void C(n,t,"Connected");if("message"!==e.type)return"close"===e.type?(this.socket.delete(t),void C(n,t,"Disconnected")):(e=>{throw console.error(e),Error("unknown message")})(e);C(n,t,{Message:{message:y(e.message)}})}});this.controllerList.set(t,s)},this.websocket_unregister_callback=e=>{const t=this.controllerList.get(e);void 0!==t?(t.dispose(),this.controllerList.delete(e)):console.error("Expected controller")},this.websocket_send_message=(e,t)=>{const n=this.socket.get(e);var s;void 0===n?console.error(`Missing socket connection for callback_id=${e}`):n.send((s=t,JSON.stringify(s)))},this.getWasm=e,this.controllerList=new Map,this.socket=new Map}}const T=e=>{const t={};for(const{k:n,v:s}of e)t[n]=s;return t},L=e=>{if("None"!==e)return JSON.stringify(e.Data.data)},x=async e=>{const t=e.status,n=e.headers.get("Content-Type");try{if(n?.startsWith("text/plain;"))return{Ok:{status:t,response:{Text:await e.text()}}};return{Ok:{status:t,response:{Json:0===(s=await e.text()).length?null:JSON.parse(s)}}}}catch(e){return{Err:{message:String(e)}}}var s};class N{constructor(e){this.timerSet=(e,t,n)=>{switch(n){case"Interval":{const n=setInterval(()=>{this.getWasm().wasmCommand({TimerCall:{callback:e}})},t);this.data.set(e,{kind:"Interval",timerId:n});break}case"Timeout":{const n=setTimeout(()=>{this.getWasm().wasmCommand({TimerCall:{callback:e}})},t);this.data.set(e,{kind:"Timeout",timerId:n});break}}},this.timerClear=e=>{const t=this.data.get(e);if(void 0===t)throw Error("panic");switch(t.kind){case"Interval":clearInterval(t.timerId);break;case"Timeout":clearTimeout(t.timerId)}},this.getWasm=e,this.data=new Map}}class S{constructor(e){this.trigger=()=>{for(const e of Array.from(this.callback.values()))e()},this.add=e=>{this.callback.set(e,()=>{this.getWasm().wasmCommand({LocationCall:{callback:e,value:this.get()}})})},this.remove=e=>{this.callback.delete(e)},this.push=e=>{this.get()!==e&&(location.hash=e,this.trigger())},this.replace=e=>{this.get()!==e&&history.replaceState(null,"",`#${e}`)},this.getWasm=e,this.callback=new Map,window.addEventListener("hashchange",this.trigger)}get(){return decodeURIComponent(location.hash.substr(1))}}class _{constructor(e){this.trigger=()=>{for(const e of Array.from(this.callback.values()))e()},this.add=e=>{this.callback.set(e,()=>{this.getWasm().wasmCommand({LocationCall:{callback:e,value:this.get()}})})},this.remove=e=>{this.callback.delete(e)},this.push=e=>{this.get()!==e&&(window.history.pushState(null,"",e),this.trigger())},this.replace=e=>{this.get()!==e&&(window.history.replaceState(null,"",e),this.trigger())},this.getWasm=e,this.callback=new Map,window.addEventListener("popstate",this.trigger)}get(){return window.location.pathname+window.location.search+window.location.hash}}class A{constructor(e){this.callback=(e,t,n)=>{switch(t){case"Add":return void this.locations[e].add(n);case"Remove":return void this.locations[e].remove(n)}},this.set=(e,t,n)=>{switch(t){case"Push":return void this.locations[e].push(n);case"Replace":return void this.locations[e].replace(n)}},this.get=e=>this.locations[e].get(),this.locations={Hash:new S(e),History:new _(e)}}}class M{constructor(){this.get=e=>{for(const t of document.cookie.split(";")){if(""===t)continue;const n=t.trim().split("=");if(2!==n.length){console.warn(`Cookies.get: Incorrect number of cookieChunk => ${n.length} in ${t}`);continue}const s=n[0],o=n[1];if(void 0!==s&&void 0!==o){if(s===e)return decodeURIComponent(o)}else console.warn(`Cookies.get: Broken cookie part => ${t}`)}return""},this.getJson=e=>{let t=this.get(e);if(0!==t.length)try{return JSON.parse(t)}catch(e){console.error("Error deserializing cookie",e)}return null},this.set=(e,t,n)=>{const s=null==t?"":encodeURIComponent(t),o=new Date;o.setTime(o.getTime()+1e3*n);let r="expires="+o.toUTCString();document.cookie=`${e}=${s};${r};path=/; samesite=Strict`},this.setJson=(e,t,n)=>{let s=JSON.stringify(t);this.set(e,s,n)}}}const I=(e,t)=>{const n=t-e+1;return e+Math.floor(Math.random()*n)};class ${constructor(e){this.getWasm=e,this.callbacks=new Map,this.observers=new Map}add(e,t,n,s){if("intersect"===n)return this.intersectAdd(e,t,s);const o=e=>"click"===n?this.click(e,s):"submit"===n?this.submit(e,s):"input"===n?this.input(e,s):"change"===n?this.change(e,s):"blur"===n?this.blur(e,s):"mousedown"===n?this.mousedown(e,s):"mouseup"===n?this.mouseup(e,s):"mouseenter"===n?this.mouseenter(e,s):"mouseleave"===n?this.mouseleave(e,s):"keydown"===n||"hook_keydown"===n?this.keydown(e,s):"drop"===n?this.drop(e,s):"load"===n?this.load(e,s):"change_file"===n?this.changeFile(e,s):void console.error(`No support for the event ${n}`);if(this.callbacks.has(s))console.error(`There was already a callback added with the callback_id=${s}`);else if(this.callbacks.set(s,o),"hook_keydown"===n)document.addEventListener("keydown",o,!1);else{const s=e.get("callback_add",t),r="change_file"===n?"change":n;s.addEventListener(r,o,!1)}}remove(e,t,n,s){if("intersect"===n)return this.intersectRemove(s);const o=this.callbacks.get(s);if(this.callbacks.delete(s),void 0!==o)if("hook_keydown"===n)document.removeEventListener("keydown",o);else{const s="change_file"===n?"change":n;e.get("callback_remove",t).removeEventListener(s,o)}else console.error(`The callback is missing with the id=${s}`)}wasmCallback(e,t){return this.getWasm().wasmCommand({CallbackCall:{callback_id:e,value:t}})}intersectAdd(e,t,n){if(this.observers.has(n))return void console.error(`There was already an intersect observer added with the callback_id=${n}`);const s=e.getNode("callback_add",t),o=new IntersectionObserver(e=>{for(const t of e)this.wasmCallback(n,[t.isIntersecting,t.intersectionRatio,t.boundingClientRect.top,t.boundingClientRect.bottom,t.boundingClientRect.height])});o.observe(s),this.observers.set(n,o)}intersectRemove(e){const t=this.observers.get(e);this.observers.delete(e),void 0!==t?t.disconnect():console.error(`The intersect observer is missing with the id=${e}`)}click(e,t){e.preventDefault();let n=this.wasmCallback(t,void 0);null===n||"object"!=typeof n||Array.isArray(n)||("stop_propagation"in n&&!0===n.stop_propagation&&e.stopPropagation(),"prevent_default"in n&&!0===n.prevent_default&&e.preventDefault())}submit(e,t){e.preventDefault(),this.wasmCallback(t,void 0)}input(e,t){const n=e.target;n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?this.wasmCallback(t,n.value):console.warn("event input ignore",n)}change(e,t){const n=e.target;n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement?this.wasmCallback(t,n.value):console.warn("event input ignore",n)}changeFile(e,t){const n=e.target;if(n instanceof HTMLInputElement&&null!==n.files&&n.files.length>0){const e=[];for(let t=0;t<n.files.length;t++){const s=n.files[t];void 0!==s&&e.push(s.arrayBuffer().then(e=>({name:s.name,data:new Uint8Array(e)})))}return e.length>0&&Promise.all(e).then(e=>{const n=[];for(const t of e)n.push([t.name,Array.from(t.data)]);this.wasmCallback(t,[n])}).catch(e=>console.error("changeFile ->",e)),void(n.value="")}console.warn("changeFile: not a file input or no files",n)}blur(e,t){this.wasmCallback(t,void 0)}mousedown(e,t){this.wasmCallback(t,void 0)&&e.preventDefault()}mouseup(e,t){this.wasmCallback(t,void 0)&&e.preventDefault()}mouseenter(e,t){this.wasmCallback(t,void 0)}mouseleave(e,t){this.wasmCallback(t,void 0)}drop(e,t){if(e.preventDefault(),e instanceof DragEvent)if(null===e.dataTransfer)console.error("dom -> drop -> dataTransfer null");else{const n=function(e){const t=[];for(let n=0;n<e.length;n++){const s=e[n];if(void 0===s)console.error("dom -> drop -> item - undefined");else{const e=s.getAsFile();null===e?console.error(`dom -> drop -> index:${n} -> It's not a file`):t.push(e.arrayBuffer().then(t=>({name:e.name,data:new Uint8Array(t)})))}}return t}(e.dataTransfer.items);n.length?Promise.all(n).then(e=>{const n=[];for(const t of e){const e=Array.from(t.data);n.push([t.name,e])}this.wasmCallback(t,[n])}).catch(e=>{console.error("callback_drop -> promise.all -> ",e)}):console.error("No files to send")}else console.warn("event drop ignore",e)}keydown(e,t){if(e instanceof KeyboardEvent){return void(!0===this.wasmCallback(t,[e.key,e.code,e.altKey,e.ctrlKey,e.shiftKey,e.metaKey])&&(e.preventDefault(),e.stopPropagation()))}console.warn("keydown ignore",e)}load(e,t){e.preventDefault(),this.wasmCallback(t,void 0)}}function U(e,t){e.addEventListener("click",n=>{let s=e.getAttribute("href");null!==s&&(s.startsWith("#")||s.startsWith("http://")||s.startsWith("https://")||s.startsWith("//")||(n.preventDefault(),t.set("History","Push",s),window.scrollTo(0,0)))})}class B{constructor(e,t,n){this.depth=-1,this.matched=0,this.nodes=t,this.appLocation=n,this.virtualNodes=this.createVirtualNodes(e)}hydrate(){this.virtualNodes.get(3)&&this.hydrateNode(3,document.body);this.virtualNodes.get(2)&&this.hydrateNode(2,document.head),console.log("Hydration complete,",(100*this.matched/this.virtualNodes.size).toFixed(2)," % vnodes matched.")}hydrateNode(e,t){const n=this.virtualNodes.get(e);if(!n)return;const s=Array.from(t.childNodes);let o=0;this.depth++;let r=!1;for(const e of n.children){const t=this.virtualNodes.get(e);if(t)if(r&&void 0!==t.value)this.matched++;else{r=!1;for(let n=o;n<s.length;n++){const i=s[n];if(!i)continue;let a=!1;if(t.name?a=this.checkElementMatch(i,t):void 0!==t.value&&(i.nodeType===Node.TEXT_NODE?(this.checkTextMatch(i,t),a=!0,r=!0):console.error(`Hydration ${this.depth}: Text node mismatch`,t,i)),a){this.removeSkippedNodes(s,o,n),this.claimNode(i,e),this.matched++,t.name&&this.hydrateNode(e,i),o=n+1;break}}}}this.removeSkippedNodes(s,o,s.length),this.depth--}checkElementMatch(e,t){let n=!1;if(e.nodeType===Node.ELEMENT_NODE&&e.tagName===t.name&&(n=!0,t.attributes)){const n=e;for(const[e,s]of t.attributes)n.getAttribute(e)!==s&&n.setAttribute(e,s)}return n}checkTextMatch(e,t){e.textContent?.replace("\n"," ").trim()!==t.value?.replace("\n"," ").trim()&&(e.textContent=t.value||"")}claimNode(e,t){var n,s;(e instanceof Element||e instanceof Comment||e instanceof Text)&&(this.nodes.claimNode(t,e),e instanceof Element&&(n=e,s=this.appLocation,"a"===n.tagName.toLowerCase()&&U(n,s)))}removeSkippedNodes(e,t,n){for(let s=t;s<n;s++){const t=e[s];t&&(0!==this.depth&&t.nodeType!==Node.TEXT_NODE&&console.warn(`Hydration ${this.depth}: Removing node`,t),t.remove())}}createVirtualNodes(e){const t=new Map,n=e=>{let n=t.get(e);return n||(n={id:e,children:[]},t.set(e,n)),n};for(const t of e)if("CreateNode"in t){n(t.CreateNode.id).name=t.CreateNode.name.toUpperCase()}else if("CreateText"in t){n(t.CreateText.id).value=t.CreateText.value}else if("InsertBefore"in t){const e=n(t.InsertBefore.parent),s=t.InsertBefore.child,o=t.InsertBefore.ref_id;if(null==o)e.children.push(s);else{const n=e.children.indexOf(o);-1!==n?e.children.splice(n,0,s):(console.warn(`Hydration: ref_id ${o} not found in parent ${t.InsertBefore.parent}`),e.children.push(s))}}else if("SetAttr"in t){const e=n(t.SetAttr.id);e.attributes||(e.attributes=new Map),e.attributes.set(t.SetAttr.name,t.SetAttr.value)}return t}}const R=1,W=2,D=3,F=4,O=5,H=6,J=7,V=8,G=9,j=10,P=11,z=12,K=13,q=new TextDecoder("utf-8");class X{constructor(e){this.bytes=e,this.at=0}isEmpty(){return this.at>=this.bytes.length}where(){return`offset ${this.at} of ${this.bytes.length}`}byte(){const e=this.bytes[this.at];if(void 0===e)throw new Error("dom command: buffer ended early");return this.at+=1,e}varint(){let e=0,t=1;for(;;){const n=this.byte();if(e+=(127&n)*t,!(128&n))return e;t*=128}}string(){const e=this.varint(),t=this.at+e;if(t>this.bytes.length)throw new Error("dom command: string runs past the end of the buffer");const n=q.decode(this.bytes.subarray(this.at,t));return this.at=t,n}name(e){const t=this.varint(),n=e[t];if(void 0===n)throw new Error(`dom command: name index ${t} is not in the dictionary`);return n}optionalId(){const e=this.varint();return 0===e?null:e}}const Q=e=>{const t=e.varint(),n=[];for(let s=0;s<t;s++)n.push(e.string());return n};class Y{constructor(){this.data=new Map,this.initNodes=[...this.getRootHead().childNodes,...this.getRootBody().childNodes],this.style=document.createElement("style")}getRootHtml(){return document.documentElement}getRootHead(){return document.head}getRootBody(){return document.body}set(e,t){1===e||2===e||3===e||this.data.set(e,t)}getAnyOption(e){return 1===e?this.getRootHtml():2===e?this.getRootHead():3===e?this.getRootBody():this.data.get(e)}getAny(e,t){const n=this.getAnyOption(t);if(void 0===n)throw Error(`${e} -> item not found=${t}`);return n}get(e,t){const n=this.getAnyOption(t);if(void 0===n)throw new Error(`${e}->get: Item id not found = ${t}`);return n}getNodeElement(e,t){const n=this.get(e,t);if(n instanceof HTMLElement)return n;throw Error(`Expected id=${t} as HTMLElement`)}getNode(e,t){const n=this.get(e,t);if(n instanceof Element)return n;throw Error(`Expected id=${t} as Element`)}getText(e,t){const n=this.get(e,t);if(n instanceof Text)return n;throw Error(`Expected id=${t} as Text`)}getComment(e,t){const n=this.get(e,t);if(n instanceof Comment)return n;throw Error(`Expected id=${t} as Comment`)}delete(e,t){const n=this.getAnyOption(t);if(this.data.delete(t),void 0===n)throw new Error(`${e}->delete: Item id not found = ${t}`);return n}insertCss(e,t){if(null!==e){const n=document.createTextNode(`\n${e} { ${t} }`);this.style.appendChild(n)}else{const e=document.createTextNode(`\n${t}`);this.style.appendChild(e)}}removeInitNodes(){const e=this.initNodes;if(this.initNodes=null,null!==e)for(const t of e)t.remove()}insertBefore(e,t,n){const s=this.get("insert_before",e),o=this.getAny("insert_before child",t);if(null==n)s.insertBefore(o,null);else{const e=this.getAny("insert_before ref",n);s.insertBefore(o,e)}}addStyles(){this.getRootHead().appendChild(this.style)}hasInitNodes(){return null!==this.initNodes}claimNode(e,t){if(this.data.set(e,t),this.initNodes){const e=this.initNodes.indexOf(t);e>-1&&this.initNodes.splice(e,1)}}has(e){return 1===e||2===e||3===e||this.data.has(e)}}const Z=new Set(["animate","animateMotion","animateTransform","circle","clipPath","defs","desc","discard","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","foreignObject","g","hatch","hatchpath","image","line","linearGradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialGradient","rect","set","stop","svg","switch","symbol","text","textPath","tspan","use","view","svg:a","svg:title","svg:desc","svg:script","svg:style"]),ee=(e,t)=>{console.error("bulk_update - item",t,e)},te=(e,t)=>e.findIndex(e=>e.toLowerCase()===t);class ne{constructor(e,t,n){this.metadata=e,this.update=e=>{this.nodes.hasInitNodes()&&this.metadata.getEnabledHydration()&&((e,t,n)=>{new B(e,t,n).hydrate()})((e=>{const t=new X(e),n=Q(t),s=[];for(;!t.isEmpty();){const e=t.byte();switch(e){case R:s.push({CreateNode:{id:t.varint(),name:t.name(n)}});break;case W:s.push({CreateText:{id:t.varint(),value:t.string()}});break;case D:s.push({UpdateText:{id:t.varint(),value:t.string()}});break;case F:s.push({SetAttr:{id:t.varint(),name:t.name(n),value:t.string()}});break;case O:s.push({RemoveAttr:{id:t.varint(),name:t.name(n)}});break;case H:s.push({RemoveNode:{id:t.varint()}});break;case J:s.push({RemoveText:{id:t.varint()}});break;case V:s.push({InsertBefore:{parent:t.varint(),child:t.varint(),ref_id:t.optionalId()}});break;case G:s.push({InsertCss:{selector:0===t.byte()?null:t.string(),value:t.string()}});break;case j:s.push({CreateComment:{id:t.varint(),value:t.string()}});break;case P:s.push({RemoveComment:{id:t.varint()}});break;case z:s.push({CallbackAdd:{id:t.varint(),event_name:t.string(),callback_id:t.varint()}});break;case K:s.push({CallbackRemove:{id:t.varint(),event_name:t.string(),callback_id:t.varint()}});break;default:throw new Error(`dom command: unknown tag ${e}`)}}return s})(e),this.nodes,this.appLocation);const t=new X(e),n=Q(t),s=te(n,"autofocus"),o=te(n,"a"),r=new Set;try{for(;!t.isEmpty();){const e=t.byte();switch(e){case R:{const e=t.varint(),s=t.varint();try{this.createNode(e,n[s]??"",s===o)}catch(e){ee(e,"CreateNode")}break}case W:{const e=t.varint(),n=t.string();try{this.createText(e,n)}catch(e){ee(e,"CreateText")}break}case D:{const e=t.varint(),n=t.string();try{this.updateText(e,n)}catch(e){ee(e,"UpdateText")}break}case F:{const e=t.varint(),o=t.varint(),i=t.string();o===s&&r.add(e);try{this.setAttr(e,n[o]??"",i)}catch(e){ee(e,"SetAttr")}break}case O:{const e=t.varint(),s=t.varint();try{this.removeAttr(e,n[s]??"")}catch(e){ee(e,"RemoveAttr")}break}case H:{const e=t.varint();try{this.removeNode(e)}catch(e){ee(e,"RemoveNode")}break}case J:{const e=t.varint();try{this.removeText(e)}catch(e){ee(e,"RemoveText")}break}case V:{const e=t.varint(),n=t.varint(),s=t.optionalId();try{this.nodes.insertBefore(e,n,s)}catch(e){ee(e,"InsertBefore")}break}case G:{const e=0===t.byte()?null:t.string(),n=t.string();try{this.nodes.insertCss(e,n)}catch(e){ee(e,"InsertCss")}break}case j:{const e=t.varint(),n=t.string();try{this.nodes.set(e,document.createComment(n))}catch(e){ee(e,"CreateComment")}break}case P:{const e=t.varint();try{this.nodes.delete("remove_comment",e).remove()}catch(e){ee(e,"RemoveComment")}break}case z:{const e=t.varint(),n=t.string(),s=t.varint();try{this.callbacks.add(this.nodes,e,n,s)}catch(e){ee(e,"CallbackAdd")}break}case K:{const e=t.varint(),n=t.string(),s=t.varint();try{this.callbacks.remove(this.nodes,e,n,s)}catch(e){ee(e,"CallbackRemove")}break}default:throw new Error(`bulk_update: unknown command tag ${e}`)}}}catch(e){console.error(`bulk_update - stream is unreadable at ${t.where()}, dropping the rest of the batch`,e)}r.size>0&&setTimeout(()=>{for(const e of r){this.nodes.getNodeElement(`set focus ${e}`,e).focus()}},0),this.nodes.removeInitNodes(),this.nodes.addStyles()},this.appLocation=t,this.nodes=new Y,this.callbacks=new $(n),document.addEventListener("dragover",e=>{e.preventDefault()})}createNode(e,t,n){if(1===e||2===e||3===e)return;if(this.nodes.has(e))return;const s=(e=>Z.has(e)?document.createElementNS("http://www.w3.org/2000/svg",e.replace("svg:","")):document.createElement(e))(t);this.nodes.set(e,s),n&&U(s,this.appLocation)}setAttr(e,t,n){const s=this.nodes.getNode("set_attribute",e);if(s.setAttribute(t,n),"value"==t){if(s instanceof HTMLInputElement)return void(s.value=n);if(s instanceof HTMLTextAreaElement)return s.value=n,void(s.defaultValue=n)}}removeAttr(e,t){const n=this.nodes.getNode("remove_attribute",e);if(n.removeAttribute(t),"value"==t){if(n instanceof HTMLInputElement)return void(n.value="");if(n instanceof HTMLTextAreaElement)return n.value="",void(n.defaultValue="")}}removeNode(e){if(1===e||2===e||3===e)return;this.nodes.delete("remove_node",e).remove()}createText(e,t){if(this.nodes.has(e))return;const n=document.createTextNode(t);this.nodes.set(e,n)}removeText(e){this.nodes.delete("remove_node",e).remove()}updateText(e,t){this.nodes.getText("set_attribute",e).textContent=t}}class se{constructor(e,t){this.metadata=e,this.getWasm=t;const n=new A(t);this.dom=new ne(e,n,t),this.websocket=new E(t),this.interval=new N(t),this.location=n,this.cookie=new M}exec(e){const t=e;if("FetchCacheGet"===t)return{data:this.metadata.getFetchCache()};if("IsBrowser"===t)return{value:!0};if("GetDateNow"===t)return{value:Date.now()};if("TimezoneOffset"===t)return{value:(new Date).getTimezoneOffset()};if("HistoryBack"===t)return window.history.back(),null;if("FetchExec"in t)return(async(e,t,n)=>{const s=e();try{const e=await fetch(n.url,{method:n.method,headers:T(n.headers),body:L(n.body)}),o=await x(e);s.wasmCommand({FetchExecResponse:{response:o,callback:t}})}catch(e){console.error("fetch error (1)",e);const n={Err:{message:new String(e).toString()}};s.wasmCommand({FetchExecResponse:{response:n,callback:t}})}})(this.getWasm,t.FetchExec.callback,t.FetchExec.request),null;if("WebsocketRegister"in t)return this.websocket.websocket_register_callback(t.WebsocketRegister.host,t.WebsocketRegister.callback),null;if("WebsocketSendMessage"in t)return this.websocket.websocket_send_message(t.WebsocketSendMessage.callback,t.WebsocketSendMessage.message),null;if("WebsocketUnregister"in t)return this.websocket.websocket_unregister_callback(t.WebsocketUnregister.callback),null;if("TimerSet"in t)return this.interval.timerSet(t.TimerSet.callback,t.TimerSet.duration,t.TimerSet.kind),null;if("TimerClear"in t)return this.interval.timerClear(t.TimerClear.callback),null;if("LocationGet"in t)return{value:this.location.get(t.LocationGet.target)};if("LocationCallback"in t)return this.location.callback(t.LocationCallback.target,t.LocationCallback.mode,t.LocationCallback.callback),null;if("LocationSet"in t)return this.location.set(t.LocationSet.target,t.LocationSet.mode,t.LocationSet.value),null;if("CookieGet"in t)return{value:this.cookie.get(t.CookieGet.name)};if("CookieSet"in t)return this.cookie.set(t.CookieSet.name,t.CookieSet.value,t.CookieSet.expires_in),null;if("CookieJsonGet"in t)return{value:this.cookie.getJson(t.CookieJsonGet.name)};if("CookieJsonSet"in t)return this.cookie.setJson(t.CookieJsonSet.name,t.CookieJsonSet.value,t.CookieJsonSet.expires_in),null;if("GetEnv"in t){const e=t.GetEnv.name;return{value:this.metadata.getEnv(e)}}if("Log"in t)switch(t.Log.kind){case"Info":return console.info(t.Log.message,t.Log.arg2,t.Log.arg3,t.Log.arg4),null;case"Debug":return console.debug(t.Log.message,t.Log.arg2,t.Log.arg3,t.Log.arg4),null;case"Error":return console.error(t.Log.message,t.Log.arg2,t.Log.arg3,t.Log.arg4),null;case"Log":return console.log(t.Log.message,t.Log.arg2,t.Log.arg3,t.Log.arg4),null;case"Warn":return console.warn(t.Log.message,t.Log.arg2,t.Log.arg3,t.Log.arg4),null}return"GetRandom"in t?{value:I(t.GetRandom.min,t.GetRandom.max)}:"JsApiCall"in t?this.executeJsApiCall(t.JsApiCall.commands):"DomBulkUpdate"in t?(this.dom.update(t.DomBulkUpdate.commands),null):(console.info("exec_command: Arg",t),(()=>{throw Error("assert never")})())}executeJsApiCall(e){let t=null;for(const n of e)if("Root"in n)if("window"===n.Root.name)t=window;else{if("document"!==n.Root.name)return console.error(`Unknown root: ${n.Root.name}`),null;t=document}else if("RootElement"in n){const e=n.RootElement.dom_id,s=this.dom.nodes.getAnyOption(e);if(void 0===s)return console.error(`Element not found: ${e}`),null;t=s}else if("Get"in n){if(null===t)return console.error("Get called on null"),null;t=t[n.Get.property]}else if("Set"in n){if(null===t)return console.error("Set called on null"),null;t[n.Set.property]=n.Set.value,t=void 0}else if("Call"in n){if(null===t)return console.error("Call called on null"),null;t=t[n.Call.method](...n.Call.args)}const n=e=>{if(null==e)return null;if("boolean"==typeof e)return e;if("string"==typeof e)return e;if("number"==typeof e)return e;if(e instanceof Uint8Array)return e;if(Array.isArray(e))return e.map(e=>n(e));if((e=>{if(null===e)return!1;if("object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t})(e)){const t={};for(const s of Object.keys(e))t[s]=n(e[s]);return t}return null};return n(t)}}class oe{constructor(){this.get=e=>this.metadata.getAttribute(e)??null,this.getEnabledHydration=()=>"true"!==this.get("data-env-disable-hydration");const e=document.getElementById("v-metadata");if(null===e)throw Error("Expected v-metadata");this.metadata=e,e.remove()}getEnv(e){return this.get(`data-env-${e}`)}getFetchCache(){return this.get("data-fetch-cache")??null}}class re{constructor(e){this.wasm=e}vertigoEntryFunction(e,t){this.wasm.exports.vertigo_entry_function(e,t)}static async create(e){let t=null;const s=()=>{if(null===t)throw Error("Wasm is no initialized");return t},o=new oe,r=new se(o,s);return window.$vertigoApi=r,t=await g(e,{mod:{panic_message:e=>{const t=Number(e%2n**32n),n=Number(e>>32n),o=new TextDecoder("utf-8"),r=s().getUint8Memory().subarray(n,n+t),i=o.decode(r);console.error("PANIC",i)},dom_access:e=>{if(0n===e)return console.error("dom_access - null pointer"),0n;const t=new n(()=>s().getUint8Memory(),e),o=m(t);s().exports.vertigo_export_free_block(e);const i=r.exec(o),a=u(i),c=s().exports.vertigo_export_alloc_block(a),l=new n(()=>s().getUint8Memory(),c);return f(i,l),c}}}),new re(t)}}const ie=new Set,ae=async()=>{document.querySelectorAll("*[data-vertigo-run-wasm]").forEach(e=>{const t=e.getAttribute("data-vertigo-run-wasm");"string"==typeof t?(async e=>{if(ie.has(e))return;if(ie.size>0)return void console.error("Only one wasm module can be run",{moduleRun:ie,wasm:e});ie.add(e),console.info(`Wasm module: "${e}" -> start`);const t=await re.create(e);console.info(`Wasm module: "${e}" -> initialized`),t.vertigoEntryFunction(0,13),console.info(`Wasm module: "${e}" -> launched vertigoEntryFunction with version 0.13`)})(t):console.error("Run error",e)})};window.addEventListener("load",ae),setTimeout(ae,3e3);
//# sourceMappingURL=wasm_run.js.map