diff --git a/.gitignore b/.gitignore index 3b735ec..9b0ee9c 100644 --- a/.gitignore +++ b/.gitignore @@ -18,4 +18,4 @@ # vendor/ # Go workspace file -go.work +# go.work diff --git a/go.mod b/go.mod index e384729..f231777 100644 --- a/go.mod +++ b/go.mod @@ -6,3 +6,5 @@ require ( github.com/mdm-code/scanner v1.2.1 github.com/pelletier/go-toml/v2 v2.1.0 ) + +require github.com/stretchr/testify v1.10.0 // indirect diff --git a/go.sum b/go.sum index 24b2f84..c1eedcf 100644 --- a/go.sum +++ b/go.sum @@ -12,8 +12,9 @@ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSS github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/go.work b/go.work new file mode 100644 index 0000000..349edc2 --- /dev/null +++ b/go.work @@ -0,0 +1,6 @@ +go 1.24.0 + +use ( + . + ./tqweb +) diff --git a/tqweb/Makefile b/tqweb/Makefile new file mode 100644 index 0000000..dab8b2f --- /dev/null +++ b/tqweb/Makefile @@ -0,0 +1,42 @@ +GO=go +GOFLAGS=-mod=vendor +HTMX_VERSION?=2.0.8 +# NOTE +# ==== +# #1 The master version of the Javascript code fom the go-wasm-http-server has +# been updated since the version v2.2.1. If for any reason it might be necessary +# to revert to the version used in Go code, here is a quick shell script to +# pull the version from the go.mod file. +# +# #2 The master version seems not to work right with Go 1.24.0. +# +GO_WASM_HTTP_SERVER_VERSION?=$(shell\ + grep go-wasm-http-server go.mod |\ + cut -d' ' -f3\ +) +# GO_WASM_HTTP_SERVER_VERSION?=master +# ==== + +# export CGO_ENABLED=0 +export GOOS=js +export GOARCH=wasm + +ifndef VERBOSE +.SILENT: +endif + +.PHONY: assets build serve + +.PHONY: .ONESHELL +.ONESHELL: + +assets: + cp $$(go env GOROOT)/lib/wasm/wasm_exec.js wasm_exec.js + curl https://cdn.jsdelivr.net/npm/htmx.org@$(HTMX_VERSION)/dist/htmx.min.js > htmx.min.js + curl https://cdn.jsdelivr.net/gh/nlepage/go-wasm-http-server@$(GO_WASM_HTTP_SERVER_VERSION)/sw.js > sw.js + +build: + $(GO) build $(GOFLAGS) -o api.wasm . + +serve: + $(shell goexec 'http.ListenAndServe(`:18080`, http.FileServer(http.Dir(`.`)))') diff --git a/tqweb/go.mod b/tqweb/go.mod new file mode 100644 index 0000000..ed39d38 --- /dev/null +++ b/tqweb/go.mod @@ -0,0 +1,16 @@ +module github.com/mdm-code/tqweb + +go 1.24.0 + +require ( + github.com/mdm-code/tq/v2 v2.4.0 + github.com/nlepage/go-wasm-http-server/v2 v2.2.1 +) + +require ( + github.com/hack-pad/safejs v0.1.1 // indirect + github.com/mdm-code/scanner v1.2.1 // indirect + github.com/nlepage/go-js-promise v1.0.0 // indirect + github.com/pelletier/go-toml/v2 v2.1.0 // indirect + github.com/stretchr/testify v1.10.0 // indirect +) diff --git a/tqweb/go.sum b/tqweb/go.sum new file mode 100644 index 0000000..420a222 --- /dev/null +++ b/tqweb/go.sum @@ -0,0 +1,29 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/hack-pad/safejs v0.1.1 h1:d5qPO0iQ7h2oVtpzGnLExE+Wn9AtytxIfltcS2b9KD8= +github.com/hack-pad/safejs v0.1.1/go.mod h1:HdS+bKF1NrE72VoXZeWzxFOVQVUSqZJAG0xNCnb+Tio= +github.com/mdm-code/scanner v1.2.1 h1:GZ1DYAkhTXK+M4AG65L5fnl5eUt7M6XDAYBVZNH+cBc= +github.com/mdm-code/scanner v1.2.1/go.mod h1:ut94FGYZVrQk7uBkf0vJ0ngKuJbdkTEDnmY07ZI8yb0= +github.com/mdm-code/tq/v2 v2.4.0 h1:vjrQfjRROhzquRSjPCrYGdlXTAqZSOdwS6/62hRsfrA= +github.com/mdm-code/tq/v2 v2.4.0/go.mod h1:VfOFONplmcxx0EXu8rLZYpC8dOJg76EYnwbnXL9R4ZA= +github.com/nlepage/go-js-promise v1.0.0 h1:K7OmJ3+0BgWJ2LfXchg2sI6RDr7AW/KWR8182epFwGQ= +github.com/nlepage/go-js-promise v1.0.0/go.mod h1:bdOP0wObXu34euibyK39K1hoBCtlgTKXGc56AGflaRo= +github.com/nlepage/go-wasm-http-server/v2 v2.2.1 h1:4tzhSb3HKQ3Ykt2TPfqEnmcPfw8n1E8agv4OzAyckr8= +github.com/nlepage/go-wasm-http-server/v2 v2.2.1/go.mod h1:r8j7cEOeUqNp+c+C52sNuWaFTvvT/cNqIwBuEtA36HA= +github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= +github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/tqweb/htmx.min.js b/tqweb/htmx.min.js new file mode 100644 index 0000000..faafa3e --- /dev/null +++ b/tqweb/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=dn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true,reportValidityOfForms:false},parseInterval:null,location:location,_:null,version:"2.0.8"};Q.onLoad=V;Q.process=Ft;Q.on=xe;Q.off=be;Q.trigger=ae;Q.ajax=Ln;Q.find=f;Q.findAll=x;Q.closest=g;Q.remove=_;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=ze;Q.defineExtension=_n;Q.removeExtension=zn;Q.logAll=j;Q.logNone=$;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:se,canAccessLocalStorage:X,findThisElement:Se,filterValues:yn,swap:ze,hasAttribute:s,getAttributeValue:a,getClosestAttributeValue:ne,getClosestMatch:q,getExpressionVars:Rn,getHeaders:mn,getInputValues:dn,getInternalData:oe,getSwapSpecification:bn,getTriggerSpecs:st,getTarget:Ee,makeFragment:D,mergeObjects:le,makeSettleInfo:Sn,oobSwap:Te,querySelectorExt:ue,settleImmediately:Yt,shouldCancel:ht,triggerEvent:ae,triggerErrorEvent:fe,withExtensions:Vt};const de=["get","post","put","delete","patch"];const R=de.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function a(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function te(){return document}function y(e,t){return e.getRootNode?e.getRootNode({composed:t}):te()}function q(e,t){while(e&&!t(e)){e=u(e)}return e||null}function o(e,t,n){const r=a(t,n);const o=a(t,"hx-disinherit");var i=a(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function ne(t,n){let r=null;q(t,function(e){return!!(r=o(t,ce(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function A(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function L(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function N(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=te().createElement("script");ie(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){H(e)}finally{e.remove()}}})}function D(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=A(t);let r;if(n==="html"){r=new DocumentFragment;const i=L(e);N(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=L(t);N(r,i.body);r.title=i.title}else{const i=L('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function re(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function P(e){return typeof e==="function"}function k(e){return t(e,"Object")}function oe(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function se(e){return e.getRootNode({composed:true})===document}function B(e){return e.trim().split(/\s+/)}function le(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function v(e){try{return JSON.parse(e)}catch(e){H(e);return null}}function X(){const e="htmx:sessionStorageTest";try{sessionStorage.setItem(e,e);sessionStorage.removeItem(e);return true}catch(e){return false}}function U(e){const t=new URL(e,"http://x");if(t){e=t.pathname+t.search}if(e!="/"){e=e.replace(/\/+$/,"")}return e}function e(e){return On(te().body,function(){return eval(e)})}function V(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function j(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function $(){Q.logger=null}function f(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return f(te(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(te(),e)}}function b(){return window}function _(e,t){e=w(e);if(t){b().setTimeout(function(){_(e);e=null},t)}else{u(e).removeChild(e)}}function ce(e){return e instanceof Element?e:null}function z(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function p(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ce(w(e));if(!e){return}if(n){b().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ce(w(e));if(!r){return}if(n){b().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=w(e);e.classList.toggle(t)}function Z(e,t){e=w(e);ie(e.parentElement.children,function(e){G(e,t)});K(ce(e),t)}function g(e,t){e=ce(w(e));if(e){return e.closest(t)}return null}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function pe(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(t,r,n){if(r.indexOf("global ")===0){return m(t,r.slice(7),true)}t=w(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=pe(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ce(t),pe(r.slice(8)))}else if(r.indexOf("find ")===0){e=f(p(t),pe(r.slice(5)))}else if(r==="next"||r==="nextElementSibling"){e=ce(t).nextElementSibling}else if(r.indexOf("next ")===0){e=ge(t,pe(r.slice(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ce(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,pe(r.slice(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=y(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=p(y(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var ge=function(t,e,n){const r=p(y(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ue(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(te().body,e)[0]}}function w(e,t){if(typeof e==="string"){return f(p(t)||document,e)}else{return e}}function ye(e,t,n,r){if(P(t)){return{target:te().body,event:J(e),listener:t,options:n}}else{return{target:w(e),event:J(t),listener:n,options:r}}}function xe(t,n,r,o){Gn(function(){const e=ye(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=P(n);return e?n:r}function be(t,n,r){Gn(function(){const e=ye(t,n,r);e.target.removeEventListener(e.event,e.listener)});return P(n)?n:r}const ve=te().createElement("output");function we(t,n){const e=ne(t,n);if(e){if(e==="this"){return[Se(t,n)]}else{const r=m(t,e);const o=/(^|,)(\s*)inherit(\s*)($|,)/.test(e);if(o){const i=ce(q(t,function(e){return e!==t&&s(ce(e),n)}));if(i){r.push(...we(i,n))}}if(r.length===0){H('The selector "'+e+'" on '+n+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ce(q(e,function(e){return a(ce(e),t)!=null}))}function Ee(e){const t=ne(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ue(e,t)}}else{const n=oe(e);if(n.boosted){return te().body}else{return e}}}function Ce(e){return Q.config.attributesToSettle.includes(e)}function Oe(t,n){ie(Array.from(t.attributes),function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});ie(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function He(t,e){const n=Jn(e);for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=m(t,n,false);if(r.length){ie(r,function(e){let t;const n=o.cloneNode(true);t=te().createDocumentFragment();t.appendChild(n);if(!He(s,e)){t=p(n)}const r={shouldSwap:true,target:e,fragment:t};if(!ae(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);$e(s,e,e,t,i);Re()}ie(i.elts,function(e){ae(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(te().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Re(){const e=f("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=f("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){ie(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=a(e,"id");const n=te().getElementById(t);if(n!=null){if(e.moveBefore){let e=f("#--htmx-preserve-pantry--");if(e==null){te().body.insertAdjacentHTML("afterend","
");e=f("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Ae(l,e,c){ie(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=p(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Le(e){return function(){G(e,Q.config.addedClass);Ft(ce(e));Ne(p(e));ae(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=z(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function c(e,t,n,r){Ae(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ce(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Le(o))}}}function Ie(e,t){let n=0;while(n0}function ze(h,d,p,g){if(!g){g={}}let m=null;let n=null;let e=function(){re(g.beforeSwapCallback);h=w(h);const r=g.contextElement?y(g.contextElement,false):te();const e=document.activeElement;let t={};t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null};const o=Sn(h);if(p.swapStyle==="textContent"){h.textContent=d}else{let n=D(d);o.title=g.title||n.title;if(g.historyRequest){n=n.querySelector("[hx-history-elt],[data-hx-history-elt]")||n}if(g.selectOOB){const i=g.selectOOB.split(",");for(let t=0;t0){b().setTimeout(n,p.settleDelay)}else{n()}};let t=Q.config.globalViewTransitions;if(p.hasOwnProperty("transition")){t=p.transition}const r=g.contextElement||te();if(t&&ae(r,"htmx:beforeTransition",g.eventInfo)&&typeof Promise!=="undefined"&&document.startViewTransition){const o=new Promise(function(e,t){m=e;n=t});const i=e;e=function(){document.startViewTransition(function(){i();return o})}}try{if(p?.swapDelay&&p.swapDelay>0){b().setTimeout(e,p.swapDelay)}else{e()}}catch(e){fe(r,"htmx:swapError",g.eventInfo);re(n);throw e}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=v(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(k(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}ae(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=On(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(te().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function O(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=O(e,Qe).trim();e.shift()}else{t=O(e,E)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{O(o,C);const l=o.length;const c=O(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};O(o,C);u.pollInterval=d(O(o,/[,\[\s]/));O(o,C);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const f={trigger:c};var i=nt(e,o,"event");if(i){f.eventFilter=i}O(o,C);while(o.length>0&&o[0]!==","){const a=o.shift();if(a==="changed"){f.changed=true}else if(a==="once"){f.once=true}else if(a==="consume"){f.consume=true}else if(a==="delay"&&o[0]===":"){o.shift();f.delay=d(O(o,E))}else if(a==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=O(o,E);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}f.from=s}else if(a==="target"&&o[0]===":"){o.shift();f.target=rt(o)}else if(a==="throttle"&&o[0]===":"){o.shift();f.throttle=d(O(o,E))}else if(a==="queue"&&o[0]===":"){o.shift();f.queue=O(o,E)}else if(a==="root"&&o[0]===":"){o.shift();f[a]=rt(o)}else if(a==="threshold"&&o[0]===":"){o.shift();f[a]=O(o,E)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}r.push(f)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=a(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){oe(e).cancelled=true}function ct(e,t,n){const r=oe(e);r.timeout=b().setTimeout(function(){if(se(e)&&r.cancelled!==true){if(!pt(n,e,Xt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function ft(e){return g(e,Q.config.disableSelector)}function at(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){gt(t,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)},n,e,true)})}}function ht(e,t){if(e.type==="submit"&&t.tagName==="FORM"){return true}else if(e.type==="click"){const n=t.closest('input[type="submit"], button');if(n&&n.form&&n.type==="submit"){return true}const r=t.closest("a");const o=/^#.+/;if(r&&r.href&&!o.test(r.getAttribute("href"))){return true}}return false}function dt(e,t){return oe(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function pt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(te().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function gt(l,c,e,u,f){const a=oe(l);let t;if(u.from){t=m(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in a)){a.lastValue=new WeakMap}t.forEach(function(e){if(!a.lastValue.has(u)){a.lastValue.set(u,new WeakMap)}a.lastValue.get(u).set(e,e.value)})}ie(t,function(i){const s=function(e){if(!se(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(f||ht(e,i)){e.preventDefault()}if(pt(u,l,e)){return}const t=oe(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ce(e.target),u.target)){return}}if(u.once){if(a.triggeredOnce){return}else{a.triggeredOnce=true}}if(u.changed){const n=e.target;const r=n.value;const o=a.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(a.delayed){clearTimeout(a.delayed)}if(a.throttle){return}if(u.throttle>0){if(!a.throttle){ae(l,"htmx:trigger");c(l,e);a.throttle=b().setTimeout(function(){a.throttle=null},u.throttle)}}else if(u.delay>0){a.delayed=b().setTimeout(function(){ae(l,"htmx:trigger");c(l,e)},u.delay)}else{ae(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let yt=null;function xt(){if(!yt){yt=function(){mt=true};window.addEventListener("scroll",yt);window.addEventListener("resize",yt);setInterval(function(){if(mt){mt=false;ie(te().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&F(e)){e.setAttribute("data-hx-revealed","true");const t=oe(e);if(t.initHash){ae(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){ae(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;ae(e,"htmx:trigger");t(e)}};if(r>0){b().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;ie(de,function(r){if(s(t,"hx-"+r)){const o=a(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){xt();gt(r,n,t,e);bt(ce(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ue(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ce(r),n,e)}else{gt(r,n,t,e)}}function Et(e){const t=ce(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Rt(e){const t=At(e.target);const n=Nt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Nt(e);if(t){t.lastButtonClicked=null}}function At(e){return g(ce(e),"button, input[type='submit']")}function Lt(e){return e.form||g(e,"form")}function Nt(e){const t=At(e.target);if(!t){return}const n=Lt(t);if(!n){return}return oe(n)}function It(e){e.addEventListener("click",Rt);e.addEventListener("focusin",Rt);e.addEventListener("focusout",qt)}function Dt(t,e,n){const r=oe(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){On(t,function(){if(ft(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Pt(t){Pe(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{sessionStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(te().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Jt(t){if(!X()){return null}t=U(t);const n=v(sessionStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){r.response=this.response;ae(te().body,"htmx:historyCacheMissLoad",r);ze(r.historyElt,r.response,n,{contextElement:r.historyElt,historyRequest:true});$t(r.path);ae(te().body,"htmx:historyRestore",{path:e,cacheMiss:true,serverResponse:r.response})}else{fe(te().body,"htmx:historyCacheMissLoadError",r)}};if(ae(te().body,"htmx:historyCacheMiss",r)){t.send()}}function en(e){Gt();e=e||location.pathname+location.search;const t=Jt(e);if(t){const n={swapStyle:"innerHTML",swapDelay:0,settleDelay:0,scroll:t.scroll};const r={path:e,item:t,historyElt:_t(),swapSpec:n};if(ae(te().body,"htmx:historyCacheHit",r)){ze(r.historyElt,t.content,n,{contextElement:r.historyElt,title:t.title});$t(r.path);ae(te().body,"htmx:historyRestore",r)}}else{if(Q.config.refreshOnHistoryMiss){Q.location.reload(true)}else{Qt(e)}}}function tn(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function nn(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function rn(e,t){ie(e.concat(t),function(e){const t=oe(e);t.requestCount=(t.requestCount||1)-1});ie(e,function(e){const t=oe(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});ie(t,function(e){const t=oe(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function on(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);ie(e,e=>r.append(t,e))}}function un(e){if(e instanceof HTMLSelectElement&&e.multiple){return M(e.querySelectorAll("option:checked")).map(function(e){return e.value})}if(e instanceof HTMLInputElement&&e.files){return M(e.files)}return e.value}function fn(t,n,r,e,o){if(e==null||on(t,e)){return}else{t.push(e)}if(sn(e)){const i=ee(e,"name");ln(i,un(e),n);if(o){an(e,r)}}if(e instanceof HTMLFormElement){ie(e.elements,function(e){if(t.indexOf(e)>=0){cn(e.name,un(e),n)}else{t.push(e)}if(o){an(e,r)}});new FormData(e).forEach(function(e,t){if(e instanceof File&&e.name===""){return}ln(t,e,n)})}}function an(e,t){const n=e;if(n.willValidate){ae(n,"htmx:validation:validate");if(!n.checkValidity()){if(ae(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})&&!t.length&&Q.config.reportValidityOfForms){n.reportValidity()}t.push({elt:n,message:n.validationMessage,validity:n.validity})}}}function hn(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function dn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=oe(e);if(s.lastButtonClicked&&!se(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||a(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){fn(n,o,i,Lt(e),l)}fn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const f=ee(u,"name");ln(f,u.value,o)}const c=we(e,"hx-include");ie(c,function(e){fn(n,r,i,ce(e),l);if(!h(e,"form")){ie(p(e).querySelectorAll(ot),function(e){fn(n,r,i,e,l)})}});hn(r,o);return{errors:i,formData:r,values:kn(r)}}function pn(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function gn(e){e=Dn(e);let n="";e.forEach(function(e,t){n=pn(n,t,e)});return n}function mn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":a(t,"id"),"HX-Current-URL":location.href};Cn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(oe(e).boosted){r["HX-Boosted"]="true"}return r}function yn(n,e){const t=ne(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){ie(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;ie(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function xn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function bn(e,t){const n=t||ne(e,"hx-swap");const r={swapStyle:oe(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&oe(e).boosted&&!xn(e)){r.show="top"}if(n){const s=B(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const f=l.slice(5);var o=f.split(":");const a=o.pop();var i=o.length>0?o.join(":"):null;r.show=a;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{H("Unknown modifier in hx-swap: "+l)}}}}return r}function vn(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function wn(t,n,r){let o=null;Vt(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(vn(n)){return hn(new FormData,Dn(r))}else{return gn(r)}}}function Sn(e){return{tasks:[],elts:[e]}}function En(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ce(ue(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}if(typeof t.scroll==="number"){b().setTimeout(function(){window.scrollTo(0,t.scroll)},0)}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ce(ue(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Cn(r,e,o,i,s){if(i==null){i={}}if(r==null){return i}const l=a(r,e);if(l){let e=l.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=On(r,function(){if(s){return Function("event","return ("+e+")").call(r,s)}else{return Function("return ("+e+")").call(r)}},{})}else{n=v(e)}for(const c in n){if(n.hasOwnProperty(c)){if(i[c]==null){i[c]=n[c]}}}}return Cn(ce(u(r)),e,o,i,s)}function On(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function Hn(e,t,n){return Cn(e,"hx-vars",true,n,t)}function Tn(e,t,n){return Cn(e,"hx-vals",false,n,t)}function Rn(e,t){return le(Hn(e,t),Tn(e,t))}function qn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function An(t){if(t.responseURL){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(te().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function T(e,t){return t.test(e.getAllResponseHeaders())}function Ln(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return he(t,n,null,null,{targetOverride:w(r)||ve,returnPromise:true})}else{let e=w(r.target);if(r.target&&!e||r.source&&!e&&!w(r.source)){e=ve}return he(t,n,w(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true,push:r.push,replace:r.replace,selectOOB:r.selectOOB})}}else{return he(t,n,null,null,{returnPromise:true})}}function Nn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function In(e,t,n){const r=new URL(t,location.protocol!=="about:"?location.href:window.origin);const o=location.protocol!=="about:"?location.origin:window.origin;const i=o===r.origin;if(Q.config.selfRequestsOnly){if(!i){return false}}return ae(e,"htmx:validateUrl",le({url:r,sameHost:i},n))}function Dn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Pn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function kn(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Pn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function he(t,n,r,o,i,k){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=te().body}const M=i.handler||Vn;const F=i.select||null;if(!se(r)){re(s);return e}const c=i.targetOverride||ce(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:ne(r,"hx-target")});re(l);return e}let u=oe(r);const f=u.lastButtonClicked;if(f){const A=ee(f,"formaction");if(A!=null){n=A}const L=ee(f,"formmethod");if(L!=null){if(de.includes(L.toLowerCase())){t=L}else{re(s);return e}}}const a=ne(r,"hx-confirm");if(k===undefined){const K=function(e){return he(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:a};if(ae(r,"htmx:confirm",G)===false){re(s);return e}}let h=r;let d=ne(r,"hx-sync");let p=null;let B=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ce(ue(r,I))}d=(N[1]||"drop").trim();u=oe(h);if(d==="drop"&&u.xhr&&u.abortable!==true){re(s);return e}else if(d==="abort"){if(u.xhr){re(s);return e}else{B=true}}else if(d==="replace"){ae(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");p=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){ae(h,"htmx:abort")}else{if(p==null){if(o){const D=oe(o);if(D&&D.triggerSpec&&D.triggerSpec.queue){p=D.triggerSpec.queue}}if(p==null){p="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(p==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="all"){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){he(t,n,r,o,i)})}re(s);return e}}const g=new XMLHttpRequest;u.xhr=g;u.abortable=B;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const X=ne(r,"hx-prompt");if(X){var y=prompt(X);if(y===null||!ae(r,"htmx:prompt",{prompt:y,target:c})){re(s);m();return e}}if(a&&!k){if(!confirm(a)){re(s);m();return e}}let x=mn(r,c,y);if(t!=="get"&&!vn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=le(x,i.headers)}const U=dn(r,t);let b=U.errors;const V=U.formData;if(i.values){hn(V,Dn(i.values))}const j=Dn(Rn(r,o));const v=hn(V,j);let w=yn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=location.href}const S=Cn(r,"hx-request");const $=oe(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:$,useUrlParams:E,formData:w,parameters:kn(w),unfilteredFormData:v,unfilteredParameters:kn(v),headers:x,elt:r,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!ae(r,"htmx:configRequest",C)){re(s);m();return e}n=C.path;t=C.verb;x=C.headers;w=Dn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){ae(r,"htmx:validation:halted",C);re(s);m();return e}const _=n.split("#");const z=_[0];const O=_[1];let H=n;if(E){H=z;const Z=!w.keys().next().done;if(Z){if(H.indexOf("?")<0){H+="?"}else{H+="&"}H+=gn(w);if(O){H+="#"+O}}}if(!In(r,H,C)){fe(r,"htmx:invalidPath",C);re(l);m();return e}g.open(t.toUpperCase(),H,true);g.overrideMimeType("text/html");g.withCredentials=C.withCredentials;g.timeout=C.timeout;if(S.noHeaders){}else{for(const P in x){if(x.hasOwnProperty(P)){const Y=x[P];qn(g,P,Y)}}}const T={xhr:g,target:c,requestConfig:C,etc:i,boosted:$,select:F,pathInfo:{requestPath:n,finalRequestPath:H,responsePath:null,anchor:O}};g.onload=function(){try{const t=Nn(r);T.pathInfo.responsePath=An(g);M(r,T);if(T.keepIndicators!==true){rn(R,q)}ae(r,"htmx:afterRequest",T);ae(r,"htmx:afterOnLoad",T);if(!se(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(se(n)){e=n}}if(e){ae(e,"htmx:afterRequest",T);ae(e,"htmx:afterOnLoad",T)}}re(s)}catch(e){fe(r,"htmx:onLoadError",le({error:e},T));throw e}finally{m()}};g.onerror=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendError",T);re(l);m()};g.onabort=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendAbort",T);re(l);m()};g.ontimeout=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:timeout",T);re(l);m()};if(!ae(r,"htmx:beforeRequest",T)){re(s);m();return e}var R=tn(r);var q=nn(r);ie(["loadstart","loadend","progress","abort"],function(t){ie([g,g.upload],function(e){e.addEventListener(t,function(e){ae(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ae(r,"htmx:beforeSend",T);const J=E?null:wn(g,r,w);g.send(J);return e}function Mn(e,t){const n=t.xhr;let r=null;let o=null;if(T(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(T(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(T(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=t.etc.push||ne(e,"hx-push-url");const c=t.etc.replace||ne(e,"hx-replace-url");const u=oe(e).boosted;let f=null;let a=null;if(l){f="push";a=l}else if(c){f="replace";a=c}else if(u){f="push";a=s||i}if(a){if(a==="false"){return{}}if(a==="true"){a=s||i}if(t.pathInfo.anchor&&a.indexOf("#")===-1){a=a+"#"+t.pathInfo.anchor}return{type:f,path:a}}else{return{}}}function Fn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Bn(e){for(var t=0;t`+`.${t}{opacity:0;visibility: hidden} `+`.${n} .${t}, .${n}.${t}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}`+"")}}function Zn(){const e=te().querySelector('meta[name="htmx-config"]');if(e){return v(e.content)}else{return null}}function Yn(){const e=Zn();if(e){Q.config=le(Q.config,e)}}Gn(function(){Yn();Wn();let e=te().body;Ft(e);const t=te().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.detail.elt||e.target;const n=oe(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){en();ie(t,function(e){ae(e,"htmx:restored",{document:te(),triggerEvent:ae})})}else{if(n){n(e)}}};b().setTimeout(function(){ae(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/tqweb/index.html b/tqweb/index.html new file mode 100644 index 0000000..7fb5661 --- /dev/null +++ b/tqweb/index.html @@ -0,0 +1,77 @@ + + + + + + + + + + +
+
+
+
+
+
+

+ QUERY +

+
+
+ +
+
+
+
+

+ TOML +

+
+
+ +
+
+
+
+
+
+

+ OUTPUT +

+
+
+ +
+
+
+
+
+
+ + diff --git a/tqweb/main.go b/tqweb/main.go new file mode 100644 index 0000000..a6e57eb --- /dev/null +++ b/tqweb/main.go @@ -0,0 +1,57 @@ +//go:build js && wasm + +package main + +import ( + "bytes" + _ "embed" + "html/template" + "net/http" + "strings" + + "github.com/mdm-code/tq/v2" + "github.com/mdm-code/tq/v2/toml" + wasmhttp "github.com/nlepage/go-wasm-http-server/v2" +) + +/* +TODO: +1. Tq config for GoTOML is sent from the frontend selection component. +- Checkboxes: send true if checked. +- Buttons: on click, keep highlighted and add to the payload. +2. The config and TQ has to be instantiated with each call. +3. Curl tailwind css scripts. +*/ + +var ( + //go:embed views/index.html + index string + indexT = template.Must(template.New("index").Parse(index)) +) + +func main() { + conf := toml.GoTOMLConf{} + goToml := toml.NewGoTOML(conf) + adapter := toml.NewAdapter(goToml) + tq := tq.New(adapter) + + http.HandleFunc("/process", func(w http.ResponseWriter, r *http.Request) { + var output bytes.Buffer + var data struct{ Output string } + input := r.FormValue("input") + query := r.FormValue("query") + err := tq.Run(strings.NewReader(input), &output, query) + if err != nil { + data.Output = err.Error() + } else { + data.Output = output.String() + } + if err := indexT.ExecuteTemplate(w, "output", data); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + }) + + wasmhttp.Serve(nil) + + select {} +} diff --git a/tqweb/sw.js b/tqweb/sw.js new file mode 100644 index 0000000..11e0ae0 --- /dev/null +++ b/tqweb/sw.js @@ -0,0 +1,42 @@ +function registerWasmHTTPListener(wasm, { base, cacheName, passthrough, args = [] } = {}) { + let path = new URL(registration.scope).pathname + if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}` + + const handlerPromise = new Promise(setHandler => { + self.wasmhttp = { + path, + setHandler, + } + }) + + const go = new Go() + go.argv = [wasm, ...args] + const source = cacheName + ? caches.open(cacheName).then((cache) => cache.match(wasm)).then((response) => response ?? fetch(wasm)) + : caches.match(wasm).then(response => (response) ?? fetch(wasm)) + WebAssembly.instantiateStreaming(source, go.importObject).then(({ instance }) => go.run(instance)) + + addEventListener('fetch', e => { + if (passthrough?.(e.request)) { + e.respondWith(fetch(e.request)) + return; + } + + const { pathname } = new URL(e.request.url) + if (!pathname.startsWith(path)) return + + e.respondWith(handlerPromise.then(handler => handler(e.request))) + }) +} + +function trimStart(s, c) { + let r = s + while (r.startsWith(c)) r = r.slice(c.length) + return r +} + +function trimEnd(s, c) { + let r = s + while (r.endsWith(c)) r = r.slice(0, -c.length) + return r +} diff --git a/tqweb/views/index.html b/tqweb/views/index.html new file mode 100644 index 0000000..b2cc191 --- /dev/null +++ b/tqweb/views/index.html @@ -0,0 +1,8 @@ +{{ block "output" . }} + +{{ end }} diff --git a/tqweb/wasm_exec.js b/tqweb/wasm_exec.js new file mode 100644 index 0000000..d71af9e --- /dev/null +++ b/tqweb/wasm_exec.js @@ -0,0 +1,575 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +"use strict"; + +(() => { + const enosys = () => { + const err = new Error("not implemented"); + err.code = "ENOSYS"; + return err; + }; + + if (!globalThis.fs) { + let outputBuf = ""; + globalThis.fs = { + constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused + writeSync(fd, buf) { + outputBuf += decoder.decode(buf); + const nl = outputBuf.lastIndexOf("\n"); + if (nl != -1) { + console.log(outputBuf.substring(0, nl)); + outputBuf = outputBuf.substring(nl + 1); + } + return buf.length; + }, + write(fd, buf, offset, length, position, callback) { + if (offset !== 0 || length !== buf.length || position !== null) { + callback(enosys()); + return; + } + const n = this.writeSync(fd, buf); + callback(null, n); + }, + chmod(path, mode, callback) { callback(enosys()); }, + chown(path, uid, gid, callback) { callback(enosys()); }, + close(fd, callback) { callback(enosys()); }, + fchmod(fd, mode, callback) { callback(enosys()); }, + fchown(fd, uid, gid, callback) { callback(enosys()); }, + fstat(fd, callback) { callback(enosys()); }, + fsync(fd, callback) { callback(null); }, + ftruncate(fd, length, callback) { callback(enosys()); }, + lchown(path, uid, gid, callback) { callback(enosys()); }, + link(path, link, callback) { callback(enosys()); }, + lstat(path, callback) { callback(enosys()); }, + mkdir(path, perm, callback) { callback(enosys()); }, + open(path, flags, mode, callback) { callback(enosys()); }, + read(fd, buffer, offset, length, position, callback) { callback(enosys()); }, + readdir(path, callback) { callback(enosys()); }, + readlink(path, callback) { callback(enosys()); }, + rename(from, to, callback) { callback(enosys()); }, + rmdir(path, callback) { callback(enosys()); }, + stat(path, callback) { callback(enosys()); }, + symlink(path, link, callback) { callback(enosys()); }, + truncate(path, length, callback) { callback(enosys()); }, + unlink(path, callback) { callback(enosys()); }, + utimes(path, atime, mtime, callback) { callback(enosys()); }, + }; + } + + if (!globalThis.process) { + globalThis.process = { + getuid() { return -1; }, + getgid() { return -1; }, + geteuid() { return -1; }, + getegid() { return -1; }, + getgroups() { throw enosys(); }, + pid: -1, + ppid: -1, + umask() { throw enosys(); }, + cwd() { throw enosys(); }, + chdir() { throw enosys(); }, + } + } + + if (!globalThis.path) { + globalThis.path = { + resolve(...pathSegments) { + return pathSegments.join("/"); + } + } + } + + if (!globalThis.crypto) { + throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)"); + } + + if (!globalThis.performance) { + throw new Error("globalThis.performance is not available, polyfill required (performance.now only)"); + } + + if (!globalThis.TextEncoder) { + throw new Error("globalThis.TextEncoder is not available, polyfill required"); + } + + if (!globalThis.TextDecoder) { + throw new Error("globalThis.TextDecoder is not available, polyfill required"); + } + + const encoder = new TextEncoder("utf-8"); + const decoder = new TextDecoder("utf-8"); + + globalThis.Go = class { + constructor() { + this.argv = ["js"]; + this.env = {}; + this.exit = (code) => { + if (code !== 0) { + console.warn("exit code:", code); + } + }; + this._exitPromise = new Promise((resolve) => { + this._resolveExitPromise = resolve; + }); + this._pendingEvent = null; + this._scheduledTimeouts = new Map(); + this._nextCallbackTimeoutID = 1; + + const setInt64 = (addr, v) => { + this.mem.setUint32(addr + 0, v, true); + this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true); + } + + const setInt32 = (addr, v) => { + this.mem.setUint32(addr + 0, v, true); + } + + const getInt64 = (addr) => { + const low = this.mem.getUint32(addr + 0, true); + const high = this.mem.getInt32(addr + 4, true); + return low + high * 4294967296; + } + + const loadValue = (addr) => { + const f = this.mem.getFloat64(addr, true); + if (f === 0) { + return undefined; + } + if (!isNaN(f)) { + return f; + } + + const id = this.mem.getUint32(addr, true); + return this._values[id]; + } + + const storeValue = (addr, v) => { + const nanHead = 0x7FF80000; + + if (typeof v === "number" && v !== 0) { + if (isNaN(v)) { + this.mem.setUint32(addr + 4, nanHead, true); + this.mem.setUint32(addr, 0, true); + return; + } + this.mem.setFloat64(addr, v, true); + return; + } + + if (v === undefined) { + this.mem.setFloat64(addr, 0, true); + return; + } + + let id = this._ids.get(v); + if (id === undefined) { + id = this._idPool.pop(); + if (id === undefined) { + id = this._values.length; + } + this._values[id] = v; + this._goRefCounts[id] = 0; + this._ids.set(v, id); + } + this._goRefCounts[id]++; + let typeFlag = 0; + switch (typeof v) { + case "object": + if (v !== null) { + typeFlag = 1; + } + break; + case "string": + typeFlag = 2; + break; + case "symbol": + typeFlag = 3; + break; + case "function": + typeFlag = 4; + break; + } + this.mem.setUint32(addr + 4, nanHead | typeFlag, true); + this.mem.setUint32(addr, id, true); + } + + const loadSlice = (addr) => { + const array = getInt64(addr + 0); + const len = getInt64(addr + 8); + return new Uint8Array(this._inst.exports.mem.buffer, array, len); + } + + const loadSliceOfValues = (addr) => { + const array = getInt64(addr + 0); + const len = getInt64(addr + 8); + const a = new Array(len); + for (let i = 0; i < len; i++) { + a[i] = loadValue(array + i * 8); + } + return a; + } + + const loadString = (addr) => { + const saddr = getInt64(addr + 0); + const len = getInt64(addr + 8); + return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len)); + } + + const testCallExport = (a, b) => { + this._inst.exports.testExport0(); + return this._inst.exports.testExport(a, b); + } + + const timeOrigin = Date.now() - performance.now(); + this.importObject = { + _gotest: { + add: (a, b) => a + b, + callExport: testCallExport, + }, + gojs: { + // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters) + // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported + // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function). + // This changes the SP, thus we have to update the SP used by the imported function. + + // func wasmExit(code int32) + "runtime.wasmExit": (sp) => { + sp >>>= 0; + const code = this.mem.getInt32(sp + 8, true); + this.exited = true; + delete this._inst; + delete this._values; + delete this._goRefCounts; + delete this._ids; + delete this._idPool; + this.exit(code); + }, + + // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32) + "runtime.wasmWrite": (sp) => { + sp >>>= 0; + const fd = getInt64(sp + 8); + const p = getInt64(sp + 16); + const n = this.mem.getInt32(sp + 24, true); + fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n)); + }, + + // func resetMemoryDataView() + "runtime.resetMemoryDataView": (sp) => { + sp >>>= 0; + this.mem = new DataView(this._inst.exports.mem.buffer); + }, + + // func nanotime1() int64 + "runtime.nanotime1": (sp) => { + sp >>>= 0; + setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000); + }, + + // func walltime() (sec int64, nsec int32) + "runtime.walltime": (sp) => { + sp >>>= 0; + const msec = (new Date).getTime(); + setInt64(sp + 8, msec / 1000); + this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true); + }, + + // func scheduleTimeoutEvent(delay int64) int32 + "runtime.scheduleTimeoutEvent": (sp) => { + sp >>>= 0; + const id = this._nextCallbackTimeoutID; + this._nextCallbackTimeoutID++; + this._scheduledTimeouts.set(id, setTimeout( + () => { + this._resume(); + while (this._scheduledTimeouts.has(id)) { + // for some reason Go failed to register the timeout event, log and try again + // (temporary workaround for https://github.com/golang/go/issues/28975) + console.warn("scheduleTimeoutEvent: missed timeout event"); + this._resume(); + } + }, + getInt64(sp + 8), + )); + this.mem.setInt32(sp + 16, id, true); + }, + + // func clearTimeoutEvent(id int32) + "runtime.clearTimeoutEvent": (sp) => { + sp >>>= 0; + const id = this.mem.getInt32(sp + 8, true); + clearTimeout(this._scheduledTimeouts.get(id)); + this._scheduledTimeouts.delete(id); + }, + + // func getRandomData(r []byte) + "runtime.getRandomData": (sp) => { + sp >>>= 0; + crypto.getRandomValues(loadSlice(sp + 8)); + }, + + // func finalizeRef(v ref) + "syscall/js.finalizeRef": (sp) => { + sp >>>= 0; + const id = this.mem.getUint32(sp + 8, true); + this._goRefCounts[id]--; + if (this._goRefCounts[id] === 0) { + const v = this._values[id]; + this._values[id] = null; + this._ids.delete(v); + this._idPool.push(id); + } + }, + + // func stringVal(value string) ref + "syscall/js.stringVal": (sp) => { + sp >>>= 0; + storeValue(sp + 24, loadString(sp + 8)); + }, + + // func valueGet(v ref, p string) ref + "syscall/js.valueGet": (sp) => { + sp >>>= 0; + const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16)); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 32, result); + }, + + // func valueSet(v ref, p string, x ref) + "syscall/js.valueSet": (sp) => { + sp >>>= 0; + Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32)); + }, + + // func valueDelete(v ref, p string) + "syscall/js.valueDelete": (sp) => { + sp >>>= 0; + Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16)); + }, + + // func valueIndex(v ref, i int) ref + "syscall/js.valueIndex": (sp) => { + sp >>>= 0; + storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16))); + }, + + // valueSetIndex(v ref, i int, x ref) + "syscall/js.valueSetIndex": (sp) => { + sp >>>= 0; + Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24)); + }, + + // func valueCall(v ref, m string, args []ref) (ref, bool) + "syscall/js.valueCall": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const m = Reflect.get(v, loadString(sp + 16)); + const args = loadSliceOfValues(sp + 32); + const result = Reflect.apply(m, v, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 56, result); + this.mem.setUint8(sp + 64, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 56, err); + this.mem.setUint8(sp + 64, 0); + } + }, + + // func valueInvoke(v ref, args []ref) (ref, bool) + "syscall/js.valueInvoke": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const args = loadSliceOfValues(sp + 16); + const result = Reflect.apply(v, undefined, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, result); + this.mem.setUint8(sp + 48, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, err); + this.mem.setUint8(sp + 48, 0); + } + }, + + // func valueNew(v ref, args []ref) (ref, bool) + "syscall/js.valueNew": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const args = loadSliceOfValues(sp + 16); + const result = Reflect.construct(v, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, result); + this.mem.setUint8(sp + 48, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, err); + this.mem.setUint8(sp + 48, 0); + } + }, + + // func valueLength(v ref) int + "syscall/js.valueLength": (sp) => { + sp >>>= 0; + setInt64(sp + 16, parseInt(loadValue(sp + 8).length)); + }, + + // valuePrepareString(v ref) (ref, int) + "syscall/js.valuePrepareString": (sp) => { + sp >>>= 0; + const str = encoder.encode(String(loadValue(sp + 8))); + storeValue(sp + 16, str); + setInt64(sp + 24, str.length); + }, + + // valueLoadString(v ref, b []byte) + "syscall/js.valueLoadString": (sp) => { + sp >>>= 0; + const str = loadValue(sp + 8); + loadSlice(sp + 16).set(str); + }, + + // func valueInstanceOf(v ref, t ref) bool + "syscall/js.valueInstanceOf": (sp) => { + sp >>>= 0; + this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0); + }, + + // func copyBytesToGo(dst []byte, src ref) (int, bool) + "syscall/js.copyBytesToGo": (sp) => { + sp >>>= 0; + const dst = loadSlice(sp + 8); + const src = loadValue(sp + 32); + if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) { + this.mem.setUint8(sp + 48, 0); + return; + } + const toCopy = src.subarray(0, dst.length); + dst.set(toCopy); + setInt64(sp + 40, toCopy.length); + this.mem.setUint8(sp + 48, 1); + }, + + // func copyBytesToJS(dst ref, src []byte) (int, bool) + "syscall/js.copyBytesToJS": (sp) => { + sp >>>= 0; + const dst = loadValue(sp + 8); + const src = loadSlice(sp + 16); + if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) { + this.mem.setUint8(sp + 48, 0); + return; + } + const toCopy = src.subarray(0, dst.length); + dst.set(toCopy); + setInt64(sp + 40, toCopy.length); + this.mem.setUint8(sp + 48, 1); + }, + + "debug": (value) => { + console.log(value); + }, + } + }; + } + + async run(instance) { + if (!(instance instanceof WebAssembly.Instance)) { + throw new Error("Go.run: WebAssembly.Instance expected"); + } + this._inst = instance; + this.mem = new DataView(this._inst.exports.mem.buffer); + this._values = [ // JS values that Go currently has references to, indexed by reference id + NaN, + 0, + null, + true, + false, + globalThis, + this, + ]; + this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id + this._ids = new Map([ // mapping from JS values to reference ids + [0, 1], + [null, 2], + [true, 3], + [false, 4], + [globalThis, 5], + [this, 6], + ]); + this._idPool = []; // unused ids that have been garbage collected + this.exited = false; // whether the Go program has exited + + // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory. + let offset = 4096; + + const strPtr = (str) => { + const ptr = offset; + const bytes = encoder.encode(str + "\0"); + new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes); + offset += bytes.length; + if (offset % 8 !== 0) { + offset += 8 - (offset % 8); + } + return ptr; + }; + + const argc = this.argv.length; + + const argvPtrs = []; + this.argv.forEach((arg) => { + argvPtrs.push(strPtr(arg)); + }); + argvPtrs.push(0); + + const keys = Object.keys(this.env).sort(); + keys.forEach((key) => { + argvPtrs.push(strPtr(`${key}=${this.env[key]}`)); + }); + argvPtrs.push(0); + + const argv = offset; + argvPtrs.forEach((ptr) => { + this.mem.setUint32(offset, ptr, true); + this.mem.setUint32(offset + 4, 0, true); + offset += 8; + }); + + // The linker guarantees global data starts from at least wasmMinDataAddr. + // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr. + const wasmMinDataAddr = 4096 + 8192; + if (offset >= wasmMinDataAddr) { + throw new Error("total length of command line and environment variables exceeds limit"); + } + + this._inst.exports.run(argc, argv); + if (this.exited) { + this._resolveExitPromise(); + } + await this._exitPromise; + } + + _resume() { + if (this.exited) { + throw new Error("Go program has already exited"); + } + this._inst.exports.resume(); + if (this.exited) { + this._resolveExitPromise(); + } + } + + _makeFuncWrapper(id) { + const go = this; + return function () { + const event = { id: id, this: this, args: arguments }; + go._pendingEvent = event; + go._resume(); + return event.result; + }; + } + } +})(); diff --git a/tqweb/worker.js b/tqweb/worker.js new file mode 100644 index 0000000..e04a585 --- /dev/null +++ b/tqweb/worker.js @@ -0,0 +1,14 @@ +importScripts('wasm_exec.js'); +importScripts('sw.js'); + +const wasm = 'api.wasm'; + +addEventListener('install', (event) => { + event.waitUntil(caches.open('api').then((cache) => cache.add(wasm))); +}); + +addEventListener('activate', (event) => { + event.waitUntil(clients.claim()); +}); + +registerWasmHTTPListener(wasm, { base: 'api' }); diff --git a/vendor/github.com/hack-pad/safejs/.env b/vendor/github.com/hack-pad/safejs/.env new file mode 100644 index 0000000..13468cb --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/.env @@ -0,0 +1,3 @@ +# Env file defines useful environment variables for editors. +GOOS=js +GOARCH=wasm diff --git a/vendor/github.com/hack-pad/safejs/.gitignore b/vendor/github.com/hack-pad/safejs/.gitignore new file mode 100644 index 0000000..e87afd9 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/.gitignore @@ -0,0 +1 @@ +/*.out diff --git a/vendor/github.com/hack-pad/safejs/.golangci.yml b/vendor/github.com/hack-pad/safejs/.golangci.yml new file mode 100644 index 0000000..423e830 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/.golangci.yml @@ -0,0 +1,22 @@ +linters: + enable: + # Default linters, plus these: + - exportloopref + - gocognit + - goconst + - gocritic + - gofmt + - gosec + - misspell + - paralleltest + - revive + +issues: + include: + # Re-enable default excluded rules + - EXC0001 + - EXC0002 + - EXC0012 + - EXC0013 + - EXC0014 + - EXC0015 diff --git a/vendor/github.com/hack-pad/safejs/LICENSE b/vendor/github.com/hack-pad/safejs/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/hack-pad/safejs/Makefile b/vendor/github.com/hack-pad/safejs/Makefile new file mode 100644 index 0000000..124a6e1 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/Makefile @@ -0,0 +1,39 @@ +SHELL := /usr/bin/env bash +BROWSERTEST_VERSION = v0.6 +LINT_VERSION = 1.50.1 +GO_BIN = $(shell printf '%s/bin' "$$(go env GOPATH)") + +.PHONY: all +all: lint test + +.PHONY: lint-deps +lint-deps: + @if ! which golangci-lint >/dev/null || [[ "$$(golangci-lint version 2>&1)" != *${LINT_VERSION}* ]]; then \ + curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b "${GO_BIN}" v${LINT_VERSION}; \ + fi + +.PHONY: lint +lint: lint-deps + "${GO_BIN}/golangci-lint" run + GOOS=js GOARCH=wasm "${GO_BIN}/golangci-lint" run + +.PHONY: test-deps +test-deps: + @if [[ ! -f "${GO_BIN}/go_js_wasm_exec" ]]; then \ + set -ex; \ + go install github.com/agnivade/wasmbrowsertest@${BROWSERTEST_VERSION}; \ + mv "${GO_BIN}/wasmbrowsertest" "${GO_BIN}/go_js_wasm_exec"; \ + fi + +.PHONY: test +test: test-deps + go test wasm_tags_test.go # Verify build tags and whatnot first + go test -race -coverprofile=native-cover.out ./... # Test non-js side + GOOS=js GOARCH=wasm go test -coverprofile=js-cover.out -covermode=atomic ./... # Test js side + { echo 'mode: atomic'; cat *-cover.out | grep -v '^mode'; } > cover.out && rm *-cover.out # Combine JS and non-JS coverage. + go tool cover -func cover.out | grep total: + +.PHONY: test-publish-coverage +test-publish-coverage: + go install github.com/mattn/goveralls@v0.0.11 + COVERALLS_TOKEN=$$GITHUB_TOKEN goveralls -coverprofile="cover.out" -service=github diff --git a/vendor/github.com/hack-pad/safejs/README.md b/vendor/github.com/hack-pad/safejs/README.md new file mode 100644 index 0000000..dd7c104 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/README.md @@ -0,0 +1,91 @@ +# SafeJS [![Go Reference](https://pkg.go.dev/badge/github.com/hack-pad/safejs.svg)](https://pkg.go.dev/github.com/hack-pad/safejs) [![CI](https://github.com/hack-pad/safejs/actions/workflows/ci.yml/badge.svg)](https://github.com/hack-pad/safejs/actions/workflows/ci.yml) [![Coverage Status](https://coveralls.io/repos/github/hack-pad/safejs/badge.svg?branch=main)](https://coveralls.io/github/hack-pad/safejs?branch=main) + +A safer, drop-in replacement for Go's `syscall/js` JavaScript package. + +## What makes it safer? + +Today, `syscall/js` panics when the JavaScript runtime throws errors. +While sensible in a JavaScript runtime, [Go libraries should avoid using `panic`](https://go.dev/doc/effective_go#panic). + +SafeJS provides a nearly identical API to `syscall/js`, but returns errors instead of panicking. + +Although returned errors aren't pretty, they make it much easier to integrate with existing Go tools and code patterns. + +#### Backward compatibility + +This package uses the same backward compatibility guarantee as `syscall/js`. + +In an effort to align with the Go standard library API, some breaking changes may become necessary and receive their own minor version bumps. + +## Quick start + +1. Get `safejs`: +``` +go get github.com/hack-pad/safejs +``` +2. Import `safejs`: +```go +import "github.com/hack-pad/safejs" +``` +3. Replace uses of `syscall/js` with the `safejs` alternative. + +Before: +```go +//go:build js && wasm + +package buttons + +import "syscall/js" + +// InsertButton creates a new button, adds it to 'container', and returns it. Usually. +func InsertButton(container js.Value) js.Value { + // *whisper:* There's a good chance it could panic! Eh, probably don't need to document it, right? + dom := js.Global().Get("document") // BOOM! + button := dom.Call("createElement", "button") // BANG! + container.Call("appendChild", button) // BAM! + return button +} +``` + +After: +```go +//go:build js && wasm + +package buttons + +import "github.com/hack-pad/safejs" + +// InsertButton creates a new button, adds it to 'container', and returns the button or the first error. +func InsertButton(container safejs.Value) (safejs.Value, error) { + dom, err := safejs.Global().Get("document") + if err != nil { + return err + } + button, err := dom.Call("createElement", "button") + if err != nil { + return err + } + _, err = container.Call("appendChild", button) + if err != nil { + return err + } + return button, nil +} +``` + +## Even safer + +For additional JavaScript safety, use the `jsguard` linter too. + +`jsguard` reports the locations of unsafe JavaScript calls, which should be replaced with calls to SafeJS. + +```bash +# When installed without specifying a version, uses the go.mod version. +go install github.com/hack-pad/safejs/jsguard/cmd/jsguard +export GOOS=js GOARCH=wasm +jsguard ./... +``` + +It *does not* report use of types like `js.Value` -- only function calls on those types. + +This makes it easy to integrate SafeJS into existing libraries which expose only standard library types. diff --git a/vendor/github.com/hack-pad/safejs/bytes.go b/vendor/github.com/hack-pad/safejs/bytes.go new file mode 100644 index 0000000..7b42a3f --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/bytes.go @@ -0,0 +1,27 @@ +//go:build js && wasm + +package safejs + +import ( + "syscall/js" + + "github.com/hack-pad/safejs/internal/catch" +) + +// CopyBytesToGo copies bytes from src to dst. +// Returns the number of bytes copied, which is the minimum of the lengths of src and dst. +// Returns an error if src is not an Uint8Array or Uint8ClampedArray. +func CopyBytesToGo(dst []byte, src Value) (int, error) { + return catch.Try(func() int { + return js.CopyBytesToGo(dst, src.jsValue) + }) +} + +// CopyBytesToJS copies bytes from src to dst. +// Returns the number of bytes copied, which is the minimum of the lengths of src and dst. +// Returns an error if dst is not an Uint8Array or Uint8ClampedArray. +func CopyBytesToJS(dst Value, src []byte) (int, error) { + return catch.Try(func() int { + return js.CopyBytesToJS(dst.jsValue, src) + }) +} diff --git a/vendor/github.com/hack-pad/safejs/doc.go b/vendor/github.com/hack-pad/safejs/doc.go new file mode 100644 index 0000000..ca77820 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/doc.go @@ -0,0 +1,8 @@ +//go:build js && wasm + +/* +Package safejs provides guardrails around the [syscall/js] package, like turning thrown exceptions into errors. + +Since [syscall/js] is experimental, this package may have breaking changes to stay aligned with the latest versions of Go. +*/ +package safejs diff --git a/vendor/github.com/hack-pad/safejs/error.go b/vendor/github.com/hack-pad/safejs/error.go new file mode 100644 index 0000000..fa81a65 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/error.go @@ -0,0 +1,23 @@ +//go:build js && wasm + +package safejs + +import ( + "syscall/js" + + "github.com/hack-pad/safejs/internal/catch" +) + +// Error wraps a JavaScript error. +type Error struct { + err js.Error +} + +// Error implements the error interface. +func (e Error) Error() string { + errStr, err := catch.Try(e.err.Error) + if err != nil { + return "failed generating error message: " + err.Error() + } + return errStr +} diff --git a/vendor/github.com/hack-pad/safejs/func.go b/vendor/github.com/hack-pad/safejs/func.go new file mode 100644 index 0000000..44bc4ec --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/func.go @@ -0,0 +1,45 @@ +//go:build js && wasm + +package safejs + +import ( + "syscall/js" + + "github.com/hack-pad/safejs/internal/catch" +) + +// Func is a wrapped Go function to be called by JavaScript. +type Func struct { + fn js.Func +} + +// FuncOf returns a function to be used by JavaScript. See [js.FuncOf] for details. +func FuncOf(fn func(this Value, args []Value) any) (Func, error) { + jsFunc, err := toJSFunc(fn) + return Func{ + fn: jsFunc, + }, err +} + +func toJSFunc(fn func(this Value, args []Value) any) (js.Func, error) { + jsFunc := func(this js.Value, args []js.Value) any { + result := fn(Safe(this), toValues(args)) + return toJSValue(result) + } + return catch.Try(func() js.Func { + return js.FuncOf(jsFunc) + }) +} + +// Release frees up resources allocated for the function. The function must not be invoked after calling Release. +// It is allowed to call Release while the function is still running. +func (f Func) Release() { + f.fn.Release() +} + +// Value returns this Func's inner Value. For example, using value.Invoke() calls the function. +// +// Equivalent to accessing [js.Func]'s embedded [js.Value] field, only as a safejs type. +func (f Func) Value() Value { + return Safe(f.fn.Value) +} diff --git a/vendor/github.com/hack-pad/safejs/global.go b/vendor/github.com/hack-pad/safejs/global.go new file mode 100644 index 0000000..e46c3f6 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/global.go @@ -0,0 +1,42 @@ +//go:build js && wasm + +package safejs + +import ( + "fmt" + "syscall/js" +) + +// Global returns the JavaScript global object, usually "window" or "global". +func Global() Value { + return Safe(js.Global()) +} + +// MustGetGlobal fetches the given global, then verifies it is truthy. Panics on error or falsy values. +// This is intended for simple global variable initialization, like preparing classes for later instantiation. +// +// For example: +// +// var jsUint8Array = safejs.MustGetGlobal("Uint8Array") +func MustGetGlobal(property string) Value { + value, err := getGlobal(property) + if err != nil { + panic(err) + } + return value +} + +func getGlobal(property string) (Value, error) { + value, err := Global().Get(property) + if err != nil { + return Value{}, err + } + truthy, err := value.Truthy() + if err != nil { + return Value{}, err + } + if !truthy { + return Value{}, fmt.Errorf("global %q is not defined", property) + } + return value, nil +} diff --git a/vendor/github.com/hack-pad/safejs/internal/catch/catch.go b/vendor/github.com/hack-pad/safejs/internal/catch/catch.go new file mode 100644 index 0000000..538daf3 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/internal/catch/catch.go @@ -0,0 +1,47 @@ +//go:build js && wasm + +// Package catch runs functions and returns panic values as errors instead. +package catch + +import ( + "fmt" + "syscall/js" + + "github.com/hack-pad/safejs/internal/stackerr" +) + +// Try runs fn and returns the result. If fn panicked, the panic value is returned as an error instead. +func Try[Result any](fn func() Result) (result Result, err error) { + defer recoverErr(&err) + result = fn() + return +} + +// TrySideEffect is like Try, but does not have a return value. +func TrySideEffect(fn func()) (err error) { + defer recoverErr(&err) + fn() + return +} + +func recoverErr(err *error) { + value := recover() + valueErr := recoverValueToError(value) + if valueErr != nil { + *err = stackerr.WithStack(valueErr) + } +} + +func recoverValueToError(value any) error { + if value == nil { + return nil + } + switch value := value.(type) { + case error: + return value + case js.Value: + return js.Error{Value: value} + default: + return fmt.Errorf("%+v", value) + } +} diff --git a/vendor/github.com/hack-pad/safejs/internal/stackerr/stackerr.go b/vendor/github.com/hack-pad/safejs/internal/stackerr/stackerr.go new file mode 100644 index 0000000..d341f22 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/internal/stackerr/stackerr.go @@ -0,0 +1,79 @@ +//go:build js && wasm + +// Package stackerr adds stack traces to verbose error messages. +package stackerr + +import ( + "fmt" + "runtime" + "strings" +) + +type stackError struct { + err error + stack *stacktrace +} + +// WithStack returns 'err' with a stack trace in its verbose formatter output. +// Returns nil if err is nil. +func WithStack(err error) error { + if err == nil { + return nil + } + + return &stackError{ + err: err, + stack: collectStacktrace(3), + } +} + +func (s *stackError) Error() string { + return s.err.Error() +} + +func (s *stackError) Unwrap() error { + return s.err +} + +func (s *stackError) Format(f fmt.State, verb rune) { + switch verb { + case 'v': + if f.Flag('+') { + fmt.Fprintf(f, "%+v\n%s", s.err, s.stack) + return + } + fmt.Fprint(f, s.Error()) + case 's': + fmt.Fprint(f, s.Error()) + case 'q': + fmt.Fprintf(f, "%q", s.Error()) + } +} + +type stacktrace struct { + callers []uintptr +} + +func collectStacktrace(skip int) *stacktrace { + const ( + maxFrames = 32 + ) + pc := make([]uintptr, maxFrames) + n := runtime.Callers(1+skip, pc) + return &stacktrace{ + callers: pc[:n], + } +} + +func (s *stacktrace) String() string { + var sb strings.Builder + frames := runtime.CallersFrames(s.callers) + for frame, next := frames.Next(); next; frame, next = frames.Next() { + funcName := "unknown" + if frame.Func != nil { + funcName = frame.Func.Name() + } + sb.WriteString(fmt.Sprintf("%s\n\t%s:%d\n", funcName, frame.File, frame.Line)) + } + return sb.String() +} diff --git a/vendor/github.com/hack-pad/safejs/type.go b/vendor/github.com/hack-pad/safejs/type.go new file mode 100644 index 0000000..62db035 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/type.go @@ -0,0 +1,25 @@ +//go:build js && wasm + +package safejs + +import "syscall/js" + +// Type represents the JavaScript type of a Value. +type Type int + +// Available JavaScript types +const ( + TypeUndefined = Type(js.TypeUndefined) + TypeNull = Type(js.TypeNull) + TypeBoolean = Type(js.TypeBoolean) + TypeNumber = Type(js.TypeNumber) + TypeString = Type(js.TypeString) + TypeSymbol = Type(js.TypeSymbol) + TypeObject = Type(js.TypeObject) + TypeFunction = Type(js.TypeFunction) +) + +func (t Type) String() string { + // String() has a panic line, however it should be impossible to hit barring memory corruption + return js.Type(t).String() +} diff --git a/vendor/github.com/hack-pad/safejs/value.go b/vendor/github.com/hack-pad/safejs/value.go new file mode 100644 index 0000000..c4542f5 --- /dev/null +++ b/vendor/github.com/hack-pad/safejs/value.go @@ -0,0 +1,242 @@ +//go:build js && wasm + +package safejs + +import ( + "fmt" + "syscall/js" + + "github.com/hack-pad/safejs/internal/catch" +) + +// Value is a safer version of js.Value. Any panic returns an error instead. +type Value struct { + jsValue js.Value +} + +// Safe wraps a js.Value into a safejs.Value. +// Ideal for use in libraries where exposed types must match the standard library. +func Safe(value js.Value) Value { + return Value{ + jsValue: value, + } +} + +// Unsafe unwraps a safejs.Value back into its js.Value. +// Ideal for use in libraries where exposed types must match the standard library. +func Unsafe(value Value) js.Value { + return value.jsValue +} + +// Null returns the JavaScript value of "null". +func Null() Value { + return Safe(js.Null()) +} + +// Undefined returns the JavaScript value of "undefined". +func Undefined() Value { + return Safe(js.Undefined()) +} + +func toJSValue(jsValue any) any { + switch value := jsValue.(type) { + case Value: + return value.jsValue + case Func: + return value.fn + case Error: + return value.err + case map[string]any: + newValue := make(map[string]any) + for mapKey, mapValue := range value { + newValue[mapKey] = toJSValue(mapValue) + } + return newValue + case []any: + newValue := make([]any, len(value)) + for i, arg := range value { + newValue[i] = toJSValue(arg) + } + return newValue + default: + return jsValue + } +} + +func toJSValues(args []any) []any { + return toJSValue(args).([]any) +} + +func toValues(args []js.Value) []Value { + newArgs := make([]Value, len(args)) + for i, arg := range args { + newArgs[i] = Safe(arg) + } + return newArgs +} + +// ValueOf returns value as a JavaScript value. See [js.ValueOf] for details. +func ValueOf(value any) (Value, error) { + jsValue, err := catch.Try(func() js.Value { + return js.ValueOf(value) + }) + return Safe(jsValue), err +} + +// Bool attempts to convert this value into a boolean, otherwise returns an error. +func (v Value) Bool() (bool, error) { + return catch.Try(v.jsValue.Bool) +} + +// Call does a JavaScript call to the method m of value v with the given arguments. +// The arguments are mapped to JavaScript values according to the ValueOf function. +// Returns an error if v has no method m, the arguments failed to map to JavaScript values, or the function throws an error. +func (v Value) Call(m string, args ...any) (Value, error) { + args = toJSValues(args) + return catch.Try(func() Value { + return Safe(v.jsValue.Call(m, args...)) + }) +} + +// Delete deletes the JavaScript property p of value v. Returns an error if v is not a JavaScript object. +func (v Value) Delete(p string) error { + return catch.TrySideEffect(func() { + v.jsValue.Delete(p) + }) +} + +// Equal reports whether v and w are equal according to JavaScript's === operator. +func (v Value) Equal(w Value) bool { + return v.jsValue.Equal(w.jsValue) +} + +// Float returns the value v as a float64. Returns an error if v is not a JavaScript number. +func (v Value) Float() (float64, error) { + return catch.Try(v.jsValue.Float) +} + +// Get returns the JavaScript property p of value v. Returns an error if v is not a JavaScript object. +func (v Value) Get(p string) (Value, error) { + return catch.Try(func() Value { + return Safe(v.jsValue.Get(p)) + }) +} + +// Index returns JavaScript index i of value v. Returns an error if v is not a JavaScript object. +func (v Value) Index(i int) (Value, error) { + return catch.Try(func() Value { + return Safe(v.jsValue.Index(i)) + }) +} + +// InstanceOf reports whether v is an instance of type t according to JavaScript's instanceof operator. +// Returns an error if v is not a constructable type. +func (v Value) InstanceOf(t Value) (bool, error) { + // Type failures in JS throw "TypeError: Right-hand side of 'instanceof' is not an object" + // so catch those cases here. + // + // A valid type is a function with a field "prototype" which is an object. + if t.Type() != TypeFunction { + return false, fmt.Errorf("invalid type for instanceof: %v", t.Type()) + } + prototype, err := t.Get("prototype") + if err != nil { + return false, fmt.Errorf("invalid constructor type for instanceof: %v", err) + } else if prototype.Type() != TypeObject { + return false, fmt.Errorf("invalid constructor type for instanceof: %v", prototype.Type()) + } + return catch.Try(func() bool { + return v.jsValue.InstanceOf(t.jsValue) + }) +} + +// Int returns the value v truncated to an int. Returns an error if v is not a JavaScript number. +func (v Value) Int() (int, error) { + return catch.Try(v.jsValue.Int) +} + +// Invoke does a JavaScript call of the value v with the given arguments. +// The arguments get mapped to JavaScript values according to the ValueOf function. +// Returns an error if v is not a JavaScript function, the arguments failed to map to JavaScript values, or the function throws an error. +func (v Value) Invoke(args ...any) (Value, error) { + args = toJSValues(args) + return catch.Try(func() Value { + return Safe(v.jsValue.Invoke(args...)) + }) +} + +// IsNaN reports whether v is the JavaScript value "NaN". +func (v Value) IsNaN() bool { + return v.jsValue.IsNaN() +} + +// IsNull reports whether v is the JavaScript value "null". +func (v Value) IsNull() bool { + return v.jsValue.IsNull() +} + +// IsUndefined reports whether v is the JavaScript value "undefined". +func (v Value) IsUndefined() bool { + return v.jsValue.IsUndefined() +} + +// Length returns the JavaScript property "length" of v. +// Returns an error if v is not a JavaScript object. +func (v Value) Length() (int, error) { + return catch.Try(v.jsValue.Length) +} + +// New uses JavaScript's "new" operator with value v as constructor and the given arguments. +// The arguments get mapped to JavaScript values according to the ValueOf function. +// Returns an error if v is not a JavaScript function, the arguments failed to map to JavaScript values, or the constructor throws an error. +func (v Value) New(args ...any) (Value, error) { + args = toJSValues(args) + return catch.Try(func() Value { + return Safe(v.jsValue.New(args...)) + }) +} + +// Set sets the JavaScript property p of value v to ValueOf(x). +// Returns an error if v is not a JavaScript object or x failed to map to a JavaScript value. +func (v Value) Set(p string, x any) error { + x = toJSValue(x) + return catch.TrySideEffect(func() { + v.jsValue.Set(p, x) + }) +} + +// SetIndex sets the JavaScript index i of value v to ValueOf(x). +// Returns an error if if v is not a JavaScript object or x failed to map to a JavaScript value. +func (v Value) SetIndex(i int, x any) error { + x = toJSValue(x) + return catch.TrySideEffect(func() { + v.jsValue.SetIndex(i, x) + }) +} + +// String returns the value v as a string. +// Unlike the other getters, String() does not return an error if v's Type is not TypeString. +// Instead, it returns a string of the form "" or "" where T is v's type and V is a string representation of v's value. +// +// Returns an error if v is an invalid type or the string failed to load from the JavaScript runtime. +// +// NOTE: [syscall/js] takes the stance that String is a special case due to Go's String method convention and avoids panicking. +// However, js.String() can still fail in other ways so an error is returned anyway. +func (v Value) String() (string, error) { + return catch.Try(v.jsValue.String) +} + +// Truthy returns the JavaScript "truthiness" of the value v. +// In JavaScript, false, 0, "", null, undefined, and NaN are "falsy", and everything else is "truthy". +// See https://developer.mozilla.org/en-US/docs/Glossary/Truthy. +// +// Returns an error if v's type is invalid or if the value fails to load from the JavaScript runtime. +func (v Value) Truthy() (bool, error) { + return catch.Try(v.jsValue.Truthy) +} + +// Type returns the JavaScript type of the value v. +// It is similar to JavaScript's typeof operator, except it returns TypeNull instead of TypeObject for null. +func (v Value) Type() Type { + return Type(v.jsValue.Type()) +} diff --git a/vendor/github.com/nlepage/go-js-promise/LICENSE b/vendor/github.com/nlepage/go-js-promise/LICENSE new file mode 100644 index 0000000..fff153b --- /dev/null +++ b/vendor/github.com/nlepage/go-js-promise/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021 Nicolas LEPAGE + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/nlepage/go-js-promise/README.md b/vendor/github.com/nlepage/go-js-promise/README.md new file mode 100644 index 0000000..4827f46 --- /dev/null +++ b/vendor/github.com/nlepage/go-js-promise/README.md @@ -0,0 +1,3 @@ +# [github.com/nlepage/go-js-promise](https://pkg.go.dev/github.com/nlepage/go-js-promise) + +Go WebAssembly utility package for interacting with JavaScript promises diff --git a/vendor/github.com/nlepage/go-js-promise/promise.go b/vendor/github.com/nlepage/go-js-promise/promise.go new file mode 100644 index 0000000..8376bdb --- /dev/null +++ b/vendor/github.com/nlepage/go-js-promise/promise.go @@ -0,0 +1,56 @@ +package promise + +import ( + "syscall/js" +) + +// New creates a new JavaScript Promise +func New() (p js.Value, resolve func(interface{}), reject func(interface{})) { + var cbFunc js.Func + cbFunc = js.FuncOf(func(_ js.Value, args []js.Value) interface{} { + cbFunc.Release() + + resolve = func(value interface{}) { + args[0].Invoke(value) + } + + reject = func(value interface{}) { + args[1].Invoke(value) + } + + return js.Undefined() + }) + + p = js.Global().Get("Promise").New(cbFunc) + + return +} + +// Await waits for the Promise to be resolved and returns the value +// or an error if the promise rejected +func Await(p js.Value) (js.Value, error) { + resCh := make(chan js.Value) + var then js.Func + then = js.FuncOf(func(_ js.Value, args []js.Value) interface{} { + resCh <- args[0] + return nil + }) + defer then.Release() + + errCh := make(chan error) + var catch js.Func + catch = js.FuncOf(func(_ js.Value, args []js.Value) interface{} { + errCh <- js.Error{args[0]} + return nil + }) + defer catch.Release() + + p.Call("then", then).Call("catch", catch) + + select { + case res := <-resCh: + return res, nil + case err := <-errCh: + return js.Undefined(), err + } +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/.all-contributorsrc b/vendor/github.com/nlepage/go-wasm-http-server/v2/.all-contributorsrc new file mode 100644 index 0000000..642c6b7 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/.all-contributorsrc @@ -0,0 +1,37 @@ +{ + "projectName": "go-wasm-http-server", + "projectOwner": "nlepage", + "repoType": "github", + "repoHost": "https://github.com", + "files": [ + "README.md" + ], + "imageSize": 100, + "commit": false, + "commitConvention": "gitmoji", + "contributors": [ + { + "login": "jphastings", + "name": "JP Hastings-Edrei", + "avatar_url": "https://avatars.githubusercontent.com/u/42999?v=4", + "profile": "https://byjp.me/", + "contributions": [ + "code", + "doc", + "example" + ] + }, + { + "login": "EliCDavis", + "name": "Eli Davis", + "avatar_url": "https://avatars.githubusercontent.com/u/9094977?v=4", + "profile": "https://recolude.com/", + "contributions": [ + "code", + "bug" + ] + } + ], + "contributorsPerLine": 7, + "linkToUsage": false +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/.gitignore b/vendor/github.com/nlepage/go-wasm-http-server/v2/.gitignore new file mode 100644 index 0000000..e3a2287 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +*.wasm +!docs/**/*.wasm diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/CODE_OF_CONDUCT.md b/vendor/github.com/nlepage/go-wasm-http-server/v2/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..c51d402 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at nicolas.lepage+go-wasm-http-server@zenika.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/LICENSE b/vendor/github.com/nlepage/go-wasm-http-server/v2/LICENSE new file mode 100644 index 0000000..907fcfd --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 Nicolas Lepage + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/README.md b/vendor/github.com/nlepage/go-wasm-http-server/v2/README.md new file mode 100644 index 0000000..c1181c9 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/README.md @@ -0,0 +1,238 @@ +

Welcome to go-wasm-http-server πŸ‘‹

+

+ + Go Reference + + + License: Apache 2.0 + +

+ +> Embed your Go HTTP handlers in a ServiceWorker (using [WebAssembly](https://mdn.io/WebAssembly/)) and emulate an HTTP server! + +## Examples + + - [Hello example](https://nlepage.github.io/go-wasm-http-server/hello) ([sources](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/hello)) + - [Hello example with state](https://nlepage.github.io/go-wasm-http-server/hello-state) ([sources](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/hello-state)) + - [Hello example with state and keepalive](https://nlepage.github.io/go-wasm-http-server/hello-state-keepalive) ([sources](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/hello-state-keepalive)) + - [Hello example with Server Sent Events](https://nlepage.github.io/go-wasm-http-server/hello-sse/) ([sources](https://nlepage.github.io/go-wasm-http-server/hello-sse/)) + - [😺 Catption generator example](https://nlepage.github.io/catption/wasm) ([sources](https://github.com/nlepage/catption/tree/wasm)) + - [Random password generator web server](https://nlepage.github.io/random-password-please/) ([sources](https://github.com/nlepage/random-password-please) forked from [jbarham/random-password-please](https://github.com/jbarham/random-password-please)) + - [Server fallbacks, and compiling with TinyGo](https://nlepage.github.io/go-wasm-http-server/tinygo/) (runs locally; see [sources & readme](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/tinygo#readme) for how to run this example) + +## How? + +Talk given at the Go devroom of FOSDEM 2021 explaining how `go-wasm-http-server` works: + +[![Deploy a Go HTTP server in your browser Youtube link](https://raw.githubusercontent.com/nlepage/go-wasm-http-talk/main/youtube.png)](https://youtu.be/O2RB_8ircdE) + +The slides are available [here](https://nlepage.github.io/go-wasm-http-talk/). + +## Why? + +`go-wasm-http-server` can help you put up a demonstration for a project without actually running a Go HTTP server. + +## Requirements + +`go-wasm-http-server` requires you to build your Go application to WebAssembly, so you need to make sure your code is compatible: +- no C bindings +- no System dependencies such as file system or network (database server for example) +- For smaller WASM blobs, your code may also benefit from being compatible with, and compiled by, [TinyGo](https://tinygo.org/docs/reference/lang-support/stdlib/). See the TinyGo specific details below. + +## Usage + +### Step 1: Build to `js/wasm` + +In your Go code, replace [`http.ListenAndServe()`](https://pkg.go.dev/net/http#ListenAndServe) (or [`net.Listen()`](https://pkg.go.dev/net#Listen) + [`http.Serve()`](https://pkg.go.dev/net/http#Serve)) by [wasmhttp.Serve()](https://pkg.go.dev/github.com/nlepage/go-wasm-http-server#Serve): + +πŸ“„ `server.go` +```go +// +build !js,!wasm + +package main + +import ( + "net/http" +) + +func main() { + // Define handlers... + + http.ListenAndServe(":8080", nil) +} +``` + +becomes: + +πŸ“„ `server_js_wasm.go` +```go +// +build js,wasm + +package main + +import ( + wasmhttp "github.com/nlepage/go-wasm-http-server/v2" +) + +func main() { + // Define handlers... + + wasmhttp.Serve(nil) +} +``` + +You may want to use build tags as shown above (or file name suffixes) in order to be able to build both to WebAssembly and other targets. + +Then build your WebAssembly binary: + +```sh +# To compile with Go +GOOS=js GOARCH=wasm go build -o server.wasm . + +# To compile with TinyGo, if your code is compatible +GOOS=js GOARCH=wasm tinygo build -o server.wasm . +``` + +### Step 2: Create ServiceWorker file + +First, check the version of Go/TinyGo you compiled your wasm with: + +```sh +$ go version +go version go1.23.4 darwin/arm64 +# ^------^ + +$ tinygo version +tinygo version 0.35.0 darwin/arm64 (using go version go1.23.4 and LLVM version 18.1.2) +# ^----^ +``` + +Create a ServiceWorker file with the following code: + +πŸ“„ `sw.js` +```js +// Note the 'go.1.23.4' below, that matches the version you just found: +importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.23.4/misc/wasm/wasm_exec.js') +// If you compiled with TinyGo then, similarly, use: +importScripts('https://cdn.jsdelivr.net/gh/tinygo-org/tinygo@0.35.0/targets/wasm_exec.js') + +importScripts('https://cdn.jsdelivr.net/gh/nlepage/go-wasm-http-server@v2.2.1/sw.js') + +registerWasmHTTPListener('path/to/server.wasm') +``` + +By default the server will deploy at the ServiceWorker's scope root, check [`registerWasmHTTPListener()`'s API](https://github.com/nlepage/go-wasm-http-server#registerwasmhttplistenerwasmurl-options) for more information. + +You may want to add these additional event listeners in your ServiceWorker: + +```js +// Skip installed stage and jump to activating stage +addEventListener('install', (event) => { + event.waitUntil(skipWaiting()) +}) + +// Start controlling clients as soon as the SW is activated +addEventListener('activate', event => { + event.waitUntil(clients.claim()) +}) +``` + +### Step 3: Register the ServiceWorker + +In your web page(s), register the ServiceWorker: + +```html + +``` + +Now your web page(s) may start fetching from the server: + +```js +// The server will receive a request for "/path/to/resource" +fetch('server/path/to/resource').then(res => { + // use response... +}) +``` + +## API + +For Go API see [pkg.go.dev/github.com/nlepage/go-wasm-http-server](https://pkg.go.dev/github.com/nlepage/go-wasm-http-server#section-documentation) + +### JavaScript API + +### `registerWasmHTTPListener(wasmUrl, options)` + +Instantiates and runs the WebAssembly module at `wasmUrl`, and registers a fetch listener forwarding requests to the WebAssembly module's server. + +⚠ This function must be called only once in a ServiceWorker, if you want to register several servers you must use several ServiceWorkers. + +The server will be "deployed" at the root of the ServiceWorker's scope by default, `base` may be used to deploy the server at a subpath of the scope. + +See [ServiceWorkerContainer.register()](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register) for more information about the scope of a ServiceWorker. + +#### `wasmUrl` + +URL string of the WebAssembly module, example: `"path/to/my-module.wasm"`. + +#### `options` + +An optional object containing: + +- `base` (`string`): Base path of the server, relative to the ServiceWorker's scope. +- `cacheName` (`string`): Name of the [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to store the WebAssembly binary. +- `args` (`string[]`): Arguments for the WebAssembly module. +- `passthrough` (`(request: Request): boolean`): Optional callback to allow passing the request through to network. + +## FAQ ❓ + +### Are WebSockets supported? + +No, WebSockets aren’t and won’t be supported, because Service Workers cannot intercept websocket connections. + +However [Server Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events), which is an alternative to WebSockets, are supported, you can find the code for an example [here](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/hello-sse) and the demo [here](https://nlepage.github.io/go-wasm-http-server/hello-sse/). + +### Is it compatible with TinyGo? + +Yes, an example and some specific information is available [here](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/tinygo). + +## Contributors ✨ + +Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): + + + + + + + + + + + +
JP Hastings-Edrei
JP Hastings-Edrei

πŸ’» πŸ“– πŸ’‘
Eli Davis
Eli Davis

πŸ’» πŸ›
+ + + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! + +## 🀝 Contributing + +Contributions, issues and feature requests are welcome!
Feel free to check [issues page](https://github.com/nlepage/go-wasm-http-server/issues). + +## Show your support + +Give a ⭐️ if this project helped you! + +## πŸ“ License + +Copyright Β© 2025 [Nicolas Lepage](https://github.com/nlepage).
+This project is [Apache 2.0](https://github.com/nlepage/go-wasm-http-server/blob/master/LICENSE) licensed. + +*** +_This README was generated with ❀️ by [readme-md-generator](https://github.com/kefranabg/readme-md-generator)_ diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/jstype/types.go b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/jstype/types.go new file mode 100644 index 0000000..71cb0b5 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/jstype/types.go @@ -0,0 +1,13 @@ +package jstype + +import ( + "syscall/js" + + "github.com/nlepage/go-wasm-http-server/v2/internal/safejs" +) + +var ( + ReadableStream = safejs.Safe(js.Global().Get("ReadableStream")) + Response = safejs.Safe(js.Global().Get("Response")) + Uint8Array = safejs.Safe(js.Global().Get("Uint8Array")) +) diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/readablestream/reader.go b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/readablestream/reader.go new file mode 100644 index 0000000..1842d4d --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/readablestream/reader.go @@ -0,0 +1,96 @@ +package readablestream + +import ( + "io" + + promise "github.com/nlepage/go-js-promise" + + "github.com/nlepage/go-wasm-http-server/v2/internal/safejs" +) + +type Reader struct { + value safejs.Value + buf []byte + off int +} + +var _ io.ReadCloser = (*Reader)(nil) + +func NewReader(r safejs.Value) *Reader { + return &Reader{ + value: r, + } +} + +func (r *Reader) Read(p []byte) (int, error) { + if r.off < len(r.buf) { + n := copy(p, r.buf[r.off:]) + + r.off += n + + return n, nil + } + + r.off = 0 + + pRes, err := r.value.Call("read") + if err != nil { + return 0, err + } + + ures, err := promise.Await(safejs.Unsafe(pRes)) + if err != nil { + return 0, err + } + + res := safejs.Safe(ures) + + done, err := res.GetBool("done") + if err != nil { + return 0, err + } + if done { + return 0, io.EOF + } + + value, err := res.Get("value") + if err != nil { + return 0, err + } + + l, err := value.GetInt("length") + if err != nil { + return 0, err + } + + if cap(r.buf) < l { + r.buf = make([]byte, l) + } + if len(r.buf) < cap(r.buf) { + r.buf = r.buf[:cap(r.buf)] + } + + n, err := safejs.CopyBytesToGo(r.buf, value) + if err != nil { + return 0, err + } + + r.buf = r.buf[:n] + + n = copy(p, r.buf[r.off:]) + + r.off += n + + return n, nil +} + +func (r *Reader) Close() error { + p, err := r.value.Call("cancel") + if err != nil { + return err + } + + _, err = promise.Await(safejs.Unsafe(p)) + + return err +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/readablestream/writer.go b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/readablestream/writer.go new file mode 100644 index 0000000..9484249 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/readablestream/writer.go @@ -0,0 +1,101 @@ +package readablestream + +import ( + "context" + "io" + + "github.com/nlepage/go-wasm-http-server/v2/internal/jstype" + "github.com/nlepage/go-wasm-http-server/v2/internal/safejs" +) + +type Writer struct { + Value safejs.Value + controller safejs.Value + ctx context.Context + cancelled bool +} + +var _ io.WriteCloser = (*Writer)(nil) + +func NewWriter() (*Writer, error) { + var rs *Writer + + var start safejs.Func + var controller safejs.Value + + start, err := safejs.FuncOf(func(_ safejs.Value, args []safejs.Value) any { + defer start.Release() + controller = args[0] + return nil + }) + if err != nil { + return nil, err + } + + var cancel safejs.Func + ctx, cancelCtx := context.WithCancel(context.Background()) + + cancel, err = safejs.FuncOf(func(_ safejs.Value, _ []safejs.Value) any { + defer cancel.Release() + rs.cancelled = true + cancelCtx() + return nil + }) + if err != nil { + return nil, err + } + + source, err := safejs.ValueOf(map[string]any{ + "start": safejs.Unsafe(start.Value()), + "cancel": safejs.Unsafe(cancel.Value()), + }) + if err != nil { + return nil, err + } + + value, err := jstype.ReadableStream.New(source) + if err != nil { + return nil, err + } + + rs = &Writer{ + Value: value, + controller: controller, + ctx: ctx, + } + + return rs, nil +} + +func (rs *Writer) Write(b []byte) (int, error) { + if rs.cancelled { + return 0, nil + } + + chunk, err := jstype.Uint8Array.New(len(b)) // FIXME reuse same Uint8Array? + if err != nil { + return 0, err + } + + n, err := safejs.CopyBytesToJS(chunk, b) + if err != nil { + return 0, err + } + + _, err = rs.controller.Call("enqueue", chunk) + + return n, err +} + +func (rs *Writer) Close() error { + if rs.cancelled { + return nil + } + + _, err := rs.controller.Call("close") + return err +} + +func (rs *Writer) Context() context.Context { + return rs.ctx +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/safejs/bytes.go b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/safejs/bytes.go new file mode 100644 index 0000000..f6087d5 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/safejs/bytes.go @@ -0,0 +1,11 @@ +package safejs + +import "github.com/hack-pad/safejs" + +func CopyBytesToGo(dst []byte, src Value) (int, error) { + return safejs.CopyBytesToGo(dst, safejs.Value(src)) +} + +func CopyBytesToJS(dst Value, src []byte) (int, error) { + return safejs.CopyBytesToJS(safejs.Value(dst), src) +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/safejs/func.go b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/safejs/func.go new file mode 100644 index 0000000..dc0b141 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/safejs/func.go @@ -0,0 +1,26 @@ +package safejs + +import ( + "github.com/hack-pad/safejs" +) + +type Func safejs.Func + +func FuncOf(fn func(this Value, args []Value) any) (Func, error) { + r, err := safejs.FuncOf(func(this safejs.Value, args []safejs.Value) any { + args2 := make([]Value, len(args)) + for i, v := range args { + args2[i] = Value(v) + } + return fn(Value(this), []Value(args2)) + }) + return Func(r), err +} + +func (f Func) Release() { + safejs.Func(f).Release() +} + +func (f Func) Value() Value { + return Value(safejs.Func(f).Value()) +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/safejs/value.go b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/safejs/value.go new file mode 100644 index 0000000..1c93691 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/internal/safejs/value.go @@ -0,0 +1,111 @@ +package safejs + +import ( + "syscall/js" + + "github.com/hack-pad/safejs" +) + +type Value safejs.Value + +func Safe(v js.Value) Value { + return Value(safejs.Safe(v)) +} + +func Unsafe(v Value) js.Value { + return safejs.Unsafe(safejs.Value(v)) +} + +func ValueOf(value any) (Value, error) { + v, err := safejs.ValueOf(value) + return Value(v), err +} + +func (v Value) Call(m string, args ...any) (Value, error) { + args = toJSValue(args).([]any) + r, err := safejs.Value(v).Call(m, args...) + return Value(r), err +} + +func (v Value) Get(p string) (Value, error) { + r, err := safejs.Value(v).Get(p) + return Value(r), err +} + +func (v Value) GetBool(p string) (bool, error) { + bv, err := v.Get(p) + if err != nil { + return false, err + } + + return safejs.Value(bv).Bool() +} + +func (v Value) GetInt(p string) (int, error) { + iv, err := v.Get(p) + if err != nil { + return 0, err + } + + return safejs.Value(iv).Int() +} + +func (v Value) GetString(p string) (string, error) { + sv, err := v.Get(p) + if err != nil { + return "", err + } + + return safejs.Value(sv).String() +} + +func (v Value) Index(i int) (Value, error) { + r, err := safejs.Value(v).Index(i) + return Value(r), err +} + +func (v Value) IndexString(i int) (string, error) { + sv, err := v.Index(i) + if err != nil { + return "", err + } + + return safejs.Value(sv).String() +} + +func (v Value) IsNull() bool { + return safejs.Value(v).IsNull() +} + +func (v Value) IsUndefined() bool { + return safejs.Value(v).IsUndefined() +} + +func (v Value) New(args ...any) (Value, error) { + args = toJSValue(args).([]any) + r, err := safejs.Value(v).New(args...) + return Value(r), err +} + +func toJSValue(jsValue any) any { + switch value := jsValue.(type) { + case Value: + return safejs.Value(value) + case Func: + return safejs.Func(value) + case map[string]any: + newValue := make(map[string]any) + for mapKey, mapValue := range value { + newValue[mapKey] = toJSValue(mapValue) + } + return newValue + case []any: + newValue := make([]any, len(value)) + for i, arg := range value { + newValue[i] = toJSValue(arg) + } + return newValue + default: + return jsValue + } +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/package-lock.json b/vendor/github.com/nlepage/go-wasm-http-server/v2/package-lock.json new file mode 100644 index 0000000..9d9e580 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/package-lock.json @@ -0,0 +1,787 @@ +{ + "name": "go-wasm-http-server", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "go-wasm-http-server", + "version": "0.1.0", + "license": "Apache-2.0", + "devDependencies": { + "all-contributors-cli": "^6.26.1" + } + }, + "node_modules/@babel/runtime": { + "version": "7.26.0", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.0.tgz", + "integrity": "sha512-FDSOghenHTiToteC/QRlv2q3DhPZ/oOXTBoirfWNx1Cx3TMVcGWQtMMmQcSvb/JjpNeGzx8Pq/b4fKEJuWm1sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "regenerator-runtime": "^0.14.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/all-contributors-cli": { + "version": "6.26.1", + "resolved": "https://registry.npmjs.org/all-contributors-cli/-/all-contributors-cli-6.26.1.tgz", + "integrity": "sha512-Ymgo3FJACRBEd1eE653FD1J/+uD0kqpUNYfr9zNC1Qby0LgbhDBzB3EF6uvkAbYpycStkk41J+0oo37Lc02yEw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.7.6", + "async": "^3.1.0", + "chalk": "^4.0.0", + "didyoumean": "^1.2.1", + "inquirer": "^7.3.3", + "json-fixer": "^1.6.8", + "lodash": "^4.11.2", + "node-fetch": "^2.6.0", + "pify": "^5.0.0", + "yargs": "^15.0.1" + }, + "bin": { + "all-contributors": "dist/cli.js" + }, + "engines": { + "node": ">=4" + }, + "optionalDependencies": { + "prettier": "^2" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "dev": true, + "license": "MIT" + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true, + "license": "MIT" + }, + "node_modules/cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-width": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", + "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 10" + } + }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/didyoumean": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", + "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dev": true, + "license": "MIT", + "dependencies": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^1.0.5" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inquirer": { + "version": "7.3.3", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-7.3.3.tgz", + "integrity": "sha512-JG3eIAj5V9CwcGvuOmoo6LB9kbAYT8HXffUl6memuszlwDC/qvFAJw49XJ5NROSFNPxp3iQg1GqkFhaY/CR0IA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^4.2.1", + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-width": "^3.0.0", + "external-editor": "^3.0.3", + "figures": "^3.0.0", + "lodash": "^4.17.19", + "mute-stream": "0.0.8", + "run-async": "^2.4.0", + "rxjs": "^6.6.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "through": "^2.3.6" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/json-fixer": { + "version": "1.6.15", + "resolved": "https://registry.npmjs.org/json-fixer/-/json-fixer-1.6.15.tgz", + "integrity": "sha512-TuDuZ5KrgyjoCIppdPXBMqiGfota55+odM+j2cQ5rt/XKyKmqGB3Whz1F8SN8+60yYGy/Nu5lbRZ+rx8kBIvBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.9", + "chalk": "^4.1.2", + "pegjs": "^0.10.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true, + "license": "MIT" + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "dev": true, + "license": "ISC" + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pegjs": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/pegjs/-/pegjs-0.10.0.tgz", + "integrity": "sha512-qI5+oFNEGi3L5HAxDwN2LA4Gg7irF70Zs25edhjld9QemOgp0CbvMtbFcMvFtEo1OityPrcCzkQFB8JP/hxgow==", + "dev": true, + "license": "MIT", + "bin": { + "pegjs": "bin/pegjs" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/pify": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-5.0.0.tgz", + "integrity": "sha512-eW/gHNMlxdSP6dmG6uJip6FXN0EQBwm2clYYd8Wul42Cwu/DK8HEftzsapcNdYe2MfLiIwZqsDk2RDEsTE79hA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "dev": true, + "license": "MIT", + "optional": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz", + "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==", + "dev": true, + "license": "MIT" + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dev": true, + "license": "ISC" + }, + "node_modules/restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/run-async": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/rxjs": { + "version": "6.6.7", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", + "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^1.9.0" + }, + "engines": { + "npm": ">=2.0.0" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "dev": true, + "license": "ISC" + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true, + "license": "0BSD" + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + } + } +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/package.go b/vendor/github.com/nlepage/go-wasm-http-server/v2/package.go new file mode 100644 index 0000000..f6b59f7 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/package.go @@ -0,0 +1,2 @@ +// Package wasmhttp allows to create a WebAssembly Go HTTP Server embedded in a ServiceWorker. +package wasmhttp diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/package.json b/vendor/github.com/nlepage/go-wasm-http-server/v2/package.json new file mode 100644 index 0000000..7756b34 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/package.json @@ -0,0 +1,12 @@ +{ + "name": "go-wasm-http-server", + "version": "0.1.0", + "description": "WebAssembly Go HTTP Server embedded in a ServiceWorker", + "main": "index.js", + "repository": "https://github.com/nlepage/go-wasm-http-server", + "author": "Nicolas Lepage <19571875+nlepage@users.noreply.github.com>", + "license": "Apache-2.0", + "devDependencies": { + "all-contributors-cli": "^6.26.1" + } +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/request.go b/vendor/github.com/nlepage/go-wasm-http-server/v2/request.go new file mode 100644 index 0000000..63de281 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/request.go @@ -0,0 +1,119 @@ +package wasmhttp + +import ( + "io" + "net/http" + "net/url" + "syscall/js" + + promise "github.com/nlepage/go-js-promise" + "github.com/nlepage/go-wasm-http-server/v2/internal/readablestream" + "github.com/nlepage/go-wasm-http-server/v2/internal/safejs" +) + +// Request builds and returns the equivalent http.Request +func Request(uvalue js.Value) (*http.Request, error) { + value := safejs.Safe(uvalue) + + method, err := value.GetString("method") + if err != nil { + return nil, err + } + + rawURL, err := value.GetString("url") + if err != nil { + return nil, err + } + u, err := url.Parse(rawURL) + if err != nil { + return nil, err + } + + body, err := value.Get("body") + if err != nil { + return nil, err + } + + var bodyReader io.ReadCloser + + if !body.IsNull() { + // WORKAROUND: Firefox does not have request.body ReadableStream + if body.IsUndefined() { + blobp, err := value.Call("blob") + if err != nil { + return nil, err + } + + blob, err := promise.Await(safejs.Unsafe(blobp)) + if err != nil { + return nil, err + } + + body, err = safejs.Safe(blob).Call("stream") + if err != nil { + return nil, err + } + } + + r, err := body.Call("getReader") + if err != nil { + return nil, err + } + + bodyReader = readablestream.NewReader(r) + } + + req := &http.Request{ + Method: method, + URL: u, + Body: bodyReader, + Header: make(http.Header), + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + } + + headers, err := value.Get("headers") + if err != nil { + return nil, err + } + + headersIt, err := headers.Call("entries") + if err != nil { + return nil, err + } + for { + e, err := headersIt.Call("next") + if err != nil { + return nil, err + } + + done, err := e.GetBool("done") + if err != nil { + return nil, err + } + + if done { + break + } + + v, err := e.Get("value") + if err != nil { + return nil, err + } + + key, err := v.IndexString(0) + if err != nil { + return nil, err + } + + value, err := v.IndexString(1) + if err != nil { + return nil, err + } + + req.Header.Set(key, value) + } + + return req, nil +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/response.go b/vendor/github.com/nlepage/go-wasm-http-server/v2/response.go new file mode 100644 index 0000000..0d878e2 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/response.go @@ -0,0 +1,178 @@ +package wasmhttp + +import ( + "bufio" + "context" + "fmt" + "io" + "log/slog" + "net/http" + "syscall/js" + + promise "github.com/nlepage/go-js-promise" + + "github.com/nlepage/go-wasm-http-server/v2/internal/jstype" + "github.com/nlepage/go-wasm-http-server/v2/internal/readablestream" + "github.com/nlepage/go-wasm-http-server/v2/internal/safejs" +) + +type Response interface { + http.ResponseWriter + io.StringWriter + http.Flusher + io.Closer + Context() context.Context + WriteError(string) + JSValue() js.Value +} + +type response struct { + header http.Header + wroteHeader bool + + promise js.Value + resolve func(any) + + rs *readablestream.Writer + body *bufio.Writer +} + +func NewResponse() (Response, error) { + rs, err := readablestream.NewWriter() + if err != nil { + return nil, err + } + + promise, resolve, _ := promise.New() + + return &response{ + promise: promise, + resolve: resolve, + + rs: rs, + body: bufio.NewWriter(rs), + }, nil +} + +var _ Response = (*response)(nil) + +// Header implements [http.ResponseWriter]. +func (r *response) Header() http.Header { + if r.header == nil { + r.header = make(http.Header) + } + return r.header +} + +func (r *response) headerValue() map[string]any { + h := r.Header() + hh := make(map[string]any, len(h)+1) + for k := range h { + hh[k] = h.Get(k) + } + return hh +} + +// Write implements http.ResponseWriter. +func (r *response) Write(buf []byte) (int, error) { + r.writeHeader(buf, "") + return r.body.Write(buf) +} + +// WriteHeader implements [http.ResponseWriter]. +func (r *response) WriteHeader(code int) { + if r.wroteHeader { + return + } + + checkWriteHeaderCode(code) + + init, err := safejs.ValueOf(map[string]any{ + "status": code, + "headers": r.headerValue(), + }) + if err != nil { + panic(err) + } + + res, err := jstype.Response.New(r.rs.Value, init) + if err != nil { + panic(err) + } + + r.wroteHeader = true + + r.resolve(safejs.Unsafe(res)) +} + +// WriteString implements [io.StringWriter]. +func (r *response) WriteString(str string) (int, error) { + r.writeHeader(nil, str) + return r.body.WriteString(str) +} + +// Flush implements [http.Flusher] +func (r *response) Flush() { + if !r.wroteHeader { + r.WriteHeader(200) + } + if err := r.body.Flush(); err != nil { + panic(err) + } +} + +// Close implements [io.Closer] +func (r *response) Close() error { + if !r.wroteHeader { + r.WriteHeader(200) + } + if err := r.body.Flush(); err != nil { + return err + } + return r.rs.Close() +} + +func (r *response) Context() context.Context { + return r.rs.Context() +} + +func (r *response) WriteError(str string) { + slog.Error(str) + if !r.wroteHeader { + r.Header().Set("Content-Type", "text/plain") + r.WriteHeader(500) + _, _ = r.WriteString(str) + } +} + +func (r *response) JSValue() js.Value { + return r.promise +} + +func (r *response) writeHeader(b []byte, str string) { + if r.wroteHeader { + return + } + + m := r.Header() + + _, hasType := m["Content-Type"] + hasTE := m.Get("Transfer-Encoding") != "" + if !hasType && !hasTE { + if b == nil { + if len(str) > 512 { + str = str[:512] + } + b = []byte(str) + } + m.Set("Content-Type", http.DetectContentType(b)) + } + + r.WriteHeader(200) +} + +func checkWriteHeaderCode(code int) { + if code < 100 || code > 999 { + panic(fmt.Sprintf("invalid WriteHeader code %v", code)) + } +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/serve.go b/vendor/github.com/nlepage/go-wasm-http-server/v2/serve.go new file mode 100644 index 0000000..f4869d5 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/serve.go @@ -0,0 +1,86 @@ +package wasmhttp + +import ( + "context" + "fmt" + "net/http" + "strings" + "syscall/js" + + "github.com/nlepage/go-wasm-http-server/v2/internal/safejs" +) + +var ( + wasmhttp = safejs.Safe(js.Global().Get("wasmhttp")) +) + +// Serve serves HTTP requests using handler or http.DefaultServeMux if handler is nil. +func Serve(handler http.Handler) (func(), error) { + h := handler + if h == nil { + h = http.DefaultServeMux + } + + prefix, err := wasmhttp.GetString("path") + if err != nil { + return nil, err + } + + for strings.HasSuffix(prefix, "/") { + prefix = strings.TrimSuffix(prefix, "/") + } + + if prefix != "" { + mux := http.NewServeMux() + mux.Handle(prefix+"/", http.StripPrefix(prefix, h)) + h = mux + } + + handlerValue, err := safejs.FuncOf(func(_ safejs.Value, args []safejs.Value) interface{} { + res, err := NewResponse() + if err != nil { + panic(err) + } + + go func() { + ctx, cancel := context.WithCancel(res.Context()) + + defer func() { + cancel() + }() + + defer func() { + if err := res.Close(); err != nil { + panic(err) + } + }() + + defer func() { + if r := recover(); r != nil { + res.WriteError(fmt.Sprintf("%+v", r)) + } + }() + + req, err := Request(safejs.Unsafe(args[0])) + if err != nil { + res.WriteError(fmt.Sprintf("%+v", err)) + return + } + + req = req.WithContext(ctx) + + h.ServeHTTP(res, req) + }() + + return res.JSValue() + }) + if err != nil { + return nil, err + } + + if _, err = wasmhttp.Call("setHandler", handlerValue); err != nil { + return nil, err + } + + return handlerValue.Release, nil +} diff --git a/vendor/github.com/nlepage/go-wasm-http-server/v2/sw.js b/vendor/github.com/nlepage/go-wasm-http-server/v2/sw.js new file mode 100644 index 0000000..11e0ae0 --- /dev/null +++ b/vendor/github.com/nlepage/go-wasm-http-server/v2/sw.js @@ -0,0 +1,42 @@ +function registerWasmHTTPListener(wasm, { base, cacheName, passthrough, args = [] } = {}) { + let path = new URL(registration.scope).pathname + if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}` + + const handlerPromise = new Promise(setHandler => { + self.wasmhttp = { + path, + setHandler, + } + }) + + const go = new Go() + go.argv = [wasm, ...args] + const source = cacheName + ? caches.open(cacheName).then((cache) => cache.match(wasm)).then((response) => response ?? fetch(wasm)) + : caches.match(wasm).then(response => (response) ?? fetch(wasm)) + WebAssembly.instantiateStreaming(source, go.importObject).then(({ instance }) => go.run(instance)) + + addEventListener('fetch', e => { + if (passthrough?.(e.request)) { + e.respondWith(fetch(e.request)) + return; + } + + const { pathname } = new URL(e.request.url) + if (!pathname.startsWith(path)) return + + e.respondWith(handlerPromise.then(handler => handler(e.request))) + }) +} + +function trimStart(s, c) { + let r = s + while (r.startsWith(c)) r = r.slice(c.length) + return r +} + +function trimEnd(s, c) { + let r = s + while (r.endsWith(c)) r = r.slice(0, -c.length) + return r +} diff --git a/vendor/modules.txt b/vendor/modules.txt index b3d6f2e..22f070a 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,6 +1,23 @@ +## workspace +# github.com/hack-pad/safejs v0.1.1 +## explicit; go 1.18 +github.com/hack-pad/safejs +github.com/hack-pad/safejs/internal/catch +github.com/hack-pad/safejs/internal/stackerr # github.com/mdm-code/scanner v1.2.1 ## explicit; go 1.21 github.com/mdm-code/scanner +# github.com/mdm-code/tq/v2 v2.4.0 +## explicit; go 1.24 +# github.com/nlepage/go-js-promise v1.0.0 +## explicit; go 1.12 +github.com/nlepage/go-js-promise +# github.com/nlepage/go-wasm-http-server/v2 v2.2.1 +## explicit; go 1.18 +github.com/nlepage/go-wasm-http-server/v2 +github.com/nlepage/go-wasm-http-server/v2/internal/jstype +github.com/nlepage/go-wasm-http-server/v2/internal/readablestream +github.com/nlepage/go-wasm-http-server/v2/internal/safejs # github.com/pelletier/go-toml/v2 v2.1.0 ## explicit; go 1.16 github.com/pelletier/go-toml/v2 @@ -8,3 +25,5 @@ github.com/pelletier/go-toml/v2/internal/characters github.com/pelletier/go-toml/v2/internal/danger github.com/pelletier/go-toml/v2/internal/tracker github.com/pelletier/go-toml/v2/unstable +# github.com/stretchr/testify v1.10.0 +## explicit; go 1.17