script.jsvar IR=Object.defineProperty;var io=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var $s=(e,t)=>{for(var r in t)IR(e,r,{get:t[r],enumerable:!0})};function _e(e){if(e)return FR(e)}function FR(e){for(var t in _e.prototype)e[t]=_e.prototype[t];return e}_e.prototype.on=_e.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};_e.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};_e.prototype.off=_e.prototype.removeListener=_e.prototype.removeAllListeners=_e.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var r=this._callbacks["$"+e];if(!r)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var o,n=0;n<r.length;n++)if(o=r[n],o===t||o.fn===t){r.splice(n,1);break}return r.length===0&&delete this._callbacks["$"+e],this};_e.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],o=1;o<arguments.length;o++)t[o-1]=arguments[o];if(r){r=r.slice(0);for(var o=0,n=r.length;o<n;++o)r[o].apply(this,t)}return this};_e.prototype.emitReserved=_e.prototype.emit;_e.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};_e.prototype.hasListeners=function(e){return!!this.listeners(e).length};var rr=Object.create(null);rr.open="0";rr.close="1";rr.ping="2";rr.pong="3";rr.message="4";rr.upgrade="5";rr.noop="6";var Hs=Object.create(null);Object.keys(rr).forEach(e=>{Hs[rr[e]]=e});var Ic={type:"error",data:"parser error"},Zu=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",em=typeof ArrayBuffer=="function",tm=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Ws=({type:e,data:t},r,o)=>Zu&&t instanceof Blob?r?o(t):Yu(t,o):em&&(t instanceof ArrayBuffer||tm(t))?r?o(t):Yu(new Blob([t]),o):o(rr[e]+(t||"")),Yu=(e,t)=>{let r=new FileReader;return r.onload=function(){let o=r.result.split(",")[1];t("b"+(o||""))},r.readAsDataURL(e)};function Ju(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Ac;function UR(e,t){if(Zu&&e.data instanceof Blob)return e.data.arrayBuffer().then(Ju).then(t);if(em&&(e.data instanceof ArrayBuffer||tm(e.data)))return t(Ju(e.data));Ws(e,!1,r=>{Ac||(Ac=new TextEncoder),t(Ac.encode(r))})}var Qu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Un=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Qu.length;e++)Un[Qu.charCodeAt(e)]=e;var DR=e=>{let t=e.length*.75,r=e.length,o,n=0,s,i,a,c;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(o=0;o<r;o+=4)s=Un[e.charCodeAt(o)],i=Un[e.charCodeAt(o+1)],a=Un[e.charCodeAt(o+2)],c=Un[e.charCodeAt(o+3)],u[n++]=s<<2|i>>4,u[n++]=(i&15)<<4|a>>2,u[n++]=(a&3)<<6|c&63;return l},$R=typeof ArrayBuffer=="function",Gs=(e,t)=>{if(typeof e!="string")return{type:"message",data:rm(e,t)};let r=e.charAt(0);return r==="b"?{type:"message",data:jR(e.substring(1),t)}:Hs[r]?e.length>1?{type:Hs[r],data:e.substring(1)}:{type:Hs[r]}:Ic},jR=(e,t)=>{if($R){let r=DR(e);return rm(r,t)}else return{base64:!0,data:e}},rm=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},om="",nm=(e,t)=>{let r=e.length,o=new Array(r),n=0;e.forEach((s,i)=>{Ws(s,!1,a=>{o[i]=a,++n===r&&t(o.join(om))})})},sm=(e,t)=>{let r=e.split(om),o=[];for(let n=0;n<r.length;n++){let s=Gs(r[n],t);if(o.push(s),s.type==="error")break}return o};function im(){return new TransformStream({transform(e,t){UR(e,r=>{let o=r.length,n;if(o<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,o);else if(o<65536){n=new Uint8Array(3);let s=new DataView(n.buffer);s.setUint8(0,126),s.setUint16(1,o)}else{n=new Uint8Array(9);let s=new DataView(n.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(o))}e.data&&typeof e.data!="string"&&(n[0]|=128),t.enqueue(n),t.enqueue(r)})}})}var Mc;function js(e){return e.reduce((t,r)=>t+r.length,0)}function Bs(e,t){if(e[0].length===t)return e.shift();let r=new Uint8Array(t),o=0;for(let n=0;n<t;n++)r[n]=e[0][o++],o===e[0].length&&(e.shift(),o=0);return e.length&&o<e[0].length&&(e[0]=e[0].slice(o)),r}function am(e,t){Mc||(Mc=new TextDecoder);let r=[],o=0,n=-1,s=!1;return new TransformStream({transform(i,a){for(r.push(i);;){if(o===0){if(js(r)<1)break;let c=Bs(r,1);s=(c[0]&128)===128,n=c[0]&127,n<126?o=3:n===126?o=1:o=2}else if(o===1){if(js(r)<2)break;let c=Bs(r,2);n=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),o=3}else if(o===2){if(js(r)<8)break;let c=Bs(r,8),l=new DataView(c.buffer,c.byteOffset,c.length),u=l.getUint32(0);if(u>Math.pow(2,21)-1){a.enqueue(Ic);break}n=u*Math.pow(2,32)+l.getUint32(4),o=3}else{if(js(r)<n)break;let c=Bs(r,n);a.enqueue(Gs(s?c:Mc.decode(c),t)),o=0}if(n===0||n>e){a.enqueue(Ic);break}}}})}var Fc=4;var Dn=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Ft=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),BR="arraybuffer";function lm(e,...t){return t.reduce((r,o)=>(e.hasOwnProperty(o)&&(r[o]=e[o]),r),{})}var HR=Ft.setTimeout,WR=Ft.clearTimeout;function $n(e,t){t.useNativeTimers?(e.setTimeoutFn=HR.bind(Ft),e.clearTimeoutFn=WR.bind(Ft)):(e.setTimeoutFn=Ft.setTimeout.bind(Ft),e.clearTimeoutFn=Ft.clearTimeout.bind(Ft))}var GR=1.33;function VR(e){return typeof e=="string"?zR(e):Math.ceil((e.byteLength||e.size)*GR)}function zR(e){let t=0,r=0;for(let o=0,n=e.length;o<n;o++)t=e.charCodeAt(o),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(o++,r+=4);return r}function pm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function qR(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}function KR(e){let t={},r=e.split("&");for(let o=0,n=r.length;o<n;o++){let s=r[o].split("=");t[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return t}var XR=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},$c=class extends _e{constructor(e){super(),this.writable=!1,$n(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new XR(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=Gs(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=qR(e);return t.length?"?"+t:""}},YR=class extends $c{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||t()})),this.writable||(r++,this.once("drain",function(){--r||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};sm(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){let e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,nm(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=pm()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},um=!1;try{um=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var JR=um;function QR(){}var ZR=class extends YR{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",r=location.port;r||(r=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(o,n)=>{this.onError("xhr post error",o,n)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,r)=>{this.onError("xhr poll error",t,r)}),this.pollXhr=e}},Vo=class Vs extends _e{constructor(t,r,o){super(),this.createRequest=t,$n(this,o),this._opts=o,this._method=o.method||"GET",this._uri=r,this._data=o.data!==void 0?o.data:null,this._create()}_create(){var t;let r=lm(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;let o=this._xhr=this.createRequest(r);try{o.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){o.setDisableHeaderCheck&&o.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&o.setRequestHeader(n,this._opts.extraHeaders[n])}}catch{}if(this._method==="POST")try{o.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{o.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(o),"withCredentials"in o&&(o.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(o.timeout=this._opts.requestTimeout),o.onreadystatechange=()=>{var n;o.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.parseCookies(o.getResponseHeader("set-cookie"))),o.readyState===4&&(o.status===200||o.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof o.status=="number"?o.status:0)},0))},o.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=Vs.requestsCount++,Vs.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=QR,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Vs.requests[this._index],this._xhr=null}}_onLoad(){let t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",cm);else if(typeof addEventListener=="function"){let e="onpagehide"in Ft?"pagehide":"unload";addEventListener(e,cm,!1)}}function cm(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}var ek=function(){let e=mm({xdomain:!1});return e&&e.responseType!==null}(),jc=class extends ZR{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=ek&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Vo(mm,this.uri(),e)}};function mm(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||JR))return new XMLHttpRequest}catch{}if(!t)try{return new Ft[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var fm=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",tk=class extends $c{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=fm?{}:lm(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],o=t===e.length-1;Ws(r,this.supportsBinary,n=>{try{this.doWrite(r,n)}catch{}o&&Dn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=pm()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Uc=Ft.WebSocket||Ft.MozWebSocket,Bc=class extends tk{createSocket(e,t,r){return fm?new Uc(e,t,r):t?new Uc(e,t):new Uc(e)}doWrite(e,t){this.ws.send(t)}},dm=class extends $c{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=am(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),o=im();o.readable.pipeTo(e.writable),this._writer=o.writable.getWriter();let n=()=>{r.read().then(({done:i,value:a})=>{i||(this.onPacket(a),n())}).catch(i=>{})};n();let s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],o=t===e.length-1;this._writer.write(r).then(()=>{o&&Dn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}},rk={websocket:Bc,webtransport:dm,polling:jc},ok=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,nk=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Xs(e){if(e.length>8e3)throw"URI too long";let t=e,r=e.indexOf("["),o=e.indexOf("]");r!=-1&&o!=-1&&(e=e.substring(0,r)+e.substring(r,o).replace(/:/g,";")+e.substring(o,e.length));let n=ok.exec(e||""),s={},i=14;for(;i--;)s[nk[i]]=n[i]||"";return r!=-1&&o!=-1&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=sk(s,s.path),s.queryKey=ik(s,s.query),s}function sk(e,t){let r=/\/{2,9}/g,o=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&o.splice(0,1),t.slice(-1)=="/"&&o.splice(o.length-1,1),o}function ik(e,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(o,n,s){n&&(r[n]=s)}),r}var Dc=typeof addEventListener=="function"&&typeof removeEventListener=="function",zs=[];Dc&&addEventListener("offline",()=>{zs.forEach(e=>e())},!1);var qs=class Ks extends _e{constructor(t,r){if(super(),this.binaryType=BR,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){let o=Xs(t);r.hostname=o.host,r.secure=o.protocol==="https"||o.protocol==="wss",r.port=o.port,o.query&&(r.query=o.query)}else r.host&&(r.hostname=Xs(r.host).host);$n(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(o=>{let n=o.prototype.name;this.transports.push(n),this._transportsByName[n]=o}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=KR(this.opts.query)),Dc&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},zs.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){let r=Object.assign({},this.opts.query);r.EIO=Fc,r.transport=t,this.id&&(r.sid=this.id);let o=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](o)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let t=this.opts.rememberUpgrade&&Ks.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){this.readyState="open",Ks.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let r=0;r<this.writeBuffer.length;r++){let o=this.writeBuffer[r].data;if(o&&(t+=VR(o)),r>0&&t>this._maxPayload)return this.writeBuffer.slice(0,r);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Dn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,o){return this._sendPacket("message",t,r,o),this}send(t,r,o){return this._sendPacket("message",t,r,o),this}_sendPacket(t,r,o,n){if(typeof r=="function"&&(n=r,r=void 0),typeof o=="function"&&(n=o,o=null),this.readyState==="closing"||this.readyState==="closed")return;o=o||{},o.compress=o.compress!==!1;let s={type:t,data:r,options:o};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){let t=()=>{this._onClose("forced close"),this.transport.close()},r=()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},o=()=>{this.once("upgrade",r),this.once("upgradeError",r)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?o():t()}):this.upgrading?o():t()),this}_onError(t){if(Ks.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Dc&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let o=zs.indexOf(this._offlineEventListener);o!==-1&&zs.splice(o,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};qs.protocol=Fc;var ak=class extends qs{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),r=!1;qs.priorWebsocketSuccess=!1;let o=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",u=>{if(!r)if(u.type==="pong"&&u.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;qs.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let p=new Error("probe error");p.transport=t.name,this.emitReserved("upgradeError",p)}}))};function n(){r||(r=!0,l(),t.close(),t=null)}let s=u=>{let p=new Error("probe error: "+u);p.transport=t.name,n(),this.emitReserved("upgradeError",p)};function i(){s("transport closed")}function a(){s("socket closed")}function c(u){t&&u.name!==t.name&&n()}let l=()=>{t.removeListener("open",o),t.removeListener("error",s),t.removeListener("close",i),this.off("close",a),this.off("upgrading",c)};t.once("open",o),t.once("error",s),t.once("close",i),this.once("close",a),this.once("upgrading",c),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}},Hc=class extends ak{constructor(e,t={}){let r=typeof e=="object"?e:t;(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(o=>rk[o]).filter(o=>!!o)),super(e,r)}};var g1=Hc.protocol;var zc={};$s(zc,{Decoder:()=>gk,Encoder:()=>hk,PacketType:()=>se,protocol:()=>ym});var ck=typeof ArrayBuffer=="function",lk=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,gm=Object.prototype.toString,pk=typeof Blob=="function"||typeof Blob<"u"&&gm.call(Blob)==="[object BlobConstructor]",uk=typeof File=="function"||typeof File<"u"&&gm.call(File)==="[object FileConstructor]";function Vc(e){return ck&&(e instanceof ArrayBuffer||lk(e))||pk&&e instanceof Blob||uk&&e instanceof File}function Ys(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,o=e.length;r<o;r++)if(Ys(e[r]))return!0;return!1}if(Vc(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return Ys(e.toJSON(),!0);for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&Ys(e[r]))return!0;return!1}function mk(e){let t=[],r=e.data,o=e;return o.data=Wc(r,t),o.attachments=t.length,{packet:o,buffers:t}}function Wc(e,t){if(!e)return e;if(Vc(e)){let r={_placeholder:!0,num:t.length};return t.push(e),r}else if(Array.isArray(e)){let r=new Array(e.length);for(let o=0;o<e.length;o++)r[o]=Wc(e[o],t);return r}else if(typeof e=="object"&&!(e instanceof Date)){let r={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=Wc(e[o],t));return r}return e}function fk(e,t){return e.data=Gc(e.data,t),delete e.attachments,e}function Gc(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Gc(e[r],t);else if(typeof e=="object")for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Gc(e[r],t));return e}var dk=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],ym=5,se;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(se||(se={}));var hk=class{constructor(e){this.replacer=e}encode(e){return(e.type===se.EVENT||e.type===se.ACK)&&Ys(e)?this.encodeAsBinary({type:e.type===se.EVENT?se.BINARY_EVENT:se.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===se.BINARY_EVENT||e.type===se.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=mk(e),r=this.encodeAsString(t.packet),o=t.buffers;return o.unshift(r),o}};function hm(e){return Object.prototype.toString.call(e)==="[object Object]"}var gk=class xm extends _e{constructor(t){super(),this.reviver=t}add(t){let r;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");r=this.decodeString(t);let o=r.type===se.BINARY_EVENT;o||r.type===se.BINARY_ACK?(r.type=o?se.EVENT:se.ACK,this.reconstructor=new yk(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(Vc(t)||t.base64)if(this.reconstructor)r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,super.emitReserved("decoded",r));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let r=0,o={type:Number(t.charAt(0))};if(se[o.type]===void 0)throw new Error("unknown packet type "+o.type);if(o.type===se.BINARY_EVENT||o.type===se.BINARY_ACK){let s=r+1;for(;t.charAt(++r)!=="-"&&r!=t.length;);let i=t.substring(s,r);if(i!=Number(i)||t.charAt(r)!=="-")throw new Error("Illegal attachments");o.attachments=Number(i)}if(t.charAt(r+1)==="/"){let s=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););o.nsp=t.substring(s,r)}else o.nsp="/";let n=t.charAt(r+1);if(n!==""&&Number(n)==n){let s=r+1;for(;++r;){let i=t.charAt(r);if(i==null||Number(i)!=i){--r;break}if(r===t.length)break}o.id=Number(t.substring(s,r+1))}if(t.charAt(++r)){let s=this.tryParse(t.substr(r));if(xm.isPayloadValid(o.type,s))o.data=s;else throw new Error("invalid payload")}return o}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case se.CONNECT:return hm(r);case se.DISCONNECT:return r===void 0;case se.CONNECT_ERROR:return typeof r=="string"||hm(r);case se.EVENT:case se.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&dk.indexOf(r[0])===-1);case se.ACK:case se.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},yk=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=fk(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function xk(e,t="",r){let o=e;r=r||typeof location<"u"&&location,e==null&&(e=r.protocol+"//"+r.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=r.protocol+e:e=r.host+e),/^(https?|wss?):\/\//.test(e)||(typeof r<"u"?e=r.protocol+"//"+e:e="https://"+e),o=Xs(e)),o.port||(/^(http|ws)$/.test(o.protocol)?o.port="80":/^(http|ws)s$/.test(o.protocol)&&(o.port="443")),o.path=o.path||"/";let n=o.host.indexOf(":")!==-1?"["+o.host+"]":o.host;return o.id=o.protocol+"://"+n+":"+o.port+t,o.href=o.protocol+"://"+n+(r&&r.port===o.port?"":":"+o.port),o}function qt(e,t,r){return e.on(t,r),function(){e.off(t,r)}}var bk=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),bm=class extends _e{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[qt(e,"open",this.onopen.bind(this)),qt(e,"packet",this.onpacket.bind(this)),qt(e,"error",this.onerror.bind(this)),qt(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,o,n;if(bk.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let s={type:se.EVENT,data:t};if(s.options={},s.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let c=this.ids++,l=t.pop();this._registerAckCallback(c,l),s.id=c}let i=(o=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||o===void 0?void 0:o.writable,a=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!i||(a?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(e,t){var r;let o=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(o===void 0){this.acks[e]=t;return}let n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let i=0;i<this.sendBuffer.length;i++)this.sendBuffer[i].id===e&&this.sendBuffer.splice(i,1);t.call(this,new Error("operation has timed out"))},o),s=(...i)=>{this.io.clearTimeoutFn(n),t.apply(this,i)};s.withError=!0,this.acks[e]=s}emitWithAck(e,...t){return new Promise((r,o)=>{let n=(s,i)=>s?o(s):r(i);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((o,...n)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(o)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:se.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case se.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case se.EVENT:case se.BINARY_EVENT:this.onevent(e);break;case se.ACK:case se.BINARY_ACK:this.onack(e);break;case se.DISCONNECT:this.ondisconnect();break;case se.CONNECT_ERROR:this.destroy();let t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,r=!1;return function(...o){r||(r=!0,t.packet({type:se.ACK,id:e,data:o}))}}onack(e){let t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:se.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let r of t)r.apply(this,e.data)}}};function qo(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}qo.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+r:e-r}return Math.min(e,this.max)|0};qo.prototype.reset=function(){this.attempts=0};qo.prototype.setMin=function(e){this.ms=e};qo.prototype.setMax=function(e){this.max=e};qo.prototype.setJitter=function(e){this.jitter=e};var qc=class extends _e{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,$n(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((r=t.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new qo({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let o=t.parser||zc;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Hc(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let o=qt(t,"open",function(){r.onopen(),e&&e()}),n=i=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",i),e?e(i):this.maybeReconnectOnOpen()},s=qt(t,"error",n);if(this._timeout!==!1){let i=this._timeout,a=this.setTimeoutFn(()=>{o(),n(new Error("timeout")),t.close()},i);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}return this.subs.push(o),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(qt(e,"ping",this.onping.bind(this)),qt(e,"data",this.ondata.bind(this)),qt(e,"error",this.onerror.bind(this)),qt(e,"close",this.onclose.bind(this)),qt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){Dn(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new bm(this,e,t),this.nsps[e]=r),r}_destroy(e){let t=Object.keys(this.nsps);for(let r of t)if(this.nsps[r].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(o=>{o?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",o)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}},jn={};function zo(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};let r=xk(e,t.path||"/socket.io"),o=r.source,n=r.id,s=r.path,i=jn[n]&&s in jn[n].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||i,c;return a?c=new qc(o,t):(jn[n]||(jn[n]=new qc(o,t)),c=jn[n]),r.query&&!t.query&&(t.query=r.queryKey),c.socket(r.path,t)}Object.assign(zo,{Manager:qc,Socket:bm,io:zo,connect:zo});function it(e){return e.val}function gt(e){return e.err}var Em=" must not return ",Ek="`transformer`",wk="`recoverer`",Rk="`defaultValue`",Ko=Ek+Em,dr="called with ",Xo=Rk+" must not be ",Yo=wk+Em;var kk="`Ok`",wm="`Err`",Rm=dr+wm,km=dr+kk,vk="Carrying `E` in "+wm+" instead of throwing it directly. See `.cause`",Kc="an instance of `Error` of the current realm.",nM="The thrown value is not "+Kc,sM="The contained E should be "+Kc,_k="This `.cause` is not "+Kc;function Ae(e){return e.ok}function te(e){return{ok:!0,val:e,err:null}}function G(e){return!e.ok}function fe(e){return{ok:!1,val:null,err:e}}function X(e){return vm(e,Rm)}function Jo(e){return _m(e,km)}function vm(e,t){if(G(e))throw new TypeError(t);return e.val}function _m(e,t){if(Ae(e))throw new TypeError(t);return e.err}async function Xc(e,t){if(G(e))return e;let r=it(e);return await t(r)}function ao(e,t){if(G(e))return e;let r=it(e),o=t(r);return te(o)}async function Re(e,t){if(G(e))return e;let r=it(e),o=await t(r);return te(o)}async function ve(e,t){if(Ae(e))return e;let r=gt(e),o=await t(r);return fe(o)}async function Js(e,t){if(Ae(e))return e;let r=gt(e);return await t(r)}var Qs="`null`",uI=Ko+Qs,Sk=dr+Qs,mI=Xo+Qs,fI=Yo+Qs;var Zs="`undefined`",xI=Ko+Zs,Ok=dr+Zs,bI=Xo+Zs,EI=Yo+Zs;var ke=e=>e.ok?te(e):fe({name:"HTTPError",message:`${e.status} ${e.statusText}`,response:e});var Pm=async(e,t)=>{let r=new Request(e,t);try{return te(await globalThis.fetch(r))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return fe({name:"AbortError",message:o.message,request:r});if(o instanceof TypeError)return fe({name:"NetworkError",message:o.message,request:r});throw o}};var le=e=>{let{fetch:t=Pm,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var Sm=e=>{let{sid:t,hostName:r}=le(e??{});return new Request(`https://${r}/api/users/me`,t?{headers:{Cookie:de(t)}}:void 0)},Om=e=>Re(ke(e),async t=>await t.json()),ei=(()=>{let e=async t=>{let{fetch:r,...o}=le(t??{}),n=await r(Sm(o));return G(n)?n:Om(X(n))};return e.toRequest=Sm,e.fromResponse=Om,e})();var de=e=>`connect.sid=${e}`,or=async e=>{let t=e?.csrf??globalThis._csrf;return t?te(t):ao(await ei(e),r=>r.csrfToken)};var Ve=(e,t)=>{if(e?.connected)return Promise.resolve(te(e));e??=zo("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"],...t?{rejectUnauthorized:!1,extraHeaders:{Cookie:de(t),Host:"scrapbox.io",Referer:"https://scrapbox.io/"}}:{}});let r=new Promise(o=>{let n=s=>o(fe(s));e.once("connect",()=>{e.off("disconnect",n),o(te(e))}),e.once("disconnect",n)});return e.connect(),r},rt=e=>{if(e.disconnected)return Promise.resolve(te(void 0));let t=new Promise(r=>{let o=n=>{if(n!=="io client disconnect"){r(fe(n));return}r(te(void 0)),e.off("disconnect",o)};e.on("disconnect",o)});return e.disconnect(),t};var Lm=e=>Nk.includes(e.name),Nk=["SocketIOError","DuplicateTitleError","NotFastForwardError"];var Nm=(e,t,r,o)=>{if(t==="cursor")return e.emit(t,r),Promise.resolve(te(void 0));let{resolve:n,promise:s,reject:i}=Promise.withResolvers(),a=()=>{e.off("disconnect",c),clearTimeout(u)},c=f=>{if(f==="io client disconnect"){a(),i(new Error("io client disconnect"));return}if(f==="io server disconnect"){a(),n(fe({name:"SocketIOError"}));return}};e.on("disconnect",c);let l=o?.timeout??9e4,u=setTimeout(()=>{a(),n(fe({name:"TimeoutError",message:`exceeded ${l} (ms)`}))},l),p=t==="commit"?{method:"commit",data:r}:{method:"room:join",data:r};return e.emit("socket.io-request",p,f=>{if(a(),"error"in f){n(fe(Lm(f.error)?f.error:{name:"UnexpectedRequestError",...f}));return}n(te(f.data))}),s};function ti(e,t={}){if(e===null)return"null";if(Array.isArray(e))return Ck(e,t);switch(typeof e){case"string":return JSON.stringify(e);case"bigint":return`${e}n`;case"object":return e.constructor?.name!=="Object"?e.constructor?.name:Ak(e,t);case"function":return e.name||"(anonymous)"}return e?.toString()??"undefined"}function Ck(e,t){let{threshold:r=20}=t,o=e.map(i=>ti(i,t)),n=o.join(", ");if(n.length<=r)return`[${n}]`;let s=o.join(`,
`);return`[
${Cm(2,s)}
]`}function Ak(e,t){let{threshold:r=20}=t,o=[...Object.keys(e),...Object.getOwnPropertySymbols(e)].map(i=>`${i.toString()}: ${ti(e[i],t)}`),n=o.join(", ");if(n.length<=r)return`{${n}}`;let s=o.join(`,
`);return`{
${Cm(2,s)}
}`}function Cm(e,t){let r=" ".repeat(e);return t.split(`
`).map(o=>`${r}${o}`).join(`
`)}function ze(e,t,...r){let o;return Object.defineProperties(e,{name:{get:()=>o||(o=`${t}(${r.map(n=>ti(n)).join(", ")})`,o)}})}function hr(e){return Array.isArray(e)}function Yc(e){return ze(t=>hr(t)&&t.every(r=>e(r)),"isArrayOf",e)}function ri(e){let t=new Set(e);return ze(r=>t.has(r),"isLiteralOneOf",e)}function Bn(e){return e!=null&&!Array.isArray(e)&&typeof e=="object"}function De(e){return typeof e=="string"}var Ie=async(e,t)=>{let r=e.response.clone(),o=ri(t);try{let n=await r.json();if(!Bn(n))return;if(r.status===422){if(!De(n.message))return;for(let s of["NoQueryError","InvalidURLError"])if(t.includes(s))return{name:s,message:n.message}}return!o(n.name)||!De(n.message)?void 0:n.name==="NotLoggedInError"?!Bn(n.detals)||!De(n.detals.project)||!Yc(Mk)(n.detals.loginStrategies)?void 0:{name:n.name,message:n.message,details:{project:n.detals.project,loginStrategies:n.detals.loginStrategies}}:{name:n.name,message:n.message}}catch(n){if(n instanceof SyntaxError)return;throw n}},Mk=ri(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var ne=e=>e.replaceAll(" ","_").toLowerCase();var me=e=>[...e].map((t,r)=>t===" "?"_":!Ik.includes(t)||r===e.length-1&&Fk.includes(t)?encodeURIComponent(t):t).join(""),Ik='@$&+=:;",',Fk=':;",';var oi="`null` or `undefined`",Qo=Ko+oi,Uk=dr+oi,ni=Xo+oi,si=Yo+oi;function Ut(e){return e!=null}function nr(e){return e==null}function Kt(e,t){if(Ut(e))return e;throw new TypeError(t)}function ii(e){return nr(e)?fe(void 0):te(e)}function Jc(e,t){return Ut(e)?e:Kt(t,ni)}var Am=(e,t,r)=>{let{sid:o,hostName:n,followRename:s,projects:i}=le(r??{}),a=new URLSearchParams([["followRename",`${s??!0}`],...i?.map?.(c=>["projects",c])??[]]);return new Request(`https://${n}/api/pages/${e}/${me(t)}?${a}`,o?{headers:{Cookie:de(o)}}:void 0)},Mm=async e=>ve(await Re(ke(e),t=>t.json()),async t=>t.response.status===414?{name:"TooLongURIError",message:"project ids may be too much."}:Jc(await Ie(t,["NotFoundError","NotLoggedInError","NotMemberError"]),t)),Dt=(()=>{let e=async(t,r,o)=>Xc(await le(o??{}).fetch(Am(t,r,o)),n=>Mm(n));return e.toRequest=Am,e.fromResponse=Mm,e})();var Im=(e,t)=>{let{sid:r,hostName:o}=le(t??{});return new Request(`https://${o}/api/projects/${e}`,r?{headers:{Cookie:de(r)}}:void 0)},Fm=async e=>Re(await ve(ke(e),async t=>await Ie(t,["NotFoundError","NotLoggedInError","NotMemberError"])??t),t=>t.json()),gr=(()=>{let e=async(t,r)=>{let{fetch:o}=le(r??{}),n=Im(t,r),s=await o(n);return G(s)?s:Fm(X(s))};return e.toRequest=Im,e.fromResponse=Fm,e})(),Um=(e,t)=>{let{sid:r,hostName:o}=le(t??{}),n=new URLSearchParams(e.map(s=>["ids",s]));return new Request(`https://${o}/api/projects?${n}`,r?{headers:{Cookie:de(r)}}:void 0)},Dm=async e=>Re(await ve(ke(e),async t=>await Ie(t,["NotLoggedInError"])??t),t=>t.json()),ai=(()=>{let e=async(t,r)=>{let{fetch:o}=le(r??{}),n=await o(Um(t,r));return G(n)?n:Dm(X(n))};return e.toRequest=Um,e.fromResponse=Dm,e})();var Zc=async(e,t,r)=>{let[o,n,s]=await Promise.all([Dt(e,t,r),Dk(r),$k(e,r)]);return G(o)?o:G(n)?n:G(s)?s:te({...X(o),projectId:X(s),userId:X(n)})},Qc,Dk=async e=>{if(Qc)return te(Qc);let t=await ei(e);if(G(t))return t;let r=X(t);return"id"in r?(Qc=r.id,te(r.id)):fe({name:"NotLoggedInError",message:"This script cannot be used without login"})},$m=new Map,$k=async(e,t)=>{let r=$m.get(e);return r?te(r):ao(await gr(e,t),({id:o})=>($m.set(e,o),o))};function Te(e,t={}){let{signal:r,persistent:o=!0}=t;return r?.aborted?Promise.reject(r.reason):new Promise((n,s)=>{let i=()=>{clearTimeout(c),s(r?.reason)},c=setTimeout(()=>{r?.removeEventListener("abort",i),n()},e);if(r?.addEventListener("abort",i,{once:!0}),o===!1)try{Deno.unrefTimer(c)}catch(l){if(!(l instanceof ReferenceError))throw l;console.error("`persistent` option is only available in Deno")}})}var co=async(e,t,r,o)=>{let n=await Ve(o?.socket,o?.sid);if(G(n))return fe({name:"UnexpectedRequestError",error:Jo(n)});let s=X(n),i=await Zc(e,t,o);if(G(i))return i;let a=X(i);try{let c=0,l=[],u;for(;o?.maxAttempts===void 0||c<o.maxAttempts;){let p=r(a,c,l,u);if(l=p instanceof Promise?await p:p,c++,l.length===0)return te(a.commitId);let f={kind:"page",projectId:a.projectId,pageId:a.id,parentId:a.commitId,userId:a.userId,changes:l,cursor:null,freeze:!0};for(;;){let m=await Nm(s,"commit",f);if(Ae(m))return a.commitId=X(m).commitId,te(a.commitId);let h=Jo(m),g=h.name;if(g==="SocketIOServerDisconnectError"||g==="UnexpectedRequestError")return fe(h);if(g==="TimeoutError"||g==="SocketIOError"){await Te(3e3);continue}if(g==="NotFastForwardError"){await Te(1e3);let y=await Zc(e,t,o);if(G(y))return y;a=X(y)}u=g;break}}return fe({name:"RetryError",attempts:c,message:`Retrying exceeded the maxAttempts (${c}).`})}finally{o?.socket||await rt(s)}};var el=(e,t)=>{let r=e.length>t.length,o=r?t:e,n=r?e:t,s=o.length+1,i=o.length+n.length+3,a=new Array(i);a.fill(-1);let c=[];function l(g,y,x){let E=Math.max(y,x),k=E-g;for(;k<o.length&&E<n.length&&o[k]===n[E];)++k,++E;return a[g+s]=c.length,c.push([{x:k,y:E},a[g+(y>x?-1:1)+s]]),E}let u=new Array(i);u.fill(-1);let p=-1,f=n.length-o.length;do{++p;for(let g=-p;g<=f-1;++g)u[g+s]=l(g,u[g-1+s]+1,u[g+1+s]);for(let g=f+p;g>=f+1;--g)u[g+s]=l(g,u[g-1+s]+1,u[g+1+s]);u[f+s]=l(f,u[f-1+s]+1,u[f+1+s])}while(u[f+s]!==n.length);let m=[],h=a[f+s];for(;h!==-1;)m.push(c[h][0]),h=c[h][1];return{from:e,to:t,editDistance:f+p*2,buildSES:function*(){let g=0,y=0;for(let{x,y:E}of jk(m))for(;g<x||y<E;)E-x>y-g?(yield{value:n[y],type:r?"deleted":"added"},++y):E-x<y-g?(yield{value:o[g],type:r?"added":"deleted"},++g):(yield{value:o[g],type:"common"},++g,++y)}}};function*tl(e){let t=[],r=[];function*o(){if(t.length>r.length){for(let n=0;n<r.length;n++)yield jm(t[n],r[n]);for(let n=r.length;n<t.length;n++)yield t[n]}else{for(let n=0;n<t.length;n++)yield jm(t[n],r[n]);for(let n=t.length;n<r.length;n++)yield r[n]}t=[],r=[]}for(let n of e)switch(n.type){case"added":t.push(n);break;case"deleted":r.push(n);break;case"common":yield*o(),yield n;break}yield*o()}var jm=(e,t)=>({value:e.value,oldValue:t.value,type:"replaced"});function*jk(e){for(let t=e.length-1;t>=0;t--)yield e[t]}var Bm=e=>e.padStart(8,"0"),rl=e=>{let t=Math.floor(new Date().getTime()/1e3).toString(16),r=Math.floor(16777214*Math.random()).toString(16);return`${Bm(t).slice(-8)}${e.slice(-6)}0000${Bm(r)}`};function*ol(e,t,{userId:r}){let{buildSES:o}=el(e.map(({text:i})=>i),t),n=0,s=e[0].id;for(let i of tl(o())){switch(i.type){case"added":yield{_insert:s,lines:{id:rl(r),text:i.value}};continue;case"deleted":yield{_delete:s,lines:-1};break;case"replaced":yield{_update:s,lines:{text:i.value}};break}n++,s=e[n]?.id??"_end"}}var Bk=(e,t)=>(e.type==="codeBlock"||e.type==="table")&&t.indent>(e.rows[0]?.indent??0),Hm=(e,t)=>{let r=e[e.length-1];return r!==void 0&&Bk(r,t)?(r.rows.push(t),e):(e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e)},Wm=(e,t)=>{if(t.hasTitle??!0){let[r,...o]=e;return r===void 0?[]:[{type:"title",rows:[r]},...o.reduce(Hm,[])]}return e.reduce(Hm,[])};var Gm=e=>e.split(`
`).map(t=>({indent:/^\s+/.exec(t)?.[0]?.length??0,text:t}));var Vm=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*code:/,"");return{indent:o,type:"codeBlock",fileName:s,content:r.map(i=>i.text.substring(o+1)).join(`
`)}};var ie=(e,{parseOnNested:t,parseOnQuoted:r,patterns:o})=>(n,s,i)=>{if(!t&&s.nested)return i?.()??[];if(!r&&s.quoted)return i?.()??[];for(let a of o){let c=a.exec(n);if(c===null)continue;let l=n.substring(0,c.index),u=n.substring(c.index+(c[0]?.length??0)),p=e(c[0]??"",s);return[...yt(l,s),...p,...yt(u,s)]}return i?.()??[]};var ue=e=>[{type:"plain",raw:e,text:e}],zm=ie(ue,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]});var Hk=/\[\s+\]/,Wk=(e,t)=>t.context==="table"?ue(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],qm=ie(Wk,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Hk]});var Gk=/`.*?`/,Vk=(e,t)=>t.context==="table"?ue(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],Km=ie(Vk,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Gk]});var zk=/^[$%] .+$/,qk=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e[0]??"",o=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:o}]},Xm=ie(qk,{parseOnNested:!1,parseOnQuoted:!1,patterns:[zk]});var Kk=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,Xk=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.indexOf(" "),o=e.substring(1,r),n=e.substring(r+1,e.length-1),s=new Set(o);if(s.has("*")){let i=o.split("*").length-1;s.delete("*"),s.add(`*-${Math.min(i,10)}`)}return[{type:"decoration",raw:e,rawDecos:o,decos:Array.from(s),nodes:yt(n,{...t,nested:!0})}]},Ym=ie(Xk,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Kk]});var Yk=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,Jk=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,Qk=/\[https?:\/\/[^\s\]]+\]/,Zk=/https?:\/\/[^\s]+/,ev=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.startsWith("[")&&e.endsWith("]")?e.substring(1,e.length-1):e,o=/^https?:\/\/[^\s\]]/.test(r),n=(o?/^https?:\/\/[^\s\]]+/:/https?:\/\/[^\s\]]+$/).exec(r);if(n?.[0]===void 0)return[];let s=o?r.substring(n[0].length):r.substring(0,n.index-1);return[{type:"link",raw:e,pathType:"absolute",href:n[0],content:s.trim()}]},Jm=ie(ev,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Yk,Jk,Qk,Zk]});var tv=/\[\$ .+? \]/,rv=/\[\$ [^\]]+\]/,ov=(e,t)=>t.context==="table"?ue(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],Qm=ie(ov,{parseOnNested:!1,parseOnQuoted:!0,patterns:[tv,rv]});var Zm=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,ef=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,nv=e=>{let[t="",r="",o=""]=e.split(","),n=Number.parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),s=Number.parseFloat(r.replace(/^E/,"").replace(/^W/,"-")),i=/^Z\d+$/.test(o)?Number.parseInt(o.replace(/^Z/,""),10):14;return{latitude:n,longitude:s,zoom:i}},sv=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.match(Zm)??e.match(ef);if(r===null)return[];let o=e.startsWith("[N")||e.startsWith("[S"),[,n="",s=""]=o?r:[r[0],r[2],r[1]],{latitude:i,longitude:a,zoom:c}=nv(n),l=s!==""?`https://www.google.com/maps/place/${encodeURIComponent(s)}/@${i},${a},${c}z`:`https://www.google.com/maps/@${i},${a},${c}z`;return[{type:"googleMap",raw:e,latitude:i,longitude:a,zoom:c,place:s,url:l}]},tf=ie(sv,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Zm,ef]});var iv=/(?:^|\s)#\S+/,av=(e,t)=>{if(t.context==="table")return ue(e,t);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),o=e.substring(1);return[...ue(r,t),{type:"hashTag",raw:o,href:o.substring(1)}]},rf=ie(av,{parseOnNested:!0,parseOnQuoted:!0,patterns:[iv]});var cv=/^\? .+$/,lv=(e,t)=>t.context==="table"?ue(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],of=ie(lv,{parseOnNested:!1,parseOnQuoted:!1,patterns:[cv]});var pv=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/,uv=e=>{let t=e.substring(1,e.length-1),r=t.lastIndexOf(".icon"),o=t.substring(0,r),n=o.startsWith("/")?"root":"relative",s=t.substring(r+5,t.length),i=s.startsWith("*")?Number.parseInt(s.substring(1),10):1;return new Array(i).fill({}).map(()=>({path:o,pathType:n,type:"icon",raw:e}))},nf=ie(uv,{parseOnNested:!0,parseOnQuoted:!0,patterns:[pv]});var mv=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,fv=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?\]/i,dv=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,hv=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,gv=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg|webp)(\?[^\]\s]+)?$/i.test(e)||yv(e),yv=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),xv=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.search(/\s/),o=r!==-1?e.substring(1,r):e.substring(1,e.length-1),n=r!==-1?e.substring(r,e.length-1).replace(/^\s+/,""):"",[s,i]=gv(n)?[n,o]:[o,n];return[{type:"image",raw:e,src:/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(s)?`${s}/thumb/1000`:s,link:i}]},sf=ie(xv,{parseOnNested:!0,parseOnQuoted:!0,patterns:[mv,fv,dv,hv]});var bv=/\[\/?[^[\]]+\]/,Ev=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},af=ie(Ev,{parseOnNested:!0,parseOnQuoted:!0,patterns:[bv]});var wv=/^[0-9]+\. .*$/,Rv=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.indexOf(" "),o=e.substring(0,r-1),n=Number.parseInt(o,10),s=e.substring(r+1,e.length);return[{type:"numberList",raw:e,rawNumber:o,number:n,nodes:yt(s,{...t,nested:!1})}]},cf=ie(Rv,{parseOnNested:!1,parseOnQuoted:!1,patterns:[wv]});var kv=/^>.*$/,vv=(e,t)=>t.context==="table"?ue(e,t):[{type:"quote",raw:e,nodes:yt(e.substring(1),{...t,quoted:!0})}],lf=ie(vv,{parseOnNested:!1,parseOnQuoted:!1,patterns:[kv]});var _v=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,Tv=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.substring(2,e.length-2),o=r.lastIndexOf(".icon"),n=r.substring(0,o),s=n.startsWith("/")?"root":"relative",i=r.substring(o+5,r.length),a=i.startsWith("*")?Number.parseInt(i.substring(1),10):1;return new Array(a).fill({}).map(()=>({path:n,pathType:s,type:"strongIcon",raw:e}))},pf=ie(Tv,{parseOnNested:!1,parseOnQuoted:!0,patterns:[_v]});var Pv=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)\]\]/i,Sv=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,Ov=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.substring(2,e.length-2),o=/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(r);return[{type:"strongImage",raw:e,src:o?`${r}/thumb/1000`:r}]},uf=ie(Ov,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Pv,Sv]});var Lv=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,Nv=(e,t)=>t.context==="table"?ue(e,t):[{type:"strong",raw:e,nodes:yt(e.substring(2,e.length-2),{...t,nested:!0})}],mf=ie(Nv,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Lv]});var Cv=(e,t,r)=>e===""?[]:r?.()??[],Av=(...e)=>(t,r)=>e.reduceRight((o,n)=>()=>n(t,r,o),()=>zm(t,r))(),yt=Av(Cv,lf,of,cf,Km,Xm,Qm,qm,Ym,uf,pf,mf,sf,Jm,nf,tf,af,rf);var ff=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:yt(r.substring(t),{nested:!1,quoted:!1,context:"line"})}};var df=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*table:/,"");return{indent:o,type:"table",fileName:s,cells:r.map(i=>i.text.substring(o+1)).map(i=>i.split(" ").map(a=>yt(a,{nested:!1,quoted:!1,context:"table"})))}};var hf=e=>({type:"title",text:e.rows[0].text});var gf=e=>{switch(e.type){case"title":return hf(e);case"codeBlock":return Vm(e);case"table":return df(e);case"line":return ff(e)}};var Be=(e,t)=>{let r=Gm(e);return Wm(r,{hasTitle:t?.hasTitle??!0}).map(gf)},yf=e=>/^\s*\S.*$/m.exec(e)?.[0]?.trim()??"Untitled";var Mv=/https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/,Iv=/https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/,Fv=/https?:\/\/(?:www\.|)youtube\.com\/shorts\/([a-zA-Z\d_-]+)(?:\?([^\s]+)|)/,Uv=/https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/,ci=e=>{if(Mv.test(e)){let t=new URL(e).searchParams,r=t.get("v");if(r)return{pathType:"com",videoId:r,params:t}}{let t=e.match(Iv);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"dotbe"}}}{let t=e.match(Fv);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"short"}}}{let t=e.match(Uv);if(t){let[,r,o]=t;return{listId:o,params:new URLSearchParams(r),pathType:"list"}}}};var Ef=e=>{let t=Be(e,{hasTitle:!0}),r="",o=new Map,n=[],s=new Set,i=[],a=new Set,c=[],l=null,u=[],p=new Set,f=new Set,m=new RegExp(`${globalThis.location?.origin??"https://scrapbox.io"}/files/([a-z0-9]{24})(?:|\\.[a-zA-Z0-9]+)(?:|\\?[^\\s]*)$`),h=x=>{switch(x.type){case"hashTag":if(o.has(ne(x.href)))return;o.set(ne(x.href),!1),n.push(x.href);return;case"link":switch(x.pathType){case"relative":{let E=bf(x.href);if(o.get(ne(E)))return;o.set(ne(E),!0),n.push(E);return}case"root":{let E=bf(x.href);if(/^\/[\w\d-]+\/?$/.test(E)||s.has(ne(E)))return;s.add(ne(E)),i.push(E);return}case"absolute":{if(x.content)return;let E=ci(x.href);if(E&&E.pathType!=="list"){l??=`https://i.ytimg.com/vi/${E.videoId}/mqdefault.jpg`;return}let k=x.href.match(m)?.[1];k&&p.add(k);return}default:return}case"icon":case"strongIcon":{if(x.pathType==="root"||a.has(ne(x.path)))return;a.add(ne(x.path)),c.push(x.path);return}case"image":case"strongImage":{l??=x.src.endsWith("/thumb/1000")?x.src.replace(/\/thumb\/1000$/,"/raw"):x.src;{let E=x.src.match(m)?.[1];E&&p.add(E)}if(x.type==="image"){let E=x.link.match(m)?.[1];E&&p.add(E)}return}case"helpfeel":f.add(x.text);return;case"numberList":case"strong":case"quote":case"decoration":{for(let E of x.nodes)h(E);return}default:return}},g=[];for(let x of t)switch(x.type){case"title":{r=x.text;continue}case"line":u.length<5&&x.nodes.length>0&&u.push(x.nodes[0].type==="helpfeel"||x.nodes[0].type==="commandLine"?xf(x.nodes[0].raw):x.nodes.map(E=>E.raw).join("").trim().slice(0,200));for(let E of x.nodes)h(E);continue;case"codeBlock":u.length<5&&u.push(xf(x.content));continue;case"table":{for(let E of x.cells)for(let k of E)for(let b of k)h(b);if(!["infobox","cosense"].includes(x.fileName))continue;g.push(...x.cells.map(E=>E.map(k=>k.map(b=>b.raw).join("")).join(" ").trim()));continue}}let y=e.split(`
`);return[r,n,i,c,l,u,[...p],[...f],g,y.length,y.reduce((x,E)=>x+[...E].length,0)]},xf=e=>`\`${e.trim().replaceAll("`","\\`").slice(0,198)}\``,bf=e=>e.replace(/#[a-f\d]{24,32}$/,""),wf=e=>e.flatMap(({text:t})=>/^\s*\? .*$/.test(t)?[t.trimStart().slice(2)]:[]);var Mr=(e,t)=>e.length===t.length&&e.every(r=>t.includes(r));function*Rf(e,t,r){let o=t.flatMap(g=>(De(g)?g:g.text).split(`
`));for(let g of ol(e.lines,o,{userId:r}))yield g;let[n,s,i,a,c,l,u,p,f,m,h]=Ef(o.join(`
`));(e.title!==n||!e.persistent)&&(yield{title:n}),Mr(e.links,s)||(yield{links:s}),Mr(e.projectLinks,i)||(yield{projectLinks:i}),Mr(e.icons,a)||(yield{icons:a}),e.image!==c&&(yield{image:c}),Mr(e.descriptions,l)||(yield{descriptions:l}),Mr(e.files,u)||(yield{files:u}),Mr(wf(e.lines),p)||(yield{helpfeels:p}),Mr(e.infoboxDefinition,f)||(yield{infoboxDefinition:f}),yield{linesCount:m},yield{charsCount:h}}var kf=e=>{let t=e.match(/(.+?)(?:_(\d+))?$/),r=t?.[1]??e,o=t?.[2]?parseInt(t[2])+1:2;return`${r}_${o}`};var vf=()=>Number.MAX_SAFE_INTEGER-Math.floor(Date.now()/1e3);var xe=(e,t,r,o)=>co(e,t,async(n,s,i,a)=>{if(a==="DuplicateTitleError"){let m=kf(t);return i.map(h=>("title"in h&&(h.title=m),h))}let c=r(n.lines,{...n,attempts:s}),l=c instanceof Promise?await c:c;if(l===void 0)return[];let[u,p]=Array.isArray(l)?[l,void 0]:[l.lines,l.pin];if(u.length===0)return[{deleted:!0}];let f=n.lines===u?[]:[...Rf(n,u,n.userId)];return p!==void 0&&(p&&n.pin===0||!p&&n.pin>0)&&f.push({pin:p?vf():0}),f},o);var _f=(e,t,r)=>co(e,t,o=>o.persistent?[{deleted:!0}]:[],r);var li=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i}=le(o??{}),a=await or(o);if(G(a))return a;let c=new Request(`https://${s}/api/pages/${e}/replace/links`,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":X(a),...n?{Cookie:de(n)}:{}},body:JSON.stringify({from:t,to:r})}),l=await i(c);return G(l)?l:Re(await ve(ke(X(l)),async u=>await Ie(u,["NotFoundError","NotLoggedInError","NotMemberError"])??u),async u=>{let{message:p}=await u.json();return parseInt(p.match(/\d+/)?.[0]??"0")})};var Tf=(e,t)=>{let{sid:r,hostName:o,followingId:n}=le(t??{});return new Request(`https://${o}/api/pages/${e}/search/titles${n?`?followingId=${n}`:""}`,r?{headers:{Cookie:de(r)}}:void 0)},Pf=async e=>Re(await ve(ke(e),async t=>t.response.status===422?{name:"InvalidFollowingIdError",message:await t.response.text()}:await Ie(t,["NotFoundError","NotLoggedInError"])??t),t=>t.json().then(r=>({pages:r,followingId:t.headers.get("X-following-id")??""}))),jv=(()=>{let e=async(t,r)=>{let o=await le(r??{}).fetch(Tf(t,r));return G(o)?o:Pf(X(o))};return e.toRequest=Tf,e.fromResponse=Pf,e})();async function*Sf(e,t){let r;do{let o=await jv(e,{followingId:r,...t});if(G(o)){yield o;return}let n=X(o);yield te(n.pages),r=n.followingId}while(r)}var Of=async(e,t,r)=>{let{sid:o,hostName:n,fetch:s}=le(r??{}),i=new Request(`https://${n}/api/pages/${t}/search/query?q=${encodeURIComponent(e)}`,o?{headers:{Cookie:de(o)}}:void 0),a=await s(i);return G(a)?a:Re(await ve(ke(X(a)),async c=>await Ie(c,["NotFoundError","NotLoggedInError","NotMemberError","NoQueryError"])??c),c=>c.json())};var Lf=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=le(t??{}),s=await or(t);if(G(s))return s;let i=new Request(`https://${o}/api/embed-text/url?url=${encodeURIComponent(`${e}`)}`,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":X(s),...r?{Cookie:de(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return G(a)?a:Re(await ve(ke(X(a)),async c=>await Ie(c,["SessionError","BadRequestError","InvalidURLError"])??c),async c=>{let{title:l}=await c.json();return l})};var Nf=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=le(t??{}),s=await or(t);if(G(s))return s;let i=new Request(`https://${o}/api/embed-text/twitter?url=${encodeURIComponent(`${e}`)}`,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":X(s),...r?{Cookie:de(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return G(a)?a:ve(await Re(ke(X(a)),c=>c.json()),async c=>c.response.status===422?{name:"InvalidURLError",message:(await c.response.json()).message}:await Ie(c,["SessionError","BadRequestError"])??c)};var Cf=async e=>{let{fetch:t,sid:r,hostName:o,gyazoTeamsName:n}=le(e??{}),s=new Request(`https://${o}/api/login/gyazo/oauth-upload/token${n?`?gyazoTeamsName=${n}`:""}`,r?{headers:{Cookie:de(r)}}:void 0),i=await t(s);return G(i)?i:Re(await ve(ke(X(i)),async a=>await Ie(a,["NotLoggedInError"])??a),a=>a.json().then(c=>c.token))};var Af=(e,t,r,o)=>{let{sid:n,hostName:s}=le(o??{});return new Request(`https://${s}/api/code/${e}/${me(t)}/${me(r)}`,n?{headers:{Cookie:de(n)}}:void 0)},Mf=async e=>Re(await ve(ke(e),async t=>t.response.status===404&&t.response.headers.get("Content-Type")?.includes?.("text/plain")?{name:"NotFoundError",message:"Code block is not found"}:await Ie(t,["NotLoggedInError","NotMemberError"])??t),t=>t.text()),pi=(()=>{let e=async(t,r,o,n)=>{let s=Af(t,r,o,n),i=await le(n??{}).fetch(s);return G(i)?i:Mf(X(i))};return e.toRequest=Af,e.fromResponse=Mf,e})();var Uf=e=>{let t=typeof e=="string"?new TextEncoder().encode(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),r=[1732584193,4023233417,2562383102,271733878],o=new Uint8Array(nl),n=0,s=0,i=0;[r,o,n,s,i]=Ff(r,o,n,s,i,t);let a=nl-n;a<9&&(a+=nl);let c=new Uint8Array(a);c[0]=128,[s,i]=[s<<3,i<<3|s>>>29],c[c.length-8]=s&255,c[c.length-7]=s>>>8&255,c[c.length-6]=s>>>16&255,c[c.length-5]=s>>>24&255,c[c.length-4]=i&255,c[c.length-3]=i>>>8&255,c[c.length-2]=i>>>16&255,c[c.length-1]=i>>>24&255,[r,o,n,s,i]=Ff(r,o,n,s,i,new Uint8Array(c.buffer));let l=new ArrayBuffer(16),u=new DataView(l);return u.setUint32(0,r[0],!0),u.setUint32(4,r[1],!0),u.setUint32(8,r[2],!0),u.setUint32(12,r[3],!0),l},nl=64,j=(e,t)=>e<<t|e>>>32-t,lt=(e,t)=>e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,If=(e,t)=>{let[r,o,n,s]=e,i=lt(t,0),a=lt(t,4),c=lt(t,8),l=lt(t,12),u=lt(t,16),p=lt(t,20),f=lt(t,24),m=lt(t,28),h=lt(t,32),g=lt(t,36),y=lt(t,40),x=lt(t,44),E=lt(t,48),k=lt(t,52),b=lt(t,56),v=lt(t,60);return r=o+j(((n^s)&o^s)+r+i+3614090360,7),s=r+j(((o^n)&r^n)+s+a+3905402710,12),n=s+j(((r^o)&s^o)+n+c+606105819,17),o=n+j(((s^r)&n^r)+o+l+3250441966,22),r=o+j(((n^s)&o^s)+r+u+4118548399,7),s=r+j(((o^n)&r^n)+s+p+1200080426,12),n=s+j(((r^o)&s^o)+n+f+2821735955,17),o=n+j(((s^r)&n^r)+o+m+4249261313,22),r=o+j(((n^s)&o^s)+r+h+1770035416,7),s=r+j(((o^n)&r^n)+s+g+2336552879,12),n=s+j(((r^o)&s^o)+n+y+4294925233,17),o=n+j(((s^r)&n^r)+o+x+2304563134,22),r=o+j(((n^s)&o^s)+r+E+1804603682,7),s=r+j(((o^n)&r^n)+s+k+4254626195,12),n=s+j(((r^o)&s^o)+n+b+2792965006,17),o=n+j(((s^r)&n^r)+o+v+1236535329,22),r=o+j(((o^n)&s^n)+r+a+4129170786,5),s=r+j(((r^o)&n^o)+s+f+3225465664,9),n=s+j(((s^r)&o^r)+n+x+643717713,14),o=n+j(((n^s)&r^s)+o+i+3921069994,20),r=o+j(((o^n)&s^n)+r+p+3593408605,5),s=r+j(((r^o)&n^o)+s+y+38016083,9),n=s+j(((s^r)&o^r)+n+v+3634488961,14),o=n+j(((n^s)&r^s)+o+u+3889429448,20),r=o+j(((o^n)&s^n)+r+g+568446438,5),s=r+j(((r^o)&n^o)+s+b+3275163606,9),n=s+j(((s^r)&o^r)+n+l+4107603335,14),o=n+j(((n^s)&r^s)+o+h+1163531501,20),r=o+j(((o^n)&s^n)+r+k+2850285829,5),s=r+j(((r^o)&n^o)+s+c+4243563512,9),n=s+j(((s^r)&o^r)+n+m+1735328473,14),o=n+j(((n^s)&r^s)+o+E+2368359562,20),r=o+j((o^n^s)+r+p+4294588738,4),s=r+j((r^o^n)+s+h+2272392833,11),n=s+j((s^r^o)+n+x+1839030562,16),o=n+j((n^s^r)+o+b+4259657740,23),r=o+j((o^n^s)+r+a+2763975236,4),s=r+j((r^o^n)+s+u+1272893353,11),n=s+j((s^r^o)+n+m+4139469664,16),o=n+j((n^s^r)+o+y+3200236656,23),r=o+j((o^n^s)+r+k+681279174,4),s=r+j((r^o^n)+s+i+3936430074,11),n=s+j((s^r^o)+n+l+3572445317,16),o=n+j((n^s^r)+o+f+76029189,23),r=o+j((o^n^s)+r+g+3654602809,4),s=r+j((r^o^n)+s+E+3873151461,11),n=s+j((s^r^o)+n+v+530742520,16),o=n+j((n^s^r)+o+c+3299628645,23),r=o+j((n^(o|~s))+r+i+4096336452,6),s=r+j((o^(r|~n))+s+m+1126891415,10),n=s+j((r^(s|~o))+n+b+2878612391,15),o=n+j((s^(n|~r))+o+p+4237533241,21),r=o+j((n^(o|~s))+r+E+1700485571,6),s=r+j((o^(r|~n))+s+l+2399980690,10),n=s+j((r^(s|~o))+n+y+4293915773,15),o=n+j((s^(n|~r))+o+a+2240044497,21),r=o+j((n^(o|~s))+r+h+1873313359,6),s=r+j((o^(r|~n))+s+v+4264355552,10),n=s+j((r^(s|~o))+n+f+2734768916,15),o=n+j((s^(n|~r))+o+k+1309151649,21),r=o+j((n^(o|~s))+r+u+4149444226,6),s=r+j((o^(r|~n))+s+x+3174756917,10),n=s+j((r^(s|~o))+n+c+718787259,15),o=n+j((s^(n|~r))+o+g+3951481745,21),[e[0]+r>>>0,e[1]+o>>>0,e[2]+n>>>0,e[3]+s>>>0]},Ff=(e,t,r,o,n,s)=>{let i=64-r;if(s.length<i)t.set(s,r),r+=s.length;else{t.set(s.slice(0,i),r),e=If(e,t);let a=i;for(;a+64<=s.length;)e=If(e,s.slice(a,a+64)),a+=64;t.fill(0).set(s.slice(a),0),r=s.length-a}return[o,n]=Bv(o,n,s.length),[e,t,r,o,n]},Bv=(e,t,r)=>(e+=r,e>4294967295&&(t+=1),[e>>>0,t]);var Hv=new TextEncoder;function Wv(e){let t=typeof e;return t!=="object"?t:e===null?"null":e?.constructor?.name??"object"}function Df(e){if(typeof e=="string")return Hv.encode(e);if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new TypeError(`Cannot validate the input as it must be a Uint8Array, a string, or an ArrayBuffer: received a value of the type ${Wv(e)}`)}var $f=new TextEncoder().encode("0123456789abcdef"),e3=new TextEncoder,Gv=new TextDecoder;function jf(e){let t=Df(e),r=new Uint8Array(t.length*2);for(let o=0;o<t.length;o++){let n=t[o];r[o*2]=$f[n>>4],r[o*2+1]=$f[n&15]}return Gv.decode(r)}var Bf=async(e,t,r)=>{let o=`${jf(Uf(await e.arrayBuffer()))}`,n=await Vv(e,t,o,r);if(G(n))return n;let s=X(n);if("embedUrl"in s)return te(s);let i=await zv(s.signedUrl,e,r);return G(i)?i:qv(t,s.fileId,o,r)},Vv=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=le(o??{}),c={md5:r,size:e.size,contentType:e.type,name:e.name},l=await Js(ii(a),()=>or(o));if(G(l))return l;let u=new Request(`https://${s}/api/gcs/${t}/upload-request`,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":X(l),...n?{Cookie:de(n)}:{}}}),p=await i(u);return G(p)?p:Re(await ve(ke(X(p)),async f=>f.response.status===402?{name:"FileCapacityError",message:(await f.response.json()).message}:f),f=>f.json())},zv=async(e,t,r)=>{let{sid:o,fetch:n}=le(r??{}),s=await n(e,{method:"PUT",body:t,headers:{"Content-Type":t.type,...o?{Cookie:de(o)}:{}}});return G(s)?s:ao(await ve(ke(X(s)),async i=>i.response.headers.get("Content-Type")?.includes?.("/xml")?{name:"GCSError",message:await i.response.text()}:i),()=>{})},qv=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=le(o??{}),c=await Js(ii(a),()=>or(o));if(G(c))return c;let l=new Request(`https://${s}/api/gcs/${e}/verify`,{method:"POST",body:JSON.stringify({md5:r,fileId:t}),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":X(c),...n?{Cookie:de(n)}:{}}}),u=await i(l);return G(u)?u:Re(await ve(ke(X(u)),async p=>p.response.status===404?{name:"NotFoundError",message:(await p.response.json()).message}:p),p=>p.json())};function pt(e){return e.val}function wt(e){return e.err}var Hf=" must not return ",Kv="`transformer`",Xv="`recoverer`",Yv="`defaultValue`",ui=Kv+Hf,lo="called with ",mi=Yv+" must not be ",fi=Xv+Hf;var Jv="`Ok`",Wf="`Err`",Gf=lo+Wf,Vf=lo+Jv,Qv="Carrying `E` in "+Wf+" instead of throwing it directly. See `.cause`",sl="an instance of `Error` of the current realm.",I3="The thrown value is not "+sl,F3="The contained E should be "+sl,Zv="This `.cause` is not "+sl;function Ne(e){return e.ok}function ae(e){return{ok:!0,val:e,err:null}}function B(e){return!e.ok}function Q(e){return{ok:!1,val:null,err:e}}function H(e){return zf(e,Gf)}function re(e){return qf(e,Vf)}function zf(e,t){if(B(e))throw new TypeError(t);return e.val}function qf(e,t){if(Ne(e))throw new TypeError(t);return e.err}async function Tt(e,t){if(B(e))return e;let r=pt(e),o=await t(r);return ae(o)}function il(e,t,r){if(Ne(e)){let n=pt(e);return r(n)}let o=wt(e);return t(o)}var di="`null`",HG=ui+di,r_=lo+di,WG=mi+di,GG=fi+di;var hi="`undefined`",XG=ui+hi,o_=lo+hi,YG=mi+hi,JG=fi+hi;var Xf=async e=>{let t=e.title??".watchlistrc",r="projectsLastAccessed.json",o=await pi(e.project,t,r),n=B(o)?{}:JSON.parse(H(o)||"{}"),s=JSON.parse(localStorage.getItem("projectsLastAccessed")??"{}"),i=new Set([...Object.keys(n),...Object.keys(s)]),a=Object.fromEntries([...i].map(l=>[l,Math.max(n[l]??0,s[l]??0)]).sort((l,u)=>u[1]-l[1])),c=JSON.stringify(a);localStorage.setItem("projectsLastAccessed",c),await xe(e.project,t,()=>[t,"This page is automatically generated. DO NOT EDIT ANYTHING, WHITCH WILL BE OVERWRITTEN.","",`code:${r}`,` ${c}`,""])};var Pt=!1,gi=e=>{Pt=typeof e=="boolean"?e:new Set(e)},Ir=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...o)=>r(`%c${e}`,al,...o)];case"log":case"info":case"debug":return[t,(...o)=>{Pt!==!0&&(!Pt||!Pt.has(e))||r(`%c${e}`,al,...o)}];case"assert":return[t,(o,...n)=>{Pt!==!0&&(!Pt||!Pt.has(e))||r(o,`%c${e}`,al,...n)}];case"time":case"timeEnd":return[t,o=>{Pt!==!0&&(!Pt||!Pt.has(e))||r(`${e} ${o}`)}];default:return[t,(...o)=>{if(!(Pt!==!0&&(!Pt||!Pt.has(e))))return r(...o)}]}})),al="color: gray";scrapbox.PageMenu.addMenu({title:"Gyazo",image:"https://i.gyazo.com/503a911fea542532aa5aba0a88eb7b60.png",onClick:()=>window.open("https://gyazo.com/captures")});var Ei,Z,Zf,s_,po,Yf,ed,cl,td,ml,ll,pl,rd,Hn={},od=[],i_=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,wi=Array.isArray;function Fr(e,t){for(var r in t)e[r]=t[r];return e}function fl(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function yr(e,t,r){var o,n,s,i={};for(s in t)s=="key"?o=t[s]:s=="ref"?n=t[s]:i[s]=t[s];if(arguments.length>2&&(i.children=arguments.length>3?Ei.call(arguments,2):r),typeof e=="function"&&e.defaultProps!=null)for(s in e.defaultProps)i[s]===void 0&&(i[s]=e.defaultProps[s]);return xi(e,i,o,n,null)}function xi(e,t,r,o,n){var s={type:e,props:t,key:r,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:n??++Zf,__i:-1,__u:0};return n==null&&Z.vnode!=null&&Z.vnode(s),s}function Y(e){return e.children}function Xt(e,t){this.props=e,this.context=t}function Zo(e,t){if(t==null)return e.__?Zo(e.__,e.__i+1):null;for(var r;t<e.__k.length;t++)if((r=e.__k[t])!=null&&r.__e!=null)return r.__e;return typeof e.type=="function"?Zo(e):null}function nd(e){var t,r;if((e=e.__)!=null&&e.__c!=null){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if((r=e.__k[t])!=null&&r.__e!=null){e.__e=e.__c.base=r.__e;break}return nd(e)}}function ul(e){(!e.__d&&(e.__d=!0)&&po.push(e)&&!bi.__r++||Yf!==Z.debounceRendering)&&((Yf=Z.debounceRendering)||ed)(bi)}function bi(){var e,t,r,o,n,s,i,a;for(po.sort(cl);e=po.shift();)e.__d&&(t=po.length,o=void 0,s=(n=(r=e).__v).__e,i=[],a=[],r.__P&&((o=Fr({},n)).__v=n.__v+1,Z.vnode&&Z.vnode(o),dl(r.__P,o,n,r.__n,r.__P.namespaceURI,32&n.__u?[s]:null,i,s??Zo(n),!!(32&n.__u),a),o.__v=n.__v,o.__.__k[o.__i]=o,ad(i,o,a),o.__e!=s&&nd(o)),po.length>t&&po.sort(cl));bi.__r=0}function sd(e,t,r,o,n,s,i,a,c,l,u){var p,f,m,h,g,y,x=o&&o.__k||od,E=t.length;for(c=a_(r,t,x,c,E),p=0;p<E;p++)(m=r.__k[p])!=null&&(f=m.__i===-1?Hn:x[m.__i]||Hn,m.__i=p,y=dl(e,m,f,n,s,i,a,c,l,u),h=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&hl(f.ref,null,m),u.push(m.ref,m.__c||h,m)),g==null&&h!=null&&(g=h),4&m.__u||f.__k===m.__k?c=id(m,c,e):typeof m.type=="function"&&y!==void 0?c=y:h&&(c=h.nextSibling),m.__u&=-7);return r.__e=g,c}function a_(e,t,r,o,n){var s,i,a,c,l,u=r.length,p=u,f=0;for(e.__k=new Array(n),s=0;s<n;s++)(i=t[s])!=null&&typeof i!="boolean"&&typeof i!="function"?(c=s+f,(i=e.__k[s]=typeof i=="string"||typeof i=="number"||typeof i=="bigint"||i.constructor==String?xi(null,i,null,null,null):wi(i)?xi(Y,{children:i},null,null,null):i.constructor===void 0&&i.__b>0?xi(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):i).__=e,i.__b=e.__b+1,a=null,(l=i.__i=c_(i,r,c,p))!==-1&&(p--,(a=r[l])&&(a.__u|=2)),a==null||a.__v===null?(l==-1&&f--,typeof i.type!="function"&&(i.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,i.__u|=4))):e.__k[s]=null;if(p)for(s=0;s<u;s++)(a=r[s])!=null&&!(2&a.__u)&&(a.__e==o&&(o=Zo(a)),cd(a,a));return o}function id(e,t,r){var o,n;if(typeof e.type=="function"){for(o=e.__k,n=0;o&&n<o.length;n++)o[n]&&(o[n].__=e,t=id(o[n],t,r));return t}e.__e!=t&&(t&&e.type&&!r.contains(t)&&(t=Zo(e)),r.insertBefore(e.__e,t||null),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function Ur(e,t){return t=t||[],e==null||typeof e=="boolean"||(wi(e)?e.some(function(r){Ur(r,t)}):t.push(e)),t}function c_(e,t,r,o){var n,s,i=e.key,a=e.type,c=t[r];if(c===null||c&&i==c.key&&a===c.type&&!(2&c.__u))return r;if(o>(c!=null&&!(2&c.__u)?1:0))for(n=r-1,s=r+1;n>=0||s<t.length;){if(n>=0){if((c=t[n])&&!(2&c.__u)&&i==c.key&&a===c.type)return n;n--}if(s<t.length){if((c=t[s])&&!(2&c.__u)&&i==c.key&&a===c.type)return s;s++}}return-1}function Jf(e,t,r){t[0]=="-"?e.setProperty(t,r??""):e[t]=r==null?"":typeof r!="number"||i_.test(t)?r:r+"px"}function yi(e,t,r,o,n){var s;e:if(t=="style")if(typeof r=="string")e.style.cssText=r;else{if(typeof o=="string"&&(e.style.cssText=o=""),o)for(t in o)r&&t in r||Jf(e.style,t,"");if(r)for(t in r)o&&r[t]===o[t]||Jf(e.style,t,r[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(td,"$1")),t=t.toLowerCase()in e||t=="onFocusOut"||t=="onFocusIn"?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=r,r?o?r.u=o.u:(r.u=ml,e.addEventListener(t,s?pl:ll,s)):e.removeEventListener(t,s?pl:ll,s);else{if(n=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=r??"";break e}catch{}typeof r=="function"||(r==null||r===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&r==1?"":r))}}function Qf(e){return function(t){if(this.l){var r=this.l[t.type+e];if(t.t==null)t.t=ml++;else if(t.t<r.u)return;return r(Z.event?Z.event(t):t)}}}function dl(e,t,r,o,n,s,i,a,c,l){var u,p,f,m,h,g,y,x,E,k,b,v,R,O,L,N,P,_=t.type;if(t.constructor!==void 0)return null;128&r.__u&&(c=!!(32&r.__u),s=[a=t.__e=r.__e]),(u=Z.__b)&&u(t);e:if(typeof _=="function")try{if(x=t.props,E="prototype"in _&&_.prototype.render,k=(u=_.contextType)&&o[u.__c],b=u?k?k.props.value:u.__:o,r.__c?y=(p=t.__c=r.__c).__=p.__E:(E?t.__c=p=new _(x,b):(t.__c=p=new Xt(x,b),p.constructor=_,p.render=p_),k&&k.sub(p),p.props=x,p.state||(p.state={}),p.context=b,p.__n=o,f=p.__d=!0,p.__h=[],p._sb=[]),E&&p.__s==null&&(p.__s=p.state),E&&_.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Fr({},p.__s)),Fr(p.__s,_.getDerivedStateFromProps(x,p.__s))),m=p.props,h=p.state,p.__v=t,f)E&&_.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),E&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(E&&_.getDerivedStateFromProps==null&&x!==m&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(x,b),!p.__e&&(p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(x,p.__s,b)===!1||t.__v==r.__v)){for(t.__v!=r.__v&&(p.props=x,p.state=p.__s,p.__d=!1),t.__e=r.__e,t.__k=r.__k,t.__k.some(function(T){T&&(T.__=t)}),v=0;v<p._sb.length;v++)p.__h.push(p._sb[v]);p._sb=[],p.__h.length&&i.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(x,p.__s,b),E&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(m,h,g)})}if(p.context=b,p.props=x,p.__P=e,p.__e=!1,R=Z.__r,O=0,E){for(p.state=p.__s,p.__d=!1,R&&R(t),u=p.render(p.props,p.state,p.context),L=0;L<p._sb.length;L++)p.__h.push(p._sb[L]);p._sb=[]}else do p.__d=!1,R&&R(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++O<25);p.state=p.__s,p.getChildContext!=null&&(o=Fr(Fr({},o),p.getChildContext())),E&&!f&&p.getSnapshotBeforeUpdate!=null&&(g=p.getSnapshotBeforeUpdate(m,h)),a=sd(e,wi(N=u!=null&&u.type===Y&&u.key==null?u.props.children:u)?N:[N],t,r,o,n,s,i,a,c,l),p.base=t.__e,t.__u&=-161,p.__h.length&&i.push(p),y&&(p.__E=p.__=null)}catch(T){if(t.__v=null,c||s!=null)if(T.then){for(t.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;s[s.indexOf(a)]=null,t.__e=a}else for(P=s.length;P--;)fl(s[P]);else t.__e=r.__e,t.__k=r.__k;Z.__e(T,t,r)}else s==null&&t.__v==r.__v?(t.__k=r.__k,t.__e=r.__e):a=t.__e=l_(r.__e,t,r,o,n,s,i,c,l);return(u=Z.diffed)&&u(t),128&t.__u?void 0:a}function ad(e,t,r){for(var o=0;o<r.length;o++)hl(r[o],r[++o],r[++o]);Z.__c&&Z.__c(t,e),e.some(function(n){try{e=n.__h,n.__h=[],e.some(function(s){s.call(n)})}catch(s){Z.__e(s,n.__v)}})}function l_(e,t,r,o,n,s,i,a,c){var l,u,p,f,m,h,g,y=r.props,x=t.props,E=t.type;if(E=="svg"?n="http://www.w3.org/2000/svg":E=="math"?n="http://www.w3.org/1998/Math/MathML":n||(n="http://www.w3.org/1999/xhtml"),s!=null){for(l=0;l<s.length;l++)if((m=s[l])&&"setAttribute"in m==!!E&&(E?m.localName==E:m.nodeType==3)){e=m,s[l]=null;break}}if(e==null){if(E==null)return document.createTextNode(x);e=document.createElementNS(n,E,x.is&&x),a&&(Z.__m&&Z.__m(t,s),a=!1),s=null}if(E===null)y===x||a&&e.data===x||(e.data=x);else{if(s=s&&Ei.call(e.childNodes),y=r.props||Hn,!a&&s!=null)for(y={},l=0;l<e.attributes.length;l++)y[(m=e.attributes[l]).name]=m.value;for(l in y)if(m=y[l],l!="children"){if(l=="dangerouslySetInnerHTML")p=m;else if(!(l in x)){if(l=="value"&&"defaultValue"in x||l=="checked"&&"defaultChecked"in x)continue;yi(e,l,null,m,n)}}for(l in x)m=x[l],l=="children"?f=m:l=="dangerouslySetInnerHTML"?u=m:l=="value"?h=m:l=="checked"?g=m:a&&typeof m!="function"||y[l]===m||yi(e,l,m,y[l],n);if(u)a||p&&(u.__html===p.__html||u.__html===e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),sd(e,wi(f)?f:[f],t,r,o,E=="foreignObject"?"http://www.w3.org/1999/xhtml":n,s,i,s?s[0]:r.__k&&Zo(r,0),a,c),s!=null)for(l=s.length;l--;)fl(s[l]);a||(l="value",E=="progress"&&h==null?e.removeAttribute("value"):h!==void 0&&(h!==e[l]||E=="progress"&&!h||E=="option"&&h!==y[l])&&yi(e,l,h,y[l],n),l="checked",g!==void 0&&g!==e[l]&&yi(e,l,g,y[l],n))}return e}function hl(e,t,r){try{if(typeof e=="function"){var o=typeof e.__u=="function";o&&e.__u(),o&&t==null||(e.__u=e(t))}else e.current=t}catch(n){Z.__e(n,r)}}function cd(e,t,r){var o,n;if(Z.unmount&&Z.unmount(e),(o=e.ref)&&(o.current&&o.current!==e.__e||hl(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){Z.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(n=0;n<o.length;n++)o[n]&&cd(o[n],t,r||typeof e.type!="function");r||fl(e.__e),e.__c=e.__=e.__e=void 0}function p_(e,t,r){return this.constructor(e,r)}function ut(e,t,r){var o,n,s,i;t==document&&(t=document.documentElement),Z.__&&Z.__(e,t),n=(o=typeof r=="function")?null:r&&r.__k||t.__k,s=[],i=[],dl(t,e=(!o&&r||t).__k=yr(Y,null,[e]),n||Hn,Hn,t.namespaceURI,!o&&r?[r]:n?null:t.firstChild?Ei.call(t.childNodes):null,s,!o&&r?r:n?n.__e:t.firstChild,o,i),ad(s,e,i)}function Wn(e,t){var r={__c:t="__cC"+rd++,__:e,Consumer:function(o,n){return o.children(n)},Provider:function(o){var n,s;return this.getChildContext||(n=new Set,(s={})[t]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){n=null},this.shouldComponentUpdate=function(i){this.props.value!==i.value&&n.forEach(function(a){a.__e=!0,ul(a)})},this.sub=function(i){n.add(i);var a=i.componentWillUnmount;i.componentWillUnmount=function(){n&&n.delete(i),a&&a.call(i)}}),o.children}};return r.Provider.__=r.Consumer.contextType=r}Ei=od.slice,Z={__e:function(e,t,r,o){for(var n,s,i;t=t.__;)if((n=t.__c)&&!n.__)try{if((s=n.constructor)&&s.getDerivedStateFromError!=null&&(n.setState(s.getDerivedStateFromError(e)),i=n.__d),n.componentDidCatch!=null&&(n.componentDidCatch(e,o||{}),i=n.__d),i)return n.__E=n}catch(a){e=a}throw e}},Zf=0,s_=function(e){return e!=null&&e.constructor==null},Xt.prototype.setState=function(e,t){var r;r=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=Fr({},this.state),typeof e=="function"&&(e=e(Fr({},r),this.props)),e&&Fr(r,e),e!=null&&this.__v&&(t&&this._sb.push(t),ul(this))},Xt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),ul(this))},Xt.prototype.render=Y,po=[],ed=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,cl=function(e,t){return e.__v.__b-t.__v.__b},bi.__r=0,td=/(PointerCapture)$|Capture$/i,ml=0,ll=Qf(!1),pl=Qf(!0),rd=0;var uo,Ce,gl,ld,Gn=0,yd=[],$e=Z,pd=$e.__b,ud=$e.__r,md=$e.diffed,fd=$e.__c,dd=$e.unmount,hd=$e.__;function Vn(e,t){$e.__h&&$e.__h(Ce,e,Gn||t),Gn=0;var r=Ce.__H||(Ce.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function J(e){return Gn=1,Dr(xd,e)}function Dr(e,t,r){var o=Vn(uo++,2);if(o.t=e,!o.__c&&(o.__=[r?r(t):xd(void 0,t),function(a){var c=o.__N?o.__N[0]:o.__[0],l=o.t(c,a);c!==l&&(o.__N=[l,o.__[1]],o.__c.setState({}))}],o.__c=Ce,!Ce.u)){var n=function(a,c,l){if(!o.__c.__H)return!0;var u=o.__c.__H.__.filter(function(f){return!!f.__c});if(u.every(function(f){return!f.__N}))return!s||s.call(this,a,c,l);var p=o.__c.props!==a;return u.forEach(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(p=!0)}}),s&&s.call(this,a,c,l)||p};Ce.u=!0;var s=Ce.shouldComponentUpdate,i=Ce.componentWillUpdate;Ce.componentWillUpdate=function(a,c,l){if(this.__e){var u=s;s=void 0,n(a,c,l),s=u}i&&i.call(this,a,c,l)},Ce.shouldComponentUpdate=n}return o.__N||o.__}function oe(e,t){var r=Vn(uo++,3);!$e.__s&&xl(r.__H,t)&&(r.__=e,r.i=t,Ce.__H.__h.push(r))}function ki(e,t){var r=Vn(uo++,4);!$e.__s&&xl(r.__H,t)&&(r.__=e,r.i=t,Ce.__h.push(r))}function qe(e){return Gn=5,C(function(){return{current:e}},[])}function C(e,t){var r=Vn(uo++,7);return xl(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function F(e,t){return Gn=8,C(function(){return e},t)}function xr(e){var t=Ce.context[e.__c],r=Vn(uo++,9);return r.c=e,t?(r.__==null&&(r.__=!0,t.sub(Ce)),t.props.value):e.__}function u_(){for(var e;e=yd.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Ri),e.__H.__h.forEach(yl),e.__H.__h=[]}catch(t){e.__H.__h=[],$e.__e(t,e.__v)}}$e.__b=function(e){Ce=null,pd&&pd(e)},$e.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),hd&&hd(e,t)},$e.__r=function(e){ud&&ud(e),uo=0;var t=(Ce=e.__c).__H;t&&(gl===Ce?(t.__h=[],Ce.__h=[],t.__.forEach(function(r){r.__N&&(r.__=r.__N),r.i=r.__N=void 0})):(t.__h.forEach(Ri),t.__h.forEach(yl),t.__h=[],uo=0)),gl=Ce},$e.diffed=function(e){md&&md(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(yd.push(t)!==1&&ld===$e.requestAnimationFrame||((ld=$e.requestAnimationFrame)||m_)(u_)),t.__H.__.forEach(function(r){r.i&&(r.__H=r.i),r.i=void 0})),gl=Ce=null},$e.__c=function(e,t){t.some(function(r){try{r.__h.forEach(Ri),r.__h=r.__h.filter(function(o){return!o.__||yl(o)})}catch(o){t.some(function(n){n.__h&&(n.__h=[])}),t=[],$e.__e(o,r.__v)}}),fd&&fd(e,t)},$e.unmount=function(e){dd&&dd(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.forEach(function(o){try{Ri(o)}catch(n){t=n}}),r.__H=void 0,t&&$e.__e(t,r.__v))};var gd=typeof requestAnimationFrame=="function";function m_(e){var t,r=function(){clearTimeout(o),gd&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(r,100);gd&&(t=requestAnimationFrame(r))}function Ri(e){var t=Ce,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),Ce=t}function yl(e){var t=Ce;e.__c=e.__(),Ce=t}function xl(e,t){return!e||e.length!==t.length||t.some(function(r,o){return r!==e[o]})}function xd(e,t){return typeof t=="function"?t(e):t}function Ke(e){return typeof e=="number"}var f_=(e,t,r)=>{let o=t.name||"anonymous predicate",n=typeof e,s=JSON.stringify(e,null,2);return`Expected ${r??"a value"} that satisfies the predicate ${o}, got ${n}: ${s}`},d_=f_,bl=class e extends Error{constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.name=this.constructor.name}};function bd(e,t,r={}){if(!t(e))throw new bl(r.message??d_(e,t,r.name))}function Ed(e,t,r={}){return bd(e,t,r),e}function St(e){return typeof e>"u"}var vi=!1,wd=null,Rd=()=>{scrapbox.addListener("lines:changed",()=>vi=!1),scrapbox.addListener("layout:changed",()=>vi=!1),Rd=void 0},kd=()=>(Rd?.(),vi||(wd=scrapbox.Page.lines,vi=!0),wd);var vd=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError(`"${t}" must be HTMLDivElememt but actual is "${e}"`)};var _d=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError(`"${t}" must be HTMLTextAreaElement but actual is "${e}"`)};var Td=()=>_i(document.getElementById("editor"),"div#editor"),zn=()=>_i(document.getElementsByClassName("lines").item(0),"div.lines");var Xe=()=>{let e=document.getElementById("text-input");if(e)return _d(e,"textarea#text-input"),e};var Pd=()=>_i(document.getElementsByClassName("popup-menu")?.[0],"div.popup-menu");var Sd=()=>_i(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),_i=(e,t)=>{if(e)return vd(e,t),e};var mt=()=>{let e=zn();if(!e)throw Error("div.lines is not found.");let t=Object.keys(e).find(r=>r.startsWith("__reactFiber"));if(!t)throw Error('div.lines must has the property whose name starts with "__reactFiber"');return e[t].return.stateNode.props.lines};var br=e=>e.match(/^(\s*)/)?.[1]?.length??0,mo=(e,t)=>{let r=br(Od(e,t)),o=0;for(;e+o+1<t.length&&br(Od(e+o+1,t))>r;)o++;return o},Od=(e,t)=>{let r=t[e];return De(r)?r:r.text};var El=e=>{if(St(e))return;if(Ke(e))return Ti(e)?.id;if(De(e))return e.startsWith("L")?e.slice(1):e;if(e.classList.contains("line"))return e.id.slice(1);let t=e.closest(".line");if(t)return t.id.slice(1)},Ld=e=>{if(St(e))return;if(Ke(e))return e;let t=El(e);return t?mt().findIndex(r=>r.id===t):-1};var Ti=e=>{if(St(e))return;if(Ke(e))return mt()[e];let t=El(e);return t?mt().find(r=>r.id===t):void 0},Er=e=>{if(Nd(e))return e;let t=El(e);if(St(t))return t;let r=document.getElementById(`L${t}`);if(!St(r))return r},Nd=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var wr=()=>Ed(kd(),hr),ot=e=>{if(St(e))return;if(Ke(e)||De(e))return Ti(e)?.text;if(!(e instanceof HTMLElement))return;if(Nd(e))return Ti(e)?.text;if(e.classList.contains("char-index"))return e.textContent??void 0;if(e.classList.contains("line")||e.getElementsByClassName("lines")?.[0])return mt().map(({text:o})=>o).join(`
`);let t=[],r=Ti(e);if(!St(r)){for(let o of g_(e))t.push(y_(o));return r.text.slice(Math.min(...t),Math.max(...t)+1)}};var Cd=()=>{let e=zn()?.firstElementChild;if(!St(e))return e},Ad=()=>{let e=zn()?.lastElementChild;if(!St(e))return e};var wl=e=>{let t=Ld(e);if(!St(t))return mo(t,wr())};function*g_(e){let t=e.getElementsByClassName("char-index");for(let r=0;r<t.length;r++)yield t[0]}var Rl=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index"),y_=e=>{if(!Rl(e))throw Error("A char DOM is required.");let t=e.className.match(/c-(\d+)/)?.[1];if(St(t))throw Error('.char-index must have ".c-{\\d}"');return parseInt(t)},Md=e=>{let t=e?.getElementsByClassName?.("c-0")?.[0];return Rl(t)?t:void 0};var qn=(e,t)=>{let r=Er(e)?.getElementsByClassName?.(`c-${t}`)?.[0];return Rl(r)?r:void 0};var He=(e,t)=>{let{noModifiedKeys:r=!1,...o}=t??{},n={bubbles:!0,cancelable:!0,keyCode:x_[e],...r?{}:{...o}},s=Xe();if(!s)throw Error("#text-input must exist.");s.dispatchEvent(new KeyboardEvent("keydown",n)),s.dispatchEvent(new KeyboardEvent("keyup",n))},x_={Backspace:8,Tab:9,Enter:13,Delete:46,Escape:27," ":32,PageUp:33,PageDown:34,End:35,Home:36,ArrowLeft:37,ArrowUp:38,ArrowRight:39,ArrowDown:40,a:65,A:65,b:66,B:66,c:67,C:67,d:68,D:68,e:69,E:69,f:70,F:70,g:71,G:71,h:72,H:72,i:73,I:73,j:74,J:74,k:75,K:75,l:76,L:76,m:77,M:77,n:78,N:78,o:79,O:79,p:80,P:80,q:81,Q:81,r:82,R:82,s:83,S:83,t:84,T:84,u:85,U:85,v:86,V:86,w:87,W:87,x:88,X:88,y:89,Y:89,z:90,Z:90,0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,F1:113,F2:114,F3:115,F4:116,F5:117,F6:118,F7:119,F8:120,F9:121,F10:122,F11:123,F12:124,":":186,"*":186,";":187,"+":187,"-":189,"=":189,".":190,">":190,"/":191,"?":191,"@":192,"`":192,"[":219,"{":219,"\\":220,"|":220,"]":221,"}":221,"^":222,"~":222,_:226};var kl=async(e,t)=>{let r={button:t.button??0,clientX:t.X,clientY:t.Y,bubbles:!0,cancelable:!0,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,view:window};e.dispatchEvent(new MouseEvent("mousedown",r)),e.dispatchEvent(new MouseEvent("mouseup",r)),e.dispatchEvent(new MouseEvent("click",r)),await Te(10)};var We=()=>{let e=Xe();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(r=>r.startsWith("__reactFiber"));if(!t)throw Error('div.cursor must has the property whose name starts with "__reactFiber"');return e[t].return.return.stateNode.props};var vl=e=>{let{top:t,bottom:r}=e.getBoundingClientRect();return t>=0&&r<=globalThis.innerHeight};function*Ot(e,t){for(let r=e;r<t;r++)yield r}var _l=()=>{He("Home"),He("Home")};var Id=async()=>{let e=Cd();if(!e)throw Error(".line:first-of-type can't be found.");vl(e)||e.scrollIntoView({block:"center"});let t=Md(e);if(!t)throw Error(".line:first-of-type .c-0 can't be found.");let{left:r,top:o}=t.getBoundingClientRect();await kl(e,{X:r,Y:o})},Fd=async()=>{await Ud(Ad())},Tl=async e=>{await Ud(Er(e))},Ud=async e=>{if(!e)throw Error("The target line DOM is failed to find.");vl(e)||e.scrollIntoView({block:"center"});let{right:t,top:r,height:o}=e.getElementsByClassName("text")[0].getBoundingClientRect();await kl(e,{X:t+1,Y:r+o/2})};var Dd=(e=1)=>{for(let t of Ot(0,e))He("z",{ctrlKey:!0})},$d=(e=1)=>{for(let t of Ot(0,e))He("z",{shiftKey:!0,ctrlKey:!0})};var jd=async(e,t)=>{await Tl(e),_l(),He("Enter"),He("ArrowUp"),await Ye(t)},Rt=async(e,t,r)=>{await Tl(e),_l();for(let o of Ot(e,t))He("ArrowDown",{shiftKey:!0});He("End",{shiftKey:!0}),await Ye(r)};var Pi=(e=1)=>{for(let t of Ot(0,e))He("ArrowRight",{ctrlKey:!0})},Si=(e=1)=>{for(let t of Ot(0,e))He("ArrowLeft",{ctrlKey:!0})};var Oi=(e=1)=>{for(let t of Ot(0,e))He("ArrowUp",{ctrlKey:!0})},Li=(e=1)=>{for(let t of Ot(0,e))He("ArrowDown",{ctrlKey:!0})},Ni=(e=1)=>{for(let t of Ot(0,e))He("ArrowRight",{altKey:!0})},Ci=(e=1)=>{for(let t of Ot(0,e))He("ArrowLeft",{altKey:!0})};var Ai=(e=1)=>{for(let t of Ot(0,e))He("ArrowUp",{altKey:!0})},Mi=(e=1)=>{for(let t of Ot(0,e))He("ArrowDown",{altKey:!0})},Ye=async e=>{let t=Xe();if(!t)throw Error("#text-input is not ditected.");t.focus(),t.value=e;let r=new InputEvent("input",{bubbles:!0});t.dispatchEvent(r),await Te(1)};var Le=()=>{let e=Sd();if(!e)throw new Error("div.status-bar can't be found");let t=document.createElement("div");return e.append(t),{render:(...r)=>{t.textContent="";let o=Bd(...r);o&&t.append(o)},dispose:()=>t.remove()}},Bd=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":return[E_()];case"check-circle":return[w_()];case"exclamation-triangle":return[R_()];case"text":return[Ii(o.text)];case"group":{let n=Bd(...o.items);return n?[n]:[]}}});if(t.length===0)return;if(t.length===1)return t[0];let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r},Ii=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},E_=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),Ii(e)},w_=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),Ii(e)},R_=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),Ii(e)};var en=e=>{let t=JSON.parse(localStorage.getItem("pageTransitionContext")??""),r=e.type==="page"?e.from.project===e.to.project?e.from.title===e.to.title?{titleHint:e.to.title}:{linkFrom:e.from.title}:{linkFrom:`/${e.from.project}/${e.from.title}`}:{searchQuery:e.query};t[`page_${ne(e.to.title)}`]=r,localStorage.setItem("pageTransitionContext",JSON.stringify(t))};var k_=(e,t,r)=>{let o=new URL(`/${e}/${me(t)}`,location.href);if(r?.body&&(o.search=`?body=${encodeURIComponent(r.body)}`),r?.id&&(o.hash=`#${r.id}`),r?.context&&en({...r?.context,to:{project:e,title:t}}),r?.newTab!==!1&&(r?.newTab===!0||e!==scrapbox.Project.name)){globalThis.open(o);return}if(r?.reload!==!1&&(r?.reload===!0||e!==scrapbox.Project.name)){globalThis.open(o,"_self");return}let n=document.createElement("a");n.href=o.toString(),document.body.append(n),n.click(),n.remove()},Kn=(e,t,r)=>k_(e,t,{newTab:!1,reload:!1,body:r});var tn=async(e,t)=>{let r=await globalThis.caches.keys();for(let o of r.sort().reverse()){let s=await(await caches.open(o)).match(e,t);if(s)return s}},Fi=async(e,t)=>{let r=t.clone();return await(await caches.open(v_(new Date))).put(e,r)},v_=e=>`api-${e.getFullYear()}-${`${e.getMonth()+1}`.padStart(2,"0")}-${`${e.getDate()}`.padStart(2,"0")}`;var Lt=()=>{let e=Xe();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(s=>s.startsWith("__reactFiber"));if(!t)throw Error('#text-input must has the property whose name starts with "__reactFiber"');let r=e[t].return.return.stateNode._stores,o=r.find(s=>s.constructor.name==="Cursor");if(!o)throw Error('#text-input must has a "Cursor" store.');let n=r.find(s=>s.constructor.name==="Selection");if(!n)throw Error('#text-input must has a "Selection" store.');return{cursor:o,selection:n}};var $r=()=>Lt().cursor;var Ui=()=>Lt().selection;var Xn=e=>e===void 0?0:typeof e=="boolean"?Number(e):(e.capture?1:0)|(e.once?2:0)|(e.passive?4:0),Hd=e=>{if(e===0)return;let t={};return e&1&&(t.capture=!0),e&2&&(t.once=!0),e&4&&(t.passive=!0),t};var Di=new Map,Pl=new Map,Sl=()=>{scrapbox.on("layout:changed",()=>{let e=Xe();if(e)for(let[t,r]of Di)for(let[o,n]of r)for(let s of n)e.addEventListener(t,o,Hd(s))}),Sl=void 0},Wd=(e,t,r)=>{Sl?.();let o=Di.get(e)??new Map,n=o.get(t)??new Set;if(n.has(Xn(r)))return;if(n.add(Xn(r)),o.set(t,n),Di.set(e,o),typeof r=="object"&&r?.once){let i=Pl.get(t)??new Map,a=Xn(r),c=function(u){return Ol(e,t,r),i.delete(a),t.call(this,u)};i.set(a,c),Pl.set(t,i);let l=Xe();if(!l)return;l.addEventListener(e,c,r)}let s=Xe();s&&s.addEventListener(e,t,r)},Ol=(e,t,r)=>{Sl?.();let o=Di.get(e);if(!o)return;let n=o.get(t);if(!n)return;let s=Xn(r);if(n.delete(s),typeof r=="object"&&r?.once){let a=Pl.get(t);if(!a)return;let c=a.get(s);if(!c)return;let l=Xe();if(!l)return;l.removeEventListener(e,c,r),a.delete(s);return}let i=Xe();i&&i.removeEventListener(e,t,r)};var Gd={"&":"\\x26","!":"\\x21","#":"\\x23",$:"\\$","%":"\\x25","*":"\\*","+":"\\+",",":"\\x2c",".":"\\.",":":"\\x3a",";":"\\x3b","<":"\\x3c","=":"\\x3d",">":"\\x3e","?":"\\?","@":"\\x40","^":"\\^","`":"\\x60","~":"\\x7e","(":"\\(",")":"\\)","[":"\\[","]":"\\]","{":"\\{","}":"\\}","/":"\\/","-":"\\x2d","\\":"\\\\","|":"\\|"},__=new RegExp(`[${Object.values(Gd).join("")}]`,"gu");function Vd(e){return e.replaceAll(__,t=>Gd[t]).replace(/^[0-9a-zA-Z]/,t=>`\\x${t.codePointAt(0).toString(16)}`)}var T_=0,cK=Array.isArray;function d(e,t,r,o,n,s){t||(t={});var i,a,c=t;if("ref"in c)for(a in c={},t)a=="ref"?i=t[a]:c[a]=t[a];var l={type:e,props:c,key:r,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--T_,__i:-1,__u:0,__source:n,__self:s};if(typeof e=="function"&&(i=e.defaultProps))for(a in i)c[a]===void 0&&(c[a]=i[a]);return Z.vnode&&Z.vnode(l),l}var zd=({project:e,title:t,words:r,lines:o,query:n,close:s})=>{let i=F(c=>{en({type:"search",query:n,to:{project:e,title:t}}),!(c.metaKey||c.ctrlKey||c.altKey||c.shiftKey)&&s()},[e,t,n,s]),a=C(()=>{let c=new RegExp(`(${r.map(l=>Vd(l)).join("|")})`,"i");return o.flatMap(l=>{let u=l.split(c);return d("span",{children:u.map((p,f)=>f%2===0?p:d("strong",{children:p}))})})},[o,r]);return d("a",{href:`/${e}/${me(t)}`,target:`${e===scrapbox.Project.name?"":"_blank"}`,rel:`${e===scrapbox.Project.name?"route":"noopener noreferrer"}`,onClick:i,children:[t,d("div",{className:"description",children:a})]})};var qd=e=>{let[t,r]=J(e),o=F(()=>r(!0),[]),n=F(()=>r(!1),[]),s=F(()=>r(i=>!i),[]);return[t,{open:o,close:n,toggle:s}]};var Kd=(e,t)=>{let[r,o]=J(),[n,s]=J(!1),i=qe(Promise.resolve());return oe(()=>{if(t===""){o(void 0);return}let a=!1;return i.current=(async()=>{if(await i.current,!a){s(!0);try{let c=await Of(t,e);if(a)return;o(Ae(c)?X(c):void 0)}finally{s(!1)}}})(),()=>a=!0},[t,e]),{loading:n,result:r}};var Xd=()=>d("style",{children:`.modal {
position:fixed;
inset:0;
z-index:1050;
background-color:#000c;
display: flex;
flex-direction: column;
align-items: center;
row-gap: 10px;
padding: 10px;
}
.closed {
display: none;
}
.modal > * {
color: var(--page-text-color, #4a4a4a);
background-color: var(--page-bg, #fefefe);
border: 2px solid var(--body-bg, #dcdde0);
border-radius: 4px;
padding: 5px;
width: calc(var(--item-width, 100%) - 10px);
}
@media (min-width: 768px) {
.modal {
padding: 30px;
}
}
.controller {
display: flex;
gap: 0.2em;
flex-direction: column;
}
input {
border-radius: 5px;
padding: 0 10px;
height: 32px;
border: transparent;
box-shadow: none;
color: var(--search-form-text-color, rgba(255, 255, 255, 0.35));
background-color: var(--search-form-bg, rgba(255, 255, 255, 0.15))
}
.result {
flex-direction: column;
width: 100%;
padding: 5px 0;
margin: 2px 0 0;
list-style: none;
font-size: 14px;
font-weight: normal;
line-height: 28px;
text-align: left;
border: 1px solid rgba(0,0,0,0.15);
border-radius: 4px;
background-clip: padding-box;
white-space: nowrap;
overflow-x: hidden;
overflow-y: auto;
}
a {
display: block;
padding: 3px 20px;
clear: both;
align-items: center;
user-select: none;
text-decoration: none;
overflow: hidden;
text-overflow: ellipsis;
color: inherit;
}
.description {
margin-top: 0.5em;
color: var(--incremental-fulltext-search-description-text-color, #c4c4c4);
font-size: 12px;
line-height: 14px;
max-height: 28px;
overflow: hidden;
text-overflow: ellipsis;
}
.description strong {
background-color: #ff0;
color: #666;
}
.spinner::before {
display: inline-block;
font-style: normal;
font-variant: normal;
text-rendering: auto;
line-height: 1;
content: "\f110";
font-family: "Font Awesome 5 Free";
font-weight: 900;
margin: 0;
padding: 0;
box-sizing: border-box;
animation: fa-spin 2s linear infinite;
}`});var P_=()=>d("i",{className:"spinner"}),Yd=({exportOps:e})=>{let[t,r]=J(""),o=scrapbox.Project.name,{loading:n,result:s}=Kd(o,t),i=F(m=>{r(m.currentTarget.value)},[]),[a,{open:c,close:l,toggle:u}]=qd(!1),p=qe({open:c,close:l,toggle:u});oe(()=>{Object.assign(p.current,{open:c,close:l,toggle:u})},[]),oe(()=>e(p.current),[e]);let f=F(m=>{m.target instanceof HTMLElement&&m.target.id==="background"&&l()},[]);return d(Y,{children:[d(Xd,{}),d("div",{id:"background",className:`modal${a?"":" closed"}`,onClick:f,children:[d("div",{className:"controller",children:[d("input",{type:"text",value:t,onInput:i}),d("div",{className:"info",children:[n&&d(P_,{}),`${s?.pages?.length??0} pages`]})]}),s?.pages&&s.pages.length>0&&d("ul",{className:"result",children:s.pages.map(m=>d("li",{children:d(zd,{...m,project:o,query:t,close:l})},m.title))})]})]})};var Jd=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"});return document.body.append(e),new Promise(r=>{ut(d(Yd,{exportOps:r}),t)})};var $i=(e,t)=>Object.hasOwn(e,t),Qd={left:"ArrowLeft",right:"ArrowRight",up:"ArrowUp",down:"ArrowDown",bs:"Backspace",menu:"ContextMenu",apps:"ContextMenu",del:"Delete",return:"Enter",cr:"Enter",esc:"Escape",pgup:"PageUp",pgdn:"PageDown",lt:"<",less:"<",lesser:"<",gt:">",greater:">"},rh=e=>{let t=e.toLowerCase();return $i(Qd,t)?Qd[t]:e},Zd={Backquote:["`","~"],Digit1:["1","!"],Digit2:["2","@"],Digit3:["3","#"],Digit4:["4","$"],Digit5:["5","%"],Digit6:["6","^"],Digit7:["7","&"],Digit8:["8","*"],Digit9:["9","("],Digit0:["0",")"],Minus:["-","_"],Equal:["=","+"],Backslash:["\\","|"],BracketLeft:["[","{"],BracketRight:["]","}"],Semicolon:[";",":"],Quote:["'",'"'],Comma:[",","<"],Period:[".",">"],Slash:["/","?"]},S_=(e,t)=>{if(e.startsWith("Key")){let r=e.slice(3);return t||(r=r.toLowerCase()),r}return $i(Zd,e)?Zd[e][t?1:0]:e},eh={"<":"lt",">":"gt"},O_=/^($|Unidentified$|Process$|Dead$|Alt|Control|Hyper|Meta|Shift|Super|OS)/,Ll=e=>{let t=e.shiftKey,r=e.key||"Unidentified";if(r==="Unidentified"?r=S_(e.code||"",t):(r=rh(r),r===" "&&(r="Space")),O_.test(r))return"";r.length===1?t=!1:r=r.toLowerCase();let o="";return e.altKey&&(o+="a-"),e.ctrlKey&&(o+="c-"),e.metaKey&&(o+="m-"),t&&(o+="s-"),$i(eh,r)&&(r=eh[r]),o||r.length>1?`<${o}${r}>`:r},th={a:"altKey",c:"ctrlKey",m:"metaKey",s:"shiftKey"},L_=e=>{if(e.length===1)return/\s/.test(e)?{ok:!1,value:{name:"InvalidKeyError",key:e,message:`Invalid key: ${e}`}}:{ok:!0,value:{key:e}};let t=e.match(/^<((?:[a-z]-)*)([a-z\d]+|[^<>\s])>$/i);if(!t)return{ok:!1,value:{name:"InvalidKeyError",key:e,message:`Invalid key: ${e}`}};let[,r,o]=t,n={key:rh(o)};for(let s of r.split("-").slice(0,-1)){let i=s.toLowerCase();if(!$i(th,i))return{ok:!1,value:{name:"UnknownModifierError",modifier:s,context:e,message:`${e}: Unknown modifier: ${s}`}};let a=th[i];if(n[a]!==void 0)return{ok:!1,value:{name:"DuplicateModifierError",modifier:s,context:e,message:`${e}: Duplicate modifier: ${s}`}};if(n[a]=!0,n.key.length===1&&n.shiftKey)return{ok:!1,value:{name:"DisallowedModifierError",modifier:s,context:e,message:`${e}: Unusable modifier with single-character keys: ${s}`}}}return{ok:!0,value:n}},oh=e=>{let t=L_(e);return t.ok?{ok:!0,value:Ll(t.value)}:t},nh=e=>e.match(/<[^<>\s]+>|[\s\S]|^$/g);var $t=!1;var sh=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...o)=>r(`%c${e}`,"color: gray",...o)];case"log":case"info":case"debug":return[t,(...o)=>{$t!==!0&&(!$t||!$t.has(e))||r(`%c${e}`,"color: gray",...o)}];case"assert":return[t,(o,...n)=>{$t!==!0&&(!$t||!$t.has(e))||r(o,`%c${e}`,"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{$t!==!0&&(!$t||!$t.has(e))||r(`${e} ${o}`)}];default:return[t,(...o)=>{if(!($t!==!0&&(!$t||!$t.has(e))))return r(...o)}]}}));var fo=sh("ScrapBindings:mod.ts"),ji=class{constructor(t,r){this.target=t;this.onSequenceUpdate=r?.onSequenceUpdate,this.flushInterval=r?.flushInterval??1e3}bind(t,r){let o=new Map,n=[];for(let[s,i]of t instanceof Map?t.entries():typeof t=="string"?[[t,r]]:Object.entries(t)){let a=ih(s);if(!a.ok){for(let l of a.value)fo.error(`${s}: ${l.message}`);o.set(s,a.value);continue}let c=a.value;this.bindings.set(c,i),c.startsWith(this.currentSequence)&&this.filtered.add(c),n.push(c)}return fo.debug("Binded the following commands:",n),this.emitChange(),o}unbind(...t){for(let r of t){let o=ih(r);if(!o.ok)continue;let n=o.value;this.bindings.delete(n),this.filtered.delete(n)}this.emitChange()}reset(){this.bindings.clear(),this.emitChange()}bindings=new Map;onSequenceUpdate;flushInterval;_sequence="";set currentSequence(t){let r=this._sequence!==t;this._sequence=t,r&&this.onSequenceUpdate?.(t)}get currentSequence(){return this._sequence}prevBestMatchCommand;filtered=new Set;timer;backToInitial=()=>{clearTimeout(this.timer),this.currentSequence="",this.prevBestMatchCommand=void 0,this.filtered=new Set(this.bindings.keys()),fo.debug("reset the sequence")};handleKeydown=t=>{if(!t.isTrusted)return;let r=Ll(t);if(!r)return;if(clearTimeout(this.timer),t.isComposing){this.backToInitial();return}this.currentSequence+=r,fo.debug("sequence",this.currentSequence);let o;for(let s of this.filtered){if(s.startsWith(this.currentSequence)||this.filtered.delete(s),this.currentSequence!==s)continue;let i=this.bindings.get(s);if(!i){this.filtered.delete(s);continue}o=()=>{fo.debug(`run ${s}`);try{i(t)}catch(a){fo.error(a)}finally{this.backToInitial()}}}let n=this.filtered.size;if(fo.debug(`${n} candidates: ${[...this.filtered.keys()].join(", ")}`),n>0&&(this.prevBestMatchCommand=o),this.prevBestMatchCommand&&n<2){if(this.prevBestMatchCommand(),n===0){this.handleKeydown(t);return}return}if(n===0){this.backToInitial();return}t.preventDefault(),t.stopPropagation(),this.timer=setTimeout(this.prevBestMatchCommand??this.backToInitial,this.flushInterval)};emitChange=()=>{if(this.bindings.size===0){this.backToInitial(),this.target.removeEventListener("keydown",this.handleKeydown);return}this.target.addEventListener("keydown",this.handleKeydown)}},N_={name:"InvalidSequenceError",message:"cannot parse the sequence"},ih=e=>{let t=nh(e);if(!t)return{ok:!1,value:[N_]};let r="",o=[];for(let n of t){let s=oh(n);if(!s.ok){o.push(s.value);continue}r+=s.value}return o.length>0?{ok:!1,value:o}:{ok:!0,value:r}};var ah=()=>{if(scrapbox.Layout!=="page")return{selectionRange:{start:{line:0,char:0},end:{line:0,char:0}},selectedText:""};let{selectionRange:e,selectedText:t,position:r}=We();if(!t){let u=wl(r.line)??0,p={start:{line:r.line,char:0},end:{line:r.line+u,char:ot(r.line+u)?.length??0}};return{selectionRange:p,selectedText:scrapbox.Page.lines.slice(p.start.line,p.end.line+1).map(f=>f.text).join(`
`)}}let{start:o,end:n}=e,s=o.line>n.line,i=s?n.line:o.line,a=s?n.char:o.char,c=s?o.line:n.line,l=s?o.char:n.char;return{selectedText:t,selectionRange:{start:{line:i,char:a},end:{line:c,char:l}}}};var Nl=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(`
`),i=n.replaceAll("[","").replaceAll("]","").trim(),a=Math.min(...[n,...s].map(l=>br(l))),c=[`from [${t}]`,n.slice(a),...s.map(l=>l.slice(a))];return{text:`[${i}]`,pages:[{project:r,title:i,lines:c,mode:o}]}};Nl.hookName="default-hook";var Rr=e=>{let{project:t=scrapbox.Project.name,mode:r="newtab"}=e??{},o=[...e?.hooks??[],Nl],{selectionRange:{start:n,end:s},selectedText:i}=ah();if(!i||scrapbox.Layout!=="page")return;let a=(()=>{for(let p of o){let f=p(i,{title:scrapbox.Page.title,projectFrom:scrapbox.Project.name,projectTo:t,lines:mt().slice(n.line,s.line+1),mode:r});if(f)return[p.hookName,f]}})();if(!a)return;let[c,l]=a,u=async()=>{let p=l instanceof Promise?await l:l;if(p.pages.length===0&&p.text===i)return;let f,{render:m,dispose:h}=Le();try{if(p.pages.length>0){let y=p.pages.length;m({type:"spinner"},{type:"text",text:`Create new ${y} pages...`});let x=await Ve(e?.socket);if(B(x))throw re(x);f=H(x);let E=0;await Promise.all(p.pages.map(async k=>{let b=Array.isArray(k.lines)?v=>[...v.map(R=>R.text),...k.lines]:k.lines;await xe(k.project,k.title,b,{socket:f}),m({type:"spinner"},{type:"text",text:`Create ${y-++E} pages...`})}))}m({type:"spinner"},{type:"text",text:`${p.pages.length>0?"Created. ":""}Removing cut text...`});let g=p.text;if(i===g)return;await xe(scrapbox.Project.name,scrapbox.Page.title,y=>{let x=y.map(E=>E.text);return[...x.slice(0,n.line),...`${x[n.line].slice(0,n.char)}${g}${x.slice(s.line).join(`
`).slice(s.char)}`.split(`
`)]}),m({type:"check-circle"},{type:"text",text:"Removed."});for(let y of p.pages)switch(y.mode){case"self":y.project===scrapbox.Project.name?Kn(y.project,y.title):globalThis.open(`https://scrapbox.io/${y.project}/${me(y.title)}`,"_self");break;case"newtab":globalThis.open(`https://scrapbox.io/${y.project}/${me(y.title)}`);break}}catch(g){m({type:"exclamation-triangle"},{type:"text",text:"Failed to create new pages (see console)."}),console.error(g)}finally{let g=Te(1e3);f&&await rt(f),await g,h()}};return u.hookName=c,u};var C_=Math.pow(10,8)*24*60*60*1e3,$5=-C_,ch=6048e5,lh=864e5,Bi=6e4,ph=36e5;var A_=3600;var uh=A_*24,j5=uh*7,M_=uh*365.2425,I_=M_/12,B5=I_*3,Cl=Symbol.for("constructDateFrom");function he(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Cl in e?e[Cl](t):e instanceof Date?new e.constructor(t):new Date(t)}function W(e,t){return he(t||e,e)}var F_={};function ho(){return F_}function ft(e,t){let r=ho(),o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=W(e,t?.in),s=n.getDay(),i=(s<o?7:0)+s-o;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}function jr(e,t){let r=W(e,t?.in);return r.setHours(0,0,0,0),r}function Br(e,...t){let r=he.bind(null,e||t.find(o=>typeof o=="object"));return t.map(r)}function Hi(e,t){let[r,o]=Br(e,t.start,t.end);return{start:r,end:o}}function Wi(e,t){let{start:r,end:o}=Hi(t?.in,e),n=+r>+o,s=n?+r:+o,i=n?o:r;i.setHours(0,0,0,0);let a=t?.step??1;if(!a)return[];a<0&&(a=-a,n=!n);let c=[];for(;+i<=s;)c.push(he(r,i)),i.setDate(i.getDate()+a),i.setHours(0,0,0,0);return n?c.reverse():c}function dt(e,t,r){let[o,n]=Br(r?.in,e,t);return+jr(o)==+jr(n)}function kr(e,t){let r=e<0?"-":"",o=Math.abs(e).toString().padStart(t,"0");return r+o}var mh={y(e,t){let r=e.getFullYear(),o=r>0?r:1-r;return kr(t==="yy"?o%100:o,t.length)},M(e,t){let r=e.getMonth();return t==="M"?String(r+1):kr(r+1,2)},d(e,t){return kr(e.getDate(),t.length)},a(e,t){let r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(e,t){return kr(e.getHours()%12||12,t.length)},H(e,t){return kr(e.getHours(),t.length)},m(e,t){return kr(e.getMinutes(),t.length)},s(e,t){return kr(e.getSeconds(),t.length)},S(e,t){let r=t.length,o=e.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return kr(n,t.length)}};function fh(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Hr(e){return!(!fh(e)&&typeof e!="number"||isNaN(+W(e)))}var U_=/(\w)\1*|''|'(''|[^'])+('|$)|./g,D_=/^'([^]*?)'?$/,$_=/''/g,j_=/[a-zA-Z]/;function be(e,t){let r=W(e);if(!Hr(r))throw new RangeError("Invalid time value");let o=t.match(U_);return o?o.map(n=>{if(n==="''")return"'";let s=n[0];if(s==="'")return B_(n);let i=mh[s];if(i)return i(r,n);if(s.match(j_))throw new RangeError("Format string contains an unescaped latin alphabet character `"+s+"`");return n}).join(""):""}function B_(e){let t=e.match(D_);return t?t[1].replace($_,"'"):e}function Fe(e,t,r){let o=W(e,r?.in);return isNaN(t)?he(r?.in||e,NaN):(t&&o.setDate(o.getDate()+t),o)}function vr(e,t,r){return Fe(e,-t,r)}function Gi(e,t,r){return he(r?.in||e,+W(e)+t)}function Vi(e,t,r){return Gi(e,t*1e3,r)}function rn(e,t,r){return Fe(e,t*7,r)}function zi(e,t){return W(e,t?.in).getDate()}function qi(e,t){let r=W(e,t?.in),o=r.getFullYear(),n=ho(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=he(t?.in||e,0);i.setFullYear(o+1,0,s),i.setHours(0,0,0,0);let a=ft(i,t),c=he(t?.in||e,0);c.setFullYear(o,0,s),c.setHours(0,0,0,0);let l=ft(c,t);return+r>=+a?o+1:+r>=+l?o:o-1}function dh(e,t){let r=ho(),o=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=qi(e,t),s=he(t?.in||e,0);return s.setFullYear(n,0,o),s.setHours(0,0,0,0),ft(s,t)}function go(e,t){let r=W(e,t?.in),o=+ft(r,t)-+dh(r,t);return Math.round(o/ch)+1}function hh(e,t){return W(e,t?.in).getMonth()}function yo(e,t){return W(e,t?.in).getFullYear()}var gh=e=>{let t=new Map;for(let r of e){let o=`${yo(r)}-${hh(r)}-${zi(r)}`,n=t.get(o);n&&n.getTime()>r.getTime()||t.set(o,r)}return[...t.values()]};function yh(e,t,r){let o=W(e,r?.in);if(isNaN(t))return he(r?.in||e,NaN);if(!t)return o;let n=o.getDate(),s=he(r?.in||e,o.getTime());s.setMonth(o.getMonth()+t+1,0);let i=s.getDate();return n>=i?s:(o.setFullYear(s.getFullYear(),s.getMonth(),n),o)}function xh(e,t,r){let{years:o=0,months:n=0,weeks:s=0,days:i=0,hours:a=0,minutes:c=0,seconds:l=0}=t,u=W(e,r?.in),p=n||o?yh(u,n+o*12):u,f=i||s?Fe(p,i+s*7):p,m=c+a*60,h=(l+m*60)*1e3;return he(r?.in||e,+f+h)}function bh(e,t){let r=W(e,t?.in),o=r.getFullYear(),n=r.getMonth(),s=he(r,0);return s.setFullYear(o,n+1,0),s.setHours(0,0,0,0),s.getDate()}function Eh(e,t,r){let o=W(e,r?.in),n=o.getFullYear(),s=o.getDate(),i=he(r?.in||e,0);i.setFullYear(n,t,15),i.setHours(0,0,0,0);let a=bh(i);return o.setMonth(t,Math.min(s,a)),o}function wh(e,t,r){let o=W(e,r?.in);return isNaN(+o)?he(r?.in||e,NaN):(t.year!=null&&o.setFullYear(t.year),t.month!=null&&(o=Eh(o,t.month)),t.date!=null&&o.setDate(t.date),t.hours!=null&&o.setHours(t.hours),t.minutes!=null&&o.setMinutes(t.minutes),t.seconds!=null&&o.setSeconds(t.seconds),t.milliseconds!=null&&o.setMilliseconds(t.milliseconds),o)}function Rh(e,t){return W(e,t?.in).getMinutes()}function Wr(e,t,r){let o=W(e,r?.in);return o.setTime(o.getTime()+t*Bi),o}function kh(e){return t=>{let r=(e?Math[e]:Math.trunc)(t);return r===0?0:r}}function vh(e,t){return+W(e)-+W(t)}function Yn(e,t,r){let o=vh(e,t)/Bi;return kh(r?.roundingMethod)(o)}function _h(e,t){return W(e,t?.in).getHours()}function Th(e,t,r){return Gi(e,t*ph,r)}function Ph(e,t){let r=W(e,t?.in);return r.setHours(23,59,59,999),r}function Al(e){let t=W(e),r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return r.setUTCFullYear(t.getFullYear()),+e-+r}function Sh(e,t,r){let[o,n]=Br(r?.in,e,t),s=jr(o),i=jr(n),a=+s-Al(s),c=+i-Al(i);return Math.round((a-c)/lh)}function Oh(e,t,r){return rn(e,-t,r)}function Lh(e,t,r){let o=W(e,r?.in),n=go(o,r)-t;return o.setDate(o.getDate()-n*7),W(o,r?.in)}function Nh(e,t){let{start:r,end:o}=Hi(t?.in,e),n=+r>+o,s=n?ft(o,t):ft(r,t),i=n?ft(r,t):ft(o,t);s.setHours(15),i.setHours(15);let a=+i.getTime(),c=s,l=t?.step??1;if(!l)return[];l<0&&(l=-l,n=!n);let u=[];for(;+c<=a;)c.setHours(0),u.push(he(r,c)),c=rn(c,l),c.setHours(15);return n?u.reverse():u}function Ch(e,t,r){let[o,n]=Br(r?.in,e,t),s=o.getFullYear()-n.getFullYear(),i=o.getMonth()-n.getMonth();return s*12+i}function Ah(e,t){let r=+W(e)-+W(t);return r<0?-1:r>0?1:r}function xo(e,t){return+W(e)>+W(t)}var Mh=e=>e==null,Gr=e=>typeof e=="string";async function*Ih(e){let t=[],r,o=i=>{if(!r){t.push(i);return}r(i),r=void 0},n=()=>t.length>0?Promise.resolve(t.pop()):new Promise(i=>r=i),s=0;for(let i of e)i.then(a=>o({state:"fulfilled",value:a})).catch(a=>o({state:"rejected",reason:a})),s++;for(let i=0;i<s;i++)yield await n()}var at=e=>{let t=e.match(/^`(\d{4})-(\d{2})-(\d{2}) (?: {5}|(\d{2}):(\d{2})) (?: {4}|(\d{4})) (?: {8}|(\d{2}):(\d{2}):(\d{2})) (?: {8}|(\d{2}):(\d{2}):(\d{2}))`([^\n]*)$/);if(!t)return;let[,r,o,n,s,i,a,c,l,u,p,f,m,h]=t,g={title:h,base:new Date(parseInt(r),parseInt(o)-1,parseInt(n)),plan:{},record:{}};if(s){let y=new Date(g.base);y.setHours(parseInt(s)),y.setMinutes(parseInt(i)),g.plan.start=y}if(a&&(g.plan.duration=parseInt(a)*60),c){let y=new Date(g.base);y.setHours(parseInt(c)),y.setMinutes(parseInt(l)),y.setSeconds(parseInt(u)),g.record.start=y}if(p){let y=new Date(g.base);y.setHours(parseInt(p)),y.setMinutes(parseInt(f)),y.setSeconds(parseInt(m)),g.record.start&&xo(g.record.start,y)&&y.setDate(y.getDate()+1),g.record.end=y}return g};var on=e=>e.record?.start??e.plan?.start??e.base,Fh=e=>e.record?.end??(Mh(e.plan?.duration)?e.base:Vi(on(e),e.plan.duration));var Pe=({title:e,base:t,plan:r,record:o})=>["`",be(t,"yyyy-MM-dd")," ",r?.start?be(r.start,"HH:mm"):" ".repeat(5)," ",r?.duration?`${r.duration/60}`.padStart(4,"0"):" ".repeat(4)," ",o?.start?be(o?.start,"HH:mm:ss"):" ".repeat(8)," ",o?.end?be(o?.end,"HH:mm:ss"):" ".repeat(8),"`",e].join("");function*Uh(e){for(let t of bo(e))Gr(t)||(yield t)}function*bo(e){for(let t=0;t<e.length;t++){let r=e[t],o=Gr(r)?r:r.text,n=mo(t,e),s=at(o);if(!s){yield o;continue}yield{...s,lines:e.slice(t+1,t+1+n).map(i=>Gr(i)?i:i.text)},t+=n}}var H_=5*60,Ml=async()=>{let e=We().position.line,t=at(ot(e)??""),r=t?.base??new Date,o={start:t?.plan?.start?Vi(t.plan.start,H_+(t.plan.duration??0)):void 0,duration:t?.plan?.duration};await jd(e+1,Pe({title:"",base:r,plan:o,record:{}}))};var Ki=async()=>{let e=We().position.line,t=at(ot(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;o||await Rt(e,e,Pe({record:{start:r?void 0:new Date},...n}))};var nn=async()=>{let e=We().position.line,t=at(ot(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;r&&await Rt(e,e,Pe({record:{start:r,end:o?void 0:new Date},...n}))};var Il=async()=>{let e=We().position.line,t=at(ot(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;if(r){if(o)return;await nn();return}if(o)return;let s;for(let{text:a}of wr().slice(0,(e??0)+1).reverse()){let{record:c}=at(a)??{};if(c?.end){s=c.end;break}}let i=new Date;await Rt(e,e,Pe({record:{start:s??i,end:i},...n}))};var Eo=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=We();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var Fl=(e,t=7)=>new Date((e+2592e3*((t+1)**1.5-1)/5221.154823442138)*1e3);var Ul=(e,t)=>{let r,o,n,s,i=null;if(i=e.match(/^(.*?)(s|e):([^\s]+)\s+d:(\d+)/))[,o,s,n,r]=i;else if(i=e.match(/^(.*?)d:(\d+)\s+(s|e):([^\s]+)/))[,o,r,s,n]=i;else if(i=e.match(/^(.*?)(s|e):([^\s]+)/))[,o,s,n]=i;else return(i=e.match(/^(.*?)d:(\d+)/))?([,o,r]=i,{name:o.trimEnd(),duration:parseInt(r)*60}):void 0;for(let{test:a,parse:c}of W_){let l=n.match(a);if(!l)continue;let u=c(l),p=u.isDuration?xh(t,u):wh(t,u);return s==="s"?{name:o.trimEnd(),start:p,...r!==void 0?{duration:parseInt(r)*60}:{}}:{name:o.trimEnd(),start:Fl(t.getTime()/1e3,(p.getTime()-t.getTime())/(24*60*60*1e3)),...r!==void 0?{duration:parseInt(r)*60}:{}}}},W_=[{test:/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3]),hours:parseInt(e[4]),minutes:parseInt(e[5])})},{test:/(\d{4})-(\d{2})-(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3]),hours:parseInt(e[4])})},{test:/(\d{4})-(\d{2})-(\d{2})T?$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3])})},{test:/(\d{2})-(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2]),hours:parseInt(e[3]),minutes:parseInt(e[4])})},{test:/(\d{2})-(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2]),hours:parseInt(e[3])})},{test:/(\d{2})-(\d{2})T?$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2])})},{test:/(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,date:parseInt(e[1]),hours:parseInt(e[2]),minutes:parseInt(e[3])})},{test:/(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,date:parseInt(e[1]),hours:parseInt(e[2])})},{test:/T?(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,hours:parseInt(e[1]),minutes:parseInt(e[2])})},{test:/T?(\d{2})$/i,parse:e=>({isDuration:!1,hours:parseInt(e[1])})},{test:/P(\d+)Y(\d+)M(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3]),hours:parseInt(e[4]),minutes:parseInt(e[5])})},{test:/P(\d+)Y(\d+)M(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3]),hours:parseInt(e[4])})},{test:/P(\d+)Y(\d+)M(\d+)D$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3])})},{test:/P(\d+)M(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2]),hours:parseInt(e[3]),minutes:parseInt(e[4])})},{test:/P(\d+)M(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2]),hours:parseInt(e[3])})},{test:/P(\d+)M(\d+)D$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2])})},{test:/P(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,days:parseInt(e[1]),hours:parseInt(e[2]),minutes:parseInt(e[3])})},{test:/P(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,days:parseInt(e[1]),hours:parseInt(e[2])})},{test:/P(\d+)D$/i,parse:e=>({isDuration:!0,days:parseInt(e[1])})},{test:/PT?(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,hours:parseInt(e[1]),minutes:parseInt(e[2])})},{test:/PT?(\d+)H$/i,parse:e=>({isDuration:!0,hours:parseInt(e[1])})},{test:/PT?(\d+)M$/i,parse:e=>({isDuration:!0,minutes:parseInt(e[1])})},{test:/P(\d+)W$/i,parse:e=>({isDuration:!0,weeks:parseInt(e[1])})}];var Jn=async()=>{let e=new Date,[t,r]=Eo(),o=wr().slice(t,r+1).map(s=>s.text),n=o.flatMap(s=>{let i=s.trimEnd();if(i==="")return s;let{name:a,start:c,duration:l}=Ul(i,e)??{};return!a||!c&&!l?s:[Pe({title:a.trim(),base:c??e,plan:{start:c,duration:l},record:{}})]}).join(`
`);o.join(`
`)!==n&&await Rt(t,r,n)};var Xi=async(e,t,r)=>{let o=[];for(let n=e;n<=t;n++){let s=ot(n)??"",i=at(s);if(!i){o.push(s);continue}o.push(Pe(r(i,n)))}await Rt(e,t,o.join(`
`))};var Dl=async(e=1)=>{let[t,r]=Eo();await Xi(t,r,o=>(o.base=Fe(o.base,e),o))};var $l=async()=>{let[e,t]=Eo(),r=new Date;await Xi(e,t,o=>(dt(o.base,r)||(o.base=r),o))};var G_="日刊記録sheet",V_=/日刊記録sheet (\d{4})-(\d{2})-(\d{2})/,Qn=["[** 00:00 - 03:00] 未明","[** 03:00 - 06:00] 明け方","[** 06:00 - 09:00] 朝","[** 09:00 - 12:00] 昼前","[** 12:00 - 15:00] 昼過ぎ","[** 15:00 - 18:00] 夕方","[** 18:00 - 21:00] 夜のはじめ頃","[** 21:00 - 00:00] 夜遅く"];var jl=e=>{let t=e.match(V_);if(!t)return;let[,r,o,n]=t,s=new Date(parseInt(r),parseInt(o)-1,parseInt(n));return Hr(s)?s:void 0},Vr=e=>be(e,`'${G_}' yyyy-MM-dd`),wo=e=>{let t=jl(e[0]);if(!t)return e;let r=z_(t),o=[],n=[];for(let a of bo(e.slice(1))){if(typeof a=="string"){if(Qn.includes(a)||r!==""&&r===a)continue;n.push(a);continue}o.push(a)}let s=o.sort((a,c)=>Ah(on(a),on(c)));if(s.length===0)return[e[0],r,...Qn,...n];let i=[0,0,0,0,0,0,0,0];for(let a=1;a<Qn.length;a++){let c=Th(new Date(t.getFullYear(),t.getMonth(),t.getDate()),3*a),l=s.findIndex(m=>xo(on(m),c));if(l<0){i[a]=-1;continue}if(l===0)continue;let u=s[l-1],p=on(u),f=Fh(u);i[a]=(f.getTime()-p.getTime())/2<c.getTime()-p.getTime()?l:l-1}return[e[0],r,...s.flatMap((a,c)=>[...i.flatMap((l,u)=>l===c?[Qn[u]]:[]),Pe(a),...a.lines]),...i.flatMap((a,c)=>a===-1?[Qn[c]]:[]),...n]},z_=e=>`yesterday: [${Vr(vr(e,1))}]`;var Bl=async(e,t)=>{let r=()=>{},o=setTimeout(()=>{let{render:n,dispose:s}=Le();r=s,n({type:"spinner"},{type:"text",text:"formatting..."})},500);await xe(e,t,n=>wo(n.map(s=>s.text))),clearTimeout(o),r()};async function*Hl(e,t,r){let o=[...t],n=[];for(;o.length>0;){let s=o.shift();if(!s)break;let i=s.base,a=[s];for(let c=0;c<o.length;c++)dt(o[c].base,i)&&(a.push(...o.splice(c,1)),c--);n.push((async()=>(await xe(e,Vr(i),c=>wo([...c.map(l=>l.text),...a.flatMap(l=>[Pe(l),...l.lines??[]])]),r),{date:i,size:a.length}))())}yield*Ih(n)}var Zn=async({from:{project:e,title:t},to:r})=>{let o=await Dt(e,t);if(B(o))throw re(o);let n=jl(t),{lines:s}=H(o),i=[];for(let p of Uh(s))n&&dt(p.base,n)||i.push(p);let{render:a,dispose:c}=Le();a({type:"spinner"},{type:"text",text:`copying ${i.length} tasks...`});let l=await Ve();if(B(l))throw re(l);let u=H(l);try{let p=0,f=!1;for await(let m of Hl(r,i,{socket:u})){if(m.state!=="fulfilled"){console.error(m.reason),f=!0;continue}p+=m.value.size,a({type:"spinner"},{type:"text",text:`copying ${i.length-p} tasks...`})}if(f){a({type:"exclamation-triangle"},{type:"text",text:"Some tasks failed to be written"});return}a({type:"spinner"},{type:"text",text:`Copied. removing ${i.length} original tasks...`}),await xe(e,t,m=>{let h=[];for(let g of bo(m)){if(Gr(g)){h.push(g);continue}n&&dt(g.base,n)&&h.push(Pe(g),...g.lines)}return h},{socket:u}),a({type:"check-circle"},{type:"text",text:"Moved"})}finally{await rt(u),await Te(1e3),c()}};var Dh=e=>typeof e=="string";var zr=e=>e.match(/^(\s*)/)?.[1]?.length??0,jh=(e,t)=>{let r=zr($h(e,t)),o=0;for(;e+o+1<t.length&&zr($h(e+o+1,t))>r;)o++;return o},$h=(e,t)=>{let r=t[e];return Dh(r)?r:r.text};var Yt=e=>`${e}`.padStart(2,"0");var Ro=e=>"hours"in e,jt=(e,t)=>e.year!==t.year?e.year<t.year:e.month!==t.month?e.month<t.month:e.date!==t.date?e.date<t.date:"hours"in t?"hours"in e?e.hours*60+e.minutes<t.hours*60+t.minutes:0<t.hours*60+t.minutes:!1,sr=e=>`${`${e.year}`.padStart(4,"0")}-${Yt(e.month)}-${Yt(e.date)}${"hours"in e?`T${Yt(e.hours)}:${Yt(e.minutes)}`:""}`,ge=e=>{let t=sr(e);return new Date(t.includes("T")?t:`${t}T00:00`)},xt=e=>({year:e.getFullYear(),month:e.getMonth()+1,date:e.getDate(),hours:e.getHours(),minutes:e.getMinutes()});var Hh=e=>{switch(e.toLowerCase()){case"y":return"yearly";case"m":return"monthly";case"w":return"weekly";case"d":return"daily";default:return}};var Wh=e=>{switch(e){case"+":return"todo";case"-":return"note";case"!":return"deadline";case".":return"done";case"~":return"up-down";default:return}},Gh=e=>{switch(e){case"todo":return"+";case"note":return"-";case"deadline":return"!";case"done":return".";case"up-down":return"~"}};var ir=e=>{let t=e.match(/(?:([\+\-!~.])(\d+)?)?@(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}))?(?:\/(\d{2}):(\d{2})|\/(?:(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)|D(\d+))?(?:R([YMWD])?(\d+))?(?:@(?:(\d{2}):(\d{2})|(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)?(?:\/(\d{2}):(\d{2})|\/(?:(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)|D(\d+))?)?/i);if(!t)return;let[r,o,n,s,i,a,c,l,u,p,f,m,h,g,y,x,E,k,b,v,R,O,L,N,P,_,T,S,A,M,D,I,z]=t,$=`${e.slice(0,t.index).trim()}${e.slice((t.index??0)+r.length).trim()}`,q=Vh(s,i,a,c,l);if(!Hr(ge(q)))return Q({name:"InvalidDateError",message:`The reference point of the task "${sr(q)}" is an invalid date.`});let K=zh(q,f,m,h,u||g,p||y,x);if(K!==void 0){if(Ke(K)&&isNaN(K)||!Ke(K)&&!Hr(ge(K)))return Q({name:"InvalidDateError",message:`The estimated end of the task${Ke(K)?"":` "${sr(K)}"`} is an invalid date.`});if(Ke(K)&&K<0||!Ke(K)&&jt(K,q))return Q({name:"TaskRangeError",message:`The reference point of an task cannot be after its estimated end.
reference point:${sr(q)}
estimated end:${sr(Ke(K)?xt(Wr(ge(q),K)):K)}`})}let ce=/^[\uFE00-\uFE0F]*[✅❌]/.test(e)?"done":Wh(o),ee=ce?{status:ce,refDate:q}:void 0;ee&&n&&(ee.speed=parseInt(n));let tt=Vh(R||s,O||i,L||a,b||N||c,v||P||l);if(!Hr(ge(tt)))return Q({name:"InvalidDateError",message:`The start of the task/event "${sr(tt)}" is an invalid date.`});let Oe=zh(tt,S||f,A||m,M||h,_||D||u||g,T||I||p||y,z||x),U=Ro(tt)&&Ke(Oe)?{start:tt,duration:Oe}:void 0;if(U){let ct={name:$,executed:U,generated:!1,raw:e};return ee&&(ct.freshness=ee),(E||k)&&(ct.recurrence={frequency:Hh(E??"D")??"daily",count:k?parseInt(k):1}),ae(ct)}if(!ee)return Q({name:"InvalidDateError",message:"Task requires freshness to be spec"});let we={name:$,freshness:ee,generated:!1,raw:e};return K&&(we.estimated=K),ae(U?{...we,executed:U}:we)},ar=e=>!("executed"in e),qr=e=>"recurrence"in e,qh=e=>!("executed"in e||"freshness"in e&&Ro(e.freshness.refDate)&&e.estimated&&(Ke(e.estimated)||Ro(e.estimated))),ts=e=>"executed"in e?e.executed.duration:Ke(e.estimated)?e.estimated:void 0,cr=e=>ar(e)?e.freshness.refDate:e.executed.start,Kh=e=>{if(!ar(e)){let r=ge(e.executed.start);return xt(Wr(r,e.executed.duration))}if(Ke(e.estimated)&&Ro(e.freshness.refDate)){let r=ge(e.freshness.refDate);return xt(Wr(r,e.estimated))}let t=ge(Ke(e.estimated)?e.freshness.refDate:e.estimated??e.freshness.refDate);return t.setHours(0),t.setMinutes(0),xt(Fe(t,1))},Q_=e=>{let t=e.freshness?`${Gh(e.freshness.status)}${e.freshness.speed??""}`:"",r=`${sr(cr(e))}`,o=ts(e);return`${t}@${r}${o===void 0?"":`D${o}`}${e.name}`},Yi=(e,t)=>{let r=xt(t),{recurrence:o,executed:n}=e;switch(o.frequency){case"yearly":{if(Math.abs(r.year-n.start.year)%(o.count??1)!==0||n.start.month!==r.month||n.start.date!==r.date)return;break}case"monthly":{if(Ch(ge(r),ge(n.start))%(o.count??1)!==0)return;break}case"weekly":case"daily":{let a=o.frequency==="weekly"?7:1;if(Sh(ge(r),ge(n.start))%((o.count??1)*a)!==0)return;break}}let s={...n.start};s.year=r.year,s.month=r.month,s.date=r.date;let i={name:e.name,executed:{start:s,duration:n.duration},generated:!0,raw:e.raw};return e.freshness&&(i.freshness=e.freshness),i},Ji=e=>e.freshness?e.generated?Q_(e):e.raw:e.generated?void 0:e.raw,Vh=(e,t,r,o,n)=>{let s=parseInt(e),i=parseInt(t),a=parseInt(r),c=o?parseInt(o):void 0,l=n?parseInt(n):void 0;return c!==void 0&&l!==void 0?{year:s,month:i,date:a,hours:c,minutes:l}:{year:s,month:i,date:a}},zh=(e,t,r,o,n,s,i)=>{if(!t&&!r&&!o&&!n&&!s&&!i)return;if(i)return parseInt(i);let a=t?parseInt(t):e.year,c=r?parseInt(r):e.month,l=o?parseInt(o):e.date,u=n?parseInt(n):void 0,p=s?parseInt(s):void 0,f=u!==void 0&&p!==void 0?{year:a,month:c,date:l,hours:u,minutes:p}:{year:a,month:c,date:l};return!Ro(e)||!Ro(f)?f:Math.round((ge(f).getTime()-ge(e).getTime())/(60*1e3))};var rs=(e,t)=>{if(!e.generated&&qr(e)){let s=Yi(e,t);return s?rs(s,t):void 0}let r=ge(ar(e)?e.freshness.refDate:e.executed.start),o=ts(e),n=Ji(e);return{title:n!==void 0?`[${n}]`:e.name,base:r,plan:{start:qh(e)?void 0:r,duration:o!==void 0?o*60:void 0},record:{}}};var Wl={あさごはん:"#log-breakfast",ひるごはん:"#log-lunch",よるごはん:"#log-dinner"},ko=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(`
`),i=at(n);if(!i)return;if(s.length===0)return{text:e,pages:[]};let{title:a,base:c,record:l,...u}=i,p=Z_(a,c,l),f=Pe({title:`[${p}]`,base:c,record:l,...u}),m=Math.min(...s.map(g=>zr(g))),h=[.../[\[\]]/.test(a)&&a!==`[${p}]`?[a]:[],...t in Wl?[...s.map(g=>g.slice(m)),"",Wl[t],"#log-eatenfood"]:[...s.map(g=>` ${g.slice(m)}`),""]];return{text:f,pages:[{project:r,title:p,lines:Xh(t,h,[l.start??c]),mode:o}]}};ko.hookName="task-hook";var Z_=(e,t,r)=>{let o=be(r.start??t,"yyyy-MM-dd");if(e in Wl)return`${o} ${e}`;if(ir(e.slice(1,-1)))return e.slice(1,-1);let n=e.replace(/[\[\]]/g,"").trim();return`${n}${n.endsWith(o)?"":` ${o}`}`},vo=(e,{title:t,projectTo:r,mode:o,lines:n})=>{let[s,...i]=e.split(`
`);if(i.length===0)return;let a=s.replace(/[\[\]]/g,"").trim(),c=Math.min(...i.map(p=>zr(p))),l=r.startsWith("takker")?gh([new Date,...n.map(({updated:p})=>new Date(p*1e3))]).sort((p,f)=>f.getTime()-p.getTime()):[],u=["",.../[\[\]]/.test(s)?[s.trimStart()]:[],...i.map(p=>p.slice(c))];return{text:`${" ".repeat(zr(s))}[${a}]`,pages:[{project:r,title:a,lines:Xh(t,u,l),mode:o}]}};vo.hookName="new-page-hook";var _o=(e,{projectTo:t,mode:r})=>{if(e.includes(`
`)||!/\[[^\]]+\]/.test(e))return;let[o,n]=e.match(/^(\s*)(.*)$/)?.slice?.(1)??["",e],s=[...n.matchAll(/\[([^\]])\]/g)].map(a=>ne(a[1])),i=n.replaceAll("[","").replaceAll("]","");return{text:`${o}[${i}]`,pages:[{project:t,title:i,lines:(a,{links:c})=>{let l=c.map(u=>ne(u));if(!s.every(u=>l.includes(u)))return[...a.map(u=>u.text),n]},mode:r}]}};_o.hookName="splitted-link-hook";var Xh=(e,t,r)=>(o,{links:n})=>{let s=n.map(p=>ne(p)),i=s.includes(ne(e))?[]:[`from [${e}]`],a=r.flatMap(p=>{let f=be(p,"yyyy-MM-dd");if(s.includes(f))return[];let m=be(p,"HH:mm:ss");return[`#${f} ${m}`]}),c=o.map(p=>p.text),l=c.findIndex(p=>/^#\d{4}-\d{2}-\d{2}/.test(p)),u=l<0?c.length:l;return[...c.slice(0,u),...i,...t,"",...a,...c.slice(u)]};var Yh=e=>e.preventDefault(),Jh=e=>e.stopPropagation(),Qh={"<A-a><A-c>":async e=>{Yh(e),Jh(e);let[t,r]=eT(),o=wr().slice(t,r+1).map(n=>{let s=n.text,i=n.text.match(/\[([^\]]+)\]/)?.[1];if(!i)return s;let a=ir(i);if(!a||G(a))return s;let c=X(a);if(c.freshness?.status==="done")return s;let l=rs(c,new Date);return l?(l.title=`[${i}]`,Pe(l)):s}).join(`
`);await Rt(t,r,o),await Jn()},"<A-a><A-m>":e=>{scrapbox.Layout==="page"&&(Yh(e),Jh(e),Zn({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"}))}},eT=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=We();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var To=e=>e.preventDefault(),Po=e=>e.stopPropagation(),Gl={"<A-a><A-a>":e=>{To(e),Po(e),Ml()},"<A-a><A-s>":e=>{To(e),Po(e),Ki()},"<A-a><A-e>":e=>{To(e),Po(e),nn()},"<A-a><A-0>":e=>{To(e),Po(e),Il()},"<A-a><A-1>":e=>{To(e),Po(e),Dl(1)},"<A-a><A-t>":e=>{To(e),Po(e),$l()},"<A-a><A-S>":e=>{scrapbox.Layout==="page"&&(To(e),Po(e),Bl(scrapbox.Project.name,scrapbox.Page.title))}};var Je=e=>e.preventDefault(),Qe=e=>e.stopPropagation(),So=(e,t)=>{let r=Pd()?.getElementsByClassName?.("button");if(!r)return;let o=[...r].find(n=>t instanceof RegExp?t.test(n.textContent??""):n.textContent===t);o instanceof HTMLDivElement&&e.target===document.activeElement&&(Je(e),Qe(e),o.click())},tT={"-":e=>So(e,""),"]":e=>So(e,""),c:e=>So(e,"Copy plain"),$:e=>So(e,""),"{":e=>So(e,/{{c\d+}}/),"}":e=>So(e,"reset cloze"),n:e=>So(e,"make note")},rT={"<C-]>":e=>{let{position:{line:t,char:r}}=We(),o=qn(t,r)?.closest("a.page-link")??Er(t)?.querySelector?.("a.page-link");o instanceof HTMLAnchorElement&&(Je(e),Qe(e),o.click())},"<C-o>":e=>{Je(e),Qe(e),history.back()}},oT={"<C-home>":e=>{Je(e),Qe(e),Id()},"<C-end>":e=>{Je(e),Qe(e),Fd()}},Zh=[ko,vo,_o],nT={"<C-X>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(Je(e),Qe(e),Rr({project:t,mode:"self",hooks:Zh})?.())},"<C-D>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(Je(e),Qe(e),Rr({project:t,mode:"noopen",hooks:Zh})?.())},"<C-h>":e=>{Je(e),Qe(e),Si()},"<C-j>":e=>{Je(e),Qe(e),Li()},"<C-k>":e=>{Je(e),Qe(e),Oi()},"<C-l>":e=>{Je(e),Qe(e),Pi()},"<A-h>":e=>{Je(e),Qe(e),Ci()},"<A-j>":e=>{Je(e),Qe(e),Mi()},"<A-k>":e=>{Je(e),Qe(e),Ai()},"<A-l>":e=>{Je(e),Qe(e),Ni()}};scrapbox.TimeStamp.removeAllFormats();var sT={"<A-t><A-t>":e=>{Je(e),Qe(e),Ye(be(new Date,"#yyyy-MM-dd HH:mm:ss "))},"<A-t><A-j>":e=>{Je(e),Qe(e),Ye(be(new Date,"yyyy-MM-dd HH:mm:ss "))},"<A-t><A-k>":e=>{Je(e),Qe(e),Ye(be(new Date,"HH:mm:ss "))},"<A-t><A-l>":e=>{Je(e),Qe(e),Ye(be(new Date,"yyyy-MM-dd"))}},eg={...tT,...rT,...oT,...nT,...sT,...Qh};var{render:iT}=Le(),Vl,aT=e=>{Vl!==void 0&&cancelAnimationFrame(Vl),Vl=requestAnimationFrame(()=>iT({type:"text",text:e}))},zl=new ji({addEventListener:Wd,removeEventListener:Ol},{onSequenceUpdate:aT}),tg=zl.bind({...eg,...scrapbox.Project.name==="takker-memex"?Gl:{}});tg.size>0&&alert([...tg.entries()].map(([e,t])=>`${e}:
${t.map(r=>`- ${r}`).join(`
`)}`).join(`
`));var cT=/https?:\/\/vimeo\.com\/([0-9]+)/i,rg=e=>{let t=e.match(cT);if(t)return t[1]};var lT=/https?:\/\/open\.spotify\.com\/(track|artist|playlist|album|episode|show)\/([a-zA-Z\d_-]+)(?:\?[^\s]{0,100}|)/,og=e=>{let t=e.match(lT);if(!t)return;let[,r,o]=t;return{videoId:o,pathType:r}};var pT=/https?:\/\/anchor\.fm\/[a-zA-Z\d_-]+\/episodes\/([a-zA-Z\d_-]+(?:\/[a-zA-Z\d_-]+)?)(?:\?[^\s]{0,100}|)/,ng=e=>{let t=e.match(pT);if(!t)return;let[,r]=t;return r};var sg=e=>{let{type:t,pathType:r,content:o,href:n,...s}=e;if(o===""){let i=ci(n);if(i)return{type:"youtube",href:n,...i,...s};let a=rg(n);if(a)return{type:"vimeo",videoId:a,href:n,...s};let c=og(n);if(c)return{type:"spotify",href:n,...c,...s};let l=ng(n);if(l)return{type:"anchor-fm",videoId:l,href:n,...s};if(mT(n))return{type:"video",href:n,...s}}return uT(n)?{type:"audio",content:o,href:n,...s}:{type:"absoluteLink",content:o,href:n,...s}},uT=e=>/\.(?:mp3|ogg|wav|aac)$/.test(e),mT=e=>/\.(?:mp4|webm)$/.test(e);var ig=async()=>{let e=localStorage.getItem("projectsLastAccessed");if(!e)return[];try{let t=JSON.parse(e),r=Object.entries(t).sort(([,s],[,i])=>i-s).map(([s])=>s),o=await ai([]);if(B(o))return r;let n=H(o).projects.map(s=>s.id);return r.filter(s=>!n.includes(s))}catch(t){if(!(t instanceof SyntaxError))throw t;return[]}};var fT;(e=>{})(fT||={});var dT="0.13.3",ql,Kl,ag=(e=dT)=>{let t=`https://cdnjs.cloudflare.com/ajax/libs/KaTeX/${e}/katex.min.js`;if(Kl)throw Kl;if(!document.querySelector(`script[src="${t}"]`)){let r=document.createElement("script");r.src=t,ql=new Promise((o,n)=>{r.onload=()=>o(window.katex),r.onerror=s=>{Kl=s,n(s)},document.head.append(r)})}return ql||new Promise(r=>{let o=setInterval(()=>{window.katex&&(clearInterval(o),r(window.katex))},500)})};var Qi=(e,t)=>{let[r,o]=J("");return{ref:F(s=>{if(!s){o("");return}ag().then(i=>{try{i.render(e,s,t),o("")}catch(a){if(a instanceof Error&&a.name==="ParseError")o(a.message.slice(19));else throw a}})},[e,...Object.values(t??{})]),error:r}};var cg=e=>{let t=[],r=new Set,o=n=>{r.delete(n);let s=t.pop();if(!s)return;let i=s[0]().finally(()=>o(i)).then(a=>s[1](a)).catch(a=>s[2](a));r.add(i)};return n=>{if(r.size<e){let s=n().finally(()=>o(s));return r.add(s),s}return new Promise((s,i)=>{t.push([n,s,i])})}};var hT="0.6.5",ug=`ScrapBubble-${hT}`,lg=await globalThis.caches.open(ug);(async()=>{for(let e of await globalThis.caches.keys())e.startsWith("ScrapBubble-")&&e!==ug&&(await globalThis.caches.delete(e),console.log(`[ScrapBubble] deleted old cache :"${e}"`))})();var pg=cg(3);async function*Zi(e,t){let r=((t?.saveFailedResponse?lg.match(e):void 0)??tn(e,t)).then(i=>["cache",i]);{let i=Te(1e3).then(()=>"timeout"),a=await Promise.race([r,i]);if(a!=="timeout"){a[1]&&(yield["cache",a[1]]);let c=await pg(()=>fetch(e));!c.ok&&t?.saveFailedResponse&&await lg.put(e,c.clone()),yield["network",c]}}let o=pg(()=>fetch(e)).then(i=>["network",i]),[n,s]=await Promise.race([r,o]);if(n==="network"){yield[n,s];return}s&&(yield[n,s]),yield await o}var mg=(e,t)=>new Date(e.headers.get("Date")??0).getTime()/1e3+t<new Date().getTime()/1e3;var ea=()=>{let e=new Map;return{dispatch:(t,r)=>{let o=e.get(t);if(o)for(let n of o)n(r)},on:(t,r)=>{let o=e.get(t)??new Set;o.add(r),e.set(t,o)},off:(t,r)=>{let o=e.get(t);o&&o.delete(r)}}};var Nt=!1,fg=e=>{Nt=typeof e=="boolean"?e:new Set(e)},Kr=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...o)=>r(`%c${e}`,"color: gray",...o)];case"log":case"info":case"debug":return[t,(...o)=>{Nt!==!0&&(!Nt||!Nt.has(e))||r(`%c${e}`,"color: gray",...o)}];case"assert":return[t,(o,...n)=>{Nt!==!0&&(!Nt||!Nt.has(e))||r(o,`%c${e}`,"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{Nt!==!0&&(!Nt||!Nt.has(e))||r(`${e} ${o}`)}];default:return[t,(...o)=>{if(!(Nt!==!0&&(!Nt||!Nt.has(e))))return r(...o)}]}}));var Xl=ea(),ta=new Map,gT=Kr("ScrapBubble:useProject.ts"),dg=e=>{let[t,r]=J();return oe(()=>{Xl.on(e,r);let o=ta.get(e);return o?r(o.loading?void 0:o.value):(ta.set(e,{loading:!0}),r(void 0),(async()=>{try{let n=gr.toRequest(e);for await(let[,s]of Zi(n)){let i=await gr.fromResponse(s);ta.set(e,{loading:!1,value:i}),Xl.dispatch(e,i);break}}catch(n){gT.error(n),ta.delete(e)}})()),()=>Xl.off(e,r)},[e]),t};var yT=["default-light","default-dark","default-minimal"],xT=["paper-light","paper-dark-dark","paper-dark"],hg=["blue","purple","green","orange","red"],bT=["hacker1","hacker2"],gg=["winter","spring","summer","automn"],yg=["tropical"],xg=["kyoto","newyork","paris"],bg=["mred","lgreen"],bie=["default-light","default-minimal","paper-light",...hg,...gg,...yg,...xg,...bg];var ET=[...yT,...xT,...hg,...bT,...gg,...yg,...xg,...bg];function Eg(e){return ET.includes(e)}var wg="default-light",Oo=e=>{let t=dg(e);return C(()=>{if(!t||B(t))return wg;let r=H(t).theme;return Eg(r)?r:wg},[t])};var sn=(e,t)=>new Promise(r=>{let o=!1,n=()=>{o=!0,r(!1)};e.addEventListener("click",n),e.addEventListener("pointerleave",n),setTimeout(()=>{o||r(!0),e.removeEventListener("click",n),e.removeEventListener("pointerleave",n),r(!1)},t)});var an=e=>{let{top:t,right:r,left:o,bottom:n}=e.getBoundingClientRect(),s=document.body.getBoundingClientRect(),i=(o-s.left)/s.width>.5;return{top:Math.round(n-s.top),bottom:Math.round(globalThis.innerHeight-globalThis.scrollY-t),...i?{right:Math.round(s.right-r)}:{left:Math.round(o-s.left)},maxWidth:i?r-10:document.documentElement.clientWidth-o-10}};var Rg=({project:e,title:t,descriptions:r,thumbnail:o,linkTo:n,bubble:s,delay:i,prefetch:a})=>{let c=C(()=>o?[]:Be(r.join(`
`),{hasTitle:!1}),[o,r]),l=Oo(e),u=F(async({currentTarget:f})=>{a(e,t),await sn(f,i)&&s({project:e,title:t,linkTo:n,type:"link",position:an(f)})},[e,t,i,n?.project,n?.titleLc]),p=C(()=>n?()=>{en({type:"page",from:{project:n.project??e,title:n.titleLc},to:{project:e,title:t}})}:()=>{},[e,t,n?.project,n?.titleLc]);return d("a",{className:"related-page-card page-link",type:"link","data-theme":l,href:`/${e}/${me(t)}`,rel:e===scrapbox.Project.name?"route":"noopner noreferrer",target:e!==scrapbox.Project.name?"_blank":"",onPointerEnter:u,onClick:p,children:[d("div",{class:"hover"}),d("div",{class:"content",children:[d("div",{class:"header",children:d("div",{class:"title",children:t})}),o?d("div",{class:"thumbnail",children:d("img",{src:o})}):d("div",{class:"description",children:c.flatMap((f,m)=>f.type==="line"?[d("p",{children:f.nodes.map(h=>d(kg,{node:h,project:e}))},m)]:[])})]})]})},kg=({node:e,project:t})=>{switch(e.type){case"code":return d("code",{children:e.text});case"formula":return d(wT,{node:e});case"commandLine":return d("code",{children:[e.symbol," $",e.text]});case"helpfeel":return d("code",{children:["? ",e.text]});case"quote":case"strong":case"decoration":return d(Y,{children:e.nodes.map(r=>d(kg,{node:r,project:t}))});case"icon":case"strongIcon":return d(RT,{node:e,project:t});case"hashTag":return d(kT,{node:e});case"link":return d(vT,{node:e});case"plain":case"blank":return d(Y,{children:e.text});default:return d(Y,{})}},wT=({node:{formula:e}})=>{let{ref:t,error:r}=Qi(e);return d("span",{className:`formula ${r?" error":""}`,children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},RT=({node:{pathType:e,path:t},project:r})=>{let[o,n]=e==="relative"?[r,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[r,t];return d("img",{class:"icon",src:`/api/pages/${o}/${me(n)}/icon`})},kT=({node:{href:e}})=>d("span",{class:"page-link",children:["#",e]}),vT=({node:{pathType:e,href:t,content:r}})=>e!=="absolute"?d("span",{class:"page-link",children:t}):d("span",{class:"link",children:r||t});var Ee=(e,t)=>`/${e.toLowerCase()}/${ne(t)}`,ra=e=>{let t=e.match("/([^/]+)/(.+)");if(!t)throw SyntaxError(`"${e}" cannnot match "/([^/]+)/(.+)"`);return{project:t[1],titleLc:t[2]}};var Og=Symbol.for("immer-nothing"),vg=Symbol.for("immer-draftable"),ye=Symbol.for("immer-state");function Bt(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var cn=Object.getPrototypeOf;function ln(e){return!!e&&!!e[ye]}function Tr(e){return e?Lg(e)||Array.isArray(e)||!!e[vg]||!!e.constructor?.[vg]||aa(e)||ca(e):!1}var _T=Object.prototype.constructor.toString();function Lg(e){if(!e||typeof e!="object")return!1;let t=cn(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===_T}function os(e,t){ia(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,o)=>t(o,r,e))}function ia(e){let t=e[ye];return t?t.type_:Array.isArray(e)?1:aa(e)?2:ca(e)?3:0}function Ql(e,t){return ia(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Ng(e,t,r){let o=ia(e);o===2?e.set(t,r):o===3?e.add(r):e[t]=r}function TT(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function aa(e){return e instanceof Map}function ca(e){return e instanceof Set}function nt(e){return e.copy_||e.base_}function Zl(e,t){if(aa(e))return new Map(e);if(ca(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Lg(e);if(t===!0||t==="class_only"&&!r){let o=Object.getOwnPropertyDescriptors(e);delete o[ye];let n=Reflect.ownKeys(o);for(let s=0;s<n.length;s++){let i=n[s],a=o[i];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(o[i]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[i]})}return Object.create(cn(e),o)}else{let o=cn(e);if(o!==null&&r)return{...e};let n=Object.create(o);return Object.assign(n,e)}}function op(e,t=!1){return la(e)||ln(e)||!Tr(e)||(ia(e)>1&&(e.set=e.add=e.clear=e.delete=PT),Object.freeze(e),t&&Object.entries(e).forEach(([r,o])=>op(o,!0))),e}function PT(){Bt(2)}function la(e){return Object.isFrozen(e)}var ep={};function Lo(e){let t=ep[e];return t||Bt(0,e),t}function ST(e,t){ep[e]||(ep[e]=t)}var ns;function oa(){return ns}function OT(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function _g(e,t){t&&(Lo("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function tp(e){rp(e),e.drafts_.forEach(LT),e.drafts_=null}function rp(e){e===ns&&(ns=e.parent_)}function Tg(e){return ns=OT(ns,e)}function LT(e){let t=e[ye];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Pg(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[ye].modified_&&(tp(t),Bt(4)),Tr(e)&&(e=na(t,e),t.parent_||sa(t,e)),t.patches_&&Lo("Patches").generateReplacementPatches_(r[ye].base_,e,t.patches_,t.inversePatches_)):e=na(t,r,[]),tp(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Og?e:void 0}function na(e,t,r){if(la(t))return t;let o=t[ye];if(!o)return os(t,(n,s)=>Sg(e,o,t,n,s,r)),t;if(o.scope_!==e)return t;if(!o.modified_)return sa(e,o.base_,!0),o.base_;if(!o.finalized_){o.finalized_=!0,o.scope_.unfinalizedDrafts_--;let n=o.copy_,s=n,i=!1;o.type_===3&&(s=new Set(n),n.clear(),i=!0),os(s,(a,c)=>Sg(e,o,n,a,c,r,i)),sa(e,n,!1),r&&e.patches_&&Lo("Patches").generatePatches_(o,r,e.patches_,e.inversePatches_)}return o.copy_}function Sg(e,t,r,o,n,s,i){if(ln(n)){let a=s&&t&&t.type_!==3&&!Ql(t.assigned_,o)?s.concat(o):void 0,c=na(e,n,a);if(Ng(r,o,c),ln(c))e.canAutoFreeze_=!1;else return}else i&&r.add(n);if(Tr(n)&&!la(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;na(e,n),(!t||!t.scope_.parent_)&&typeof o!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,o)&&sa(e,n)}}function sa(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&op(t,r)}function NT(e,t){let r=Array.isArray(e),o={type_:r?1:0,scope_:t?t.scope_:oa(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=o,s=np;r&&(n=[o],s=ss);let{revoke:i,proxy:a}=Proxy.revocable(n,s);return o.draft_=a,o.revoke_=i,a}var np={get(e,t){if(t===ye)return e;let r=nt(e);if(!Ql(r,t))return CT(e,r,t);let o=r[t];return e.finalized_||!Tr(o)?o:o===Yl(e.base_,t)?(Jl(e),e.copy_[t]=is(o,e)):o},has(e,t){return t in nt(e)},ownKeys(e){return Reflect.ownKeys(nt(e))},set(e,t,r){let o=Cg(nt(e),t);if(o?.set)return o.set.call(e.draft_,r),!0;if(!e.modified_){let n=Yl(nt(e),t),s=n?.[ye];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(TT(r,n)&&(r!==void 0||Ql(e.base_,t)))return!0;Jl(e),_r(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Yl(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,Jl(e),_r(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=nt(e),o=Reflect.getOwnPropertyDescriptor(r,t);return o&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:o.enumerable,value:r[t]}},defineProperty(){Bt(11)},getPrototypeOf(e){return cn(e.base_)},setPrototypeOf(){Bt(12)}},ss={};os(np,(e,t)=>{ss[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ss.deleteProperty=function(e,t){return ss.set.call(this,e,t,void 0)};ss.set=function(e,t,r){return np.set.call(this,e[0],t,r,e[0])};function Yl(e,t){let r=e[ye];return(r?nt(r):e)[t]}function CT(e,t,r){let o=Cg(t,r);return o?"value"in o?o.value:o.get?.call(e.draft_):void 0}function Cg(e,t){if(!(t in e))return;let r=cn(e);for(;r;){let o=Object.getOwnPropertyDescriptor(r,t);if(o)return o;r=cn(r)}}function _r(e){e.modified_||(e.modified_=!0,e.parent_&&_r(e.parent_))}function Jl(e){e.copy_||(e.copy_=Zl(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var AT=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,o)=>{if(typeof t=="function"&&typeof r!="function"){let s=r;r=t;let i=this;return function(a=s,...c){return i.produce(a,l=>r.call(this,l,...c))}}typeof r!="function"&&Bt(6),o!==void 0&&typeof o!="function"&&Bt(7);let n;if(Tr(t)){let s=Tg(this),i=is(t,void 0),a=!0;try{n=r(i),a=!1}finally{a?tp(s):rp(s)}return _g(s,o),Pg(n,s)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===Og&&(n=void 0),this.autoFreeze_&&op(n,!0),o){let s=[],i=[];Lo("Patches").generateReplacementPatches_(t,n,s,i),o(s,i)}return n}else Bt(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...i)=>this.produceWithPatches(s,a=>t(a,...i));let o,n;return[this.produce(t,r,(s,i)=>{o=s,n=i}),o,n]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Tr(e)||Bt(8),ln(e)&&(e=MT(e));let t=Tg(this),r=is(e,void 0);return r[ye].isManual_=!0,rp(t),r}finishDraft(e,t){let r=e&&e[ye];(!r||!r.isManual_)&&Bt(9);let{scope_:o}=r;return _g(o,t),Pg(void 0,o)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let n=t[r];if(n.path.length===0&&n.op==="replace"){e=n.value;break}}r>-1&&(t=t.slice(r+1));let o=Lo("Patches").applyPatches_;return ln(e)?o(e,t):this.produce(e,n=>o(n,t))}};function is(e,t){let r=aa(e)?Lo("MapSet").proxyMap_(e,t):ca(e)?Lo("MapSet").proxySet_(e,t):NT(e,t);return(t?t.scope_:oa()).drafts_.push(r),r}function MT(e){return ln(e)||Bt(10,e),Ag(e)}function Ag(e){if(!Tr(e)||la(e))return e;let t=e[ye],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Zl(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Zl(e,!0);return os(r,(o,n)=>{Ng(r,o,Ag(n))}),t&&(t.finalized_=!1),r}function Mg(){class e extends Map{constructor(c,l){super(),this[ye]={type_:2,parent_:l,scope_:l?l.scope_:oa(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:c,draft_:this,isManual_:!1,revoked_:!1}}get size(){return nt(this[ye]).size}has(c){return nt(this[ye]).has(c)}set(c,l){let u=this[ye];return i(u),(!nt(u).has(c)||nt(u).get(c)!==l)&&(r(u),_r(u),u.assigned_.set(c,!0),u.copy_.set(c,l),u.assigned_.set(c,!0)),this}delete(c){if(!this.has(c))return!1;let l=this[ye];return i(l),r(l),_r(l),l.base_.has(c)?l.assigned_.set(c,!1):l.assigned_.delete(c),l.copy_.delete(c),!0}clear(){let c=this[ye];i(c),nt(c).size&&(r(c),_r(c),c.assigned_=new Map,os(c.base_,l=>{c.assigned_.set(l,!1)}),c.copy_.clear())}forEach(c,l){let u=this[ye];nt(u).forEach((p,f,m)=>{c.call(l,this.get(f),f,this)})}get(c){let l=this[ye];i(l);let u=nt(l).get(c);if(l.finalized_||!Tr(u)||u!==l.base_.get(c))return u;let p=is(u,l);return r(l),l.copy_.set(c,p),p}keys(){return nt(this[ye]).keys()}values(){let c=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{let l=c.next();return l.done?l:{done:!1,value:this.get(l.value)}}}}entries(){let c=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{let l=c.next();if(l.done)return l;let u=this.get(l.value);return{done:!1,value:[l.value,u]}}}}[Symbol.iterator](){return this.entries()}}function t(a,c){return new e(a,c)}function r(a){a.copy_||(a.assigned_=new Map,a.copy_=new Map(a.base_))}class o extends Set{constructor(c,l){super(),this[ye]={type_:3,parent_:l,scope_:l?l.scope_:oa(),modified_:!1,finalized_:!1,copy_:void 0,base_:c,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return nt(this[ye]).size}has(c){let l=this[ye];return i(l),l.copy_?!!(l.copy_.has(c)||l.drafts_.has(c)&&l.copy_.has(l.drafts_.get(c))):l.base_.has(c)}add(c){let l=this[ye];return i(l),this.has(c)||(s(l),_r(l),l.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let l=this[ye];return i(l),s(l),_r(l),l.copy_.delete(c)||(l.drafts_.has(c)?l.copy_.delete(l.drafts_.get(c)):!1)}clear(){let c=this[ye];i(c),nt(c).size&&(s(c),_r(c),c.copy_.clear())}values(){let c=this[ye];return i(c),s(c),c.copy_.values()}entries(){let c=this[ye];return i(c),s(c),c.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(c,l){let u=this.values(),p=u.next();for(;!p.done;)c.call(l,p.value,p.value,this),p=u.next()}}function n(a,c){return new o(a,c)}function s(a){a.copy_||(a.copy_=new Set,a.base_.forEach(c=>{if(Tr(c)){let l=is(c,a);a.drafts_.set(c,l),a.copy_.add(l)}else a.copy_.add(c)}))}function i(a){a.revoked_&&Bt(3,JSON.stringify(nt(a)))}ST("MapSet",{proxyMap_:t,proxySet_:n})}var Ct=new AT,pa=Ct.produce,Hie=Ct.produceWithPatches.bind(Ct),Wie=Ct.setAutoFreeze.bind(Ct),Gie=Ct.setUseStrictShallowCopy.bind(Ct),Vie=Ct.applyPatches.bind(Ct),zie=Ct.createDraft.bind(Ct),qie=Ct.finishDraft.bind(Ct);Mg();var Ig=e=>{let t=0;for(let r of e)if(r&&(r.exists||(t+=(r.linked?.length??0)+(r.projectLinked?.length??0),t>1)))return!1;return t<2},Fg=(e,t)=>pa(e,r=>{if(!r)return t;if(r.updated<t.updated){let{lines:o,linked:n,projectLinked:s,...i}=t;Object.assign(r,i),sp(t)||(r.lines=o),n&&(r.linked??=n),s&&(r.projectLinked??=s);return}sp(r)&&!sp(t)&&(r.lines=t.lines),t.linked&&(t.isLinkedCorrect||!r.isLinkedCorrect&&(r.linked?.length??0)<=t.linked.length)&&(r.linked=t.linked),t.projectLinked&&(r.projectLinked=t.projectLinked)}),sp=e=>e.lines[0].id==="dummy";var Ug=(e,t)=>{let r=new Map,o=ne(t.title);for(let c of t.links){let l=ip(e,c);l.linked=[o],r.set(Ee(e,c),l)}let n=Ee(e,o),s=t.projectLinks.map(c=>{let l=ra(c);return Ee(l.project,l.titleLc)}),i={...ua(e,t),linked:[],projectLinked:[]};r.set(n,i);let a=t.links.map(c=>ne(c));for(let c of t.relatedPages.links1hop){c.linksLc.includes(o)&&i.linked.push(c.titleLc);for(let f of c.linksLc.filter(m=>a.includes(m))){let m=Ee(e,f),h=r.get(m)??ip(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=Ee(e,c.titleLc),u=ua(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}for(let c of t.relatedPages.projectLinks1hop){let l=Ee(c.projectName,c.titleLc);s.includes(l)||i.projectLinked.push(l);let u=ua(c.projectName,c),p=r.get(l)?.projectLinked;p&&(u.projectLinked=p),r.set(l,u)}i.isLinkedCorrect=!0;for(let c of t.relatedPages.links2hop){for(let f of c.linksLc){let m=Ee(e,f),h=r.get(m)??ip(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=Ee(e,c.titleLc),u=ua(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}return r},ua=(e,t)=>({project:e,titleLc:"titleLc"in t?t.titleLc:ne(t.title),exists:"persistent"in t?t.persistent:!0,descriptions:t.descriptions,image:t.image,lines:"lines"in t?t.lines:[t.title,...t.descriptions].map(r=>({text:r,id:"dummy",userId:"dummy",updated:t.updated,created:t.updated})),updated:t.updated,isLinkedCorrect:!1}),ip=(e,t)=>({project:e,titleLc:ne(t),exists:!1,descriptions:[],image:null,lines:[{text:t,id:"dummy",userId:"dummy",updated:0,created:0}],updated:0,isLinkedCorrect:!1});var ma=Kr("ScrapBubble:bubble.ts"),ap=new Map,fa=new Set,cp=ea();function*$g(e){for(let t of e)yield ap.get(t)}var jg=(e,t)=>cp.on(e,t),Bg=(e,t)=>cp.off(e,t),Hg=async(e,t,r,o)=>{let n=[];for(let s of[...t].reverse()){let i=Ee(s,e);fa.has(i)||n.push(IT(s,e,r,o))}await Promise.all(n)},Dg=0,IT=async(e,t,r,o)=>{let n=Ee(e,t);if(fa.has(n))return;fa.add(n);let s=Dg++,i=`[${s}] Check update ${n}`;ma.time(i);try{let a=Dt.toRequest(e,t,{followRename:!0,projects:[...r]});for await(let[c,l]of Zi(a,{ignoreSearch:!0,saveFailedResponse:!0})){ma.debug(`[${s}]${c} ${n}`);let u=await Dt.fromResponse(l);if(Ne(u)){let p=Ug(e,H(u));for(let[f,m]of p){let h=ap.get(f),g=Fg(h,m);g&&h!==g&&(ap.set(f,g),cp.dispatch(f,m))}}if(o?.ignoreFetch===!0||c==="cache"&&!mg(l,o?.maxAge??60))break}}catch(a){ma.error(a)}finally{fa.delete(n),ma.timeEnd(i),Dg--}};var Wg=Kr("ScrapBubble:useBubbleData.ts"),pn=e=>{let[t,r]=J(lp(e));return oe(()=>{r(lp(e));let o,n=()=>{clearTimeout(o),o=setTimeout(()=>{Wg.debug(`Update ${e.length} pages`),r(lp(e))},10)};return e.forEach(s=>jg(s,n)),()=>e.forEach(s=>Bg(s,n))},e),t},lp=e=>{let t=[...$g(e)].flatMap(r=>r?[r]:[]);return Wg.debug(`Required: ${e.length} pages, ${t.length} found`,t),t};var Gg=({source:e,linked:t,externalLinked:r,projectsForSort:o,...n})=>{let s=C(()=>[...t.keys(),...r.keys()],[t,r]),i=pn(s),a=C(()=>[...o],[o]),c=C(()=>{let u=(p,f)=>{let m=a.indexOf(p.project),h=a.indexOf(f.project);return m===h?f.updated-p.updated:m<0?1:h<0?-1:m-h};return[...i].sort(u)},[i,a]),l=C(()=>({bottom:`${e.position.bottom}px`,maxWidth:`${e.position.maxWidth}px`,..."left"in e.position?{left:`${e.position.left}px`}:{right:`${e.position.right}px`}}),[e.position]);return d("ul",{className:"card-bubble",style:l,onClick:n.onClick,children:c.map(({project:u,titleLc:p,lines:[{text:f}],descriptions:m,image:h})=>{let g=Ee(u,p),y=t.get(g)??r.get(g);return d("li",{children:d(Rg,{project:u,title:f,linkTo:y,descriptions:m,thumbnail:h??"",...n})},g)})})};var un=e=>{e:if(e.pathType==="root"){let[,r="",o=""]=e.href.match(/\/([\w\-]+)(?:\/?|\/(.*))$/)??["","",""];if(r==="")break e;let[,n]=o?.match?.(/#([a-f\d]{24,32})$/)??["",""];return o===""?{project:r}:n===""?{project:r,title:o}:{project:r,title:o.slice(0,-1-n.length),hash:n}}let[,t]=e.href.match(/#([a-f\d]{24,32})$/)??["",""];return t===""?{title:e.href}:{title:e.href.slice(0,-1-t.length),hash:t}};var pp=(e,t)=>t.some(r=>{let o=!e.project;switch(r.type){case"hashTag":return o&&ne(r.href)===e.titleLc;case"link":{if(r.pathType=="absolute"||r.pathType==="relative"!==o)return!1;let{project:n,title:s=""}=un({pathType:r.pathType,href:r.href});return o?!n&&ne(s)===e.titleLc:n===e.project&&ne(s)===e.titleLc}case"quote":case"strong":case"decoration":return pp(e,r.nodes)}});var Xr=Wn({title:"",project:"",whiteList:new Set,bubble:()=>{},hide:()=>{},delay:0,prefetch:()=>{}}),zg=({lines:e,project:t,title:r,whiteList:o,noIndent:n,hash:s,linkTo:i,...a})=>{let c=C(()=>e.flatMap(m=>typeof m=="string"?[]:[m.id]),[e]),l=C(()=>{let m=0;return Be(e.map(h=>typeof h=="string"?h:h.text).join(`
`),{hasTitle:!0}).map(h=>{switch(h.type){case"title":case"line":return{...h,id:c[m++]};case"codeBlock":{let g=m;return m+=h.content.split(`
`).length+1,{...h,ids:c.slice(g,m)}}case"table":{let g=m;return m+=h.cells.length+1,{...h,ids:c.slice(g,m)}}}})},[e,c]),u=C(()=>{if(s&&c.includes(s))return s;if(i)return l.find(m=>m.type!=="line"?!1:pp(i,m.nodes))?.id},[l,c,s,i?.project,i?.titleLc]),p=qe(null);oe(()=>{if(!u)return;let m=p.current?.querySelector(`[data-id="${u}"]`),h=globalThis.scrollY;m?.scrollIntoView?.({block:"center"}),globalThis.scroll(0,h)},[u]);let f=Oo(t);return d("div",{className:"lines","data-theme":f,ref:p,children:d(Xr.Provider,{value:{project:t,title:r,whiteList:o,...a},children:l.map(m=>{switch(m.type){case"title":return d(Y,{children:[d(fn,{index:m.id,indent:0,noIndent:n,permalink:m.id===u,children:d("a",{className:"page-link",type:"link",href:`/${t}/${me(m.text)}`,rel:t===scrapbox.Project.name?"route":"noopener noreferrer",target:t===scrapbox.Project.name?"":"_blank",children:m.text})},m.id),d("hr",{})]});case"codeBlock":return d(FT,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"table":return d(UT,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"line":return d(fn,{index:m.id,indent:m.indent,noIndent:n,permalink:m.id===u,children:m.nodes.length>0?m.nodes.map(h=>d(mn,{node:h})):d("br",{})},m.id)}})})})},fn=({index:e,indent:t,noIndent:r,children:o,permalink:n})=>d("div",{className:`line${n?" permalink":""}`,"data-id":e,"data-indent":t,style:{"margin-left":r?"":`${1*t}em`},children:o}),FT=({block:{fileName:e,content:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=xr(Xr),[a,c]=J(""),l=F(async u=>{u.preventDefault(),u.stopPropagation();try{await navigator.clipboard.writeText(t),c("Copied"),await Te(1e3),c("")}catch(p){alert(`Failed to copy the code block
Error: ${p}`)}},[t]);return d(Y,{children:[d(fn,{index:o[0],indent:r,permalink:o[0]===n,children:d("span",{className:"code-block",children:[d("span",{className:"code-block-start",children:d("a",{href:`/api/code/${s}/${me(i)}/${e}`,target:"_blank",children:e})}),d("span",{className:"copy",title:"Copy",onClick:l,children:a})]})}),d(Y,{children:t.split(`
`).map((u,p)=>d(fn,{index:o[p+1],indent:r,permalink:o[p+1]===n,children:d("code",{className:"code-block",children:u})}))})]})},UT=({block:{fileName:e,cells:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=xr(Xr);return d(Y,{children:[d(fn,{index:o[0],indent:r,permalink:o[0]===n,children:d("span",{className:"table-block",children:d("span",{className:"table-block-start",children:d("a",{href:`/api/table/${s}/${me(i)}/${e}.csv`,target:"_blank",children:e})})})}),d(Y,{children:t.map((a,c)=>d(fn,{index:o[c+1],indent:r,permalink:o[c+1]===n,children:d("span",{className:"table-block table-block-row",children:a.map((l,u)=>d("span",{className:`cell col-${u}`,children:l.map(p=>d(mn,{node:p}))}))})}))})]})},mn=({node:e})=>{switch(e.type){case"code":return d("code",{className:"code",children:e.text});case"formula":return d(DT,{node:e});case"commandLine":return d(jT,{node:e});case"helpfeel":return d("code",{className:"helpfeel",children:[d("span",{className:"prefix",children:"?"})," ",d("span",{className:"entry",children:e.text})]});case"quote":return d("blockquote",{className:"quote",children:e.nodes.map(t=>d(mn,{node:t}))});case"strong":return d("strong",{children:e.nodes.map(t=>d(mn,{node:t}))});case"decoration":return d($T,{node:e});case"plain":case"blank":return d(Y,{children:e.text});case"hashTag":return d(WT,{node:e});case"link":return d(GT,{node:e});case"googleMap":return d(BT,{node:e});case"icon":return d(Vg,{node:e});case"strongIcon":return d(Vg,{node:e,strong:!0});case"image":return d(HT,{node:e});case"strongImage":return d("img",{className:"image strong-image",src:e.src});case"numberList":return d(Y,{children:[`${e.number}. `,e.nodes.map(t=>d(mn,{node:t}))]})}},DT=({node:{formula:e}})=>{let{ref:t,error:r}=Qi(e);return d("span",{className:`formula ${r?" error":""}`,children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},$T=({node:{decos:e,nodes:t}})=>d("span",{className:e.map(r=>`deco-${r}`).join(" "),children:t.map(r=>d(mn,{node:r}))}),jT=({node:e})=>{let[t,r]=J(""),o=F(async n=>{n.preventDefault(),n.stopPropagation();try{await navigator.clipboard.writeText(e.text),r("Copied"),await Te(1e3),r("")}catch(s){alert(`Failed to copy the code block
Error: ${s}`)}},[e.text]);return d(Y,{children:[d("code",{className:"cli",children:[d("span",{className:"prefix",children:e.symbol})," ",d("span",{className:"command",children:e.text})]}),d("span",{className:"tool-buttons",children:d("span",{title:"Copy",className:"copy",onClick:o,children:t})})]})},BT=({node:{place:e,latitude:t,longitude:r,zoom:o}})=>d("span",{className:"pointing-device-map",children:d("a",{href:`https://www.google.com/maps/search/${e}/@${t},${r},${o}z`,rel:"noopner noreferrer",target:"_blank",children:d("img",{className:"google-map",src:`/api/google-map/static-map?center=${t}%2C${r}&markers=${e}&zoom=${o}&_csrf=${globalThis._csrf}`})})}),Vg=({node:{pathType:e,path:t},strong:r})=>{let{project:o}=xr(Xr),[n,s]=e==="relative"?[o,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[o,t],i=me(s);return d("a",{href:`/${n}/${i}`,rel:n===scrapbox.Project.name?"route":"noopener noreferrer",target:n===scrapbox.Project.name?"":"_blank",children:d("img",{className:r?"icon strong-icon":"icon",alt:s,src:`/api/pages/${n}/${i}/icon`,children:s})})},HT=({node:{link:e,src:t}})=>{let r=e||(/https:\/\/gyazo\.com\/[^\/]+\/thumb\/1000/.test(t)?t.slice(0,-11):t);return d("a",{className:e?"link":"",href:r,rel:"noopner noreferrer",target:"_blank",children:d("img",{className:"image",src:t})})},WT=({node:{href:e}})=>{let{project:t}=xr(Xr),r=qg(t,e),o=Kg(t,e,"hashtag");return d("a",{href:`/${t}/${me(e)}`,className:`page-link${r?" empty-page-link":""}`,type:"hashTag",rel:t===scrapbox.Project.name?"route":"noopener noreferrer",target:t===scrapbox.Project.name?"":"_blank",onPointerEnter:o,children:["#",e]})},GT=({node:{pathType:e,...t}})=>{switch(e){case"relative":case"root":return d(VT,{pathType:e,href:t.href});case"absolute":{let r=sg({pathType:e,...t});switch(r.type){case"youtube":return d(zT,{...r});case"vimeo":return d(qT,{...r});case"spotify":return d(KT,{...r});case"anchor-fm":return d(XT,{...r});case"audio":return d(YT,{...r});case"video":return d(QT,{...r});case"absoluteLink":return d("a",{className:"link",href:r.href,rel:"noopener noreferrer",target:"_blank",children:r.content||r.href})}}}},VT=({pathType:e,href:t})=>{let{project:r}=xr(Xr),{project:o=r,title:n,hash:s=""}=un({pathType:e,href:t}),i=Kg(o,n,"link",s),a=qg(o,n??"");return d("a",{className:`page-link${n!==void 0&&a?" empty-page-link":""}`,type:"link",href:`/${o}${n===void 0?"":`/${me(n)}${s===""?"":`#${s}`}`}`,rel:o===scrapbox.Project.name?"route":"noopener noreferrer",target:o===scrapbox.Project.name?"":"_blank",onPointerEnter:i,children:t})},zT=e=>{e.params.append("autoplay","0");let t=e.pathType==="list"?`https://www.youtube.com/embed/?${e.params.toString()}&list=${e.listId}`:`https://www.youtube.com/embed/${e.videoId}?${e.params.toString()}`;return d("div",{className:"iframe-video-player",children:d("iframe",{src:t,allowFullScreen:!0})})},qT=({videoId:e})=>d("div",{className:"iframe-video-player",children:d("iframe",{src:`https://player.vimeo.com/video/${e}`,allowFullScreen:!0})}),KT=e=>d("div",{className:"iframe-video-player",children:d("iframe",{className:`spotify type-${e.pathType}`,src:`https://open.spotify.com/embed/${e.pathType}/${e.videoId}`,allowFullScreen:!0})}),XT=e=>d("div",{className:"iframe-video-player",children:d("iframe",{className:"anchor-fm",src:e.href.replace("/episodes/","/embed/episodes/"),allowFullScreen:!0})}),YT=e=>e.content===""?d("audio",{className:"audio-player",preload:"none",controls:!0,src:e.href}):d(JT,{...e}),JT=({href:e,content:t})=>{let r=qe(null),o=F(()=>{r.current?.paused?(r.current.currentTime=0,r.current.play()):r.current?.pause?.()},[]);return d("span",{className:"audio-link",children:[d("a",{href:e,rel:"noopener noreferrer",target:"_blank",children:t}),d("span",{className:"play",onClick:o,children:"♬"}),d("audio",{preload:"none",src:e,ref:r})]})},QT=({href:e})=>d("div",{className:"video-player",children:d("video",{class:"video",style:{display:"inline-block"},controls:!0,loop:!0,src:e})}),qg=(e,t)=>{let{whiteList:r}=xr(Xr),o=C(()=>(r.has(e)?[...r]:[e,...r]).map(s=>Ee(s,t)),[r,e]),n=pn(o);return C(()=>Ig(n),n)},Kg=(e,t,r,o)=>{let{delay:n,bubble:s,prefetch:i}=xr(Xr);return F(async({currentTarget:a})=>{t&&(i(e,t),await sn(a,n)&&s({project:e,title:t,hash:o,type:r,position:an(a)}))},[e,t,o,r,n,i,s])};var Xg=({pages:e,onClick:t,source:r,whiteList:o,...n})=>{let[s,i]=J(Ee(e[0].project,e[0].titleLc)),a=C(()=>({top:`${r.position.top}px`,maxWidth:`${r.position.maxWidth}px`,..."left"in r.position?{left:`${r.position.left}px`}:{right:`${r.position.right}px`}}),[r.position]);return d("div",{className:"text-bubble",style:a,onClick:t,children:[e.length>1&&d("div",{role:"tablist",children:e.map(c=>d(ZT,{project:c.project,titleLc:c.titleLc,selected:s===Ee(c.project,c.titleLc),tabSelector:i},Ee(c.project,c.titleLc)))}),e.map(c=>d(e0,{selected:s===Ee(c.project,c.titleLc),...c,title:c.lines[0].text,hash:r.hash,linkTo:r.linkTo,whiteList:o,...n},Ee(c.project,c.titleLc)))]})},ZT=({project:e,titleLc:t,tabSelector:r,selected:o})=>{let n=F(()=>r(Ee(e,t)),[e,t]),s=Oo(e);return d("button",{role:"tab","aria-selected":o,"data-theme":s,tabIndex:-1,onClick:n,children:e})},e0=({selected:e,...t})=>{let r=Oo(t.project);return d("div",{role:"tabpanel","data-theme":r,hidden:!e,children:d(zg,{...t})})};var Yg=Kr("ScrapBubble:Bubble.tsx"),Jg=({source:e,parentTitles:t,whiteList:r,...o})=>{let n=C(()=>r.has(e.project)?new Set([e.project,...r]):new Set([e.project]),[r,e.project]),[s,i,a]=r0(e,n,r,t);return d(Y,{children:[t0(a)&&d(Xg,{pages:a,source:e,whiteList:r,onClick:o.hide,...o}),d(Gg,{linked:s,externalLinked:i,onClick:o.hide,source:e,projectsForSort:n,...o})]})},t0=e=>e.length>0,r0=(e,t,r,o)=>{let[[n,s,i],a]=J([new Map,new Map,[]]),c=C(()=>{let p=[...t].map(f=>Ee(f,e.title));return Yg.debug("projects",p),p},[t,e.title]),l=pn(c),u=C(()=>o.map(p=>ne(p)),[o]);return ki(()=>{let p=new Map,f=new Map,m=[];for(let h of l){let g={project:h.project,titleLc:h.titleLc};for(let x of h.projectLinked??[]){let{project:E,titleLc:k}=ra(x);u.includes(k)&&r.has(E)||f.has(x)||f.set(x,g)}if(!r.has(h.project))continue;let y={titleLc:h.titleLc};for(let x of h.linked??[]){if(u.includes(x))continue;let E=Ee(h.project,x);p.has(E)||p.set(E,y)}u.includes(h.titleLc)||h.exists&&m.push(h)}a(pa(h=>{Yg.debug(`depth: ${u.length}, bubbled from ${Ee(e.project,e.title)}, bubbles,`,l,"before",h[0],"internal cards,",p,"external cards",f);for(let g of h[0].keys())p.has(g)||h[0].delete(g);for(let[g,y]of p)h[0].set(g,y);for(let g of h[1].keys())f.has(g)||h[1].delete(g);for(let[g,y]of f)h[1].set(g,y);h[2]=m}))},[l,r,u]),[n,s,i]};var Qg=(e,t)=>{if(e instanceof URL)return e;try{return new URL(e)}catch(r){if(!(r instanceof TypeError))throw r;if(!t||!/^\.\/|^\.\.\/|^\//.test(e))return e;try{return new URL(e,t)}catch(o){if(!(o instanceof TypeError))throw o;return e}}};var Zg=e=>{let t=C(()=>Qg(e.style,import.meta.url),[e.style]);return d(Y,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var ey=String.raw`*{box-sizing:border-box}a{background-color:transparent;text-decoration:none;cursor:pointer}img{display:inline-block;max-width:100%;max-height:100px}code{font-family:var(--code-text-font, Menlo, Monaco, Consolas, "Courier New", monospace);font-size:90%;color:var(--code-color, #342d9c);background-color:var(--code-bg, rgba(0,0,0,.04));padding:0;white-space:pre-wrap;word-wrap:break-word}blockquote{background-color:var(--quote-bg-color, rgba(0,0,0,.05));display:block;border-left:solid 4px #a0a0a0;padding-left:4px;margin:0}strong{font-weight:700}iframe{display:inline-block;margin:3px 0;vertical-align:middle;max-width:100%;width:640px;height:360px;border:0}audio{display:inline-block;vertical-align:middle;white-space:initial;max-width:100%}.formula{margin:auto 6px}.formula.error code{color:#fd7373}.katex-display{display:inline-block!important;margin:0!important;text-align:inherit!important}.error .katex-display{display:none}.cli{border-radius:4px}.cli .prefix{color:#9c6248}.helpfeel{background-color:#fbebdd;border-radius:4px;padding:3px!important}.helpfeel .prefix{color:#f17c00}.helpfeel .entry{color:#cc5020}.code-block{display:block;line-height:1.7em;background-color:var(--code-bg, rgba(0,0,0,.04))}.code-block-start{font-family:Menlo,Monaco,Consolas,Courier New,monospace;color:#342d9c;background-color:#ffcfc6;font-size:.9em;padding:1px 2px}.code-block-start a{color:#342d9c;text-decoration:underline}code.code-block,.table-block.table-block-row{padding-left:1em}.copy{font-family:"Font Awesome 5 Free";cursor:pointer}.table-block{white-space:nowrap}.table-block-start{padding:1px 2px;font-size:.9em;background-color:#ffcfc6}.table-block-start a{color:#342d9c;text-decoration:underline}.cell{margin:0;padding:0 2px 0 8px;box-sizing:content-box;display:inline-block;white-space:pre}.cell:nth-child(odd){background-color:#0000000a}.cell:nth-child(2n){background-color:#0000000f}.strong-image{max-height:100%}.icon{height:11px;vertical-align:middle}.strong-icon{height:13.2px}.tool-button{margin-left:1em;cursor:pointer;font-size:.9em}.deco-\/{font-style:italic}.deco-\*-1{font-weight:700}.deco-\*-2{font-weight:700;font-size:1.2em}.deco-\*-3{font-weight:700;font-size:1.44em}.deco-\*-4{font-weight:700;font-size:1.73em}.deco-\*-5{font-weight:700;font-size:2.07em}.deco-\*-6{font-weight:700;font-size:2.49em}.deco-\*-7{font-weight:700;font-size:3em}.deco-\*-8{font-weight:700;font-size:3.58em}.deco-\*-9{font-weight:700;font-size:4.3em}.deco-\*-10{font-weight:700;font-size:5.16em}.deco--{text-decoration:line-through}.deco-_{text-decoration:underline}.page-link{color:var(--page-link-color, #5e8af7)}a.page-link:hover{color:var(--page-link-hover-color, #2d67f5)}.empty-page-link{color:var(--empty-page-link-color, #fd7373)}a.empty-page-link:hover{color:var(--empty-page-link-hover-color, #fd7373)}.link{color:var(--page-link-color, #5e8af7);text-decoration:underline}a.link:hover{color:var(--page-link-color-hover-color, #2d67f5)}.link img{padding-bottom:3px;border-style:none none solid;border-width:1.5px;border-color:#8fadf9}.permalink{background-color:var(--line-permalink-color, rgba(234,218,74,.75))}.status-bar{display:inline-block;position:absolute;background-color:var(--page-bg, #fefefe);cursor:default}.status-bar>*{border:1px solid var(--status-bar-border-color, #a9aaaf)}.status-bar.top-left{top:0;left:0}.status-bar.top-left>*{border-top:none;border-left:none}.status-bar.top-left :last-of-type{border-bottom-right-radius:3px}.status-bar.top-right{top:0;right:0}.status-bar.top-right>*{border-top:none;border-right:none}.status-bar.top-right :last-of-type{border-bottom-left-radius:3px}.status-bar.bottom-right{bottom:0;right:0}.status-bar.bottom-right>*{border-bottom:none;border-right:none}.status-bar.bottom-right :last-of-type{border-top-left-radius:3px}.status-bar.bottom-left{bottom:0;left:0}.status-bar.bottom-left>*{border-bottom:none;border-left:none}.status-bar.bottom-left :last-of-type{border-top-right-radius:3px}.text-bubble{font-size:11px;line-height:1.42857;user-select:text;position:absolute;color:var(--page-text-color, #4a4a4a);box-shadow:0 6px 12px #0000002d;display:flex;flex-direction:column;z-index:9000;&.no-scroll{overflow-y:hidden}[data-theme=default-dark]{--text-bubble-border-color: hsl(0, 0%, 39%)}[data-theme=default-minimal]{--text-bubble-border-color: hsl(0, 0%, 89%)}[data-theme=paper-light]{--text-bubble-border-color: hsl(53, 8%, 58%)}[data-theme=paper-dark-dark]{--text-bubble-border-color: hsl(203, 42%, 17%)}[data-theme=blue]{--text-bubble-border-color: hsl(227, 68%, 62%)}[data-theme=purple]{--text-bubble-border-color: hsl(267, 39%, 60%)}[data-theme=green]{--text-bubble-border-color: hsl(136, 29%, 50%)}[data-theme=orange]{--text-bubble-border-color: hsl(43, 71%, 51%)}[data-theme=red]{--text-bubble-border-color: hsl(4, 58%, 56%)}[data-theme=spring]{--text-bubble-border-color: hsl(72, 64%, 57%)}[data-theme=kyoto]{--text-bubble-border-color: hsl(331, 21%, 26%)}[data-theme=newyork]{--text-bubble-border-color: hsl(176, 29%, 67%)}[role=tabpanel]{padding:5px 0 5px 5px;border-radius:4px;background-color:var(--page-bg, #fefefe);max-height:80vh;overflow-y:auto}[role=tabpanel],button{border:1px solid var(--text-bubble-border-color, hsl(221, 15%, 25%))}button{cursor:default;color:inherit;font-size:inherit;line-height:inherit;background-color:var(--page-bg, #fefefe);border-radius:4px 4px 0 0}button[aria-selected=true]{background-color:var(--text-bubble-border-color, hsl(221, 15%, 25%))}}.project-badge{text-decoration:none;color:var(--tool-text-color, #363c49)}.related-page-card[data-theme=default-dark]{--card-title-bg: hsl(0, 0%, 39%)}.related-page-card[data-theme=default-minimal]{--card-title-bg: hsl(0, 0%, 89%)}.related-page-card[data-theme=paper-light]{--card-title-bg: hsl(53, 8%, 58%)}.related-page-card[data-theme=paper-dark-dark]{--card-title-bg: hsl(203, 42%, 17%)}.related-page-card[data-theme=blue]{--card-title-bg: hsl(227, 68%, 62%)}.related-page-card[data-theme=purple]{--card-title-bg: hsl(267, 39%, 60%)}.text-bubble[data-theme=green]{--card-title-bg: hsl(136, 29%, 50%)}.related-page-card[data-theme=orange]{--card-title-bg: hsl(43, 71%, 51%)}.related-page-card[data-theme=red]{--card-title-bg: hsl(4, 58%, 56%)}.related-page-card[data-theme=spring]{--card-title-bg: hsl(72, 64%, 57%)}.related-page-card[data-theme=kyoto]{--card-title-bg: hsl(331, 21%, 26%)}.related-page-card[data-theme=newyork]{--card-title-bg: hsl(176, 29%, 67%)}.related-page-card{display:block;position:relative;height:inherit;width:inherit;overflow:hidden;text-overflow:ellipsis;font-family:Roboto,Helvetica,Arial,Hiragino Sans,sans-serif;background-color:var(--card-bg, #fff);color:var(--card-title-color, #555);word-break:break-word;text-decoration:none}.related-page-card:hover{box-shadow:var(--card-box-hover-shadow, 0 2px 0 rgba(0,0,0,.23))}.related-page-card:focus{outline:0;box-shadow:0 0 0 3px #66afe999;border-color:#66afe9;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.related-page-card.hover{opacity:0;position:absolute;width:100%;height:100%;top:0;left:0;background-color:var(--card-hover-bg, rgba(0,0,0,.05));mix-blend-mode:multiply;z-index:1;transition:background-color .1s}.related-page-card:hover .hover{opacity:1}.related-page-card:active .hover{opacity:1;background-color:var(--card-active-bg, rgba(0,0,0,.1))}.related-page-card .content{height:calc(100% - 5px);width:inherit;display:flex;flex-direction:column;overflow:hidden}.related-page-card .content .header{width:100%;color:#396bdd;text-overflow:ellipsis;border-top:var(--card-title-bg, #f2f2f3) solid 10px;padding:8px 10px}.related-page-card .content .header .title{font-size:11px;line-height:16px;font-weight:700;max-height:48px;color:var(--card-title-color, #363c49);margin:0;overflow:hidden;display:block;-webkit-line-clamp:3;-webkit-box-orient:vertical;text-overflow:ellipsis}.related-page-card .content .description{line-height:16px;padding:8px 10px 0;font-size:10px;white-space:pre-line;column-count:1;column-gap:2em;column-width:10em;height:inherit;color:var(--card-description-color, gray);flex-shrink:16;overflow:hidden}.related-page-card .content .thumbnail{display:block;width:100%;margin:0 auto;padding:0 5px}.related-page-card .content .description p{margin:0;display:block}.related-page-card .content .description code{font-family:Menlo,Monaco,Consolas,Courier New,monospace;font-size:90%;color:var(--code-color, #342d9c);background-color:var(--code-bg, rgba(0,0,0,.04));padding:0;white-space:pre-wrap;word-wrap:break-word}.related-page-card .content .description .icon{height:9px;vertical-align:middle}.related-page-card .content .description .page-link{background-color:transparent;text-decoration:none;cursor:pointer;color:var(--page-link-color, #5e8af7)}.card-bubble{background-color:var(--page-bg, #FFF);box-shadow:0 2px 2px #00000024,0 3px 1px -2px #0003,0 1px 5px #0000001f;position:absolute;max-width:80vw;box-sizing:content-box;z-index:9000;font-size:11px;line-height:1.42857;display:flex;padding:0;margin:0;list-style:none;overflow-x:auto;overflow-y:visible}.card-bubble li{display:block;position:relative;float:none;margin:5px;box-sizing:border-box;box-shadow:var(--card-box-shadow, 0 2px 0 rgba(0,0,0,.12));border-radius:2px;width:120px;height:120px}
`;var ty=()=>{let[e,t]=J([{bubble:o=>r(0,o),hide:()=>r(0)}]),r=F((o,n)=>{t(([s,...i])=>[s,...n?[...i.slice(0,o),n===i.at(o)?.source?i.at(o):{source:n,parentTitles:[scrapbox.Page.title??"",...i.slice(0,o).map(a=>a.source.title)],bubble:a=>r(o+1,a),hide:()=>r(o+1)}]:[...i.slice(0,o)]])},[]);return e};var up=(e,t,r,o,n)=>{oe(()=>(e.addEventListener(t,r,o),()=>e.removeEventListener(t,r,o)),[e,t,o,...n??[]])};var ry=e=>e instanceof HTMLSpanElement&&e.matches(".line-title .text"),da=e=>e instanceof HTMLAnchorElement&&e.classList.contains("page-link");var mp="scrap-bubble",oy=({delay:e,whiteList:t,watchList:r,style:o})=>{let[{bubble:n,hide:s},...i]=ty(),a=F((c,l)=>Hg(l,t.has(c)?t:new Set([c]),r),[t,r]);return up(document,"pointerenter",async c=>{let l=c.target;if(!da(l)&&!ry(l))return;let{project:u=scrapbox.Project.name,title:p,hash:f=""}=da(l)?un({pathType:"root",href:`${new URL(l.href).pathname}${new URL(l.href).hash}`}):{project:scrapbox.Project.name,title:scrapbox.Page.title};if(u==="")return;let m=decodeURIComponent(p??"");a(u,m),await sn(l,e)&&n({project:u,title:m,hash:f,position:an(l),type:o0(l)})},{capture:!0},[e,t,r]),up(document,"click",c=>{c.target.dataset.userscriptName!==mp&&s()},{capture:!0},[s]),oe(()=>(scrapbox.addListener("page:changed",s),()=>scrapbox.removeListener("page:changed",s)),[s]),d(Y,{children:[d("link",{rel:"stylesheet",href:"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.12.0/katex.min.css"}),d("style",{children:ey}),d(Zg,{style:o}),i.map(c=>d(Jg,{...c,whiteList:t,delay:e,prefetch:a},Ee(c.source.project,c.source.title)))]})},o0=e=>da(e)?e.type==="link"?"link":"hashtag":"title";var ny=async e=>{let{delay:t=500,whiteList:r=[],watchList:o=(await ig()).slice(0,100),style:n="",debug:s=!1}=e??{};fg(s);let i=document.createElement("div");i.dataset.userscriptName=mp,document.body.append(i);let a=i.attachShadow({mode:"open"});ut(d(oy,{delay:t,whiteList:new Set([scrapbox.Project.name,...r]),watchList:new Set(o),style:n}),a)};var n0=["takker-memex","takker-private","takker","takker-books","villagepump"],No=[];switch(scrapbox.Project.name){case"hub":case"villagepump":case"verbalizing-community":No.push("villagepump","hub","verbalizing-community");break;case"programming-notes":case"customize":case"scrapboxlab":No.push("programming-notes","customize","scrapboxlab");break;case"sta":No.push("sta-taskmanagement");break;case"sta-taskmanagement":case"taskmanagement":No.push("sta-taskmanagement","taskmanagement");break;case"plurality-japanese":No.push("nishio","tkgshn");case"takker-books":No.push("work4ai");break}ny({delay:/mobile/i.test(navigator.userAgent)?300:500,whiteList:[...n0,...No],style:`@import "/api/code/takker/kakeruの背景を白にするUserCSS/style.css";
@import "/api/code/takker/アイコン記法を画像記法っぽくするUserCSS/style2.css";`});var sy=e=>{{let r=e.match(/^([^(]+)\(([^)]+)\)$/);if(r)return{fileName:r[1],lang:r[2]}}let t=e.split(".").pop();return t===void 0?{fileName:e,lang:e}:{fileName:e,lang:t}};var iy=(e,t,r)=>{if(r.length===0)return[];let o=r.map(a=>a.text).join(`
`),n=Be(o,{hasTitle:!0}),s=new Map,i=0;for(let a of n)switch(a.type){case"title":case"line":{i++;break}case"table":i+=a.cells.length+1;break;case"codeBlock":{let{fileName:c,lang:l}=sy(a.fileName),u=s.get(c);s.set(c,{path:u?.path??`https://scrapbox.io/api/code/${e}/${me(t)}/${me(c)}`,lang:u?.lang??l,startIds:[...u?.startIds??[],r[i].id]}),i+=a.content.split(`
`).length+1;break}}return s.values()};function dp(e){let t=o=>{if(o===null)r.write8(0);else if(typeof o=="boolean")r.write8(1),r.write8(+o);else if(typeof o=="number")r.write8(2),r.write32(o|0);else if(typeof o=="string")r.write8(3),r.write(Jt(o));else if(o instanceof Uint8Array)r.write8(4),r.write(o);else if(o instanceof Array){r.write8(5),r.write32(o.length);for(let n of o)t(n)}else{let n=Object.keys(o);r.write8(6),r.write32(n.length);for(let s of n)r.write(Jt(s)),t(o[s])}},r=new ha;return r.write32(0),r.write32(e.id<<1|+!e.isRequest),t(e.value),fp(r.buf,r.len-4,0),r.buf.subarray(0,r.len)}function ay(e){let t=()=>{switch(r.read8()){case 0:return null;case 1:return!!r.read8();case 2:return r.read32();case 3:return dn(r.read());case 4:return r.read();case 5:{let i=r.read32(),a=[];for(let c=0;c<i;c++)a.push(t());return a}case 6:{let i=r.read32(),a={};for(let c=0;c<i;c++)a[dn(r.read())]=t();return a}default:throw new Error("Invalid packet")}},r=new ha(e),o=r.read32(),n=(o&1)===0;o>>>=1;let s=t();if(r.ptr!==e.length)throw new Error("Invalid packet");return{id:o,isRequest:n,value:s}}var ha=class{constructor(t=new Uint8Array(1024)){this.buf=t}len=0;ptr=0;_write(t){if(this.len+t>this.buf.length){let r=new Uint8Array((this.len+t)*2);r.set(this.buf),this.buf=r}return this.len+=t,this.len-t}write8(t){let r=this._write(1);this.buf[r]=t}write32(t){let r=this._write(4);fp(this.buf,t,r)}write(t){let r=this._write(4+t.length);fp(this.buf,t.length,r),this.buf.set(t,r+4)}_read(t){if(this.ptr+t>this.buf.length)throw new Error("Invalid packet");return this.ptr+=t,this.ptr-t}read8(){return this.buf[this._read(1)]}read32(){return hp(this.buf,this._read(4))}read(){let t=this.read32(),r=new Uint8Array(t),o=this._read(r.length);return r.set(this.buf.subarray(o,o+t)),r}},Jt,dn,cy;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let e=new TextEncoder,t=new TextDecoder;Jt=r=>e.encode(r),dn=r=>t.decode(r),cy='new TextEncoder().encode("")'}else throw new Error("No UTF-8 codec found");if(!(Jt("")instanceof Uint8Array))throw new Error(`Invariant violation: "${cy} instanceof Uint8Array" is incorrectly false
This indicates that your JavaScript environment is broken. You cannot use
esbuild in this environment because esbuild relies on this invariant. This
is not a problem with esbuild. You need to fix your environment instead.
`);function hp(e,t){return e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}function fp(e,t,r){e[r++]=t,e[r++]=t>>8,e[r++]=t>>16,e[r++]=t>>24}var as="0.24.0";var Ge=JSON.stringify,ly="warning",py="silent";function uy(e){if(st(e,"target"),e.indexOf(",")>=0)throw new Error(`Invalid target: ${e}`);return e}var xa=()=>null,Me=e=>typeof e=="boolean"?null:"a boolean",V=e=>typeof e=="string"?null:"a string",ba=e=>e instanceof RegExp?null:"a RegExp object",Ao=e=>typeof e=="number"&&e===(e|0)?null:"an integer",dy=e=>typeof e=="function"?null:"a function",Ue=e=>Array.isArray(e)?null:"an array",Ht=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"an object",i0=e=>typeof e=="object"&&e!==null?null:"an array or an object";var my=e=>typeof e=="object"&&!Array.isArray(e)?null:"an object or null",hy=e=>typeof e=="string"||typeof e=="boolean"?null:"a string or a boolean",a0=e=>typeof e=="string"||typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"a string or an object",c0=e=>typeof e=="string"||Array.isArray(e)?null:"a string or an array",gy=e=>typeof e=="string"||e instanceof Uint8Array?null:"a string or a Uint8Array";function w(e,t,r,o){let n=e[r];if(t[r+""]=!0,n===void 0)return;let s=o(n);if(s!==null)throw new Error(`${Ge(r)} must be ${s}`);return n}function Ze(e,t,r){for(let o in e)if(!(o in t))throw new Error(`Invalid option ${r}: ${Ge(o)}`)}function yy(e){let t;if(e!==void 0){t=Object.create(null);for(let r in e){let o=e[r];if(typeof o=="string"||o===!1)t[r]=o;else throw new Error(`Expected ${Ge(r)} in mangle cache to map to either a string or false`)}}return t}function Ea(e,t,r,o,n){let s=w(t,r,"color",Me),i=w(t,r,"logLevel",V),a=w(t,r,"logLimit",Ao);s!==void 0?e.push(`--color=${s}`):o&&e.push("--color=true"),e.push(`--log-level=${i||n}`),e.push(`--log-limit=${a||0}`)}function st(e,t,r){if(typeof e!="string")throw new Error(`Expected value for ${t}${r!==void 0?" "+Ge(r):""} to be a string, got ${typeof e} instead`);return e}function xy(e,t,r){let o=w(t,r,"legalComments",V),n=w(t,r,"sourceRoot",V),s=w(t,r,"sourcesContent",Me),i=w(t,r,"target",c0),a=w(t,r,"format",V),c=w(t,r,"globalName",V),l=w(t,r,"mangleProps",ba),u=w(t,r,"reserveProps",ba),p=w(t,r,"mangleQuoted",Me),f=w(t,r,"minify",Me),m=w(t,r,"minifySyntax",Me),h=w(t,r,"minifyWhitespace",Me),g=w(t,r,"minifyIdentifiers",Me),y=w(t,r,"lineLimit",Ao),x=w(t,r,"drop",Ue),E=w(t,r,"dropLabels",Ue),k=w(t,r,"charset",V),b=w(t,r,"treeShaking",Me),v=w(t,r,"ignoreAnnotations",Me),R=w(t,r,"jsx",V),O=w(t,r,"jsxFactory",V),L=w(t,r,"jsxFragment",V),N=w(t,r,"jsxImportSource",V),P=w(t,r,"jsxDev",Me),_=w(t,r,"jsxSideEffects",Me),T=w(t,r,"define",Ht),S=w(t,r,"logOverride",Ht),A=w(t,r,"supported",Ht),M=w(t,r,"pure",Ue),D=w(t,r,"keepNames",Me),I=w(t,r,"platform",V),z=w(t,r,"tsconfigRaw",a0);if(o&&e.push(`--legal-comments=${o}`),n!==void 0&&e.push(`--source-root=${n}`),s!==void 0&&e.push(`--sources-content=${s}`),i&&(Array.isArray(i)?e.push(`--target=${Array.from(i).map(uy).join(",")}`):e.push(`--target=${uy(i)}`)),a&&e.push(`--format=${a}`),c&&e.push(`--global-name=${c}`),I&&e.push(`--platform=${I}`),z&&e.push(`--tsconfig-raw=${typeof z=="string"?z:JSON.stringify(z)}`),f&&e.push("--minify"),m&&e.push("--minify-syntax"),h&&e.push("--minify-whitespace"),g&&e.push("--minify-identifiers"),y&&e.push(`--line-limit=${y}`),k&&e.push(`--charset=${k}`),b!==void 0&&e.push(`--tree-shaking=${b}`),v&&e.push("--ignore-annotations"),x)for(let $ of x)e.push(`--drop:${st($,"drop")}`);if(E&&e.push(`--drop-labels=${Array.from(E).map($=>st($,"dropLabels")).join(",")}`),l&&e.push(`--mangle-props=${l.source}`),u&&e.push(`--reserve-props=${u.source}`),p!==void 0&&e.push(`--mangle-quoted=${p}`),R&&e.push(`--jsx=${R}`),O&&e.push(`--jsx-factory=${O}`),L&&e.push(`--jsx-fragment=${L}`),N&&e.push(`--jsx-import-source=${N}`),P&&e.push("--jsx-dev"),_&&e.push("--jsx-side-effects"),T)for(let $ in T){if($.indexOf("=")>=0)throw new Error(`Invalid define: ${$}`);e.push(`--define:${$}=${st(T[$],"define",$)}`)}if(S)for(let $ in S){if($.indexOf("=")>=0)throw new Error(`Invalid log override: ${$}`);e.push(`--log-override:${$}=${st(S[$],"log override",$)}`)}if(A)for(let $ in A){if($.indexOf("=")>=0)throw new Error(`Invalid supported: ${$}`);let q=A[$];if(typeof q!="boolean")throw new Error(`Expected value for supported ${Ge($)} to be a boolean, got ${typeof q} instead`);e.push(`--supported:${$}=${q}`)}if(M)for(let $ of M)e.push(`--pure:${st($,"pure")}`);D&&e.push("--keep-names")}function l0(e,t,r,o,n){let s=[],i=[],a=Object.create(null),c=null,l=null;Ea(s,t,a,r,o),xy(s,t,a);let u=w(t,a,"sourcemap",hy),p=w(t,a,"bundle",Me),f=w(t,a,"splitting",Me),m=w(t,a,"preserveSymlinks",Me),h=w(t,a,"metafile",Me),g=w(t,a,"outfile",V),y=w(t,a,"outdir",V),x=w(t,a,"outbase",V),E=w(t,a,"tsconfig",V),k=w(t,a,"resolveExtensions",Ue),b=w(t,a,"nodePaths",Ue),v=w(t,a,"mainFields",Ue),R=w(t,a,"conditions",Ue),O=w(t,a,"external",Ue),L=w(t,a,"packages",V),N=w(t,a,"alias",Ht),P=w(t,a,"loader",Ht),_=w(t,a,"outExtension",Ht),T=w(t,a,"publicPath",V),S=w(t,a,"entryNames",V),A=w(t,a,"chunkNames",V),M=w(t,a,"assetNames",V),D=w(t,a,"inject",Ue),I=w(t,a,"banner",Ht),z=w(t,a,"footer",Ht),$=w(t,a,"entryPoints",i0),q=w(t,a,"absWorkingDir",V),K=w(t,a,"stdin",Ht),ce=w(t,a,"write",Me)??n,ee=w(t,a,"allowOverwrite",Me),tt=w(t,a,"mangleCache",Ht);if(a.plugins=!0,Ze(t,a,`in ${e}() call`),u&&s.push(`--sourcemap${u===!0?"":`=${u}`}`),p&&s.push("--bundle"),ee&&s.push("--allow-overwrite"),f&&s.push("--splitting"),m&&s.push("--preserve-symlinks"),h&&s.push("--metafile"),g&&s.push(`--outfile=${g}`),y&&s.push(`--outdir=${y}`),x&&s.push(`--outbase=${x}`),E&&s.push(`--tsconfig=${E}`),L&&s.push(`--packages=${L}`),k){let U=[];for(let we of k){if(st(we,"resolve extension"),we.indexOf(",")>=0)throw new Error(`Invalid resolve extension: ${we}`);U.push(we)}s.push(`--resolve-extensions=${U.join(",")}`)}if(T&&s.push(`--public-path=${T}`),S&&s.push(`--entry-names=${S}`),A&&s.push(`--chunk-names=${A}`),M&&s.push(`--asset-names=${M}`),v){let U=[];for(let we of v){if(st(we,"main field"),we.indexOf(",")>=0)throw new Error(`Invalid main field: ${we}`);U.push(we)}s.push(`--main-fields=${U.join(",")}`)}if(R){let U=[];for(let we of R){if(st(we,"condition"),we.indexOf(",")>=0)throw new Error(`Invalid condition: ${we}`);U.push(we)}s.push(`--conditions=${U.join(",")}`)}if(O)for(let U of O)s.push(`--external:${st(U,"external")}`);if(N)for(let U in N){if(U.indexOf("=")>=0)throw new Error(`Invalid package name in alias: ${U}`);s.push(`--alias:${U}=${st(N[U],"alias",U)}`)}if(I)for(let U in I){if(U.indexOf("=")>=0)throw new Error(`Invalid banner file type: ${U}`);s.push(`--banner:${U}=${st(I[U],"banner",U)}`)}if(z)for(let U in z){if(U.indexOf("=")>=0)throw new Error(`Invalid footer file type: ${U}`);s.push(`--footer:${U}=${st(z[U],"footer",U)}`)}if(D)for(let U of D)s.push(`--inject:${st(U,"inject")}`);if(P)for(let U in P){if(U.indexOf("=")>=0)throw new Error(`Invalid loader extension: ${U}`);s.push(`--loader:${U}=${st(P[U],"loader",U)}`)}if(_)for(let U in _){if(U.indexOf("=")>=0)throw new Error(`Invalid out extension: ${U}`);s.push(`--out-extension:${U}=${st(_[U],"out extension",U)}`)}if($)if(Array.isArray($))for(let U=0,we=$.length;U<we;U++){let ct=$[U];if(typeof ct=="object"&&ct!==null){let mr=Object.create(null),fr=w(ct,mr,"in",V),tr=w(ct,mr,"out",V);if(Ze(ct,mr,"in entry point at index "+U),fr===void 0)throw new Error('Missing property "in" for entry point at index '+U);if(tr===void 0)throw new Error('Missing property "out" for entry point at index '+U);i.push([tr,fr])}else i.push(["",st(ct,"entry point at index "+U)])}else for(let U in $)i.push([U,st($[U],"entry point",U)]);if(K){let U=Object.create(null),we=w(K,U,"contents",gy),ct=w(K,U,"resolveDir",V),mr=w(K,U,"sourcefile",V),fr=w(K,U,"loader",V);Ze(K,U,'in "stdin" object'),mr&&s.push(`--sourcefile=${mr}`),fr&&s.push(`--loader=${fr}`),ct&&(l=ct),typeof we=="string"?c=Jt(we):we instanceof Uint8Array&&(c=we)}let Oe=[];if(b)for(let U of b)U+="",Oe.push(U);return{entries:i,flags:s,write:ce,stdinContents:c,stdinResolveDir:l,absWorkingDir:q,nodePaths:Oe,mangleCache:yy(tt)}}function p0(e,t,r,o){let n=[],s=Object.create(null);Ea(n,t,s,r,o),xy(n,t,s);let i=w(t,s,"sourcemap",hy),a=w(t,s,"sourcefile",V),c=w(t,s,"loader",V),l=w(t,s,"banner",V),u=w(t,s,"footer",V),p=w(t,s,"mangleCache",Ht);return Ze(t,s,`in ${e}() call`),i&&n.push(`--sourcemap=${i===!0?"external":i}`),a&&n.push(`--sourcefile=${a}`),c&&n.push(`--loader=${c}`),l&&n.push(`--banner=${l}`),u&&n.push(`--footer=${u}`),{flags:n,mangleCache:yy(p)}}function by(e){let t={},r={didClose:!1,reason:""},o={},n=0,s=0,i=new Uint8Array(16*1024),a=0,c=k=>{let b=a+k.length;if(b>i.length){let R=new Uint8Array(b*2);R.set(i),i=R}i.set(k,a),a+=k.length;let v=0;for(;v+4<=a;){let R=hp(i,v);if(v+4+R>a)break;v+=4,h(i.subarray(v,v+R)),v+=R}v>0&&(i.copyWithin(0,v,a),a-=v)},l=k=>{r.didClose=!0,k&&(r.reason=": "+(k.message||k));let b="The service was stopped"+r.reason;for(let v in o)o[v](b,null);o={}},u=(k,b,v)=>{if(r.didClose)return v("The service is no longer running"+r.reason,null);let R=n++;o[R]=(O,L)=>{try{v(O,L)}finally{k&&k.unref()}},k&&k.ref(),e.writeToStdin(dp({id:R,isRequest:!0,value:b}))},p=(k,b)=>{if(r.didClose)throw new Error("The service is no longer running"+r.reason);e.writeToStdin(dp({id:k,isRequest:!1,value:b}))},f=async(k,b)=>{try{if(b.command==="ping"){p(k,{});return}if(typeof b.key=="number"){let v=t[b.key];if(!v)return;let R=v[b.command];if(R){await R(k,b);return}}throw new Error("Invalid command: "+b.command)}catch(v){let R=[Co(v,e,null,void 0,"")];try{p(k,{errors:R})}catch{}}},m=!0,h=k=>{if(m){m=!1;let v=String.fromCharCode(...k);if(v!==as)throw new Error(`Cannot start service: Host version "${as}" does not match binary version ${Ge(v)}`);return}let b=ay(k);if(b.isRequest)f(b.id,b.value);else{let v=o[b.id];delete o[b.id],b.value.error?v(b.value.error,{}):v(null,b.value)}};return{readFromStdout:c,afterClose:l,service:{buildOrContext:({callName:k,refs:b,options:v,isTTY:R,defaultWD:O,callback:L})=>{let N=0,P=s++,_={},T={ref(){++N===1&&b&&b.ref()},unref(){--N===0&&(delete t[P],b&&b.unref())}};t[P]=_,T.ref(),u0(k,P,u,p,T,e,_,v,R,O,(S,A)=>{try{L(S,A)}finally{T.unref()}})},transform:({callName:k,refs:b,input:v,options:R,isTTY:O,fs:L,callback:N})=>{let P=Ey(),_=T=>{try{if(typeof v!="string"&&!(v instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:S,mangleCache:A}=p0(k,R,O,py),M={command:"transform",flags:S,inputFS:T!==null,input:T!==null?Jt(T):typeof v=="string"?Jt(v):v};A&&(M.mangleCache=A),u(b,M,(D,I)=>{if(D)return N(new Error(D),null);let z=hn(I.errors,P),$=hn(I.warnings,P),q=1,K=()=>{if(--q===0){let ce={warnings:$,code:I.code,map:I.map,mangleCache:void 0,legalComments:void 0};"legalComments"in I&&(ce.legalComments=I?.legalComments),I.mangleCache&&(ce.mangleCache=I?.mangleCache),N(null,ce)}};if(z.length>0)return N(cs("Transform failed",z,$),null);I.codeFS&&(q++,L.readFile(I.code,(ce,ee)=>{ce!==null?N(ce,null):(I.code=ee,K())})),I.mapFS&&(q++,L.readFile(I.map,(ce,ee)=>{ce!==null?N(ce,null):(I.map=ee,K())})),K()})}catch(S){let A=[];try{Ea(A,R,{},O,py)}catch{}let M=Co(S,e,P,void 0,"");u(b,{command:"error",flags:A,error:M},()=>{M.detail=P.load(M.detail),N(cs("Transform failed",[M],[]),null)})}};if((typeof v=="string"||v instanceof Uint8Array)&&v.length>1024*1024){let T=_;_=()=>L.writeFile(v,T)}_(null)},formatMessages:({callName:k,refs:b,messages:v,options:R,callback:O})=>{if(!R)throw new Error(`Missing second argument in ${k}() call`);let L={},N=w(R,L,"kind",V),P=w(R,L,"color",Me),_=w(R,L,"terminalWidth",Ao);if(Ze(R,L,`in ${k}() call`),N===void 0)throw new Error(`Missing "kind" in ${k}() call`);if(N!=="error"&&N!=="warning")throw new Error(`Expected "kind" to be "error" or "warning" in ${k}() call`);let T={command:"format-msgs",messages:Pr(v,"messages",null,"",_),isWarning:N==="warning"};P!==void 0&&(T.color=P),_!==void 0&&(T.terminalWidth=_),u(b,T,(S,A)=>{if(S)return O(new Error(S),null);O(null,A.messages)})},analyzeMetafile:({callName:k,refs:b,metafile:v,options:R,callback:O})=>{R===void 0&&(R={});let L={},N=w(R,L,"color",Me),P=w(R,L,"verbose",Me);Ze(R,L,`in ${k}() call`);let _={command:"analyze-metafile",metafile:v};N!==void 0&&(_.color=N),P!==void 0&&(_.verbose=P),u(b,_,(T,S)=>{if(T)return O(new Error(T),null);O(null,S.result)})}}}}function u0(e,t,r,o,n,s,i,a,c,l,u){let p=Ey(),f=e==="context",m=(y,x)=>{let E=[];try{Ea(E,a,{},c,ly)}catch{}let k=Co(y,s,p,void 0,x);r(n,{command:"error",flags:E,error:k},()=>{k.detail=p.load(k.detail),u(cs(f?"Context failed":"Build failed",[k],[]),null)})},h;if(typeof a=="object"){let y=a.plugins;if(y!==void 0){if(!Array.isArray(y))return m(new Error('"plugins" must be an array'),"");h=y}}if(h&&h.length>0){if(s.isSync)return m(new Error("Cannot use plugins in synchronous API calls"),"");m0(t,r,o,n,s,i,a,h,p).then(y=>{if(!y.ok)return m(y.error,y.pluginName);try{g(y.requestPlugins,y.runOnEndCallbacks,y.scheduleOnDisposeCallbacks)}catch(x){m(x,"")}},y=>m(y,""));return}try{g(null,(y,x)=>x([],[]),()=>{})}catch(y){m(y,"")}function g(y,x,E){let k=s.hasFS,{entries:b,flags:v,write:R,stdinContents:O,stdinResolveDir:L,absWorkingDir:N,nodePaths:P,mangleCache:_}=l0(e,a,c,ly,k);if(R&&!s.hasFS)throw new Error('The "write" option is unavailable in this environment');let T={command:"build",key:t,entries:b,flags:v,write:R,stdinContents:O,stdinResolveDir:L,absWorkingDir:N||l,nodePaths:P,context:f};y&&(T.plugins=y),_&&(T.mangleCache=_);let S=(D,I)=>{let z={errors:hn(D.errors,p),warnings:hn(D.warnings,p),outputFiles:void 0,metafile:void 0,mangleCache:void 0},$=z.errors.slice(),q=z.warnings.slice();D.outputFiles&&(z.outputFiles=D.outputFiles.map(d0)),D.metafile&&(z.metafile=JSON.parse(D.metafile)),D.mangleCache&&(z.mangleCache=D.mangleCache),D.writeToStdout!==void 0&&console.log(dn(D.writeToStdout).replace(/\n$/,"")),x(z,(K,ce)=>{if($.length>0||K.length>0){let ee=cs("Build failed",$.concat(K),q.concat(ce));return I(ee,null,K,ce)}I(null,z,K,ce)})},A,M;f&&(i["on-end"]=(D,I)=>new Promise(z=>{S(I,($,q,K,ce)=>{let ee={errors:K,warnings:ce};M&&M($,q),A=void 0,M=void 0,o(D,ee),z()})})),r(n,T,(D,I)=>{if(D)return u(new Error(D),null);if(!f)return S(I,(q,K)=>(E(),u(q,K)));if(I.errors.length>0)return u(cs("Context failed",I.errors,I.warnings),null);let z=!1,$={rebuild:()=>(A||(A=new Promise((q,K)=>{let ce;M=(tt,Oe)=>{ce||(ce=()=>tt?K(tt):q(Oe))};let ee=()=>{r(n,{command:"rebuild",key:t},(Oe,U)=>{Oe?K(new Error(Oe)):ce?ce():ee()})};ee()})),A),watch:(q={})=>new Promise((K,ce)=>{if(!s.hasFS)throw new Error('Cannot use the "watch" API in this environment');Ze(q,{},"in watch() call"),r(n,{command:"watch",key:t},Oe=>{Oe?ce(new Error(Oe)):K(void 0)})}),serve:(q={})=>new Promise((K,ce)=>{if(!s.hasFS)throw new Error('Cannot use the "serve" API in this environment');let ee={},tt=w(q,ee,"port",Ao),Oe=w(q,ee,"host",V),U=w(q,ee,"servedir",V),we=w(q,ee,"keyfile",V),ct=w(q,ee,"certfile",V),mr=w(q,ee,"fallback",V),fr=w(q,ee,"onRequest",dy);Ze(q,ee,"in serve() call");let tr={command:"serve",key:t,onRequest:!!fr};tt!==void 0&&(tr.port=tt),Oe!==void 0&&(tr.host=Oe),U!==void 0&&(tr.servedir=U),we!==void 0&&(tr.keyfile=we),ct!==void 0&&(tr.certfile=ct),mr!==void 0&&(tr.fallback=mr),r(n,tr,(Xu,CR)=>{if(Xu)return ce(new Error(Xu));fr&&(i["serve-request"]=(AR,MR)=>{fr(MR.args),o(AR,{})}),K(CR)})}),cancel:()=>new Promise(q=>{if(z)return q();r(n,{command:"cancel",key:t},()=>{q()})}),dispose:()=>new Promise(q=>{if(z)return q();z=!0,r(n,{command:"dispose",key:t},()=>{q(),E(),n.unref()})})};n.ref(),u(null,$)})}}var m0=async(e,t,r,o,n,s,i,a,c)=>{let l=[],u=[],p={},f={},m=[],h=0,g=0,y=[],x=!1;a=[...a];for(let b of a){let v={};if(typeof b!="object")throw new Error(`Plugin at index ${g} must be an object`);let R=w(b,v,"name",V);if(typeof R!="string"||R==="")throw new Error(`Plugin at index ${g} is missing a name`);try{let O=w(b,v,"setup",dy);if(typeof O!="function")throw new Error("Plugin is missing a setup function");Ze(b,v,`on plugin ${Ge(R)}`);let L={name:R,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};g++;let P=O({initialOptions:i,resolve:(_,T={})=>{if(!x)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof _!="string")throw new Error("The path to resolve must be a string");let S=Object.create(null),A=w(T,S,"pluginName",V),M=w(T,S,"importer",V),D=w(T,S,"namespace",V),I=w(T,S,"resolveDir",V),z=w(T,S,"kind",V),$=w(T,S,"pluginData",xa),q=w(T,S,"with",Ht);return Ze(T,S,"in resolve() call"),new Promise((K,ce)=>{let ee={command:"resolve",path:_,key:e,pluginName:R};if(A!=null&&(ee.pluginName=A),M!=null&&(ee.importer=M),D!=null&&(ee.namespace=D),I!=null&&(ee.resolveDir=I),z!=null)ee.kind=z;else throw new Error('Must specify "kind" when calling "resolve"');$!=null&&(ee.pluginData=c.store($)),q!=null&&(ee.with=f0(q,"with")),t(o,ee,(tt,Oe)=>{tt!==null?ce(new Error(tt)):K({errors:hn(Oe.errors,c),warnings:hn(Oe.warnings,c),path:Oe.path,external:Oe.external,sideEffects:Oe.sideEffects,namespace:Oe.namespace,suffix:Oe.suffix,pluginData:c.load(Oe.pluginData)})})})},onStart(_){let T='This error came from the "onStart" callback registered here:',S=ga(new Error(T),n,"onStart");l.push({name:R,callback:_,note:S}),L.onStart=!0},onEnd(_){let T='This error came from the "onEnd" callback registered here:',S=ga(new Error(T),n,"onEnd");u.push({name:R,callback:_,note:S}),L.onEnd=!0},onResolve(_,T){let S='This error came from the "onResolve" callback registered here:',A=ga(new Error(S),n,"onResolve"),M={},D=w(_,M,"filter",ba),I=w(_,M,"namespace",V);if(Ze(_,M,`in onResolve() call for plugin ${Ge(R)}`),D==null)throw new Error("onResolve() call is missing a filter");let z=h++;p[z]={name:R,callback:T,note:A},L.onResolve.push({id:z,filter:D.source,namespace:I||""})},onLoad(_,T){let S='This error came from the "onLoad" callback registered here:',A=ga(new Error(S),n,"onLoad"),M={},D=w(_,M,"filter",ba),I=w(_,M,"namespace",V);if(Ze(_,M,`in onLoad() call for plugin ${Ge(R)}`),D==null)throw new Error("onLoad() call is missing a filter");let z=h++;f[z]={name:R,callback:T,note:A},L.onLoad.push({id:z,filter:D.source,namespace:I||""})},onDispose(_){m.push(_)},esbuild:n.esbuild});P&&await P,y.push(L)}catch(O){return{ok:!1,error:O,pluginName:R}}}s["on-start"]=async(b,v)=>{c.clear();let R={errors:[],warnings:[]};await Promise.all(l.map(async({name:O,callback:L,note:N})=>{try{let P=await L();if(P!=null){if(typeof P!="object")throw new Error(`Expected onStart() callback in plugin ${Ge(O)} to return an object`);let _={},T=w(P,_,"errors",Ue),S=w(P,_,"warnings",Ue);Ze(P,_,`from onStart() callback in plugin ${Ge(O)}`),T!=null&&R.errors.push(...Pr(T,"errors",c,O,void 0)),S!=null&&R.warnings.push(...Pr(S,"warnings",c,O,void 0))}}catch(P){R.errors.push(Co(P,n,c,N&&N(),O))}})),r(b,R)},s["on-resolve"]=async(b,v)=>{let R={},O="",L,N;for(let P of v.ids)try{({name:O,callback:L,note:N}=p[P]);let _=await L({path:v.path,importer:v.importer,namespace:v.namespace,resolveDir:v.resolveDir,kind:v.kind,pluginData:c.load(v.pluginData),with:v.with});if(_!=null){if(typeof _!="object")throw new Error(`Expected onResolve() callback in plugin ${Ge(O)} to return an object`);let T={},S=w(_,T,"pluginName",V),A=w(_,T,"path",V),M=w(_,T,"namespace",V),D=w(_,T,"suffix",V),I=w(_,T,"external",Me),z=w(_,T,"sideEffects",Me),$=w(_,T,"pluginData",xa),q=w(_,T,"errors",Ue),K=w(_,T,"warnings",Ue),ce=w(_,T,"watchFiles",Ue),ee=w(_,T,"watchDirs",Ue);Ze(_,T,`from onResolve() callback in plugin ${Ge(O)}`),R.id=P,S!=null&&(R.pluginName=S),A!=null&&(R.path=A),M!=null&&(R.namespace=M),D!=null&&(R.suffix=D),I!=null&&(R.external=I),z!=null&&(R.sideEffects=z),$!=null&&(R.pluginData=c.store($)),q!=null&&(R.errors=Pr(q,"errors",c,O,void 0)),K!=null&&(R.warnings=Pr(K,"warnings",c,O,void 0)),ce!=null&&(R.watchFiles=ya(ce,"watchFiles")),ee!=null&&(R.watchDirs=ya(ee,"watchDirs"));break}}catch(_){R={id:P,errors:[Co(_,n,c,N&&N(),O)]};break}r(b,R)},s["on-load"]=async(b,v)=>{let R={},O="",L,N;for(let P of v.ids)try{({name:O,callback:L,note:N}=f[P]);let _=await L({path:v.path,namespace:v.namespace,suffix:v.suffix,pluginData:c.load(v.pluginData),with:v.with});if(_!=null){if(typeof _!="object")throw new Error(`Expected onLoad() callback in plugin ${Ge(O)} to return an object`);let T={},S=w(_,T,"pluginName",V),A=w(_,T,"contents",gy),M=w(_,T,"resolveDir",V),D=w(_,T,"pluginData",xa),I=w(_,T,"loader",V),z=w(_,T,"errors",Ue),$=w(_,T,"warnings",Ue),q=w(_,T,"watchFiles",Ue),K=w(_,T,"watchDirs",Ue);Ze(_,T,`from onLoad() callback in plugin ${Ge(O)}`),R.id=P,S!=null&&(R.pluginName=S),A instanceof Uint8Array?R.contents=A:A!=null&&(R.contents=Jt(A)),M!=null&&(R.resolveDir=M),D!=null&&(R.pluginData=c.store(D)),I!=null&&(R.loader=I),z!=null&&(R.errors=Pr(z,"errors",c,O,void 0)),$!=null&&(R.warnings=Pr($,"warnings",c,O,void 0)),q!=null&&(R.watchFiles=ya(q,"watchFiles")),K!=null&&(R.watchDirs=ya(K,"watchDirs"));break}}catch(_){R={id:P,errors:[Co(_,n,c,N&&N(),O)]};break}r(b,R)};let E=(b,v)=>v([],[]);u.length>0&&(E=(b,v)=>{(async()=>{let R=[],O=[];for(let{name:L,callback:N,note:P}of u){let _,T;try{let S=await N(b);if(S!=null){if(typeof S!="object")throw new Error(`Expected onEnd() callback in plugin ${Ge(L)} to return an object`);let A={},M=w(S,A,"errors",Ue),D=w(S,A,"warnings",Ue);Ze(S,A,`from onEnd() callback in plugin ${Ge(L)}`),M!=null&&(_=Pr(M,"errors",c,L,void 0)),D!=null&&(T=Pr(D,"warnings",c,L,void 0))}}catch(S){_=[Co(S,n,c,P&&P(),L)]}if(_){R.push(..._);try{b.errors.push(..._)}catch{}}if(T){O.push(...T);try{b.warnings.push(...T)}catch{}}}v(R,O)})()});let k=()=>{for(let b of m)setTimeout(()=>b(),0)};return x=!0,{ok:!0,requestPlugins:y,runOnEndCallbacks:E,scheduleOnDisposeCallbacks:k}};function Ey(){let e=new Map,t=0;return{clear(){e.clear()},load(r){return e.get(r)},store(r){if(r===void 0)return-1;let o=t++;return e.set(o,r),o}}}function ga(e,t,r){let o,n=!1;return()=>{if(n)return o;n=!0;try{let s=(e.stack+"").split(`
`);s.splice(1,1);let i=wy(t,s,r);if(i)return o={text:e.message,location:i},o}catch{}}}function Co(e,t,r,o,n){let s="Internal error",i=null;try{s=(e&&e.message||e)+""}catch{}try{i=wy(t,(e.stack+"").split(`
`),"")}catch{}return{id:"",pluginName:n,text:s,location:i,notes:o?[o]:[],detail:r?r.store(e):-1}}function wy(e,t,r){let o=" at ";if(e.readFileSync&&!t[0].startsWith(o)&&t[1].startsWith(o))for(let n=1;n<t.length;n++){let s=t[n];if(s.startsWith(o))for(s=s.slice(o.length);;){let i=/^(?:new |async )?\S+ \((.*)\)$/.exec(s);if(i){s=i[1];continue}if(i=/^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(s),i){s=i[1];continue}if(i=/^(\S+):(\d+):(\d+)$/.exec(s),i){let a;try{a=e.readFileSync(i[1],"utf8")}catch{break}let c=a.split(/\r\n|\r|\n|\u2028|\u2029/)[+i[2]-1]||"",l=+i[3]-1,u=c.slice(l,l+r.length)===r?r.length:0;return{file:i[1],namespace:"file",line:+i[2],column:Jt(c.slice(0,l)).length,length:Jt(c.slice(l,l+u)).length,lineText:c+`
`+t.slice(1).join(`
`),suggestion:""}}break}}return null}function cs(e,t,r){let o=5;e+=t.length<1?"":` with ${t.length} error${t.length<2?"":"s"}:`+t.slice(0,o+1).map((s,i)=>{if(i===o)return`
...`;if(!s.location)return`
error: ${s.text}`;let{file:a,line:c,column:l}=s.location,u=s.pluginName?`[plugin: ${s.pluginName}] `:"";return`
${a}:${c}:${l}: ERROR: ${u}${s.text}`}).join("");let n=new Error(e);for(let[s,i]of[["errors",t],["warnings",r]])Object.defineProperty(n,s,{configurable:!0,enumerable:!0,get:()=>i,set:a=>Object.defineProperty(n,s,{configurable:!0,enumerable:!0,value:a})});return n}function hn(e,t){for(let r of e)r.detail=t.load(r.detail);return e}function fy(e,t,r){if(e==null)return null;let o={},n=w(e,o,"file",V),s=w(e,o,"namespace",V),i=w(e,o,"line",Ao),a=w(e,o,"column",Ao),c=w(e,o,"length",Ao),l=w(e,o,"lineText",V),u=w(e,o,"suggestion",V);if(Ze(e,o,t),l){let p=l.slice(0,(a&&a>0?a:0)+(c&&c>0?c:0)+(r&&r>0?r:80));!/[\x7F-\uFFFF]/.test(p)&&!/\n/.test(l)&&(l=p)}return{file:n||"",namespace:s||"",line:i||0,column:a||0,length:c||0,lineText:l||"",suggestion:u||""}}function Pr(e,t,r,o,n){let s=[],i=0;for(let a of e){let c={},l=w(a,c,"id",V),u=w(a,c,"pluginName",V),p=w(a,c,"text",V),f=w(a,c,"location",my),m=w(a,c,"notes",Ue),h=w(a,c,"detail",xa),g=`in element ${i} of "${t}"`;Ze(a,c,g);let y=[];if(m)for(let x of m){let E={},k=w(x,E,"text",V),b=w(x,E,"location",my);Ze(x,E,g),y.push({text:k||"",location:fy(b,g,n)})}s.push({id:l||"",pluginName:u||o,text:p||"",location:fy(f,g,n),notes:y,detail:r?r.store(h):-1}),i++}return s}function ya(e,t){let r=[];for(let o of e){if(typeof o!="string")throw new Error(`${Ge(t)} must be an array of strings`);r.push(o)}return r}function f0(e,t){let r=Object.create(null);for(let o in e){let n=e[o];if(typeof n!="string")throw new Error(`key ${Ge(o)} in object ${Ge(t)} must be a string`);r[o]=n}return r}function d0({path:e,contents:t,hash:r}){let o=null;return{path:e,contents:t,hash:r,get text(){let n=this.contents;return(o===null||n!==t)&&(t=n,o=dn(n)),o}}}var ky=as,Ra=e=>ka().build(e),vy=(e,t)=>ka().transform(e,t),_y=(e,t)=>ka().formatMessages(e,t),Ty=(e,t)=>ka().analyzeMetafile(e,t);var Mo,Ry,wa,ka=()=>{if(wa)return wa;throw Mo?new Error('You need to wait for the promise returned from "initialize" to be resolved before calling this'):new Error('You need to call "initialize" before calling this')},va=e=>{let t=e.wasm,r=e.worker;if(Mo)throw new Error('Cannot call "initialize" more than once');return Mo=h0(t,r),Mo.catch(()=>{Mo=void 0}),Mo},h0=async(e,t)=>{let r=new Worker(t.toString(),{type:"module"}),o,n,s=new Promise((c,l)=>{o=c,n=l});r.onmessage=({data:c})=>{r.onmessage=({data:l})=>i(l),c?n(c):o()},r.postMessage(e);let{readFromStdout:i,service:a}=by({writeToStdin(c){r.postMessage(c)},isSync:!1,hasFS:!1,esbuild:{build:Ra,transform:vy,formatMessages:_y,analyzeMetafile:Ty,version:ky,initialize:va}});await s,Ry=()=>{r.terminate(),Mo=void 0,Ry=void 0,wa=void 0},wa={build:c=>new Promise((l,u)=>a.buildOrContext({callName:"build",refs:null,options:c,isTTY:!1,defaultWD:"/",callback:(p,f)=>p?u(p):l(f)})),transform:(c,l)=>new Promise((u,p)=>a.transform({callName:"transform",refs:null,input:c,options:l||{},isTTY:!1,fs:{readFile(f,m){m(new Error("Internal error"),null)},writeFile(f,m){m(null)}},callback:(f,m)=>f?p(f):u(m)})),formatMessages:(c,l)=>new Promise((u,p)=>a.formatMessages({callName:"formatMessages",refs:null,messages:c,options:l,callback:(f,m)=>f?p(f):u(m)})),analyzeMetafile:(c,l)=>new Promise((u,p)=>a.analyzeMetafile({callName:"analyzeMetafile",refs:null,metafile:typeof c=="string"?c:JSON.stringify(c),options:l,callback:(f,m)=>f?p(f):u(m)}))}};self.Deno||(self.Deno={build:{os:"linux"},errors:{AlreadyExists:Error},env:{get:()=>{}},permissions:{query:()=>Promise.resolve("denied")},cwd:()=>location.href});function ht(e){if(typeof e!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(e)}`)}function lr(e){return e===47||e===92}function Sr(e){return e>=97&&e<=122||e>=65&&e<=90}function Pa(e){if(e=e instanceof URL?e:new URL(e),e.protocol!=="file:")throw new TypeError("Must be a file URL.");return e}function Py(e){e=Pa(e);let t=decodeURIComponent(e.pathname.replace(/\//g,"\\").replace(/%(?![0-9A-Fa-f]{2})/g,"%25")).replace(/^\\*([A-Za-z]:)(\\|$)/,"$1\\");return e.hostname!==""&&(t=`\\\\${e.hostname}${t}`),t}function yp(e){ht(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return lr(r)?!0:!!(Sr(r)&&t>2&&e.charCodeAt(1)===58&&lr(e.charCodeAt(2)))}var Sa=class extends Error{constructor(t){super(t),this.name="AssertionError"}};function Oa(e,t=""){if(!e)throw new Sa(t)}var S0={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function La(e){return e.replaceAll(/[\s]/g,t=>S0[t]??t)}function Ly(e){if(!yp(e))throw new TypeError("Must be an absolute path.");let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),o=new URL("file:///");if(o.pathname=La(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(o.hostname=t,!o.hostname))throw new TypeError("Invalid hostname.");return o}function Or(e){return e===47}function Cy(e){return e=Pa(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function bp(e){return ht(e),e.length>0&&Or(e.charCodeAt(0))}function My(e){if(!bp(e))throw new TypeError("Must be an absolute path.");let t=new URL("file:///");return t.pathname=La(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}var j0=(()=>{let{Deno:e}=globalThis;if(typeof e?.build?.os=="string")return e.build.os;let{navigator:t}=globalThis;return t?.appVersion?.includes?.("Win")?"windows":"linux"})(),je=j0==="windows";var gn=je?"\\":"/";function Na(e){return je?Py(e):Cy(e)}function ps(e){return je?Ly(e):My(e)}function Ca(e){return typeof e=="object"&&e!==null&&e.constructor===Object}function Aa(e){let t={},r=Object.keys(e).sort((o,n)=>n.length-o.length);for(let o of r)t[o]=e[o];return t}function Iy(e){return Ca(e)&&(e.imports!==void 0?Ep(e.imports):!0)&&(e.scopes!==void 0?wp(e.scopes):!0)}function Ep(e){return Ca(e)}function wp(e){return Ca(e)&&Object.values(e).every(t=>Rp(t))}function Rp(e){return Ca(e)}function Ma(e){try{return new URL(e),!0}catch{return!1}}function Uy(e,t){let r={};for(let[o,n]of Object.entries(e)){let s=H0(o,t);if(s===null)continue;if(typeof n!="string"){console.warn("addresses need to be strings."),r[s]=null;continue}let i=kp(n,t);if(i===null){console.warn("the address was invalid."),r[s]=null;continue}if(o.endsWith("/")&&!pr(i).endsWith("/")){console.warn("an invalid address was given for the specifier key specifierKey; since specifierKey ended in a slash, the address needs to as well."),r[s]=null;continue}r[s]=pr(i)}return Aa(r)}function pr(e){return e.href}function B0(e,t){let r={};for(let[n,s]of Object.entries(e)){if(!Rp(s))throw new TypeError("the value of the scope with prefix scopePrefix needs to be an object.");let i;try{i=new URL(n,t)}catch{console.warn("the scope prefix URL was not parseable.");continue}let a=pr(i);r[a]=Uy(s,t)}let o={};for(let n of Object.keys(r))o[n]=Aa(r[n]);return Aa(o)}function H0(e,t){if(!e.length)return console.warn("specifier key cannot be an empty string."),null;let r=kp(e,t);return r!==null?pr(r):e}function kp(e,t){if(t&&(e.startsWith("/")||e.startsWith("./")||e.startsWith("../")))try{return new URL(e,t)}catch{return null}try{return new URL(e)}catch{return null}}var W0=["ftp","file","http","https","ws","wss"];function G0(e){return W0.some(t=>pr(e).startsWith(t))}function Fy(e,t,r){for(let[o,n]of Object.entries(r))if(o===e){if(n===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!Ma(n))throw new TypeError("resolutionResult must be an URL.");return n}else if(o.endsWith("/")&&e.startsWith(o)&&(t===null||G0(t))){if(n===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!Ma(n))throw new TypeError("resolutionResult must be an URL.");let s=e.slice(o.length);if(!n.endsWith("/"))throw new TypeError('resolutionResult does not end with "/"');try{let i=new URL(s,n);if(!Ma(i))throw new TypeError("url must be an URL.");if(!pr(i).startsWith(n))throw new TypeError("resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.");return pr(i)}catch{throw new TypeError("resolution of normalizedSpecifier was blocked since the afterPrefix portion could not be URL-parsed relative to the resolutionResult mapped to by the specifierKey prefix.")}}return null}function vp(e,t){let r={};if(!Iy(e))throw new TypeError("the top-level value needs to be a JSON object.");let{imports:o,scopes:n}=e;if(o!==void 0){if(!Ep(o))throw new TypeError('"imports" top-level key needs to be an object.');r=Uy(o,t)}let s={};if(n!==void 0){if(!wp(n))throw new TypeError('"scopes" top-level key needs to be an object.');s=B0(n,t)}return Object.keys(e).find(i=>i!=="imports"&&i!=="scopes")&&console.warn("an invalid top-level key was present in the import map."),{imports:r,scopes:s}}function Dy(e,{imports:t={},scopes:r={}},o){let n=pr(o),s=kp(e,o),i=s!==null?pr(s):e;for(let[c,l]of Object.entries(r))if(c===n||c.endsWith("/")&&n.startsWith(c)){let u=Fy(i,s,l);if(u!==null)return u}let a=Fy(i,s,t);if(a!==null)return a;if(s!==null)return pr(s);throw new TypeError("specifier was a bare specifier, but was not remapped to anything by importMap.")}function jy(e,{allowTrailingComma:t=!0}={}){if(new.target)throw new TypeError("parse is not a constructor");return new _p(e,{allowTrailingComma:t}).parse()}var $y=globalThis.JSON.parse,_p=class{#i=new Set(` \r
`);#o=new Set([..."[]{}:,/",...this.#i]);#t;#e;#s;#a;constructor(t,r){this.#t=`${t}`,this.#e=this.#t.length,this.#s=this.#m(),this.#a=r}parse(){let t=this.#n(),r=this.#p(t),{done:o,value:n}=this.#s.next();if(!o)throw new SyntaxError(Jr(n));return r}#n(){let{done:t,value:r}=this.#s.next();if(t)throw new SyntaxError("Unexpected end of JSONC input");return r}*#m(){for(let t=0;t<this.#e;t++)if(!this.#i.has(this.#t[t])){if(this.#t[t]==="/"&&this.#t[t+1]==="*"){t+=2;let r=!1;for(;t<this.#e;t++)if(this.#t[t]==="*"&&this.#t[t+1]==="/"){r=!0;break}if(!r)throw new SyntaxError("Unexpected end of JSONC input");t++;continue}if(this.#t[t]==="/"&&this.#t[t+1]==="/"){for(t+=2;t<this.#e&&!(this.#t[t]===`
`||this.#t[t]==="\r");t++);continue}switch(this.#t[t]){case"{":yield{type:"BeginObject",position:t};break;case"}":yield{type:"EndObject",position:t};break;case"[":yield{type:"BeginArray",position:t};break;case"]":yield{type:"EndArray",position:t};break;case":":yield{type:"NameSeparator",position:t};break;case",":yield{type:"ValueSeparator",position:t};break;case'"':{let r=t,o=!1;for(t++;t<this.#e&&!(this.#t[t]==='"'&&!o);t++)o=this.#t[t]==="\\"&&!o;yield{type:"String",sourceText:this.#t.substring(r,t+1),position:r};break}default:{let r=t;for(;t<this.#e&&!this.#o.has(this.#t[t]);t++);t--,yield{type:"NullOrTrueOrFalseOrNumber",sourceText:this.#t.substring(r,t+1),position:r}}}}}#p(t){switch(t.type){case"BeginObject":return this.#f();case"BeginArray":return this.#r();case"NullOrTrueOrFalseOrNumber":return this.#g(t);case"String":return this.#h(t);default:throw new SyntaxError(Jr(t))}}#f(){let t={};for(let r=!0;;r=!1){let o=this.#n();if((r||this.#a.allowTrailingComma)&&o.type==="EndObject")return t;if(o.type!=="String")throw new SyntaxError(Jr(o));let n=this.#h(o),s=this.#n();if(s.type!=="NameSeparator")throw new SyntaxError(Jr(s));let i=this.#n();Object.defineProperty(t,n,{value:this.#p(i),writable:!0,enumerable:!0,configurable:!0});let a=this.#n();if(a.type==="EndObject")return t;if(a.type!=="ValueSeparator")throw new SyntaxError(Jr(a))}}#r(){let t=[];for(let r=!0;;r=!1){let o=this.#n();if((r||this.#a.allowTrailingComma)&&o.type==="EndArray")return t;t.push(this.#p(o));let n=this.#n();if(n.type==="EndArray")return t;if(n.type!=="ValueSeparator")throw new SyntaxError(Jr(n))}}#h(t){let r;try{r=$y(t.sourceText)}catch{throw new SyntaxError(Jr(t))}return Oa(typeof r=="string"),r}#g(t){if(t.sourceText==="null")return null;if(t.sourceText==="true")return!0;if(t.sourceText==="false")return!1;let r;try{r=$y(t.sourceText)}catch{throw new SyntaxError(Jr(t))}return Oa(typeof r=="number"),r}};function Jr({type:e,sourceText:t,position:r}){let o="";switch(e){case"BeginObject":o="{";break;case"EndObject":o="}";break;case"BeginArray":o="[";break;case"EndArray":o="]";break;case"NameSeparator":o=":";break;case"ValueSeparator":o=",";break;case"NullOrTrueOrFalseOrNumber":case"String":o=30<t.length?`${t.slice(0,30)}...`:t;break;default:throw new Error("unreachable")}return`Unexpected token ${o} in JSONC at position ${r}`}function Fa(e){if(e.protocol==="file:")return{path:Na(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}}async function Tp(e){let t=await Deno.readTextFile(e),r=jy(t);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`Deno config at ${e} must be an object`);if("imports"in r&&(typeof r.imports!="object"||r.imports===null||Array.isArray(r.imports)))throw new Error(`Deno config at ${e} has invalid "imports" key`);if("scopes"in r&&(typeof r.scopes!="object"||r.scopes===null||Array.isArray(r.scopes)))throw new Error(`Deno config at ${e} has invalid "scopes" key`);if("lock"in r&&typeof r.lock!="boolean"&&typeof r.lock!="string")throw new Error(`Deno config at ${e} has invalid "lock" key`);if("importMap"in r&&typeof r.importMap!="string")throw new Error(`Deno config at ${e} has invalid "importMap" key`);return r}function By(e){if(e.imports!==void 0){let t=[];for(let[r,o]of Object.entries(e.imports))if(t.push([r,o]),!r.endsWith("/")&&o&&(o.startsWith("jsr:")||o.startsWith("npm:"))&&!e.imports[r+"/"]){let n=r+"/",s=o.slice(0,4)+"/"+o.slice(o[4]==="/"?5:4)+"/";t.push([n,s])}e.imports=Object.fromEntries(t)}}var z0=`${gn}node_modules${gn}`,q0=`${gn}node_modules`;function Ia(e){return e.includes(z0)||e.endsWith(q0)}function Pp(e){return(e.namespace===""||e.namespace==="file")&&(Ia(e.resolveDir)||Ia(e.path)||Ia(e.importer))}function Sp(e={}){return{name:"deno-resolver",setup(t){let r=null,o=(t.initialOptions.external??[]).map(n=>new RegExp("^"+n.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*")+"$"));t.onStart(async function(){let s;if(e.importMapURL===void 0&&e.configPath!==void 0){let i=await Tp(e.configPath);if(i.imports!==void 0||i.scopes!==void 0){let a={imports:i.imports,scopes:i.scopes};By(a),r=vp(a,ps(e.configPath))}else i.importMap!==void 0&&(s=new URL(i.importMap,ps(e.configPath)).href)}else e.importMapURL!==void 0&&(s=e.importMapURL);if(s){let i=await fetch(s),a=await i.json();r=vp(a,new URL(i.url))}}),t.onResolve({filter:/.*/},async function(s){if(Pp(s))return;let i;if(s.importer!==""){if(s.namespace==="")throw new Error("[assert] namespace is empty");i=new URL(`${s.namespace}:${s.importer}`)}else if(s.resolveDir!=="")i=new URL(`${ps(s.resolveDir).href}/`);else return;let a;if(r!==null){let p=Dy(s.path,r,new URL(i));a=new URL(p)}else a=new URL(s.path,i);for(let p of o)if(p.test(a.href))return{path:a.href,external:!0};let{path:c,namespace:l}=Fa(a);return await t.resolve(c,{namespace:l,kind:s.kind})})}}}var Uhe=new TextEncoder;var K0=[],X0=[],Op="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";for(let e=0,t=Op.length;e<t;++e)K0[e]=Op[e],X0[Op.charCodeAt(e)]=e;var nge=Deno.env.get("DENO_REGISTRY_URL")??"https://jsr.io";var oP=await Deno.permissions.query({name:"run"}).then(e=>e.state!=="granted")?"portable":"native";var Hy=Sp;var Wy=" must not return ",nP="`transformer`",sP="`recoverer`",iP="`defaultValue`",yn=nP+Wy,Lr="called with ",xn=iP+" must not be ",bn=sP+Wy;var Ua="`null` or `undefined`",En=yn+Ua,aP=Lr+Ua,Lp=xn+Ua,Da=bn+Ua;function Qt(e){return e!=null}var cP="`Ok`",Gy="`Err`",Vy=Lr+Gy,zy=Lr+cP,lP="Carrying `E` in "+Gy+" instead of throwing it directly. See `.cause`",Np="an instance of `Error` of the current realm.",Zge="The thrown value is not "+Np,eye="The contained E should be "+Np,pP="This `.cause` is not "+Np;function et(e){return e.ok}function bt(e){return{ok:!0,val:e,err:null}}function kt(e){return!e.ok}function At(e){return{ok:!1,val:null,err:e}}function Io(e){return qy(e,Vy)}function wn(e){return Ky(e,zy)}function qy(e,t){if(kt(e))throw new TypeError(t);return e.val}function Ky(e,t){if(et(e))throw new TypeError(t);return e.err}function Cp(e,t){if(Qt(e))return bt(e);let r=t();return At(r)}var Xy=e=>!!(uP.includes(e.hostname)||e.hostname.endsWith(".openai.azure.com")),uP=["i.gyazo.com","t.gyazo.com","scrapbox.io","api.openai.com","*.openai.azure.com","maps.googleapis.com","upload.gyazo.com","storage.googleapis.com","sentry.io"];function Zr(e){if(typeof e!="string")throw new TypeError(`Path must be a string, received "${JSON.stringify(e)}"`)}function Fo(e){return e===47}function Yy(e){Zr(e);let t=-1,r=0,o=-1,n=!0,s=0;for(let i=e.length-1;i>=0;--i){let a=e.charCodeAt(i);if(Fo(a)){if(!n){r=i+1;break}continue}o===-1&&(n=!1,o=i+1),a===46?t===-1?t=i:s!==1&&(s=1):t!==-1&&(s=-1)}return t===-1||o===-1||s===0||s===1&&t===o-1&&t===r+1?"":e.slice(t,o)}function Jy(e,t){if(t.length>=e.length)return e;let r=e.length-t.length;for(let o=t.length-1;o>=0;--o)if(e.charCodeAt(r+o)!==t.charCodeAt(o))return e;return e.slice(0,-t.length)}function Qy(e,t,r=0){let o=!1,n=e.length;for(let s=e.length-1;s>=r;--s)if(t(e.charCodeAt(s))){if(o){r=s+1;break}}else o||(o=!0,n=s+1);return e.slice(r,n)}function Zy(e,t){if(Zr(e),e.length===0)return e;if(typeof t!="string")throw new TypeError(`Suffix must be a string, received "${JSON.stringify(t)}"`)}function ex(e,t){if(e.length<=1)return e;let r=e.length;for(let o=e.length-1;o>0&&t(e.charCodeAt(o));o--)r=o;return e.slice(0,r)}function tx(e,t=""){Zy(e,t);let r=Qy(e,Fo),o=ex(r,Fo);return t?Jy(o,t):o}var $a=globalThis.Deno?.build.os==="windows"||globalThis.navigator?.platform?.startsWith("Win")||globalThis.process?.platform?.startsWith("win")||!1;function ja(e){if(e=e instanceof URL?e:new URL(e),e.protocol!=="file:")throw new TypeError(`URL must be a file URL: received "${e.protocol}"`);return e}function rx(e){return e=ja(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function ox(e){e=ja(e);let t=decodeURIComponent(e.pathname.replace(/\//g,"\\").replace(/%(?![0-9A-Fa-f]{2})/g,"%25")).replace(/^\\*([A-Za-z]:)(\\|$)/,"$1\\");return e.hostname!==""&&(t=`\\\\${e.hostname}${t}`),t}function nx(e){return $a?ox(e):rx(e)}var fP={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function Ba(e){return e.replaceAll(/[\s]/g,t=>fP[t]??t)}function sx(e){return Zr(e),e.length>0&&Fo(e.charCodeAt(0))}function ix(e){if(!sx(e))throw new TypeError(`Path must be absolute: received "${e}"`);let t=new URL("file:///");return t.pathname=Ba(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}function Mp(e){return e===47||e===92}function ax(e){return e>=97&&e<=122||e>=65&&e<=90}function cx(e){Zr(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return Mp(r)?!0:!!(ax(r)&&t>2&&e.charCodeAt(1)===58&&Mp(e.charCodeAt(2)))}function lx(e){if(!cx(e))throw new TypeError(`Path must be absolute: received "${e}"`);let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),o=new URL("file:///");if(o.pathname=Ba(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(o.hostname=t,!o.hostname))throw new TypeError(`Invalid hostname: "${o.hostname}"`);return o}function px(e){return $a?lx(e):ix(e)}var ux=e=>{if(e.protocol==="file:")return{path:nx(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}},Ip=e=>e.namespace==="file"?px(e.path):new URL(`${e.namespace}:${e.path}`);var mx=(e,t)=>{let r=Cp(EP(e),()=>({name:"NotFoundError",message:"Source map URL is not found"}));if(B(r))return r;let{url:o,start:n,end:s}=H(r);return URL.canParse(o,t)?ae({url:new URL(o,t),start:n,end:s}):Q({name:"InvalidURLError",message:`Invalid URL: ${o}`})},EP=e=>{for(let t of e.matchAll(/\/([*/])[#@] *sourceMappingURL=/g)){let r=t.index+t[0].length,o=e.length,n=r;for(;n<o&&e.charCodeAt(n)>32;)n++;if(n!==r&&(t[1]==="/"||e.indexOf("*/",n)>0))return{url:e.slice(r,n),start:r,end:n}}};var wP=["base64","binary","copy","css","dataurl","default","empty","file","js","json","jsx","local-css","text","ts","tsx"],fx=e=>wP.includes(e),dx=e=>/^js|^ts|css$/.test(e),hx=e=>{let t=e.url,r=tx(t);if(fx(r))return r;if(r==="mjs")return"js";let o=new URL(t);o.search="",o.hash="";let n=Yy(o.href).slice(1);if(fx(n))return n;if(n==="mjs")return"js";let i=(e.headers.get("Content-Type")??"text/plain").split(";")[0]?.trim?.()??"text/plain";return RP(i)},RP=e=>{let t=e.split("/")[1]??"plain";if(/(?:^plain$|^xml|^svg|^x?html)/.test(t))return"text";if(t.startsWith("json"))return"json";switch(t){case"javascript":return"js";case"typescript":return"ts";case"css":return"css";default:return"text"}};function Ha(e,t){if(isNaN(e)||isNaN(t))throw new Error("Cannot compare against non-numbers");return e===t?0:e<t?-1:1}function xx(e=[],t=[]){return e.length&&!t.length?-1:!e.length&&t.length?1:0}function Up(e=[],t=[]){let r=Math.max(e.length,t.length);for(let o=0;o<r;o++){let n=e[o],s=t[o];if(n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(typeof n=="string"&&typeof s=="number")return 1;if(typeof n=="number"&&typeof s=="string"||n<s)return-1;if(n>s)return 1}return 0}var Rn="0|[1-9]\\d*",kP="\\d*[a-zA-Z-][a-zA-Z0-9-]*",vP=`(?<major>${Rn})\\.(?<minor>${Rn})\\.(?<patch>${Rn})`,gx=`(?:${Rn}|${kP})`,bx=`(?:-(?<prerelease>${gx}(?:\\.${gx})*))`,yx="[0-9A-Za-z-]+",Ex=`(?:\\+(?<buildmetadata>${yx}(?:\\.${yx})*))`,wx=`v?${vP}${bx}?${Ex}?`,Rx=new RegExp(`^${wx}$`),kx="(?:<|>)?=?",_P="x|X|\\*",Fp=`${Rn}|${_P}`,Wa=`[v=\\s]*(?<major>${Fp})(?:\\.(?<minor>${Fp})(?:\\.(?<patch>${Fp})${bx}?${Ex}?)?)?`,vx=new RegExp(`^(?<operator>~>?|\\^|${kx})\\s*${Wa}$`),_x=new RegExp(`^(?<operator>${kx})\\s*(${wx})$|^$`);function Dp(e){return typeof e=="number"&&!Number.isNaN(e)&&(!Number.isFinite(e)||0<=e&&e<=Number.MAX_SAFE_INTEGER)}var $p=256;var TP=new RegExp(`^${Rn}$`);function vt(e){return e.split(".").filter(Boolean).map(t=>{if(TP.test(t)){let r=Number(t);if(Dp(r))return r}return t})}function ur(e){return e.split(".").filter(Boolean)}function eo(e,t){let r=Number(e);if(!Dp(r))throw new TypeError(t);return r}function Uo(e){return Number.isNaN(e.major)&&Number.isNaN(e.minor)&&Number.isNaN(e.patch)&&(e.prerelease===void 0||e.prerelease.length===0)&&(e.build===void 0||e.build.length===0)}function Wt(e,t){return e===t?0:Ha(e.major,t.major)||Ha(e.minor,t.minor)||Ha(e.patch,t.patch)||xx(e.prerelease,t.prerelease)||Up(e.prerelease,t.prerelease)}function jp(e){return e.toFixed(0)}function Do(e){let t=jp(e.major),r=jp(e.minor),o=jp(e.patch),n=e.prerelease?.join(".")??"",s=e.build?.join(".")??"";return[[`${t}.${r}.${o}`,n].filter(c=>c).join("-"),s].filter(c=>c).join("+")}function PP(e,t){if(Uo(t))return!0;let r=Wt(e,t);switch(t.operator){case"=":case void 0:return r===0;case"!=":return r!==0;case">":return r>0;case"<":return r<0;case">=":return r>=0;case"<=":return r<=0}}function Ga(e,t){for(let r of t)if(!PP(e,r))return!1;if(e.prerelease&&e.prerelease.length>0){for(let r of t){if(Uo(r))continue;let{major:o,minor:n,patch:s,prerelease:i}=r;if(i&&i.length>0&&e.major===o&&e.minor===n&&e.patch===s)return!0}return!1}return!0}function Va(e,t){return t.some(r=>Ga(e,r))}var za={major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]},kn={operator:void 0,...za};function Tx(e,t){return Wt(e,t)>0}function us(e,t){let r;for(let o of e)Va(o,t)&&(r=r&&Tx(r,o)?r:o);return r}function SP(e){let r=e.match(_x)?.groups;if(!r)return null;let{operator:o,prerelease:n,buildmetadata:s}=r,i=r.major?{major:eo(r.major,`Cannot parse comparator ${e}: invalid major version`),minor:eo(r.minor,`Cannot parse comparator ${e}: invalid minor version`),patch:eo(r.patch,`Cannot parse comparator ${e}: invalid patch version`),prerelease:n?vt(n):[],build:s?ur(s):[]}:za;return{operator:o||void 0,...i}}function Se(e){return!e||e.toLowerCase()==="x"||e==="*"}function OP(e){if(!Se(e.major))return Se(e.minor)?{operator:">=",major:+e.major,minor:0,patch:0,prerelease:[],build:[]}:Se(e.patch)?{operator:">=",major:+e.major,minor:+e.minor,patch:0,prerelease:[],build:[]}:{operator:">=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:e.prerelease?vt(e.prerelease):[],build:[]}}function LP(e){if(!Se(e.major))return Se(e.minor)?{operator:"<",major:+e.major+1,minor:0,patch:0,prerelease:[],build:[]}:Se(e.patch)?{operator:"<",major:+e.major,minor:+e.minor+1,patch:0,prerelease:[],build:[]}:e.prerelease?{operator:"<=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:vt(e.prerelease),build:[]}:{operator:"<=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:e.prerelease?vt(e.prerelease):[],build:[]}}function NP(e){let t=e.match(new RegExp(`^${Wa}`)),r=t?.groups;if(!r)return;let o=t[0].length,n=e.slice(o).match(/^\s+-\s+/);if(!n)return;let s=n[0].length,a=e.slice(o+s).match(new RegExp(`^${Wa}\\s*$`))?.groups;if(!a)return;let c=OP(r),l=LP(a);return[c,l].filter(Boolean)}function CP(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[kn];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return n===0?[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}]:[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];let a=vt(e.prerelease??"");return n===0?s===0?[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s,patch:i+1}]:[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s+1,patch:0}]:[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n+1,minor:0,patch:0}]}function AP(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[kn];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}];let a=vt(e.prerelease??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s+1,patch:0}]}function MP(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return o?[{operator:"<",major:n,minor:0,patch:0}]:[{operator:"<",major:n,minor:s,patch:0}];if(o)return[{operator:"<",major:n,minor:s,patch:0}];let a=vt(e.prerelease??""),c=ur(e.build??"");return[{operator:"<",major:n,minor:s,patch:i,prerelease:a,build:c}]}function IP(e){let t=Se(e.minor),r=Se(e.patch),o=+e.major,n=+e.minor,s=+e.patch;if(t)return r?[{operator:"<",major:o+1,minor:0,patch:0}]:[{operator:"<",major:o,minor:n+1,patch:0}];if(r)return[{operator:"<",major:o,minor:n+1,patch:0}];let i=vt(e.prerelease??""),a=ur(e.build??"");return[{operator:"<=",major:o,minor:n,patch:s,prerelease:i,build:a}]}function FP(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return[{operator:">=",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s+1,patch:0}];let a=vt(e.prerelease??""),c=ur(e.build??"");return[{operator:">",major:n,minor:s,patch:i,prerelease:a,build:c}]}function UP(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[kn];if(r)return o?[{operator:">=",major:n,minor:0,patch:0}]:[{operator:">=",major:n,minor:s,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0}];let a=vt(e.prerelease??""),c=ur(e.build??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a,build:c}]}function DP(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[kn];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}];let a=vt(e.prerelease??""),c=ur(e.build??"");return[{operator:void 0,major:n,minor:s,patch:i,prerelease:a,build:c}]}function $P(e){let t=e.match(vx)?.groups;if(!t)return SP(e);switch(t.operator){case"^":return CP(t);case"~":case"~>":return AP(t);case"<":return MP(t);case"<=":return IP(t);case">":return FP(t);case">=":return UP(t);case"=":case"":return DP(t);default:throw new Error(`Cannot parse version range: '${t.operator}' is not a valid operator`)}}function jP(e){return e.split(/\s+/).flatMap($P)}function Px(e){let t=e.replaceAll(/(?<=<|>|=|~|\^)(\s+)/g,"").split(/\s*\|\|\s*/).map(r=>NP(r)||jP(r));if(t.some(r=>r.includes(null)))throw new TypeError(`Cannot parse version range: range "${e}" is invalid`);return t}function Bp(e){if(typeof e!="string")throw new TypeError(`Cannot parse version as version must be a string: received ${typeof e}`);if(e.length>$p)throw new TypeError(`Cannot parse version as version length is too long: length is ${e.length}, max length is ${$p}`);e=e.trim();let t=e.match(Rx)?.groups;if(!t)throw new TypeError(`Cannot parse version: ${e}`);let r=eo(t.major,`Cannot parse version ${e}: invalid major version`),o=eo(t.minor,`Cannot parse version ${e}: invalid minor version`),n=eo(t.patch,`Cannot parse version ${e}: invalid patch version`),s=t.prerelease?vt(t.prerelease):[],i=t.buildmetadata?ur(t.buildmetadata):[];return{major:r,minor:o,patch:n,prerelease:s,build:i}}function Hp(e){try{return Px(e)}catch{return}}function Wp(e){try{return Bp(e)}catch{return}}var ms={operator:void 0,major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]};var to=async e=>{try{let t=await fetch(e);return t.ok?ae([t,!1]):Q({name:"HTTPError",message:`${t.status} ${t.statusText}`,response:t})}catch(t){if(t instanceof TypeError)return Q({name:"NetworkError",message:t.message,request:e});if(t instanceof DOMException)return Q({name:"AbortError",message:t.message,request:e});throw t}};var Gp="https://jsr.io",Sx=async(e,t)=>{let r=await(t?.fetch??to)(new Request(`${t?.endpoint??Gp}/${e}/meta.json`),t?.cacheFirst);return Tt(r,([o])=>o.json())};var Ox=async(e,t,r)=>{let o=await(r?.fetch??to)(new Request(`${r?.endpoint??Gp}/${e}/${t}_meta.json`),r?.cacheFirst);return Tt(o,([n])=>n.json())};var Lx=async(e,t)=>{let r=await(t?.fetch??to)(new Request(`${t?.endpoint??"https://registry.npmjs.org"}/${e}`),t?.cacheFirst);return Tt(r,([o])=>o.json())};var Ax=(e,t)=>({name:"InvalidPackageVersionError",message:`No version of ${e.name} satisfies "${e.tag??"*"}" (available: ${t.slice(0,10).join(", ")}${t.length>10?`, ... (${t.length-10} more versions)`:""})`,packageName:e.name,range:e.range,tag:e.tag,entryPoint:e.entryPoint,availableVersions:t}),qa=(e,t)=>({name:"InvalidEntryPointError",message:`${e.entryPoint} is not a valid entry point for ${e.name}@${e.tag??"*"} (available: ${t.join(", ")})`,packageName:e.name,range:e.range,tag:e.tag,entryPoint:e.entryPoint,availableEntryPoints:t}),Mx=async(e,t)=>{if(t?.resolvedVersions){let c=new Map(t.resolvedVersions.get(e.name)??[]),l=us([...c.keys()],e.range);if(l){let u=c.get(l)??fs,p=u[e.entryPoint];return typeof p!="string"&&console.log(p),p?ae(Nx(e.name,Do(l),p)):Q(qa(e,Object.keys(u)))}}let r=await Lx(e.name,t);if(B(r))return r;let o=H(r),n=new Map(Object.entries(o.versions).flatMap(([c,{exports:l}])=>{let u=Wp(c);return u?[[u,l??fs]]:[]})),s=us([...n.keys()],e.range);if(!s)return Q(Ax(e,Object.keys(o.versions)));let i={...fs};for(let c of Object.keys(n.get(s)??fs))i[c]=c;let a=i[e.entryPoint];return a?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[s,i]]),ae(Nx(e.name,Do(s),a))):Q(qa(e,Object.keys(i)))},Nx=(e,t,r)=>new URL(r,`https://esm.sh/${e}@${t}/`),Ix=async(e,t)=>{if(t?.resolvedVersions){let a=new Map(t.resolvedVersions.get(e.name)??[]),c=us([...a.keys()],e.range);if(c){let l=a.get(c)??fs,u=l[e.entryPoint];return u?ae(Cx(e.name,Do(c),u)):Q(qa(e,Object.keys(l)))}}let r=await BP(e,t);if(B(r))return r;let o=H(r),n=await Ox(e.name,Do(o),t);if(B(n))return n;let s=H(n).exports,i=s[e.entryPoint];return i?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[o,s]]),ae(Cx(e.name,Do(o),i))):Q(qa(e,Object.keys(H(n).exports)))},Cx=(e,t,r)=>new URL(r,`https://jsr.io/${e}/${t}/`),BP=async(e,t)=>{let r=await Sx(e.name,t);if(B(r))return r;let o=H(r),n=Object.keys(o.versions).flatMap(i=>{let a=Wp(i);return a?[a]:[]}),s=us(n,e.range);return s?ae(s):Q(Ax(e,Object.keys(o.versions)))},fs={".":"./"};var HP=e=>({name:"OnlyScopeProvidedError",specifier:e}),Fx=e=>({name:"PackageNotFoundError",specifier:e}),Ux=e=>{if(e.protocol!=="npm:")return Q({name:"NotNpmProtocolError",specifier:e});let t=e.pathname,r=t[0]==="/"?1:0,o,n;if(t[r]==="@"){let p=t.indexOf("/",r);if(p===-1)return Q(HP(e));o=t.indexOf("/",p+1),n=t.indexOf("@",p+1)}else o=t.indexOf("/",r),n=t.indexOf("@",r);if(o===-1&&(o=t.length),n===-1&&(n=t.length),n=Math.min(n,o),r===n)return Q(Fx(e));let s=t.slice(r,n),i=decodeURIComponent(t.slice(n+1,o)),a=i?Hp(i)??[[ms]]:[[ms]],c=t.slice(o+1),l=c?`./${c}`:".",u={name:s,range:a,entryPoint:l};return i&&(u.tag=i),ae(u)},Dx=e=>{if(e.protocol!=="jsr:")return Q({name:"NotJsrProtocolError",specifier:e});let t=e.pathname,r=t[0]==="/"?1:0;if(t[r]!=="@")return Q({name:"ScopeNotFoundError",specifier:e});let o=t.indexOf("/",r);if(o===-1)return Q(Fx(e));let n=t.indexOf("/",o+1),s=t.indexOf("@",o+1);n===-1&&(n=t.length),s===-1&&(s=t.length),s=Math.min(s,n);let i=t.slice(r,s),a=decodeURIComponent(t.slice(s+1,n)),c=a?Hp(a)??[[ms]]:[[ms]],l=t.slice(n+1),u=l?`./${l}`:".",p={name:i,range:c,entryPoint:u};return a&&(p.tag=a),ae(p)};var $x=e=>new Promise((t,r)=>{let o=new FileReader;o.addEventListener("load",()=>{let n=o.result,s=n.indexOf(";");n.startsWith("; charset=utf-8",s)?t(`${n.slice(0,s)}${n.slice(s+15)}`):t(n)}),o.addEventListener("error",()=>r(o.error)),o.readAsDataURL(e)});var Hx=e=>{let t=new Map,r=async o=>{let n=o.namespace==="npm",s=(n?Ux:Dx)(Ip(o));if(B(s)){let a=re(s);return{errors:[{text:a.name,detail:a}]}}let i=await(n?Mx:Ix)(H(s),{resolvedVersions:t,...e});if(B(i)){let a=re(i);return{errors:[{text:`${a.name} ${a.message}`,detail:a}]}}return ux(H(i))};return{name:"remote-loader",setup({onLoad:o,onResolve:n,initialOptions:s}){for(let i of[...jx,...Bx])n({filter:/.*/,namespace:i.slice(0,-1)},WP);n({filter:/.*/,namespace:"npm"},r),n({filter:/.*/,namespace:"jsr"},r);for(let i of jx)o({filter:/.*/,namespace:i.slice(0,-1)},a=>GP(Ip(a),{...e,sourcemap:s.sourcemap!==!1&&s.sourcemap!==void 0}));for(let i of Bx)o({filter:/.*/,namespace:i.slice(0,-1)},()=>{throw new Error(`${i} import is not supported yet.`)})}}},WP=e=>({path:e.path,namespace:e.namespace}),jx=["http:","https:","data:"],Bx=["node:"],GP=async(e,t)=>{let r=t.reload?t.reload===!0?!1:!t.reload.some(l=>l.test(e)):!0,o=t.fetch??to,n=await o(new Request(e),r);if(B(n))return{errors:[{text:`[${re(n).message}] Failed to fetch ${e}`,detail:re(n)}]};let[s,i]=H(n),a=hx(s);t.onProgress?.({path:e,done:s.clone().blob().then(l=>({size:l.size,loader:a,isCache:i}))});let c=await s.blob();if(t.sourcemap&&dx(a)){let l=await c.text(),u=mx(l,e);if(Ne(u)){let{url:p,start:f,end:m}=H(u);if(p.protocol!=="data:"){let h=await o(new Request(p),r);if(B(h))return{contents:l,loader:a,warnings:[{text:`[${re(h).message}] Failed to fetch the source map URL`,notes:[{text:`Source map URL: ${p}`},{text:`Original URL: ${e}`}],detail:re(h)}]};let g=await H(h)[0].blob().then($x);return{contents:l.slice(0,f)+g+l.slice(m),loader:a}}}}return{contents:new Uint8Array(await c.arrayBuffer()),loader:a}};var gs=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(e,t,r,o,n,s){this.type=e,this.name=t,this.prefix=r,this.value=o,this.suffix=n,this.modifier=s}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},VP=/[$_\p{ID_Start}]/u,zP=/[$_\u200C\u200D\p{ID_Continue}]/u,zp=".*";function qP(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function Vx(e,t=!1){let r=[],o=0;for(;o<e.length;){let n=e[o],s=function(i){if(!t)throw new TypeError(i);r.push({type:"INVALID_CHAR",index:o,value:e[o++]})};if(n==="*"){r.push({type:"ASTERISK",index:o,value:e[o++]});continue}if(n==="+"||n==="?"){r.push({type:"OTHER_MODIFIER",index:o,value:e[o++]});continue}if(n==="\\"){r.push({type:"ESCAPED_CHAR",index:o++,value:e[o++]});continue}if(n==="{"){r.push({type:"OPEN",index:o,value:e[o++]});continue}if(n==="}"){r.push({type:"CLOSE",index:o,value:e[o++]});continue}if(n===":"){let i="",a=o+1;for(;a<e.length;){let c=e.substr(a,1);if(a===o+1&&VP.test(c)||a!==o+1&&zP.test(c)){i+=e[a++];continue}break}if(!i){s(`Missing parameter name at ${o}`);continue}r.push({type:"NAME",index:o,value:i}),o=a;continue}if(n==="("){let i=1,a="",c=o+1,l=!1;if(e[c]==="?"){s(`Pattern cannot start with "?" at ${c}`);continue}for(;c<e.length;){if(!qP(e[c],!1)){s(`Invalid character '${e[c]}' at ${c}.`),l=!0;break}if(e[c]==="\\"){a+=e[c++]+e[c++];continue}if(e[c]===")"){if(i--,i===0){c++;break}}else if(e[c]==="("&&(i++,e[c+1]!=="?")){s(`Capturing groups are not allowed at ${c}`),l=!0;break}a+=e[c++]}if(l)continue;if(i){s(`Unbalanced pattern at ${o}`);continue}if(!a){s(`Missing pattern at ${o}`);continue}r.push({type:"REGEX",index:o,value:a}),o=c;continue}r.push({type:"CHAR",index:o,value:e[o++]})}return r.push({type:"END",index:o,value:""}),r}function zx(e,t={}){let r=Vx(e);t.delimiter??="/#?",t.prefixes??="./";let o=`[^${Gt(t.delimiter)}]+?`,n=[],s=0,i=0,a="",c=new Set,l=k=>{if(i<r.length&&r[i].type===k)return r[i++].value},u=()=>l("OTHER_MODIFIER")??l("ASTERISK"),p=k=>{let b=l(k);if(b!==void 0)return b;let{type:v,index:R}=r[i];throw new TypeError(`Unexpected ${v} at ${R}, expected ${k}`)},f=()=>{let k="",b;for(;b=l("CHAR")??l("ESCAPED_CHAR");)k+=b;return k},m=k=>k,h=t.encodePart||m,g="",y=k=>{g+=k},x=()=>{g.length&&(n.push(new gs(3,"","",h(g),"",3)),g="")},E=(k,b,v,R,O)=>{let L=3;switch(O){case"?":L=1;break;case"*":L=0;break;case"+":L=2;break}if(!b&&!v&&L===3){y(k);return}if(x(),!b&&!v){if(!k)return;n.push(new gs(3,"","",h(k),"",L));return}let N;v?v==="*"?N=zp:N=v:N=o;let P=2;N===o?(P=1,N=""):N===zp&&(P=0,N="");let _;if(b?_=b:v&&(_=s++),c.has(_))throw new TypeError(`Duplicate name '${_}'.`);c.add(_),n.push(new gs(P,_,h(k),N,h(R),L))};for(;i<r.length;){let k=l("CHAR"),b=l("NAME"),v=l("REGEX");if(!b&&!v&&(v=l("ASTERISK")),b||v){let O=k??"";t.prefixes.indexOf(O)===-1&&(y(O),O=""),x();let L=u();E(O,b,v,"",L);continue}let R=k??l("ESCAPED_CHAR");if(R){y(R);continue}if(l("OPEN")){let O=f(),L=l("NAME"),N=l("REGEX");!L&&!N&&(N=l("ASTERISK"));let P=f();p("CLOSE");let _=u();E(O,L,N,P,_);continue}x(),p("END")}return n}function Gt(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function Wx(e){return e&&e.ignoreCase?"ui":"u"}function KP(e,t,r){return qx(zx(e,r),t,r)}function vn(e){switch(e){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}function qx(e,t,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let o=r.start?"^":"";for(let a of e){if(a.type===3){a.modifier===3?o+=Gt(a.value):o+=`(?:${Gt(a.value)})${vn(a.modifier)}`;continue}t&&t.push(a.name);let c=`[^${Gt(r.delimiter)}]+?`,l=a.value;if(a.type===1?l=c:a.type===0&&(l=zp),!a.prefix.length&&!a.suffix.length){a.modifier===3||a.modifier===1?o+=`(${l})${vn(a.modifier)}`:o+=`((?:${l})${vn(a.modifier)})`;continue}if(a.modifier===3||a.modifier===1){o+=`(?:${Gt(a.prefix)}(${l})${Gt(a.suffix)})`,o+=vn(a.modifier);continue}o+=`(?:${Gt(a.prefix)}`,o+=`((?:${l})(?:`,o+=Gt(a.suffix),o+=Gt(a.prefix),o+=`(?:${l}))*)${Gt(a.suffix)})`,a.modifier===0&&(o+="?")}let n=`[${Gt(r.endsWith)}]|$`,s=`[${Gt(r.delimiter)}]`;if(r.end)return r.strict||(o+=`${s}?`),r.endsWith.length?o+=`(?=${n})`:o+="$",new RegExp(o,Wx(r));r.strict||(o+=`(?:${s}(?=${n}))?`);let i=!1;if(e.length){let a=e[e.length-1];a.type===3&&a.modifier===3&&(i=r.delimiter.indexOf(a)>-1)}return i||(o+=`(?=${s}|${n})`),new RegExp(o,Wx(r))}var oo={delimiter:"",prefixes:"",sensitive:!0,strict:!0},XP={delimiter:".",prefixes:"",sensitive:!0,strict:!0},YP={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function JP(e,t){return e.length?e[0]==="/"?!0:!t||e.length<2?!1:(e[0]=="\\"||e[0]=="{")&&e[1]=="/":!1}function Kx(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function QP(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function Xx(e){return!e||e.length<2?!1:e[0]==="["||(e[0]==="\\"||e[0]==="{")&&e[1]==="["}var Yx=["ftp","file","http","https","ws","wss"];function Jx(e){if(!e)return!0;for(let t of Yx)if(e.test(t))return!0;return!1}function ZP(e,t){if(e=Kx(e,"#"),t||e==="")return e;let r=new URL("https://example.com");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):""}function eS(e,t){if(e=Kx(e,"?"),t||e==="")return e;let r=new URL("https://example.com");return r.search=e,r.search?r.search.substring(1,r.search.length):""}function tS(e,t){return t||e===""?e:Xx(e)?eb(e):Zx(e)}function rS(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.password=e,r.password}function oS(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.username=e,r.username}function nS(e,t,r){if(r||e==="")return e;if(t&&!Yx.includes(t))return new URL(`${t}:${e}`).pathname;let o=e[0]=="/";return e=new URL(o?e:"/-"+e,"https://example.com").pathname,o||(e=e.substring(2,e.length)),e}function sS(e,t,r){return Qx(t)===e&&(e=""),r||e===""?e:tb(e)}function iS(e,t){return e=QP(e,":"),t||e===""?e:qp(e)}function Qx(e){switch(e){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}function qp(e){if(e==="")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}function aS(e){if(e==="")return e;let t=new URL("https://example.com");return t.username=e,t.username}function cS(e){if(e==="")return e;let t=new URL("https://example.com");return t.password=e,t.password}function Zx(e){if(e==="")return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL("https://example.com");return t.hostname=e,t.hostname}function eb(e){if(e==="")return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function tb(e){if(e===""||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}function lS(e){if(e==="")return e;let t=new URL("https://example.com");return t.pathname=e[0]!=="/"?"/-"+e:e,e[0]!=="/"?t.pathname.substring(2,t.pathname.length):t.pathname}function pS(e){return e===""?e:new URL(`data:${e}`).pathname}function uS(e){if(e==="")return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function mS(e){if(e==="")return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var fS=class{#i;#o=[];#t={};#e=0;#s=1;#a=0;#n=0;#m=0;#p=0;#f=!1;constructor(e){this.#i=e}get result(){return this.#t}parse(){for(this.#o=Vx(this.#i,!0);this.#e<this.#o.length;this.#e+=this.#s){if(this.#s=1,this.#o[this.#e].type==="END"){if(this.#n===0){this.#g(),this.#u()?this.#r(9,1):this.#d()?this.#r(8,1):this.#r(7,0);continue}else if(this.#n===2){this.#y(5);continue}this.#r(10,0);break}if(this.#m>0)if(this.#T())this.#m-=1;else continue;if(this.#_()){this.#m+=1;continue}switch(this.#n){case 0:this.#w()&&this.#y(1);break;case 1:if(this.#w()){this.#O();let e=7,t=1;this.#R()?(e=2,t=3):this.#f&&(e=2),this.#r(e,t)}break;case 2:this.#b()?this.#y(3):(this.#E()||this.#d()||this.#u())&&this.#y(5);break;case 3:this.#k()?this.#r(4,1):this.#b()&&this.#r(5,1);break;case 4:this.#b()&&this.#r(5,1);break;case 5:this.#P()?this.#p+=1:this.#S()&&(this.#p-=1),this.#v()&&!this.#p?this.#r(6,1):this.#E()?this.#r(7,0):this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 6:this.#E()?this.#r(7,0):this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 7:this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 8:this.#u()&&this.#r(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port="")}#r(e,t){switch(this.#n){case 0:break;case 1:this.#t.protocol=this.#l();break;case 2:break;case 3:this.#t.username=this.#l();break;case 4:this.#t.password=this.#l();break;case 5:this.#t.hostname=this.#l();break;case 6:this.#t.port=this.#l();break;case 7:this.#t.pathname=this.#l();break;case 8:this.#t.search=this.#l();break;case 9:this.#t.hash=this.#l();break;case 10:break}this.#n!==0&&e!==10&&([1,2,3,4].includes(this.#n)&&[6,7,8,9].includes(e)&&(this.#t.hostname??=""),[1,2,3,4,5,6].includes(this.#n)&&[8,9].includes(e)&&(this.#t.pathname??=this.#f?"/":""),[1,2,3,4,5,6,7].includes(this.#n)&&e===9&&(this.#t.search??="")),this.#h(e,t)}#h(e,t){this.#n=e,this.#a=this.#e+t,this.#e+=t,this.#s=0}#g(){this.#e=this.#a,this.#s=0}#y(e){this.#g(),this.#n=e}#x(e){return e<0&&(e=this.#o.length-e),e<this.#o.length?this.#o[e]:this.#o[this.#o.length-1]}#c(e,t){let r=this.#x(e);return r.value===t&&(r.type==="CHAR"||r.type==="ESCAPED_CHAR"||r.type==="INVALID_CHAR")}#w(){return this.#c(this.#e,":")}#R(){return this.#c(this.#e+1,"/")&&this.#c(this.#e+2,"/")}#b(){return this.#c(this.#e,"@")}#k(){return this.#c(this.#e,":")}#v(){return this.#c(this.#e,":")}#E(){return this.#c(this.#e,"/")}#d(){if(this.#c(this.#e,"?"))return!0;if(this.#o[this.#e].value!=="?")return!1;let e=this.#x(this.#e-1);return e.type!=="NAME"&&e.type!=="REGEX"&&e.type!=="CLOSE"&&e.type!=="ASTERISK"}#u(){return this.#c(this.#e,"#")}#_(){return this.#o[this.#e].type=="OPEN"}#T(){return this.#o[this.#e].type=="CLOSE"}#P(){return this.#c(this.#e,"[")}#S(){return this.#c(this.#e,"]")}#l(){let e=this.#o[this.#e],t=this.#x(this.#a).index;return this.#i.substring(t,e.index)}#O(){let e={};Object.assign(e,oo),e.encodePart=qp;let t=KP(this.#l(),void 0,e);this.#f=Jx(t)}},Vp=["protocol","username","password","hostname","port","pathname","search","hash"],ro="*";function Gx(e,t){if(typeof e!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(e,t);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}function Cr(e,t){return t?hs(e):e}function ds(e,t,r){let o;if(typeof t.baseURL=="string")try{o=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=Cr(o.protocol.substring(0,o.protocol.length-1),r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=Cr(o.username,r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=Cr(o.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=Cr(o.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=Cr(o.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=Cr(o.pathname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=Cr(o.search.substring(1,o.search.length),r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=Cr(o.hash.substring(1,o.hash.length),r))}catch{throw new TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol=="string"&&(e.protocol=iS(t.protocol,r)),typeof t.username=="string"&&(e.username=oS(t.username,r)),typeof t.password=="string"&&(e.password=rS(t.password,r)),typeof t.hostname=="string"&&(e.hostname=tS(t.hostname,r)),typeof t.port=="string"&&(e.port=sS(t.port,e.protocol,r)),typeof t.pathname=="string"){if(e.pathname=t.pathname,o&&!JP(e.pathname,r)){let n=o.pathname.lastIndexOf("/");n>=0&&(e.pathname=Cr(o.pathname.substring(0,n+1),r)+e.pathname)}e.pathname=nS(e.pathname,e.protocol,r)}return typeof t.search=="string"&&(e.search=eS(t.search,r)),typeof t.hash=="string"&&(e.hash=ZP(t.hash,r)),e}function hs(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function dS(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function hS(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let r=".*",o=`[^${dS(t.delimiter)}]+?`,n=/[$_\u200C\u200D\p{ID_Continue}]/u,s="";for(let i=0;i<e.length;++i){let a=e[i];if(a.type===3){if(a.modifier===3){s+=hs(a.value);continue}s+=`{${hs(a.value)}}${vn(a.modifier)}`;continue}let c=a.hasCustomName(),l=!!a.suffix.length||!!a.prefix.length&&(a.prefix.length!==1||!t.prefixes.includes(a.prefix)),u=i>0?e[i-1]:null,p=i<e.length-1?e[i+1]:null;if(!l&&c&&a.type===1&&a.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let f=p.value.length>0?p.value[0]:"";l=n.test(f)}else l=!p.hasCustomName();if(!l&&!a.prefix.length&&u&&u.type===3){let f=u.value[u.value.length-1];l=t.prefixes.includes(f)}l&&(s+="{"),s+=hs(a.prefix),c&&(s+=`:${a.name}`),a.type===2?s+=`(${a.value})`:a.type===1?c||(s+=`(${o})`):a.type===0&&(!c&&(!u||u.type===3||u.modifier!==3||l||a.prefix!=="")?s+="*":s+=`(${r})`),a.type===1&&c&&a.suffix.length&&n.test(a.suffix[0])&&(s+="\\"),s+=hs(a.suffix),l&&(s+="}"),a.modifier!==3&&(s+=vn(a.modifier))}return s}var rb=class{#i;#o={};#t={};#e={};#s={};#a=!1;constructor(e={},t,r){try{let o;if(typeof t=="string"?o=t:r=t,typeof e=="string"){let a=new fS(e);if(a.parse(),e=a.result,o===void 0&&typeof e.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");e.baseURL=o}else{if(!e||typeof e!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(o)throw new TypeError("parameter 1 is not of type 'string'.")}typeof r>"u"&&(r={ignoreCase:!1});let n={ignoreCase:r.ignoreCase===!0},s={pathname:ro,protocol:ro,username:ro,password:ro,hostname:ro,port:ro,search:ro,hash:ro};this.#i=ds(s,e,!0),Qx(this.#i.protocol)===this.#i.port&&(this.#i.port="");let i;for(i of Vp){if(!(i in this.#i))continue;let a={},c=this.#i[i];switch(this.#t[i]=[],i){case"protocol":Object.assign(a,oo),a.encodePart=qp;break;case"username":Object.assign(a,oo),a.encodePart=aS;break;case"password":Object.assign(a,oo),a.encodePart=cS;break;case"hostname":Object.assign(a,XP),Xx(c)?a.encodePart=eb:a.encodePart=Zx;break;case"port":Object.assign(a,oo),a.encodePart=tb;break;case"pathname":Jx(this.#o.protocol)?(Object.assign(a,YP,n),a.encodePart=lS):(Object.assign(a,oo,n),a.encodePart=pS);break;case"search":Object.assign(a,oo,n),a.encodePart=uS;break;case"hash":Object.assign(a,oo,n),a.encodePart=mS;break}try{this.#s[i]=zx(c,a),this.#o[i]=qx(this.#s[i],this.#t[i],a),this.#e[i]=hS(this.#s[i],a),this.#a=this.#a||this.#s[i].some(l=>l.type===2)}catch{throw new TypeError(`invalid ${i} pattern '${this.#i[i]}'.`)}}}catch(o){throw new TypeError(`Failed to construct 'URLPattern': ${o.message}`)}}test(e={},t){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof e!="string"&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return!1;try{typeof e=="object"?r=ds(r,e,!1):r=ds(r,Gx(e,t),!1)}catch{return!1}let o;for(o of Vp)if(!this.#o[o].exec(r[o]))return!1;return!0}exec(e={},t){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof e!="string"&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return;try{typeof e=="object"?r=ds(r,e,!1):r=ds(r,Gx(e,t),!1)}catch{return null}let o={};t?o.inputs=[e,t]:o.inputs=[e];let n;for(n of Vp){let s=this.#o[n].exec(r[n]);if(!s)return null;let i={};for(let[a,c]of this.#t[n].entries())if(typeof c=="string"||typeof c=="number"){let l=s[a+1];i[c]=l}o[n]={input:r[n]??"",groups:i}}return o}static compareComponent(e,t,r){let o=(a,c)=>{for(let l of["type","modifier","prefix","value","suffix"]){if(a[l]<c[l])return-1;if(a[l]!==c[l])return 1}return 0},n=new gs(3,"","","","",3),s=new gs(0,"","","","",3),i=(a,c)=>{let l=0;for(;l<Math.min(a.length,c.length);++l){let u=o(a[l],c[l]);if(u)return u}return a.length===c.length?0:o(a[l]??n,c[l]??n)};return!t.#e[e]&&!r.#e[e]?0:t.#e[e]&&!r.#e[e]?i(t.#s[e],[s]):!t.#e[e]&&r.#e[e]?i([s],r.#s[e]):i(t.#s[e],r.#s[e])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#a}};globalThis.URLPattern||(globalThis.URLPattern=rb);var ob,nb=async(e,t)=>(ob??=va({wasm:e,worker:t}),await ob,async r=>{let{outputFiles:o}=await Ra({entryPoints:[r],format:"esm",bundle:!0,minify:!0,charset:"utf8",plugins:[Hy(),Hx({fetch:gS,reload:[new URLPattern({hostname:location.hostname}),new URLPattern({hostname:"scrapbox.io"})]})],write:!1});return{contents:o[0].text}}),gS=async(e,t)=>{let r=Xy(new URL(e.url))||!GM_fetch?globalThis.fetch:GM_fetch;if(t){let o=await Kp(e);if(o)return o}try{let o=await r(e);return o.ok?(r===GM_fetch&&!e.url.startsWith("data:")&&await Fi(e,o),ae([o,!1])):await Kp(e)??Q({name:"HTTPError",message:`${o.status} ${o.statusText}`,response:o})}catch(o){let n=await Kp(e);if(n)return n;if(o instanceof TypeError)return Q({name:"NetworkError",message:o.message,request:e});if(o instanceof DOMException)return Q({name:"AbortError",message:o.message,request:e});throw o}},Kp=async e=>{if(e.url.startsWith("data:"))return;let t=await tn(e);if(t)return t.url||Object.defineProperty(t,"url",{value:e.url}),ae([t,!0])};var sb=e=>["ts","js","tsx","jsx","mjs","javascript","typescript"].includes(e);var ib=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle-fill"),e.style.color="hsl(133, 46.1%, 47.3%)",e},ab=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-cross-circle"),e.style.color="hsl(1.7, 64.5%, 58%)",e},cb=()=>{let e=document.createElement("i");return e.classList.add("i","fa","fa-spinner"),e},lb=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-play"),e};var pb=()=>{let e;return{show:(o,{x:n,y:s})=>{e=yS(),e.append(xS(o)),e.style.visibility="hidden",document.body.append(e);let{height:i}=e.getBoundingClientRect();e.style.top=`${s-i}px`,e.style.left=`${n}px`,e.style.removeProperty("visibility")},hide:async()=>{e?.classList?.remove?.("in"),await new Promise(o=>setTimeout(o,150)),e?.remove?.()}}},yS=()=>{let e=document.createElement("div");return e.setAttribute("role","tooltip"),e.classList.add("fade","in","tooltip","top"),e},xS=e=>{let t=document.createElement("pre");return t.classList.add("tooltip-inner"),t.style.textAlign="unset",t.style.maxWidth="70vw",t.style.margin="unset",t.innerText=e,t};var ub=()=>{let e=document.createElement("a");e.classList.add("tool-btn"),e.type="button",e.setAttribute("aria-haspopup","true");let t=!1,{show:r,hide:o}=pb();return{component:e,setStatus:async(s,i)=>{switch(e.textContent="",await o(),s){case"loading":e.append(cb());break;case"pass":e.append(ib());break;case"fail":e.append(ab());break;case"none":break}i!==void 0&&s!=="none"?(e.style.removeProperty("pointer-events"),e.onclick=async()=>{if(t)await o();else{let{top:a,left:c}=e.getBoundingClientRect();r(i,{y:a+globalThis.scrollY,x:c})}t=!t}):e.style.pointerEvents="none"}}};var mb=e=>{let t=document.createElement("a");return t.classList.add("tool-btn"),t.type="button",t.setAttribute("aria-haspopup","true"),t.append(lb()),t.addEventListener("click",e),t};var fb=e=>{let{component:t,setStatus:r}=ub(),o=document.createElement("div");return o.style.position="absolute",o.style.left="-2em",o.style.zIndex="1",o.style.display="flex",o.style.flexFlow="column",o.append(mb(e),t),{menu:o,setStatus:r}};function db(e){return new Promise(t=>setTimeout(t,e))}function hb(e,t){let{trailing:r=!1,interval:o=0}=t??{},n,s=!1,i=l=>{n?.resolve?.({executed:!1}),n=l},a=()=>{let{...l}=n;return n=void 0,l},c=async()=>{if(s||!n)return;s=!0,o>0&&await db(o);let{parameters:l,resolve:u,reject:p}=a();try{let f=await e(...l);s=!1,u({result:f,executed:!0})}catch(f){s=!1,p(f)}finally{r?await c():(i(),await Promise.resolve())}};return(...l)=>new Promise((u,p)=>{i({parameters:l,resolve:u,reject:p}),c()})}var gb,yb=async(e,t)=>{let r=[],n=hb(async()=>{r.forEach(({menu:i,setStatus:a})=>{a("none"),i.remove()});let s=iy(scrapbox.Project.name,scrapbox.Page.title??"",mt());for(let i of s){let a=i.lang.toLowerCase();if(sb(a))for(let c of i.startIds){let l=document.getElementById(`L${c}`),{menu:u,setStatus:p}=fb(async()=>{await p("loading");try{gb??=await nb(e,t);let{contents:f}=await gb(i.path);console.debug("execute:",f),await Function(`return (async()=>{${f}})()`)(),await p("pass")}catch(f){console.error(f),await p("fail",`${f}`)}});r.push({menu:u,setStatus:p}),l?.insertBefore?.(u,l?.firstElementChild)}}await Promise.resolve()},{interval:100,trailing:!0});return await n(),scrapbox.addListener("lines:changed",n),()=>{scrapbox.removeListener("lines:changed",n),r.forEach(({menu:s,setStatus:i})=>{i("none"),s.remove()})}};function ES(e,t){for(var r in t)e[r]=t[r];return e}function xb(e,t){for(var r in e)if(r!=="__source"&&!(r in t))return!0;for(var o in t)if(o!=="__source"&&e[o]!==t[o])return!0;return!1}function _n(e,t){var r=t(),o=J({t:{__:r,u:t}}),n=o[0].t,s=o[1];return ki(function(){n.__=r,n.u=t,Xp(n)&&s({t:n})},[e,r,t]),oe(function(){return Xp(n)&&s({t:n}),e(function(){Xp(n)&&s({t:n})})},[e]),r}function Xp(e){var t,r,o=e.u,n=e.__;try{var s=o();return!((t=n)===(r=s)&&(t!==0||1/t==1/r)||t!=t&&r!=r)}catch{return!0}}function bb(e,t){this.props=e,this.context=t}(bb.prototype=new Xt).isPureReactComponent=!0,bb.prototype.shouldComponentUpdate=function(e,t){return xb(this.props,e)||xb(this.state,t)};var Eb=Z.__b;Z.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Eb&&Eb(e)};var Jke=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;var wS=Z.__e;Z.__e=function(e,t,r,o){if(e.then){for(var n,s=t;s=s.__;)if((n=s.__c)&&n.__c)return t.__e==null&&(t.__e=r.__e,t.__k=r.__k),n.__c(e,t)}wS(e,t,r,o)};var wb=Z.unmount;function Pb(e,t,r){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(o){typeof o.__c=="function"&&o.__c()}),e.__c.__H=null),(e=ES({},e)).__c!=null&&(e.__c.__P===r&&(e.__c.__P=t),e.__c=null),e.__k=e.__k&&e.__k.map(function(o){return Pb(o,t,r)})),e}function Sb(e,t,r){return e&&r&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(o){return Sb(o,t,r)}),e.__c&&e.__c.__P===t&&(e.__e&&r.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=r)),e}function Yp(){this.__u=0,this.o=null,this.__b=null}function Ob(e){var t=e.__.__c;return t&&t.__a&&t.__a(e)}function Ka(){this.i=null,this.l=null}Z.unmount=function(e){var t=e.__c;t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),wb&&wb(e)},(Yp.prototype=new Xt).__c=function(e,t){var r=t.__c,o=this;o.o==null&&(o.o=[]),o.o.push(r);var n=Ob(o.__v),s=!1,i=function(){s||(s=!0,r.__R=null,n?n(a):a())};r.__R=i;var a=function(){if(!--o.__u){if(o.state.__a){var c=o.state.__a;o.__v.__k[0]=Sb(c,c.__c.__P,c.__c.__O)}var l;for(o.setState({__a:o.__b=null});l=o.o.pop();)l.forceUpdate()}};o.__u++||32&t.__u||o.setState({__a:o.__b=o.__v.__k[0]}),e.then(i,i)},Yp.prototype.componentWillUnmount=function(){this.o=[]},Yp.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var r=document.createElement("div"),o=this.__v.__k[0].__c;this.__v.__k[0]=Pb(this.__b,r,o.__O=o.__P)}this.__b=null}var n=t.__a&&yr(Y,null,e.fallback);return n&&(n.__u&=-33),[yr(Y,null,t.__a?null:e.children),n]};var Rb=function(e,t,r){if(++r[1]===r[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(r=e.i;r;){for(;r.length>3;)r.pop()();if(r[1]<r[0])break;e.i=r=r[2]}};(Ka.prototype=new Xt).__a=function(e){var t=this,r=Ob(t.__v),o=t.l.get(e);return o[0]++,function(n){var s=function(){t.props.revealOrder?(o.push(n),Rb(t,e,o)):n()};r?r(s):s()}},Ka.prototype.render=function(e){this.i=null,this.l=new Map;var t=Ur(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var r=t.length;r--;)this.l.set(t[r],this.i=[1,0,this.i]);return e.children},Ka.prototype.componentDidUpdate=Ka.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,r){Rb(e,r,t)})};var RS=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,kS=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,vS=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,_S=/[A-Z0-9]/g,TS=typeof document<"u",PS=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};Xt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(Xt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var kb=Z.event;function SS(){}function OS(){return this.cancelBubble}function LS(){return this.defaultPrevented}Z.event=function(e){return kb&&(e=kb(e)),e.persist=SS,e.isPropagationStopped=OS,e.isDefaultPrevented=LS,e.nativeEvent=e};var Lb,NS={enumerable:!1,configurable:!0,get:function(){return this.class}},vb=Z.vnode;Z.vnode=function(e){typeof e.type=="string"&&function(t){var r=t.props,o=t.type,n={},s=o.indexOf("-")===-1;for(var i in r){var a=r[i];if(!(i==="value"&&"defaultValue"in r&&a==null||TS&&i==="children"&&o==="noscript"||i==="class"||i==="className")){var c=i.toLowerCase();i==="defaultValue"&&"value"in r&&r.value==null?i="value":i==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?i="ondblclick":c!=="onchange"||o!=="input"&&o!=="textarea"||PS(r.type)?c==="onfocus"?i="onfocusin":c==="onblur"?i="onfocusout":vS.test(i)&&(i=c):c=i="oninput":s&&kS.test(i)?i=i.replace(_S,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&n[i=c]&&(i="oninputCapture"),n[i]=a}}o=="select"&&n.multiple&&Array.isArray(n.value)&&(n.value=Ur(r.children).forEach(function(l){l.props.selected=n.value.indexOf(l.props.value)!=-1})),o=="select"&&n.defaultValue!=null&&(n.value=Ur(r.children).forEach(function(l){l.props.selected=n.multiple?n.defaultValue.indexOf(l.props.value)!=-1:n.defaultValue==l.props.value})),r.class&&!r.className?(n.class=r.class,Object.defineProperty(n,"className",NS)):(r.className&&!r.class||r.class&&r.className)&&(n.class=n.className=r.className),t.props=n}(e),e.$$typeof=RS,vb&&vb(e)};var _b=Z.__r;Z.__r=function(e){_b&&_b(e),Lb=e.__c};var Tb=Z.diffed;Z.diffed=function(e){Tb&&Tb(e);var t=e.props,r=e.__e;r!=null&&e.type==="textarea"&&"value"in t&&t.value!==r.value&&(r.value=t.value==null?"":t.value),Lb=null};var ys=e=>e.replaceAll(" ","_").toLowerCase(),Nb=e=>e.replaceAll("_"," "),Xa=e=>[...e].map((t,r)=>t===" "?"_":!CS.includes(t)||r===e.length-1&&AS.includes(t)?encodeURIComponent(t):t).join(""),CS='@$&+=:;",',AS=':;",';var Cb=({title:e,projects:t,selected:r,confirm:o})=>d("div",{className:`candidate${r?" selected":""}`,children:[d(MS,{title:e,confirm:o}),t.map(n=>d(IS,{project:n.name,title:e,mark:n.mark,confirm:n.confirm}))]}),MS=({title:e,confirm:t})=>d("a",{className:"button",tabIndex:0,role:"menuitem",href:`./${Xa(e)}`,onClick:Ab(t),children:e}),IS=({project:e,title:t,mark:r,confirm:o})=>r===""?d(Y,{}):d("a",{className:"mark",tabIndex:0,href:`../${e}/${Xa(t)}`,onClick:Ab(o),title:`/${e}/${Xa(t)}`,children:r instanceof URL?d("img",{src:r.href}):`[${r}]`}),Ab=e=>F(t=>{t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),t.stopPropagation(),e())},[e]);var Mb=(e,t)=>{let[r,o]=J(null),n=F(c=>o(l=>{if(e.length===0)return null;if(l===null)return t(e[0]);let u=e.findIndex(p=>t(p)===l);return t(c?.cyclic?e[(u+1)%e.length]:e.at(u+1)??e[0])}),[e,t]),s=F(c=>o(l=>{if(e.length===0)return null;if(l===null)return t(e[e.length-1]);let u=e.findIndex(p=>t(p)===l);return u<0?t(e[e.length-1]):t(c?.cyclic?e[(u-1+e.length)%e.length]:e.at(u-1)??e[e.length-1])}),[e,t]),i=F(()=>o(e.length===0?null:t(e[0])),[e,t]),a=F(()=>o(e.length===0?null:t(e[e.length-1])),[e,t]);return{selectedId:r,next:n,prev:s,selectFirst:i,selectLast:a}};var Ib=e=>{let[t,r]=J(null),o=C(()=>{let n=t?.getBoundingClientRect?.(),i=qn(e.line,e.char)?.getBoundingClientRect?.();return!i||!n?{}:{top:`${i.bottom-n.top}px`,left:`${i?.left??0-n.left}px`,right:`${n.right-(i?.left??0)}px`}},[t,e.line,e.char]);return{updateStandardElement:r,...o}};var Qp="enableProjectsOnSuggestion",Fb=(e,t)=>{let[r,o]=J(Ya([...e],t)),n=F((s,i)=>{FS(s,i,e,t),o(Ya([...e],t))},[e,t.enableSelfProjectOnStart]);return oe(()=>{let s=i=>{i.key===Qp&&o(Ya([...e],t))};return addEventListener("storage",s),()=>removeEventListener("storage",s)},[e,t.enableSelfProjectOnStart]),{projects:r,set:n}},Jp=!0,Ya=(e,t)=>{try{let r=localStorage.getItem(Qp);if(r===null)return Ja(e),e;let o=JSON.parse(r);return Array.isArray(o)&&o.every(n=>typeof n=="string")?!t.enableSelfProjectOnStart||!e.includes(scrapbox.Project.name)?o:o.includes(scrapbox.Project.name)?Jp?o:o.filter(n=>n!==scrapbox.Project.name):Jp?[...o,scrapbox.Project.name]:o:(Ja(e),e)}catch(r){if(!(r instanceof TypeError))throw r;return Ja(e),e}},FS=(e,t,r,o)=>{let n=Ya([...r],o);o.enableSelfProjectOnStart&&e===scrapbox.Project.name&&(Jp=t),Ja(t?[...n,e]:n.filter(s=>s!==e))},Ja=e=>localStorage.setItem(Qp,JSON.stringify(e));var Ub=()=>C(()=>document.documentElement.dataset.os??"",[]);var xs=(e,t)=>{if(e instanceof URL)return e;try{return new URL(e)}catch(r){if(!(r instanceof TypeError))throw r;if(!t||!/^\.\/|^\.\.\/|^\//.test(e))return e;try{return new URL(e,t)}catch(o){if(!(o instanceof TypeError))throw o;return e}}};var Db=({progress:e})=>d("div",{className:"progress",style:`background: linear-gradient(to right, var(--select-suggest-border-color, #eee) ${(e*100).toPrecision(3)}%, transparent ${(e*100).toPrecision(3)}%)`});var jb=({position:e,start:t,enableSelfProjectOnStart:r,projects:o,...n})=>{let{projects:s,set:i}=Fb(o,{enableSelfProjectOnStart:r}),{updateStandardElement:a,top:c,left:l,right:u}=Ib({line:e.line,char:t}),p=Ub();return d(Y,{children:[d(DS,{itemCount:n.items.length,enableProjects:s,projects:o,top:c,right:u,set:i,os:p,...n}),d(US,{updateStandardElement:a,start:t,enableProjects:s,projects:o,top:c,left:l,os:p,...n})]})},US=({start:e,updateStandardElement:t,confirmAfter:r,cancel:o,query:n,enableProjects:s,projects:i,items:a,top:c,left:l,progress:u,callback:p,limit:f,mark:m,os:h})=>{let g=F((P,_,T)=>{let S=`[${_?`/${_}/${P}`:P}${T?.icon?".icon":""}]`;r((A,{line:M})=>[`${[...A].slice(0,e).join("")}${S}${[...A].slice(e+[...n].length).join("")}`,{line:M,char:e+[...S].length}])},[e,n]),y=C(()=>i.size>1||!i.has(scrapbox.Project.name),[i]),x=C(()=>{let P=[];for(let _ of a){if(P.length===f)break;_.projects.some(T=>s.includes(T))&&P.push({title:_.title,projects:_.projects.flatMap(T=>s.includes(T)?[{name:T,mark:y?xs(m[T]??"",import.meta.url)||T[0]:"",confirm:S=>g(_.title,T,S)}]:[]),confirm:T=>g(_.title,void 0,T)})}return P},[s,y,a,f,m,g]),{selectedId:E,next:k,prev:b,selectLast:v,selectFirst:R}=Mb(x,$b),O=F(P=>E===null?!1:(x.find(_=>$b(_)===E)?.confirm?.(P),!0),[E,x]);oe(()=>p(x.length===0?void 0:{selectNext:P=>(k(P),!0),selectPrev:P=>(b(P),!0),selectFirst:()=>(R(),!0),selectLast:()=>(v(),!0),confirm:O,cancel:()=>(o(),!0)}),[p,x.length,k,b,R,v,O]);let L=C(()=>x.length>0&&c!=null&&l!=null?{top:c,left:l}:{display:"none"},[x.length,c,l]),N=F(P=>{if(!P){t(P);return}let _=P.parentNode;if(!(_ instanceof ShadowRoot))throw Error('The parent of "div.container" must be ShadowRoot');t(_.host.parentElement)},[t]);return d("div",{ref:N,className:"container candidates","data-os":h,style:L,children:[x.map(P=>d(Cb,{...P,selected:E===P.title},P.title)),a.length>f&&d("div",{className:"counter",children:`${a.length-f} more links`}),d(Db,{progress:u})]})},DS=({enableProjects:e,projects:t,projectScore:r,mark:o,itemCount:n,top:s,right:i,set:a,os:c,freezeUntil:l})=>{let u=C(()=>[...t].sort((f,m)=>(r.get(m)??0)-(r.get(f)??0)).flatMap(f=>r.has(f)?[{name:f,enable:e.includes(f),mark:xs(o[f]??"",import.meta.url)||f[0],score:r.get(f),onClick:()=>l(()=>{a(f,!e.includes(f)),Xe().focus()})}]:[]),[t,r,e,o]),p=C(()=>n>0&&s!=null&&i!=null&&t.size>1?{top:s,right:i}:{display:"none"},[s,i,n,t.size]);return d("div",{className:"container projects","data-os":c,style:p,children:u.map(f=>d($S,{...f},f.name))})},$S=e=>d("div",{className:e.enable?"mark":"mark disabled","data-score":e.score.toPrecision(3),onClick:e.onClick,title:e.name,children:e.mark instanceof URL?d("img",{src:e.mark.href}):`[${e.mark}]`}),$b=e=>e.title;var Bb=function(){};function Es(e,t={}){Bb.prototype.name=e;let r={};return new Proxy(Bb,{get(o,n){return n==="caller"?null:n==="__createMock__"?Es:n==="__unenv__"?!0:n in t?t[n]:r[n]=r[n]||Es(`${e}.${n.toString()}`)},apply(o,n,s){return Es(`${e}()`)},construct(o,n,s){return Es(`[${e}]`)},enumerate(){return[]}})}var Zp=Es("mock");function jS(e){return new Error(`[unenv] ${e} is not implemented yet!`)}function pe(e){return Object.assign(()=>{throw jS(e)},{__unenv__:!0})}var BS=Object.freeze(Object.create(null,{__unenv__:{get:()=>!0}})),Qa=Object.create(null),HS=globalThis.process?.env,bs=e=>HS||globalThis.__env__||(e?Qa:globalThis),WS=new Proxy(Qa,{get(e,t){return bs()[t]??Qa[t]},has(e,t){let r=bs();return t in r||t in Qa},set(e,t,r){let o=bs(!0);return o[t]=r,!0},deleteProperty(e,t){let r=bs(!0);return delete r[t],!0},ownKeys(){let e=bs();return Object.keys(e)}}),GS=Object.assign(function(e){let t=Date.now(),r=Math.trunc(t/1e3),o=t%1e3*1e6;if(e){let n=r-e[0],s=o-e[0];return s<0&&(n=n-1,s=1e9+s),[n,s]}return[r,o]},{bigint:function(){return BigInt(Date.now()*1e6)}}),VS=globalThis.queueMicrotask?(e,...t)=>{globalThis.queueMicrotask(e.bind(void 0,...t))}:zS();function zS(){let e=[],t=!1,r,o=-1;function n(){!t||!r||(t=!1,r.length>0?e=[...r,...e]:o=-1,e.length>0&&s())}function s(){if(t)return;let i=setTimeout(n);t=!0;let a=e.length;for(;a;){for(r=e,e=[];++o<a;)r&&r[o]();o=-1,a=e.length}r=void 0,t=!1,clearTimeout(i)}return(i,...a)=>{e.push(i.bind(void 0,...a)),e.length===1&&!t&&setTimeout(s)}}var qS="unenv",KS=[],XS="",YS={ares:"",http_parser:"",icu:"",modules:"",node:"",openssl:"",uv:"",v8:"",zlib:""};function Zt(){return eu}var JS=Zt,QS=Zt,ZS=Zt,eO=Zt,tO=Zt,rO=Zt,oO=function(e){return e==="message"||e==="multipleResolves"?eu:!1},nO=Zt,sO=Zt,iO=function(e){return[]},aO=()=>0,cO=function(e){throw new Error("[unenv] process.binding is not supported")},Hb="/",lO=function(){return Hb},pO=function(e){Hb=e},uO=function(){return 0},mO=function(){return 1e3},fO=function(){return 1e3},dO=function(){return 1e3},hO=function(){return 1e3},gO=function(){return[]},yO=e=>{},xO=pe("process.abort"),bO=new Set,EO="",wO="",RO=BS,kO=!1,vO=()=>0,_O=()=>0,TO=pe("process.cpuUsage"),PO=0,SO=pe("process.dlopen"),OO=Zt,LO=Zt,NO=pe("process.eventNames"),CO=[],AO="",MO=pe("process.exit"),IO=Object.create({inspector:void 0,debug:void 0,uv:void 0,ipv6:void 0,tls_alpn:void 0,tls_sni:void 0,tls_ocsp:void 0,tls:void 0,cached_builtins:void 0}),FO=()=>[],UO=pe("process.getMaxListeners"),DO=pe("process.kill"),$O=Object.assign(()=>({arrayBuffers:0,rss:0,external:0,heapTotal:0,heapUsed:0}),{rss:()=>0}),jO=1e3,BO="",HO=1e3,WO=pe("process.rawListeners"),GO=Object.create({name:"",lts:"",sourceUrl:void 0,headersUrl:void 0}),VO=Object.create({compact:void 0,directory:void 0,filename:void 0,getReport:pe("process.report.getReport"),reportOnFatalError:void 0,reportOnSignal:void 0,reportOnUncaughtException:void 0,signal:void 0,writeReport:pe("process.report.writeReport")}),zO=pe("process.resourceUsage"),qO=pe("process.setegid"),KO=pe("process.seteuid"),XO=pe("process.setgid"),YO=pe("process.setgroups"),JO=pe("process.setuid"),QO=pe("process.setMaxListeners"),ZO=pe("process.setSourceMapsEnabled"),eL=Zp.__createMock__("process.stdout"),tL=Zp.__createMock__("process.stderr"),rL=Zp.__createMock__("process.stdin"),oL=!1,nL=()=>0,sL=0,iL=pe("process.setUncaughtExceptionCaptureCallback"),aL=()=>!1,cL=!1,lL=pe("process.loadEnvFile"),pL=void 0,uL={has:()=>!1},mL={ref(){},unref(){}},fL=!1,dL={register(){},unregister(){},registerBeforeExit(){}},hL=pe("process.assert"),gL=pe("process.openStdin"),yL=pe("process._debugEnd"),xL=pe("process._debugProcess"),bL=pe("process._fatalException"),EL=pe("process._getActiveHandles"),wL=pe("process._getActiveRequests"),RL=pe("process._kill"),kL=[],vL=pe("process._rawDebug"),_L=pe("process._startProfilerIdleNotifier"),TL=pe("process.__stopProfilerIdleNotifier"),PL=pe("process._tickCallback"),Vve=pe("process._linkedBinding"),SL=void 0,OL=pe("process.initgroups"),LL=[],NL=Zt,CL=!1,AL=[],ML=0,IL=0,eu={_events:AL,_eventsCount:ML,_exiting:CL,_maxListeners:IL,_debugEnd:yL,_debugProcess:xL,_fatalException:bL,_getActiveHandles:EL,_getActiveRequests:wL,_kill:RL,_preload_modules:kL,_rawDebug:vL,_startProfilerIdleNotifier:_L,_stopProfilerIdleNotifier:TL,_tickCallback:PL,domain:SL,initgroups:OL,moduleLoadList:LL,reallyExit:NL,exitCode:sL,abort:xO,addListener:QS,allowedNodeEnvironmentFlags:bO,hasUncaughtExceptionCaptureCallback:aL,setUncaughtExceptionCaptureCallback:iL,loadEnvFile:lL,sourceMapsEnabled:cL,throwDeprecation:fL,mainModule:pL,permission:uL,channel:mL,arch:EO,argv:KS,argv0:wO,assert:hL,binding:cO,chdir:pO,config:RO,connected:kO,constrainedMemory:vO,availableMemory:_O,cpuUsage:TO,cwd:lO,debugPort:PO,dlopen:SO,disconnect:OO,emit:oO,emitWarning:LO,env:WS,eventNames:NO,execArgv:CO,execPath:AO,exit:MO,finalization:dL,features:IO,getBuiltinModule:yO,getegid:mO,geteuid:fO,getgid:dO,getgroups:gO,getuid:hO,getActiveResourcesInfo:FO,getMaxListeners:UO,hrtime:GS,kill:DO,listeners:iO,listenerCount:aO,memoryUsage:$O,nextTick:VS,on:JS,off:eO,once:ZS,openStdin:gL,pid:jO,platform:BO,ppid:HO,prependListener:nO,prependOnceListener:sO,rawListeners:WO,release:GO,removeAllListeners:rO,removeListener:tO,report:VO,resourceUsage:zO,setegid:qO,seteuid:KO,setgid:XO,setgroups:YO,setuid:JO,setMaxListeners:QO,setSourceMapsEnabled:ZO,stderr:tL,stdin:rL,stdout:eL,title:qS,traceDeprecation:oL,umask:uO,uptime:nL,version:XS,versions:YS},ws=eu;var FL=Object.create,Kb=Object.defineProperty,UL=Object.getOwnPropertyDescriptor,DL=Object.getOwnPropertyNames,$L=Object.getPrototypeOf,jL=Object.prototype.hasOwnProperty,Xb=(e=>typeof io<"u"?io:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof io<"u"?io:t)[r]}):e)(function(e){if(typeof io<"u")return io.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Yb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),BL=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of DL(t))!jL.call(e,n)&&n!==r&&Kb(e,n,{get:()=>t[n],enumerable:!(o=UL(t,n))||o.enumerable});return e},Jb=(e,t,r)=>(r=e!=null?FL($L(e)):{},BL(t||!e||!e.__esModule?Kb(r,"default",{value:e,enumerable:!0}):r,e)),HL=Yb((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in ws&&"node"in ws.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[Xb][0](`${["node","util"].join(":")}`)}catch{r=null}t.exports=r}),WL=Yb((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in ws&&"node"in ws.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[Xb][0](`${["node","fs"].join(":")}`)}catch{r=null}t.exports=r}),GL={},Za=VL(globalThis,GL);function VL(e,t){return new Proxy(e,{get(r,o,n){return o in t?t[o]:e[o]},set(r,o,n){return o in t&&delete t[o],e[o]=n,!0},deleteProperty(r,o){let n=!1;return o in t&&(delete t[o],n=!0),o in e&&(delete e[o],n=!0),n},ownKeys(r){let o=Reflect.ownKeys(e),n=Reflect.ownKeys(t),s=new Set(n);return[...o.filter(i=>!s.has(i)),...n]},defineProperty(r,o,n){return o in t&&delete t[o],Reflect.defineProperty(e,o,n),!0},getOwnPropertyDescriptor(r,o){return o in t?Reflect.getOwnPropertyDescriptor(t,o):Reflect.getOwnPropertyDescriptor(e,o)},has(r,o){return o in t||o in e}})}var Wb=["debug","info","warning","error","fatal"];function Gb(e,t){let r=Wb.indexOf(e);if(r<0)throw new TypeError(`Invalid log level: ${JSON.stringify(e)}.`);let o=Wb.indexOf(t);if(o<0)throw new TypeError(`Invalid log level: ${JSON.stringify(t)}.`);return r-o}function ks(e=[]){return Qb.getLogger(e)}var tu=Symbol.for("logtape.rootLogger"),Qb=class no{static getLogger(t=[]){let r=tu in Za?Za[tu]??null:null;return r==null&&(r=new no(null,[]),Za[tu]=r),typeof t=="string"?r.getChild(t):t.length===0?r:r.getChild(t)}constructor(t,r){Object.defineProperty(this,"parent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"children",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"category",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sinks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parentSinks",{enumerable:!0,configurable:!0,writable:!0,value:"inherit"}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lowestLevel",{enumerable:!0,configurable:!0,writable:!0,value:"debug"}),Object.defineProperty(this,"contextLocalStorage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.parent=t,this.children={},this.category=r,this.sinks=[],this.filters=[]}getChild(t){let r=typeof t=="string"?t:t[0],o=this.children[r],n=o instanceof no?o:o?.deref();return n==null&&(n=new no(this,[...this.category,r]),this.children[r]="WeakRef"in Za?new WeakRef(n):n),typeof t=="string"||t.length===1?n:n.getChild(t.slice(1))}reset(){for(;this.sinks.length>0;)this.sinks.shift();for(this.parentSinks="inherit";this.filters.length>0;)this.filters.shift();this.lowestLevel="debug"}resetDescendants(){for(let t of Object.values(this.children))(t instanceof no?t:t.deref())?.resetDescendants();this.reset()}with(t){return new zL(this,{...t})}filter(t){for(let r of this.filters)if(!r(t))return!1;return this.filters.length<1?this.parent?.filter(t)??!0:!0}*getSinks(t){if(!(this.lowestLevel===null||Gb(t,this.lowestLevel)<0)){if(this.parent!=null&&this.parentSinks==="inherit")for(let r of this.parent.getSinks(t))yield r;for(let r of this.sinks)yield r}}emit(t,r){if(!(this.lowestLevel===null||Gb(t.level,this.lowestLevel)<0||!this.filter(t))){for(let o of this.getSinks(t.level))if(!r?.has(o))try{o(t)}catch(n){let s=new Set(r);s.add(o),qL.log("fatal","Failed to emit a log record to sink {sink}: {error}",{sink:o,error:n,record:t},s)}}}log(t,r,o,n){let s=no.getLogger().contextLocalStorage?.getStore()??{},i,a=typeof o=="function"?{category:this.category,level:t,timestamp:Date.now(),get message(){return Vb(r,this.properties)},rawMessage:r,get properties(){return i==null&&(i={...s,...o()}),i}}:{category:this.category,level:t,timestamp:Date.now(),message:Vb(r,{...s,...o}),rawMessage:r,properties:{...s,...o}};this.emit(a,n)}logLazily(t,r,o={}){let n=no.getLogger().contextLocalStorage?.getStore()??{},s,i;function a(){if((i==null||s==null)&&(i=r((c,...l)=>(s=c,zb(c,l))),s==null))throw new TypeError("No log record was made.");return[i,s]}this.emit({category:this.category,level:t,get message(){return a()[0]},get rawMessage(){return a()[1]},timestamp:Date.now(),properties:{...n,...o}})}logTemplate(t,r,o,n={}){let s=no.getLogger().contextLocalStorage?.getStore()??{};this.emit({category:this.category,level:t,message:zb(r,o),rawMessage:r,timestamp:Date.now(),properties:{...s,...n}})}debug(t,...r){typeof t=="string"?this.log("debug",t,r[0]??{}):typeof t=="function"?this.logLazily("debug",t):this.logTemplate("debug",t,r)}info(t,...r){typeof t=="string"?this.log("info",t,r[0]??{}):typeof t=="function"?this.logLazily("info",t):this.logTemplate("info",t,r)}warn(t,...r){typeof t=="string"?this.log("warning",t,r[0]??{}):typeof t=="function"?this.logLazily("warning",t):this.logTemplate("warning",t,r)}error(t,...r){typeof t=="string"?this.log("error",t,r[0]??{}):typeof t=="function"?this.logLazily("error",t):this.logTemplate("error",t,r)}fatal(t,...r){typeof t=="string"?this.log("fatal",t,r[0]??{}):typeof t=="function"?this.logLazily("fatal",t):this.logTemplate("fatal",t,r)}},zL=class Zb{constructor(t,r){Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=t,this.properties=r}get category(){return this.logger.category}get parent(){return this.logger.parent}getChild(t){return this.logger.getChild(t).with(this.properties)}with(t){return new Zb(this.logger,{...this.properties,...t})}log(t,r,o,n){this.logger.log(t,r,typeof o=="function"?()=>({...this.properties,...o()}):{...this.properties,...o},n)}logLazily(t,r){this.logger.logLazily(t,r,this.properties)}logTemplate(t,r,o){this.logger.logTemplate(t,r,o,this.properties)}debug(t,...r){typeof t=="string"?this.log("debug",t,r[0]??{}):typeof t=="function"?this.logLazily("debug",t):this.logTemplate("debug",t,r)}info(t,...r){typeof t=="string"?this.log("info",t,r[0]??{}):typeof t=="function"?this.logLazily("info",t):this.logTemplate("info",t,r)}warn(t,...r){typeof t=="string"?this.log("warning",t,r[0]??{}):typeof t=="function"?this.logLazily("warning",t):this.logTemplate("warning",t,r)}error(t,...r){typeof t=="string"?this.log("error",t,r[0]??{}):typeof t=="function"?this.logLazily("error",t):this.logTemplate("error",t,r)}fatal(t,...r){typeof t=="string"?this.log("fatal",t,r[0]??{}):typeof t=="function"?this.logLazily("fatal",t):this.logTemplate("fatal",t,r)}},qL=Qb.getLogger(["logtape","meta"]);function Vb(e,t){let r=[],o="";for(let n=0;n<e.length;n++){let s=e.charAt(n),i=e.charAt(n+1);if(s==="{"&&i==="{")o=o+s,n++;else if(s==="}"&&i==="}")o=o+s,n++;else if(s==="{")r.push(o),o="";else if(s==="}"){let a;o.match(/^\s|\s$/)?a=o in t?t[o]:t[o.trim()]:a=t[o],r.push(a),o=""}else o=o+s}return r.push(o),r}function zb(e,t){let r=[];for(let o=0;o<e.length;o++)r.push(e[o]),o<t.length&&r.push(t[o]);return r}var KL=Jb(HL()),Rs=KL.default,qb={debug:"DBG",info:"INF",warning:"WRN",error:"ERR",fatal:"FTL"},eE="Deno"in globalThis&&"inspect"in globalThis.Deno&&typeof globalThis.Deno.inspect=="function"?globalThis.Deno.inspect.bind(globalThis.Deno):Rs!=null&&"inspect"in Rs&&typeof Rs.inspect=="function"?Rs.inspect.bind(Rs):e=>JSON.stringify(e);function tE(e={}){let t=e.timestamp==null||e.timestamp==="date-time-timezone"?i=>new Date(i).toISOString().replace("T"," ").replace("Z"," +00:00"):e.timestamp==="date-time-tz"?i=>new Date(i).toISOString().replace("T"," ").replace("Z"," +00"):e.timestamp==="date-time"?i=>new Date(i).toISOString().replace("T"," ").replace("Z",""):e.timestamp==="time-timezone"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z"," +00:00"):e.timestamp==="time-tz"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z"," +00"):e.timestamp==="time"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z",""):e.timestamp==="date"?i=>new Date(i).toISOString().replace(/T.*/,""):e.timestamp==="rfc3339"?i=>new Date(i).toISOString():e.timestamp,r=e.category??"·",o=e.value??eE,n=e.level==null||e.level==="ABBR"?i=>qb[i]:e.level==="abbr"?i=>qb[i].toLowerCase():e.level==="FULL"?i=>i.toUpperCase():e.level==="full"?i=>i:e.level==="L"?i=>i.charAt(0).toUpperCase():e.level==="l"?i=>i.charAt(0):e.level,s=e.format??(({timestamp:i,level:a,category:c,message:l})=>`${i} [${a}] ${c}: ${l}`);return i=>{let a="";for(let p=0;p<i.message.length;p++)p%2===0?a+=i.message[p]:a+=o(i.message[p]);let c=t(i.timestamp),l=n(i.level),u=typeof r=="function"?r(i.category):i.category.join(r);return`${s({timestamp:c,level:l,category:u,message:a,record:i})}
`}}var Kve=tE(),ru="\x1B[0m",ou={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},nu={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",strikethrough:"\x1B[9m"},XL={debug:"blue",info:"green",warning:"yellow",error:"red",fatal:"magenta"};function YL(e={}){let t=e.format,r=typeof e.timestampStyle>"u"?"dim":e.timestampStyle,o=e.timestampColor??null,n=`${r==null?"":nu[r]}${o==null?"":ou[o]}`,s=r==null&&o==null?"":ru,i=typeof e.levelStyle>"u"?"bold":e.levelStyle,a=e.levelColors??XL,c=typeof e.categoryStyle>"u"?"dim":e.categoryStyle,l=e.categoryColor??null,u=`${c==null?"":nu[c]}${l==null?"":ou[l]}`,p=c==null&&l==null?"":ru;return tE({timestamp:"date-time-tz",value(f){return eE(f,{colors:!0})},...e,format({timestamp:f,level:m,category:h,message:g,record:y}){let x=a[y.level];return f=`${n}${f}${s}`,m=`${i==null?"":nu[i]}${x==null?"":ou[x]}${m}${i==null&&x==null?"":ru}`,t==null?`${f} ${m} ${u}${h}:${p} ${g}`:t({timestamp:f,level:m,category:`${u}${h}${p}`,message:g,record:y})}})}var Xve=YL();var JL=Jb(WL()),QL=JL.default;function Tn(){throw new Error("File sink is not available in the browser.")}var ZL={openSync:Tn,writeSync:Tn,flushSync:Tn,closeSync:Tn,statSync:Tn,renameSync:Tn},$o=QL,Yve=$o==null?ZL:{openSync(e){return $o.openSync(e,"a")},writeSync:$o.writeSync,flushSync:$o.fsyncSync,closeSync:$o.closeSync,statSync:$o.statSync,renameSync:$o.renameSync};var ec="`null`",sTe=yn+ec,rN=Lr+ec,iTe=xn+ec,aTe=bn+ec;var tc="`undefined`",mTe=yn+tc,oN=Lr+tc,fTe=xn+tc,dTe=bn+tc;async function*oE(e){let t=[],r=[],o=new Map,n=[];for(let s of e)s.isValid&&(s.id?s.isMember||t.push(s.id):r.push(s.name),n.push(s.name),o.set(s.name,s.checked));for(let s=0;s<t.length;s+=50){let i=t.slice(s,s+50);if(i.length===0)break;i.length===1&&i.push(i[0]);let a=await ai(i);if(kt(a)){r=n;break}for(let c of Io(a).projects)o.has(c.name)&&(yield bt({...c,checked:o.get(c.name)??0}))}for(let s of r){let i=await gr(s);yield et(i)?bt({...Io(i),checked:o.get(s)??0}):At({...wn(i),project:s})}}var au=(e,t)=>t.some(r=>e instanceof r),nE,sE;function sN(){return nE||(nE=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function iN(){return sE||(sE=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var cu=new WeakMap,su=new WeakMap,rc=new WeakMap;function aN(e){let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{r(so(e.result)),n()},i=()=>{o(e.error),n()};e.addEventListener("success",s),e.addEventListener("error",i)});return rc.set(t,e),t}function cN(e){if(cu.has(e))return;let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{r(),n()},i=()=>{o(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)});cu.set(e,t)}var lu={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return cu.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return so(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function lE(e){lu=e(lu)}function lN(e){return iN().includes(e)?function(...t){return e.apply(pu(this),t),so(this.request)}:function(...t){return so(e.apply(pu(this),t))}}function pN(e){return typeof e=="function"?lN(e):(e instanceof IDBTransaction&&cN(e),au(e,sN())?new Proxy(e,lu):e)}function so(e){if(e instanceof IDBRequest)return aN(e);if(su.has(e))return su.get(e);let t=pN(e);return t!==e&&(su.set(e,t),rc.set(t,e)),t}var pu=e=>rc.get(e);function pE(e,t,{blocked:r,upgrade:o,blocking:n,terminated:s}={}){let i=indexedDB.open(e,t),a=so(i);return o&&i.addEventListener("upgradeneeded",c=>{o(so(i.result),c.oldVersion,c.newVersion,so(i.transaction),c)}),r&&i.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),n&&c.addEventListener("versionchange",l=>n(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function uE(e,{blocked:t}={}){let r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",o=>t(o.oldVersion,o)),so(r).then(()=>{})}var uN=["get","getKey","getAll","getAllKeys","count"],mN=["put","add","delete","clear"],iu=new Map;function iE(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(iu.get(t))return iu.get(t);let r=t.replace(/FromIndex$/,""),o=t!==r,n=mN.includes(r);if(!(r in(o?IDBIndex:IDBObjectStore).prototype)||!(n||uN.includes(r)))return;let s=async function(i,...a){let c=this.transaction(i,n?"readwrite":"readonly"),l=c.store;return o&&(l=l.index(a.shift())),(await Promise.all([l[r](...a),n&&c.done]))[0]};return iu.set(t,s),s}lE(e=>({...e,get:(t,r,o)=>iE(t,r)||e.get(t,r,o),has:(t,r)=>!!iE(t,r)||e.has(t,r)}));var fN=["continue","continuePrimaryKey","advance"],aE={},uu=new WeakMap,mE=new WeakMap,dN={get(e,t){if(!fN.includes(t))return e[t];let r=aE[t];return r||(r=aE[t]=function(...o){uu.set(this,mE.get(this)[t](...o))}),r}};async function*hN(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,dN);for(mE.set(r,t),rc.set(r,pu(t));t;)yield r,t=await(uu.get(r)||t.continue()),uu.delete(r)}function cE(e,t){return t===Symbol.asyncIterator&&au(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&au(e,[IDBIndex,IDBObjectStore])}lE(e=>({...e,get(t,r,o){return cE(t,r)?hN:e.get(t,r,o)},has(t,r){return cE(t,r)||e.has(t,r)}}));var fE,mu=async()=>{let e=ks(["@takker/cosense-storage","open"]);return fE??=await pE("scrapbox-storage",4,{upgrade(t,r,o){e.info`start updating DB: ${r} -> ${o}`;let n=Date.now();for(let a of t.objectStoreNames)t.deleteObjectStore(a);t.createObjectStore("titles",{keyPath:"id"}).createIndex("project","project");let i=t.createObjectStore("projects",{keyPath:"id"});i.createIndex("checked","checked"),i.createIndex("name","name"),e.info`finish updating DB: ${Date.now()-n}ms`},blocked(t,r){let o=`The database "@takker/cosense-storage"(v${r}) is blocked because the older one (v${t}) is opened in other tabs.
Please close the other tabs and reload this page.`;e.error(o),alert(o)},blocking(t,r){let o=`The database "@takker/cosense-storage"(v${t}) is blocking the newer one (v${r}) opened.
Please close this page.`;e.error(o),alert(o)}}),fE};var nc=(e,t)=>(fu||(fu=new BroadcastChannel(hE),fu.addEventListener("message",r=>dE(r.data))),oc.set(t,new Set(e).union(oc.get(t)??new Set)),()=>oc.delete(t)),du=(e,t)=>{if((t.added?.size??0)+(t.updated?.size??0)+(t.deleted?.size??0)===0)return;let r={type:"links:changed",project:e,diff:t};dE(r);let o=new BroadcastChannel(hE);o.postMessage(r),o.close()},dE=e=>{for(let[t,r]of oc)r.has(e.project)&&t(e)},hE="scrapbox-storage-notify",fu,oc=new Map;function hu(e){return Math.trunc(+W(e)/1e3)}var sc=async(e,t)=>{let r=await mu(),o=ks(["@takker/cosense-storage","check"]),n=new Map;try{{o.debug`check updates of links...`;let i=new Set,a=r.transaction("projects","readwrite"),c=hu(new Date),l=c-600;for await(let f of a.store.index("checked").iterate(IDBKeyRange.lowerBound(l,!0))){let m=f.value;if(m.isValid===!1){i.add(m.id);continue}i.add(m.name);let h=m.checked;if(h+t>c||m?.updating&&h>l)continue;let g=structuredClone(m);g.updating=!0,n.set(m.id,g),f.update(g)}let u=[],p=a.store.index("name");for(let f of e)i.has(f)||u.push(p.get(f).then(m=>{m?.updating&&(m?.checked??0)>l||n.set(f,m??gN(f))}));if(await Promise.all(u),await a.done,n.size===0){o.debug`checked. No project needs upgrade.`;return}o.debug`checked. ${n.size} projects maybe need upgrade.`}let s=hu(new Date);for await(let i of oE(n.values())){if(kt(i)){let{project:h,name:g}=wn(i);switch(g){default:continue;case"NotFoundError":o.warn(`"${h}" is not found.`);break;case"NotMemberError":o.warn(`You are not a member of "${h}".`);break;case"NotLoggedInError":o.warn(`You are not a member of "${h}" or You are not logged in yet.`);break}n.set(h,{id:h,name:h,checked:s,updating:!1,isValid:!1,reason:g});continue}let{checked:a,...c}=Io(i);if(c.updated<a){o.debug`no updates in "${c.name}"`,n.set(c.name,{...c,isValid:!0,checked:s,updating:!1});continue}o.debug`start downloading and storing links of "${c.name}"`;let l=new Set(await r.getAllKeysFromIndex("titles","project",c.name)),u=0,p=0;for await(let h of Sf(c.name)){if(kt(h)){let{name:E,message:k}=wn(h);o.error`Failed to get links of "${c.name}" with ${E}: ${k}`;break}let g=Io(h),y={},x=r.transaction("titles","readwrite");await Promise.all(g.map(async E=>{let k={...E,project:c.name},b=await x.store.get(E.id);if(!b)return y.added?.set?.(E.id,k)??(y.added=new Map([[E.id,k]])),x.store.add(k);if(l.delete(E.id),!!yN(k,b))return y.updated?.set?.(E.id,[b,k])??(y.updated=new Map([[E.id,[b,k]]])),x.store.put(k)})),await x.done,u+=y.added?.size??0,p+=y.updated?.size??0,o.debug`Updating "/${c.name}": +${u} pages, ~${p} pages`,du(c.name,y)}let f=r.transaction("titles","readwrite"),m=new Map((await Promise.all([...l].map(async h=>{let g=await f.store.get(h);if(!g)return[];let y=[[h,g]];return await f.store.delete(h),y}))).flat());await f.done,o.debug`Finish downloading and storing links of "${c.name}"`,o.debug`Update "/${c.name}": +${u} pages, ~${p} pages, -${m.size} pages`,n.set(c.name,{...c,isValid:!0,checked:s,updating:!1}),du(c.name,{deleted:m})}}finally{let s=r.transaction("projects","readwrite");await Promise.all([...n].map(([,i])=>(i.updating=!1,s.store.put({...i})))),await s.done}},Pn=async e=>{let t=[...new Set(e)];if(t.length===0)return[];let r=Date.now(),n=(await mu()).transaction("titles","readonly"),s=n.store.index("project"),i=(await Promise.all(t.map(c=>s.getAll(c)))).flat();return await n.done,ks(["@takker/cosense-storage","load"]).debug`Read ${i.length} links from ${t.length} projects in ${Date.now()-r}ms`,i},gN=e=>({name:e,displayName:e,id:"",isValid:!0,publicVisible:!0,isMember:!0,loginStrategies:[],theme:"default",gyazoTeamsName:null,translation:!0,infobox:!0,checked:0,updated:0,created:0,updating:!0}),yN=(e,t)=>e.updated>t.updated||e.links.sort().join()!==t.links.sort().join();uE("userscript-links").catch(e=>console.error(e));var xN=Ir("scrapbox-select-suggestion:useSource.ts"),yE=e=>_n(...C(()=>{let t=[];return[n=>{let s=Pn(e).then(i=>{let a=bN(i);return t=[...a.values()],n(),a});return sc(e,600),nc(e,({diff:i})=>s=s.then(a=>(xN.debug(`Update: +${i.added?.size??0} pages, ~${i.updated?.size??0} pages, -${i.deleted?.size??0} pages`),a=EN(a,i),t=[...a.values()],n(),a)))},()=>t]},[e])),bN=e=>{let t=new Map;for(let r of e)gu(t,r);return t},EN=(e,t)=>{let r=new Map(e);if(t.added)for(let[,o]of t.added)gu(r,o);if(t.updated)for(let[,[o,n]]of t.updated)gE(r,o),gu(r,n);if(t.deleted)for(let[,o]of t.deleted)gE(r,o);return r},gu=(e,t)=>{let r=ys(t.title),o=e.get(r);if((o?.updated??0)>t.updated)return;let n=o?.metadata??new Map;n.set(t.project,{image:t.image}),e.set(r,{title:t.title,titleLc:r,updated:t.updated,linked:o?.linked??0,metadata:n});for(let s of t.links){let i=ys(s),a=e.get(i),c=a?.metadata??new Map;c.set(t.project,c.get(t.project)??{image:t.image}),e.set(i,{title:a?.title??s,titleLc:i,updated:a?.updated??0,linked:(a?.linked??0)+1,metadata:c})}},gE=(e,t)=>{let r=ys(t.title),o=e.get(r);if(!o||(o.updated??0)>t.updated)return;let n=o.metadata;n.delete(t.project),n.size<=0?e.delete(r):e.set(r,{title:o.title,titleLc:r,updated:t.updated,linked:o.linked,metadata:n});for(let s of t.links){let i=ys(s),a=e.get(i);if(!a)continue;let c=a.metadata;c.delete(t.project),c.size<=0?e.delete(i):e.set(i,{title:a.title,titleLc:i,updated:t.updated,linked:a.linked-1,metadata:c})}};var xE=e=>{let t=C(()=>xs(e.style,import.meta.url),[e.style]);return d(Y,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var bE=()=>d("style",{children:`.container {
position: absolute;
margin-top: 14px;
max-height: 80vh;
z-index: 301;
background-color: var(--select-suggest-bg, #111);
font-family: var(--select-suggest-font-family, "Open Sans", Helvetica, Arial, "Hiragino Sans", sans-serif);
font-size: 14px;
color: var(--select-suggest-text-color, #eee);
border-radius: 4px;
}
.candidates {
max-width: 80vw;
}
.candidates:not([data-os*="android"]):not([data-os*="ios"]) {
font-size:11px;
}
.projects {
margin-right: 4px;
display: grid;
grid-template-rows: repeat(4, min-content);
grid-auto-flow: column;
direction: rtl;
}
.projects:is([data-os*="android"], [data-os*="ios"]) > * {
padding: 6px;
}
.candidates > :not(:first-child) {
border-top: 1px solid var(--select-suggest-border-color, #eee);
}
.candidates > *{
line-height: 1.2em;
padding: 0.5em 10px;
}
.candidate {
display: flex;
}
a {
display: block;
text-decoration: none;
color: inherit;
}
a:not(.mark) {
width: 100%;
}
.selected a {
background-color: var(--select-suggest-selected-bg, #222);
text-decoration: underline
}
img {
height: 1.3em;
width: 1.3em;
position: relative;
object-fit: cover;
object-position: 0% 0%;
}
.disabled {
filter: grayscale(1.0) opacity(0.5);
}
.counter {
color: var(--select-suggest-information-text-color, #aaa);
font-size: 80%;
font-style: italic;
}
.progress[style] {
padding: unset;
border: unset;
height: 0.5px;
transition: background 0.1s;
}`});function*EE(e){if(!("nodes"in e))return;let t=0;function*r(o){for(let n of Array.isArray(o)?o:[o]){if(typeof n=="string"){t+=[...n].length;continue}switch(n.type){case"link":yield{whole:n.unit.whole,start:t},t+=[...n.unit.whole].length;break;case"indent":case"quote":t+=[...n.unit.tag].length,yield*r(n.children);break;case"deco":t+=[...n.unit.deco].length+2,yield*r(n.children),t++;break;case"strong":t+=2,yield*r(n.children),t+=2;break;default:t+=[...n.unit.whole].length;break}}}yield*r(e.nodes)}var wE=(e,t)=>{if(t.type==="unlock"){if(!e.lock)return e;let{lock:i,...a}=e;return{...a}}if(e.lock)return e;switch(t.type){case"lock":{let{lock:i,...a}=e;return{lock:!0,...a}}case"enable":return e.type==="disabled"&&e.isManuallyDisabled?{type:"ready"}:e;case"disable":return e.type==="disabled"&&e.isManuallyDisabled?e:{type:"disabled",isManuallyDisabled:!0}}if(e.type==="disabled")return e.isManuallyDisabled||!t.lines?e:{type:"ready"};if(t.type==="cancel")return e.type==="completion"?{type:"cancelled",context:e.context}:e;if(!t.lines)return{type:"disabled"};let r=Math.min(t.range.start.char,t.range.end.char),o=Math.max(t.range.start.char,t.range.end.char),n=t.lines?t.range.start.line!==t.range.end.line?`
`:[...t.lines[t.range.start.line].text].slice(r,o).join(""):"";if(RN(t.lines[t.position.line],n)&&e.type!=="cancelled")return{type:"completion",context:"selection",query:n,start:r,position:t.position};if(n!=="")return e.type==="completion"?{type:"ready"}:e;let s=wN(t.lines[t.position.line],t.position.char);return s?e.type==="cancelled"&&e.context==="input"?e:e.type==="completion"||t.type==="lines:changed"?{type:"completion",context:"input",query:s.whole,start:s.start,position:t.position}:e.type==="ready"?e:{type:"ready"}:e.type==="ready"?e:{type:"ready"}},wN=(e,t)=>{for(let{whole:r,start:o}of EE(e))if(!(t<=o||o+[...r].length<=t))return{whole:r,start:o}},RN=(e,t)=>!(t.trim()===""||t.includes(`
`)||"codeBlock"in e||"title"in e||"tableBlock"in e&&e.tableBlock.start);var RE=()=>{let e=qe(scrapbox.Page.lines),t=qe(!1);return oe(()=>{let r=()=>{t.current=!0};return scrapbox.addListener("lines:changed",r),scrapbox.addListener("layout:changed",r),()=>{scrapbox.removeListener("lines:changed",r),scrapbox.removeListener("layout:changed",r)}},[]),F(()=>(t.current&&(e.current=scrapbox.Page.lines,t.current=!1),e.current??void 0),[])};var kN=Ir("scrapbox-select-suggestion:useLifecycle.ts"),kE=()=>{let[e,t]=Dr(wE,{type:"ready"}),r=RE(),o=C(()=>{let i;return a=>{i!==void 0&&clearTimeout(i),i=setTimeout(()=>{let{cursor:c,selection:l}=Lt();t({type:a,lines:r(),range:l.getRange({normalizeOrder:!0}),position:c.getPosition()})},a==="cursor:changed"?100:void 0)}},[]);oe(()=>{let i=()=>{o("lines:changed")};scrapbox.addListener("lines:changed",i),scrapbox.addListener("layout:changed",i);let a=()=>{o("selection:changed")},c=Ui();return c.addChangeListener(a),()=>{scrapbox.removeListener("lines:changed",i),scrapbox.removeListener("layout:changed",i),c.removeChangeListener(a)}},[]),oe(()=>{if(e.context!=="input")return;let i=()=>{o("cursor:changed")},a=$r();return a.addChangeListener(i),()=>a.removeChangeListener(i)},[e.context]);let[n,s]=J(e);return n!==e&&(s(e),kN.debug("Detect changes",e)),{state:e,setEnable:F(i=>t({type:i?"enable":"disable"}),[]),cancel:F(()=>t({type:"cancel"}),[]),freezeUntil:F(i=>{t({type:"lock"});let a=i();if(a instanceof Promise)return a.then(()=>{t({type:"unlock"})});t({type:"unlock"})},[]),confirmAfter:F(async i=>{let a=r();if(!a)return;t({type:"lock"});let{cursor:c,selection:l}=Lt(),u=c.getPosition().line,p=a[u].text,[f,m]=i(p,c.getPosition());l.setRange({start:{line:u,char:0},end:{line:u,char:[...p].length}}),await Ye(f),c.setPosition(m),c.focus(),t({type:"unlock"}),t({type:"cancel"})},[])}};var vE=(e,t)=>{let r=e.dist-t.dist;if(r!==0)return r;let o=e.matches.map(([i])=>i).sort(),n=t.matches.map(([i])=>i).sort();for(let i=0;i<o.length;i++){let a=o[i]-(n[i]??n.length);if(a!==0)return a}let s=e.title.length-t.title.length;return s!==0?s:t.updated-e.updated};var _E=e=>{let t=new Map,r=[...e].reverse();{let i=1;for(let a of r){t.set(a,(t.get(a)??0)|i);let c=a.toLowerCase();t.set(c,(t.get(c)??0)|i);let l=a.toUpperCase();t.set(l,(t.get(l)??0)|i),i<<=1}}let o=r.length,n=~(-1<<o),s=1<<o-1;return i=>{let a=0,c=n,l=[...i].reverse(),u=[],p=l.length;u[p]=o;for(let f of l){let m=t.get(f)??0,h=m|a,g=(m&c)+c^c|m,y=a|~(g|c),x=c&g;u[p-1]=u[p]+(y&s?1:x&s?-1:0),c=x<<1|~(h|y<<1),a=y<<1&h,p--}return u}};var vN=[0,0,0,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6],TE=e=>{let t=Nb(e.trim()).split(/\s+/).sort((r,o)=>o.length-r.length);if(!(t.length===0||t.every(r=>r==="")))return r=>{let o=[...r];for(let n of t)o=_N(n,o);return o}},_N=(e,t)=>{let r=[...e].length,o=vN[r],n=_E(e);return t.flatMap(({title:s,dist:i,matches:a,...c})=>{a??=[],i??=0;let l=n(s).flatMap((p,f)=>p<=o&&a.every(([m,h])=>f+r<=m||h<f)?[[f,p]]:[]);if(l.length===0)return[];let u=l.reduce((p,[f,m])=>(p.dist<=m||(p.dist=m,p.start=f),p),{dist:r,start:0});return a.push([u.start,u.start+r-1]),[{title:s,dist:u.dist+i,matches:a,...c}]})};var TN=Ir("scrapbox-select-suggestion:cancelableSearch.ts");async function*PE(e,t,r){let o=TE(e);if(!o)return;let n=r?.chunk??1e3,s=Math.floor(t.length/n)+1,i=0,a=new Date;try{for(;i<s;i++)await new Promise(c=>requestAnimationFrame(c)),yield[o(t.slice(i*n,(i+1)*n)),(i+1)/s]}finally{let l=new Date().getTime()-a.getTime();TN.debug(`search ${(i/s*100).toPrecision(3)}% of the source for "${e}" in ${l}ms`)}}var SE=(e,t)=>{let r=t?.interval??0,o=t?.maxQueued??1/0,n,s,i=[],a=(...c)=>{if(!n)return n=(async()=>{do{await new Promise(m=>{let h=setTimeout(m,r);s=()=>{for(clearTimeout(h);i.length>0;)i.shift()("discarded");m()}});let f=i.pop();if(!f)break;f("delayed")}while(i.length>0);n=void 0})(),new Promise(f=>f(e.call(a,...c,"immediate")));for(;i.length>Math.max(o,0);)i.shift()("discarded");let{promise:l,resolve:u,reject:p}=Promise.withResolvers();return i.push(f=>{try{u(e.call(a,...c,f))}catch(m){p(m)}}),l};return a.clear=()=>{s?.()},Object.defineProperty(a,"ready",{get:()=>n}),a};var jo=e=>"query"in e,OE=e=>(t,r)=>{if("query"in r){let i=jo(t)?t.query:"";if(r.query===i)return t;let a=jo(t)?t.job:void 0;if(!r.query)return a?.abort?.(),{source:t.source};let{run:c,abort:l}=e(r.query,t.source,!1),u=a?.abort?.()?.then?.(c)??c();return{query:r.query,source:t.source,job:{done:u,abort:()=>(l(),u)},progress:0,candidates:!i||!jo(t)?[]:t.candidates}}if("source"in r){if(!jo(t))return r.source===t.source?t:r;let{source:i,job:a,...c}=t;if(r.source===i)return t;let{run:l,abort:u}=e(c.query,r.source,!0),p=a.done.then(l);return{source:r.source,job:{done:p,abort:()=>a.abort().then(()=>(u(),p))},...c}}if(!jo(t))return t;if(!r.candidates){let{progress:i,...a}=t;return i===r.progress?t:{progress:r.progress,...a}}let{candidates:o,progress:n,...s}=t;return o===r.candidates&&n===r.progress?t:{candidates:r.candidates??o,progress:r.progress,...s}};var PN=Ir("scrapbox-select-suggestion:useSearch.ts"),LE=e=>{let t=F((n,s,i)=>{let a=!1,c=PE(n,s,{chunk:5e3});return{run:async()=>{if(i){let p=[];for await(let[f]of c){if(a)return;p.push(...f)}o({progress:1,candidates:p});return}let l=SE((p,f)=>{f!=="discarded"&&(a||o(p))},{interval:500,maxQueued:0}),u=[];for await(let[p,f]of c){if(a)return;u=[...u,...p],o({progress:f}),p.length!==0&&l({progress:f,candidates:u})}l({progress:1,candidates:u})},abort:()=>a=!0}},[]),[r,o]=Dr(C(()=>OE(t),[t]),{source:e});return[C(()=>{if(!jo(r))return;let[n,s]=SN(r.candidates);return PN.debug("Detect changes",{progress:r.progress,items:s}),{progress:r.progress,projectScore:n,items:s}},[r]),{search:F(n=>o({query:n}),[]),update:F(n=>o({source:n}),[])}]},SN=e=>{let t=new Map,r=[];for(let o of e.sort(vE)){let n=[...o.metadata.keys()];for(let s of n)t.set(s,(t.get(s)??0)+.5**o.dist);r.push({title:o.title,dist:o.dist,projects:n})}return[t,r]};var NE=(e,t)=>{let r=qe({...t});oe(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),oe(()=>{e(r.current)},[e])};var ON={selectNext:()=>!1,selectPrev:()=>!1,selectFirst:()=>!1,selectLast:()=>!1,confirm:()=>!1,cancel:()=>!1},CE=e=>{let t=yE(e.projects),[r,{update:o,search:n}]=LE(t),{state:s,setEnable:i,...a}=kE();o(t),n(s.type==="completion"?s.context==="input"?s.query.slice(1,-1):s.query:"");let[c,l]=J(),{callback:u,style:p,...f}=e;return NE(u,{enable:F(()=>i(!0),[]),disable:F(()=>i(!1),[]),...s.type!=="completion"||!c?ON:c}),d(Y,{children:[d(bE,{}),d(xE,{style:p}),s.type==="completion"&&r&&d(jb,{callback:l,...r,...s,...a,...f})]})};var AE=e=>{let t=document.createElement("div");t.dataset.userscriptName="scrapbox-select-suggestion";let r=t.attachShadow({mode:"open"});document.body.append(t);let{limit:o=5,debug:n=!1,mark:s={},style:i="",enableSelfProjectOnStart:a=!0}=e??{},c=new Set([...a?[scrapbox.Project.name]:[],...e?.projects??[scrapbox.Project.name]]);return gi(n),new Promise(l=>ut(d(CE,{limit:o,projects:c,mark:s,style:i,callback:l,enableSelfProjectOnStart:a}),r))};var It=e=>e.flatMap(t=>{let r=t.slice(1),o=Math.min(...r.map(n=>n.text.length-n.text.trimStart().length));return r.map(n=>n.text.slice(o))}).join(`
`).trim();function*ME(e,t){for(let[r,o]of t.entries()){let n=e.get(r);if(n&&It(n.blocks)===It(o)){yield{changed:!1,filename:r};continue}yield{changed:!0,filename:r}}for(let r of e.keys())t.has(r)||(yield{changed:!0,filename:r})}var ic={};$s(ic,{getTitle:()=>yf,parse:()=>Be});var IE=e=>{let t=new Map;if(e.length===0)return t;let r=Be(e.map(n=>n.text).join(`
`),{hasTitle:!0}),o=0;for(let n of r)switch(n.type){case"title":case"line":o++;break;case"table":o+=n.cells.length+1;break;case"codeBlock":{let s=t.get(n.fileName)??[],i=n.content.split(`
`).length+1;s.push(e.slice(o,o+i)),t.set(n.fileName,s),o+=i;break}}return t};var FE=e=>{let t,r,o=async()=>{for(;t;){let[n,s]=t;t=void 0;try{let i=await e(...n);s({type:"resolve",value:i})}catch(i){s({type:"reject",value:i})}}r=void 0};return(...n)=>{let{resolve:s,promise:i}=Promise.withResolvers();return t?.[1]?.({type:"cancel"}),t=[n,s],r??=o(),i}};var ac=class{constructor(t,r){this._filename=t;this._preview=FE(async(o,n,s)=>(this._dispose=await r(s?{filename:this.filename,before:o,after:n,render:(...i)=>{s.textContent="",s.append(...i)}}:{filename:this.filename,before:o}),!1))}get filename(){return this._filename}get blocks(){return this._blocks??[]}async update(t){if(await this._dispose?.(),!t||It(t)===""){let a=await this._preview(this.blocks);if(a.type==="cancel")return a;if(a.type==="reject")throw a.value;return this._area?.remove?.(),this._style?.remove?.(),this._area=void 0,this._style=void 0,this._blocks=void 0,{type:"resolve",value:!0}}let r=this.blocks;this._blocks=t,this.makeStyle();let o=this.makeArea(),n=t.at(0)?.at?.(-1)?.id,s=Er(n);if(!s)throw new Error(`"div.lines#L${n}" could not be found.`);s.insertAdjacentElement("afterend",o);let i=()=>{let a=s.getElementsByClassName("indent")[0];a instanceof HTMLElement&&(o.style.marginLeft=a.style.marginLeft)};return this._observer?.disconnect?.(),i(),this._observer=new MutationObserver(i),this._observer.observe(s,{childList:!0,subtree:!0}),this._preview(r,t,o)}makeArea(){if(this._area)return this._area;let t=document.createElement("div");return t.classList.add("scrap-run"),t.dataset.filename=this.filename,this._area=t,t}makeStyle(){let t=this.blocks.flatMap(o=>o.slice(1).map(({id:n})=>`#L${n}`)),r=this.blocks.flatMap(o=>o.map(({id:n})=>`#L${n}`));this._style||(this._style=document.createElement("style"),document.head.append(this._style)),this._style.textContent=`.lines:not(:has(:is(${[...r].join(",")}).cursor-line)) :is(${[...t].join(",")}){display:none}`}_blocks;_dispose;_preview;_area;_observer;_style};var UE=({previewers:e})=>{let t=new Map,r=()=>{let s=IE(mt());for(let{changed:i,filename:a}of ME(t,s)){if(!i)continue;let c=s.get(a),l=t.get(a);if(!l){if(!c)continue;let u=e.find(({when:p})=>p.test(a))?.preview;if(!u)continue;l=new ac(a,u),t.set(a,l)}l.update(c).then(u=>{switch(u.type){case"resolve":u.value&&t.delete(a);return;case"reject":throw u.value;case"cancel":return}})}},o=()=>{if(scrapbox.Layout!=="page"){scrapbox.off("lines:changed",r);return}r(),scrapbox.on("lines:changed",r)};o(),scrapbox.on("page:changed",o);let n=document.createElement("style");return n.textContent=".scrap-run{display:block;width:95%}",document.head.append(n),()=>{scrapbox.off("page:changed",o),n.remove()}};var vs=e=>{let t=new FileReader,r=new Promise(o=>t.onload=()=>o(t.result));return t.readAsDataURL(e),r};var DE=async e=>{if(!("after"in e))return;let t=It(e.after),o=new DOMParser().parseFromString(t,"image/svg+xml").querySelector("parsererror");if(o){let i=document.createElement("pre"),a=document.createElement("code");a.innerText=o.innerHTML,i.append(a),e.render(i);return}let n=await vs(new Blob([t],{type:"image/svg+xml"})),s=document.createElement("img");s.src=n,e.render(s)};var yu={};$s(yu,{default:()=>BE});var sC=Object.create,jE=Object.defineProperty,iC=Object.getOwnPropertyDescriptor,aC=Object.getOwnPropertyNames,cC=Object.getPrototypeOf,lC=Object.prototype.hasOwnProperty,pC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),uC=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of aC(t))!lC.call(e,n)&&n!==r&&jE(e,n,{get:()=>t[n],enumerable:!(o=iC(t,n))||o.enumerable});return e},mC=(e,t,r)=>(r=e!=null?sC(cC(e)):{},uC(t||!e||!e.__esModule?jE(r,"default",{value:e,enumerable:!0}):r,e)),fC=pC((e,t)=>{t.exports=o;var r=Object.prototype.toString;function o(n){if(!n)return!1;var s=r.call(n);return s==="[object Function]"||typeof n=="function"&&s!=="[object RegExp]"||typeof window<"u"&&(n===window.setTimeout||n===window.alert||n===window.confirm||n===window.prompt)}}),$E=mC(fC()),BE=$E.default??$E;var xu={};$s(xu,{default:()=>GE});var dC=Object.create,WE=Object.defineProperty,hC=Object.getOwnPropertyDescriptor,gC=Object.getOwnPropertyNames,yC=Object.getPrototypeOf,xC=Object.prototype.hasOwnProperty,bC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),EC=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of gC(t))!xC.call(e,n)&&n!==r&&WE(e,n,{get:()=>t[n],enumerable:!(o=hC(t,n))||o.enumerable});return e},wC=(e,t,r)=>(r=e!=null?dC(yC(e)):{},EC(t||!e||!e.__esModule?WE(r,"default",{value:e,enumerable:!0}):r,e)),RC=bC((e,t)=>{var r=function(n){return n.replace(/^\s+|\s+$/g,"")},o=function(n){return Object.prototype.toString.call(n)==="[object Array]"};t.exports=function(n){if(!n)return{};for(var s={},i=r(n).split(`
`),a=0;a<i.length;a++){var c=i[a],l=c.indexOf(":"),u=r(c.slice(0,l)).toLowerCase(),p=r(c.slice(l+1));typeof s[u]>"u"?s[u]=p:o(s[u])?s[u].push(p):s[u]=[s[u],p]}return s}}),HE=wC(RC()),GE=HE.default??HE;var kC=(()=>{var e=globalThis;return{default:e}})(),vC=(()=>{var e=(...t)=>Object.assign({},...t);return{default:e}})(),Sn=e=>{let t=o=>typeof o.default<"u"?o.default:o,r=o=>Object.assign({__esModule:!0},o);switch(e){case"npm:global/window":return t(kC);case"is-function":return t(yu);case"parse-headers":return t(xu);case"npm:xtend":return t(vC);default:return console.error('module "'+e+'" not found'),null}},_C=Object.create,zE=Object.defineProperty,TC=Object.getOwnPropertyDescriptor,PC=Object.getOwnPropertyNames,SC=Object.getPrototypeOf,OC=Object.prototype.hasOwnProperty,cc=(e=>typeof Sn<"u"?Sn:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof Sn<"u"?Sn:t)[r]}):e)(function(e){if(typeof Sn<"u")return Sn.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),LC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),NC=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of PC(t))!OC.call(e,n)&&n!==r&&zE(e,n,{get:()=>t[n],enumerable:!(o=TC(t,n))||o.enumerable});return e},CC=(e,t,r)=>(r=e!=null?_C(SC(e)):{},NC(t||!e||!e.__esModule?zE(r,"default",{value:e,enumerable:!0}):r,e)),AC=LC((e,t)=>{"use strict";var r=cc("npm:global/window"),o=cc("is-function"),n=cc("parse-headers"),s=cc("npm:xtend");t.exports=l,t.exports.default=l,l.XMLHttpRequest=r.XMLHttpRequest||f,l.XDomainRequest="withCredentials"in new l.XMLHttpRequest?l.XMLHttpRequest:r.XDomainRequest,i(["get","put","post","patch","head","delete"],function(m){l[m==="delete"?"del":m]=function(h,g,y){return g=c(h,g,y),g.method=m.toUpperCase(),u(g)}});function i(m,h){for(var g=0;g<m.length;g++)h(m[g])}function a(m){for(var h in m)if(m.hasOwnProperty(h))return!1;return!0}function c(m,h,g){var y=m;return o(h)?(g=h,typeof m=="string"&&(y={uri:m})):y=s(h,{uri:m}),y.callback=g,y}function l(m,h,g){return h=c(m,h,g),u(h)}function u(m){if(typeof m.callback>"u")throw new Error("callback argument missing");var h=!1,g=function(M,D,I){h||(h=!0,m.callback(M,D,I))};function y(){b.readyState===4&&setTimeout(k,0)}function x(){var M=void 0;if(b.response?M=b.response:M=b.responseText||p(b),T)try{M=JSON.parse(M)}catch{}return M}function E(M){return clearTimeout(S),M instanceof Error||(M=new Error(""+(M||"Unknown XMLHttpRequest Error"))),M.statusCode=0,g(M,A)}function k(){if(!R){var M;clearTimeout(S),m.useXDR&&b.status===void 0?M=200:M=b.status===1223?204:b.status;var D=A,I=null;return M!==0?(D={body:x(),statusCode:M,method:L,headers:{},url:O,rawRequest:b},b.getAllResponseHeaders&&(D.headers=n(b.getAllResponseHeaders()))):I=new Error("Internal XMLHttpRequest Error"),g(I,D,D.body)}}var b=m.xhr||null;b||(m.cors||m.useXDR?b=new l.XDomainRequest:b=new l.XMLHttpRequest);var v,R,O=b.url=m.uri||m.url,L=b.method=m.method||"GET",N=m.body||m.data,P=b.headers=m.headers||{},_=!!m.sync,T=!1,S,A={body:void 0,headers:{},statusCode:0,method:L,url:O,rawRequest:b};if("json"in m&&m.json!==!1&&(T=!0,P.accept||P.Accept||(P.Accept="application/json"),L!=="GET"&&L!=="HEAD"&&(P["content-type"]||P["Content-Type"]||(P["Content-Type"]="application/json"),N=JSON.stringify(m.json===!0?N:m.json))),b.onreadystatechange=y,b.onload=k,b.onerror=E,b.onprogress=function(){},b.onabort=function(){R=!0},b.ontimeout=E,b.open(L,O,!_,m.username,m.password),_||(b.withCredentials=!!m.withCredentials),!_&&m.timeout>0&&(S=setTimeout(function(){if(!R){R=!0,b.abort("timeout");var M=new Error("XMLHttpRequest timeout");M.code="ETIMEDOUT",E(M)}},m.timeout)),b.setRequestHeader)for(v in P)P.hasOwnProperty(v)&&b.setRequestHeader(v,P[v]);else if(m.headers&&!a(m.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in m&&(b.responseType=m.responseType),"beforeSend"in m&&typeof m.beforeSend=="function"&&m.beforeSend(b),b.send(N||null),b}function p(m){try{if(m.responseType==="document")return m.responseXML;var h=m.responseXML&&m.responseXML.documentElement.nodeName==="parsererror";if(m.responseType===""&&!h)return m.responseXML}catch{}return null}function f(){}}),VE=CC(AC()),lc=VE.default??VE;var pc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},SNe=function(){function e(r){this.value=r}function t(r){var o,n;function s(c,l){return new Promise(function(u,p){var f={key:c,arg:l,resolve:u,reject:p,next:null};n?n=n.next=f:(o=n=f,i(c,l))})}function i(c,l){try{var u=r[c](l),p=u.value;p instanceof e?Promise.resolve(p.value).then(function(f){i("next",f)},function(f){i("throw",f)}):a(u.done?"return":"normal",u.value)}catch(f){a("throw",f)}}function a(c,l){switch(c){case"return":o.resolve({value:l,done:!0});break;case"throw":o.reject(l);break;default:o.resolve({value:l,done:!1});break}o=o.next,o?i(o.key,o.arg):n=null}this._invoke=s,typeof r.return!="function"&&(this.return=void 0)}return typeof Symbol=="function"&&Symbol.asyncIterator&&(t.prototype[Symbol.asyncIterator]=function(){return this}),t.prototype.next=function(r){return this._invoke("next",r)},t.prototype.throw=function(r){return this._invoke("throw",r)},t.prototype.return=function(r){return this._invoke("return",r)},{wrap:function(r){return function(){return new t(r.apply(this,arguments))}},await:function(r){return new e(r)}}}(),XE=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},YE=function(){function e(t,r){for(var o=0;o<r.length;o++){var n=r[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),bu=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}else return Array.from(e)},_s="";function MC(e){return`
<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>
<td align="center">
<div style="display: table-cell; vertical-align: middle;">
<div style="">`+e+`</div>
</div>
</td></tr></table>
`}var IC=`
This page requires a browser that supports WebGL.<br/>
<a href="http://get.webgl.org">Click here to upgrade your browser.</a>
`,FC=`
It does not appear your computer can support WebGL.<br/>
<a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>
`,UC=1,DC=2;function $C(e,t,r){function o(i){var a=e.parentNode;a&&(a.innerHTML=MC(i))}function n(i,a){typeof r=="function"?r(i):o(a)}if(!window.WebGLRenderingContext)return n(UC,IC),null;var s=jC(e,t);return s?s.getExtension("OES_standard_derivatives"):n(DC,FC),s}function jC(e,t){for(var r=["webgl","experimental-webgl"],o=null,n=0;n<r.length;++n)try{o=e.getContext(r[n],t)}catch{if(o)break}return o}function On(e,t,r,o){var n=e.gl,s=n.createShader(r);n.shaderSource(s,t),n.compileShader(s);var i=n.getShaderParameter(s,n.COMPILE_STATUS);return i?s:(_s=n.getShaderInfoLog(s),console.error("*** Error compiling shader "+s+":"+_s),e.trigger("error",{shader:s,source:t,type:r,error:_s,offset:o||0}),n.deleteShader(s),null)}function qE(e,t,r,o){for(var n=e.gl,s=n.createProgram(),i=0;i<t.length;++i)n.attachShader(s,t[i]);if(r)for(var a=0;a<r.length;++a)n.bindAttribLocation(s,o?o[a]:a,r[a]);n.linkProgram(s);var c=n.getProgramParameter(s,n.LINK_STATUS);return c?s:(_s=n.getProgramInfoLog(s),console.log("Error in program linking:"+_s),n.deleteProgram(s),null)}function Eu(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r=[];for(var o in e){var n=e[o],s=void 0;if(t&&(o=t+"."+o),typeof n=="number")r.push({type:"float",method:"1f",name:o,value:n});else if(Array.isArray(n)){if(typeof n[0]=="number")n.length===1?r.push({type:"float",method:"1f",name:o,value:n}):n.length>=2&&n.length<=4?r.push({type:"vec"+n.length,method:n.length+"fv",name:o,value:n}):n.length>4&&r.push({type:"float[]",method:"1fv",name:o+"[0]",value:n});else if(typeof n[0]=="string")r.push({type:"sampler2D",method:"1i",name:o,value:n});else if(Array.isArray(n[0])&&typeof n[0][0]=="number"){if(n[0].length>=2&&n[0].length<=4)for(s=0;s<n.length;s++)r.push({type:"vec"+n[0].length,method:n[s].length+"fv",name:o+"["+s+"]",value:n[s]})}else if(pc(n[0])==="object")for(s=0;s<n.length;s++)r.push.apply(r,bu(Eu(n[s],o+"["+s+"]")))}else typeof n=="boolean"?r.push({type:"bool",method:"1i",name:o,value:n}):typeof n=="string"?r.push({type:"sampler2D",method:"1i",name:o,value:n}):(typeof n>"u"?"undefined":pc(n))==="object"&&r.push.apply(r,bu(Eu(n,o)))}return r}function BC(e){var t=e.getBoundingClientRect();return t.top+t.height>0&&t.top<(window.innerHeight||document.documentElement.clientHeight)}function KE(e){return(e&e-1)===0}function HC(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function WC(e,t){return e&&t?e.toString()!==t.toString():!1}function GC(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(),t.status==200?t.responseText:""}function JE(e){var t=new Set;return Object.assign(e,{on:function(r,o){var n={};n[r]=o,t.add(n)},off:function(r,o){if(o){var n={};n[r]=o,t.delete(n)}else{var s=!0,i=!1,a=void 0;try{for(var c=t[Symbol.iterator](),l;!(s=(l=c.next()).done);s=!0){var u=l.value,p=!0,f=!1,m=void 0;try{for(var h=Object.keys(u)[Symbol.iterator](),g;!(p=(g=h.next()).done);p=!0){var y=g.value;if(y===r){t.delete(u);return}}}catch(x){f=!0,m=x}finally{try{!p&&h.return&&h.return()}finally{if(f)throw m}}}}catch(x){i=!0,a=x}finally{try{!s&&c.return&&c.return()}finally{if(i)throw a}}}},listSubscriptions:function(){var r=!0,o=!1,n=void 0;try{for(var s=t[Symbol.iterator](),i;!(r=(i=s.next()).done);r=!0){var a=i.value;console.log(a)}}catch(c){o=!0,n=c}finally{try{!r&&s.return&&s.return()}finally{if(o)throw n}}},subscribe:function(r){t.add(r)},unsubscribe:function(r){t.delete(r)},unsubscribeAll:function(){t.clear()},trigger:function(r){for(var o=arguments.length,n=Array(o>1?o-1:0),s=1;s<o;s++)n[s-1]=arguments[s];var i=!0,a=!1,c=void 0;try{for(var l=t[Symbol.iterator](),u;!(i=(u=l.next()).done);i=!0){var p=u.value;typeof p[r]=="function"&&p[r].apply(p,bu(n))}}catch(f){a=!0,c=f}finally{try{!i&&l.return&&l.return()}finally{if(a)throw c}}}})}var wu=function(){function e(t,r){var o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};XE(this,e),JE(this),this.gl=t,this.texture=t.createTexture(),this.texture&&(this.valid=!0),this.bind(),this.name=r,this.source=null,this.sourceType=null,this.loading=null,this.setData(1,1,new Uint8Array([0,0,0,255]),{filtering:"linear"}),this.setFiltering(o.filtering),this.load(o)}return YE(e,[{key:"destroy",value:function(){this.valid&&(this.gl.deleteTexture(this.texture),this.texture=null,delete this.data,this.data=null,this.valid=!1)}},{key:"bind",value:function(t){this.valid&&(typeof t=="number"&&e.activeUnit!==t&&(this.gl.activeTexture(this.gl.TEXTURE0+t),e.activeUnit=t),e.activeTexture!==this.texture&&(this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),e.activeTexture=this.texture))}},{key:"load",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.loading=null,typeof t.url=="string"?(this.url===void 0||t.url!==this.url)&&this.setUrl(t.url,t):t.element?this.setElement(t.element,t):t.data&&t.width&&t.height&&this.setData(t.width,t.height,t.data,t)}},{key:"setUrl",value:function(t){var r=this,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.valid)return this.url=t,this.source=this.url,this.sourceType="url",this.loading=new Promise(function(n,s){var i=t.split(".").pop().toLowerCase(),a=i==="ogv"||i==="webm"||i==="mp4",c=void 0;a?(c=document.createElement("video"),c.autoplay=!0,c.muted=!0,setTimeout(function(){c.play()},1),o.filtering="nearest"):c=new Image,c.onload=function(){try{r.setElement(c,o)}catch(l){console.log("Texture '"+r.name+"': failed to load url: '"+r.source+"'",l,o)}n(r)},c.onerror=function(l){console.log("Texture '"+r.name+"': failed to load url: '"+r.source+"'",l,o),n(r)},HC()&&r.source.slice(0,5)==="data:"||(c.crossOrigin="anonymous"),c.src=r.source,a&&r.setElement(c,o)}),this.loading}},{key:"setData",value:function(t,r,o){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.width=t,this.height=r,this.source=o,this.sourceType="data",this.update(n),this.setFiltering(n),this.loading=Promise.resolve(this),this.loading}},{key:"setElement",value:function(t,r){var o=this,n=t;if(typeof t=="string"&&(t=document.querySelector(t)),t instanceof HTMLCanvasElement||t instanceof HTMLImageElement||t instanceof HTMLVideoElement)this.source=t,this.sourceType="element",t instanceof HTMLVideoElement?(this.width=this.source.videoWidth,this.height=this.source.videoHeight,t.addEventListener("canplaythrough",function(){o.intervalID=setInterval(function(){o.update(r)},15)},!0),t.addEventListener("ended",function(){t.currentTime=0,t.play()},!0)):this.update(r),this.setFiltering(r);else{var s="the 'element' parameter (`element: "+JSON.stringify(n)+"`) must be a CSS ";s+="selector string, or a <canvas>, <image> or <video> object",console.log("Texture '"+this.name+"': "+s,r)}return this.loading=Promise.resolve(this),this.loading}},{key:"update",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.valid&&(this.bind(),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,t.UNPACK_FLIP_Y_WEBGL!==!1),this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.UNPACK_PREMULTIPLY_ALPHA_WEBGL||!1),this.sourceType==="element"&&(this.source instanceof HTMLCanvasElement||this.source instanceof HTMLVideoElement||this.source instanceof HTMLImageElement&&this.source.complete)?(this.source instanceof HTMLVideoElement?(this.width=this.source.videoWidth,this.height=this.source.videoHeight):(this.width=this.source.width,this.height=this.source.height),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.source)):this.sourceType==="data"&&this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.width,this.height,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.source),this.trigger("loaded",this))}},{key:"setFiltering",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.valid){this.powerOf2=KE(this.width)&&KE(this.height),this.filtering=t.filtering||"linear";var r=this.gl;this.bind(),this.powerOf2?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,t.TEXTURE_WRAP_S||r.REPEAT),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,t.TEXTURE_WRAP_T||r.REPEAT),this.filtering==="mipmap"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR_MIPMAP_LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.generateMipmap(r.TEXTURE_2D)):this.filtering==="linear"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR)):this.filtering==="nearest"&&(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST))):(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),this.filtering==="mipmap"&&(this.filtering="linear"),this.filtering==="nearest"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST)):(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR)))}}}]),e}();wu.getMaxTextureSize=function(e){return e.getParameter(e.MAX_TEXTURE_SIZE)};wu.activeUnit=-1;var QE=function(){function e(t,r,o){var n=this;XE(this,e),JE(this),r=r||{},o=o||{},t.hasAttribute("data-fullscreen")&&(t.getAttribute("data-fullscreen")=="1"||t.getAttribute("data-fullscreen")=="true")?(this.width=window.innerWidth,this.height=window.innerHeight,t.width=window.innerWidth,t.height=window.innerHeight):(this.width=t.clientWidth,this.height=t.clientHeight),this.canvas=t,this.gl=void 0,this.deps={},this.program=void 0,this.textures={},this.buffers={},this.uniforms={},this.vbo={},this.isValid=!1,this.animationFrameRequest=void 0,this.BUFFER_COUNT=0,this.vertexString=r.vertexString||`
#ifdef GL_ES
precision mediump float;
#endif
attribute vec2 a_position;
attribute vec2 a_texcoord;
varying vec2 v_texcoord;
void main() {
gl_Position = vec4(a_position, 0.0, 1.0);
v_texcoord = a_texcoord;
}
`,this.fragmentString=r.fragmentString||`
#ifdef GL_ES
precision mediump float;
#endif
varying vec2 v_texcoord;
void main(){
gl_FragColor = vec4(0.0);
}
`;var s=$C(t,r,o.onError);if(!s)return;if(this.gl=s,this.timeLoad=this.timePrev=performance.now(),this.timeDelta=0,this.forceRender=!0,this.paused=!1,this.realToCSSPixels=window.devicePixelRatio||1,t.style.backgroundColor=r.backgroundColor||"rgba(1,1,1,0)",t.hasAttribute("data-fragment"))this.fragmentString=t.getAttribute("data-fragment");else if(t.hasAttribute("data-fragment-url")){var i=t.getAttribute("data-fragment-url");lc.get(i,function(g,y,x){n.load(x,n.vertexString)})}if(t.hasAttribute("data-vertex"))this.vertexString=t.getAttribute("data-vertex");else if(t.hasAttribute("data-vertex-url")){var a=t.getAttribute("data-vertex-url");lc.get(a,function(g,y,x){n.load(n.fragmentString,x)})}if(this.load(),!this.program)return;var c=s.getAttribLocation(this.program,"a_texcoord");this.vbo.texCoords=s.createBuffer(),this.gl.bindBuffer(s.ARRAY_BUFFER,this.vbo.texCoords),this.gl.bufferData(s.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),s.STATIC_DRAW),this.gl.enableVertexAttribArray(c),this.gl.vertexAttribPointer(c,2,s.FLOAT,!1,0,0);var l=s.getAttribLocation(this.program,"a_position");if(this.vbo.vertices=s.createBuffer(),this.gl.bindBuffer(s.ARRAY_BUFFER,this.vbo.vertices),this.gl.bufferData(s.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),s.STATIC_DRAW),this.gl.enableVertexAttribArray(l),this.gl.vertexAttribPointer(l,2,s.FLOAT,!1,0,0),t.hasAttribute("data-textures")){var u=t.getAttribute("data-textures").split(",");for(var p in u)this.setUniform("u_tex"+p,u[p])}var f={x:0,y:0};document.addEventListener("mousemove",function(g){f.x=g.clientX||g.pageX,f.y=g.clientY||g.pageY},!1);var m=this;function h(){m.nMouse>1&&m.setMouse(f),m.resize()&&(m.forceRender=!0),m.render(),m.animationFrameRequest=window.requestAnimationFrame(h)}return this.setMouse({x:0,y:0}),h(),this}return YE(e,[{key:"destroy",value:function(){cancelAnimationFrame(this.animationFrameRequest),this.animated=!1,this.isValid=!1;for(var t in this.textures)t.destroy&&t.destroy();this.textures={};for(var r in this.attribs)this.gl.deleteBuffer(this.attribs[r]);this.gl.useProgram(null),this.gl.deleteProgram(this.program);for(var o in this.buffers){var n=this.buffers[o];this.gl.deleteProgram(n.program)}this.program=null,this.gl=null}},{key:"load",value:function(t,r){var o=this;r&&(this.vertexString=r),t&&(this.fragmentString=t);var n=this.fragmentString.split(/\r?\n/);this.fragmentString=`#define PLATFORM_WEBGL
#line 0
`,n.forEach(function(g,y){var x=g.trim();if(x.startsWith('#include "lygia')){var E=x.substring(15).replace(/\'|\"|\;|\s/g,"");if(E.endsWith("glsl")){if(o.deps[E]===void 0){var k="https://lygia.xyz"+E;o.deps[E]=GC(k)}o.fragmentString+=o.deps[E]+`
#line `+(y+1)+`
`}}else o.fragmentString+=g+`
`}),this.animated=!1,this.nDelta=(this.fragmentString.match(/u_delta/g)||[]).length,this.nTime=(this.fragmentString.match(/u_time/g)||[]).length,this.nDate=(this.fragmentString.match(/u_date/g)||[]).length,this.nMouse=(this.fragmentString.match(/u_mouse/g)||[]).length,this.animated=this.nDate>1||this.nTime>1||this.nMouse>1;var s=this.fragmentString.search(/sampler2D/g);if(s)for(var i=this.fragmentString.split(`
`),a=0;a<i.length;a++){var c=i[a].match(/uniform\s*sampler2D\s*([\w]*);\s*\/\/\s*([\w|\:\/\/|\.|\-|\_]*)/i);if(c){var l=c[2].split(".").pop().toLowerCase();c[1]&&c[2]&&(l==="jpg"||l==="jpeg"||l==="png"||l==="ogv"||l==="webm"||l==="mp4")&&this.setUniform(c[1],c[2])}var u=i[a].match(/\s*void\s*main\s*/g);if(u)break}var p=On(this,this.vertexString,this.gl.VERTEX_SHADER),f=On(this,this.fragmentString,this.gl.FRAGMENT_SHADER);f?this.isValid=!0:(f=On(this,`void main(){
gl_FragColor = vec4(1.0);
}`,this.gl.FRAGMENT_SHADER),this.isValid=!1);var m=qE(this,[p,f]);this.gl.useProgram(m),this.gl.deleteShader(p),this.gl.deleteShader(f),this.program=m,this.change=!0,this.BUFFER_COUNT=0;var h=this.getBuffers(this.fragmentString);Object.keys(h).length&&this.loadPrograms(h),this.buffers=h,this.texureIndex=this.BUFFER_COUNT,this.trigger("load",{}),this.forceRender=!0,this.render()}},{key:"test",value:function(t,r,o){var n=this.vertexString,s=this.fragmentString,i=this.paused,a=this.gl.getExtension("EXT_disjoint_timer_query"),c=a.createQueryEXT(),l=this.isValid;(r||o)&&(this.load(r,o),l=this.isValid,this.forceRender=!0,this.render()),this.paused=!0,a.beginQueryEXT(a.TIME_ELAPSED_EXT,c),this.forceRender=!0,this.render(),a.endQueryEXT(a.TIME_ELAPSED_EXT);var u=this;function p(){u.paused=i,(r||o)&&u.load(s,n)}function f(){u.forceRender=!0,u.render();var m=a.getQueryObjectEXT(c,a.QUERY_RESULT_AVAILABLE_EXT),h=u.gl.getParameter(a.GPU_DISJOINT_EXT);if(m&&!h){var g={wasValid:l,frag:r||u.fragmentString,vert:o||u.vertexString,timeElapsedMs:a.getQueryObjectEXT(c,a.QUERY_RESULT_EXT)/1e6};p(),t(g)}else window.requestAnimationFrame(f)}f()}},{key:"loadTexture",value:function(t,r,o){var n=this;o||(o={}),typeof r=="string"?o.url=r:(typeof r>"u"?"undefined":pc(r))==="object"&&r.data&&r.width&&r.height?(o.data=r.data,o.width=r.width,o.height=r.height):(typeof r>"u"?"undefined":pc(r))==="object"&&(o.element=r),this.textures[t]?this.textures[t]&&(this.textures[t].load(o),this.textures[t].on("loaded",function(s){n.forceRender=!0})):(this.textures[t]=new wu(this.gl,t,o),this.textures[t].on("loaded",function(s){n.forceRender=!0}))}},{key:"refreshUniforms",value:function(){this.uniforms={}}},{key:"setUniform",value:function(t){for(var r={},o=arguments.length,n=Array(o>1?o-1:0),s=1;s<o;s++)n[s-1]=arguments[s];r[t]=n,this.setUniforms(r)}},{key:"setUniforms",value:function(t){var r=Eu(t);for(var o in r)r[o].type==="sampler2D"?this.loadTexture(r[o].name,r[o].value[0]):this.uniform(r[o].method,r[o].type,r[o].name,r[o].value);this.forceRender=!0}},{key:"setMouse",value:function(t){var r=this.canvas.getBoundingClientRect();if(t&&t.x&&t.x>=r.left&&t.x<=r.right&&t.y&&t.y>=r.top&&t.y<=r.bottom){var o=(t.x-r.left)*this.realToCSSPixels,n=this.canvas.height-(t.y-r.top)*this.realToCSSPixels;this.uniform("2f","vec2","u_mouse",o,n)}}},{key:"uniform",value:function(t,r,o){this.uniforms[o]=this.uniforms[o]||{};for(var n=this.uniforms[o],s=arguments.length,i=Array(s>3?s-3:0),a=3;a<s;a++)i[a-3]=arguments[a];var c=WC(n.value,i);if(c||this.change||!n.location||!n.value){n.name=o,n.type=r,n.value=i,n.method="uniform"+t,this.gl.useProgram(this.program),n.location=this.gl.getUniformLocation(this.program,o),this.gl[n.method].apply(this.gl,[n.location].concat(n.value));for(var l in this.buffers){var u=this.buffers[l];this.gl.useProgram(u.program);var p=this.gl.getUniformLocation(u.program,o);this.gl[n.method].apply(this.gl,[p].concat(n.value))}}}},{key:"uniformTexture",value:function(t,r,o){if(this.textures[t]===void 0)this.loadTexture(t,r,o);else{this.uniform("1i","sampler2D",t,this.texureIndex);for(var n in this.buffers){var s=this.buffers[n];this.gl.useProgram(s.program),this.gl.activeTexture(this.gl.TEXTURE0+this.texureIndex),this.gl.bindTexture(this.gl.TEXTURE_2D,this.textures[t].texture)}this.gl.useProgram(this.program),this.gl.activeTexture(this.gl.TEXTURE0+this.texureIndex),this.gl.bindTexture(this.gl.TEXTURE_2D,this.textures[t].texture),this.uniform("2f","vec2",t+"Resolution",this.textures[t].width,this.textures[t].height)}}},{key:"resize",value:function(){if(this.width!==this.canvas.clientWidth||this.height!==this.canvas.clientHeight){this.realToCSSPixels=window.devicePixelRatio||1;var t=Math.floor(this.gl.canvas.clientWidth*this.realToCSSPixels),r=Math.floor(this.gl.canvas.clientHeight*this.realToCSSPixels);return(this.gl.canvas.width!==t||this.gl.canvas.height!==r)&&(this.gl.canvas.width=t,this.gl.canvas.height=r,this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height)),this.width=this.canvas.clientWidth,this.height=this.canvas.clientHeight,this.resizeSwappableBuffers(),!0}else return!1}},{key:"render",value:function(){if(this.visible=BC(this.canvas),this.forceRender||this.change||this.animated&&this.visible&&!this.paused){var t=new Date,r=performance.now();this.timeDelta=(r-this.timePrev)/1e3,this.timePrev=r,this.nDelta>1&&this.uniform("1f","float","u_delta",this.timeDelta),this.nTime>1&&this.uniform("1f","float","u_time",(r-this.timeLoad)/1e3),this.nDate&&this.uniform("4f","float","u_date",t.getFullYear(),t.getMonth(),t.getDate(),t.getHours()*3600+t.getMinutes()*60+t.getSeconds()+t.getMilliseconds()*.001),this.uniform("2f","vec2","u_resolution",this.canvas.width,this.canvas.height);for(var o in this.buffers){var n=this.buffers[o];this.uniform("1i","sampler2D",n.name,n.bundle.input.index)}this.texureIndex=this.BUFFER_COUNT;for(var s in this.textures)this.uniformTexture(s),this.texureIndex++;this.renderPrograms(),this.trigger("render",{}),this.change=!1,this.forceRender=!1}}},{key:"pause",value:function(){this.paused=!0}},{key:"play",value:function(){this.paused=!1}},{key:"renderPrograms",value:function(){var t=this.gl,r=t.canvas.width,o=t.canvas.height;t.viewport(0,0,r,o);for(var n in this.buffers){var s=this.buffers[n];s.bundle.render(r,o,s.program,s.name),t.bindFramebuffer(t.FRAMEBUFFER,null)}t.useProgram(this.program),t.drawArrays(t.TRIANGLES,0,6)}},{key:"getBuffers",value:function(t){var r={};return t&&t.replace(/(?:^\s*)((?:#if|#elif)(?:\s*)(defined\s*\(\s*BUFFER_)(\d+)(?:\s*\))|(?:#ifdef)(?:\s*BUFFER_)(\d+)(?:\s*))/gm,function(){var o=arguments[3]||arguments[4];r["u_buffer"+o]={fragment:"#define BUFFER_"+o+`
`+t}}),r}},{key:"loadPrograms",value:function(t){var r=this,o=this.gl,n=On(r,r.vertexString,o.VERTEX_SHADER);for(var s in t){var i=t[s],a=On(r,i.fragment,o.FRAGMENT_SHADER,1);a?r.isValid=!0:(a=On(r,`void main(){
gl_FragColor = vec4(1.0);
}`,o.FRAGMENT_SHADER),r.isValid=!1);var c=qE(r,[n,a]);i.name=s,i.program=c,i.bundle=r.createSwappableBuffer(r.canvas.width,r.canvas.height,c),o.deleteShader(a)}o.deleteShader(n)}},{key:"createSwappableBuffer",value:function(t,r,o){var n=this.createBuffer(t,r,o),s=this.createBuffer(t,r,o),i=this.gl;return{input:n,output:s,swap:function(){var a=n;n=s,s=a,this.input=n,this.output=s},render:function(a,c,l,u){i.useProgram(l),i.viewport(0,0,a,c),i.bindFramebuffer(i.FRAMEBUFFER,this.input.buffer),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.output.texture,0),i.drawArrays(i.TRIANGLES,0,6),this.swap()},resize:function(a,c,l,u){i.useProgram(l),i.viewport(0,0,a,c),this.input.resize(a,c),this.output.resize(a,c)}}}},{key:"createBuffer",value:function(t,r,o){var n=this.gl,s=this.BUFFER_COUNT;this.BUFFER_COUNT+=2,n.getExtension("OES_texture_float");var i=n.createTexture();n.activeTexture(n.TEXTURE0+s),n.bindTexture(n.TEXTURE_2D,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,t,r,0,n.RGBA,n.FLOAT,null),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);var a=n.createFramebuffer();return{index:s,texture:i,buffer:a,W:t,H:r,resize:function(c,l){n.bindFramebuffer(n.FRAMEBUFFER,a);var u=Math.min(c,this.W),p=Math.min(l,this.H),f=new Float32Array(u*p*4);n.readPixels(0,0,u,p,n.RGBA,n.FLOAT,f),n.bindFramebuffer(n.FRAMEBUFFER,null);var m=s+1,h=n.createTexture();n.activeTexture(n.TEXTURE0+m),n.bindTexture(n.TEXTURE_2D,h),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,c,l,0,n.RGBA,n.FLOAT,null),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texSubImage2D(n.TEXTURE_2D,0,0,0,u,p,n.RGBA,n.FLOAT,f);var g=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(i),n.activeTexture(n.TEXTURE0+s),n.bindTexture(n.TEXTURE_2D,h),s=this.index=s,i=this.texture=h,a=this.buffer=g,this.W=c,this.H=l}}}},{key:"resizeSwappableBuffers",value:function(){var t=this.gl,r=t.canvas.width,o=t.canvas.height;t.viewport(0,0,r,o);for(var n in this.buffers){var s=this.buffers[n];s.bundle.resize(r,o,s.program,s.name)}t.useProgram(this.program)}},{key:"version",value:function(){return"0.1.7"}}]),e}();function VC(){var e=document.getElementsByClassName("glslCanvas");if(e.length>0){window.glslCanvases=[];for(var t=0;t<e.length;t++){var r=new QE(e[t]);r.isValid&&window.glslCanvases.push(r)}}}window.addEventListener("load",function(){VC()});var uc=QE;var ZE=e=>{if(!("after"in e))return Promise.resolve(void 0);let t=document.createElement("canvas");return new uc(t).load(It(e.after)),e.render(t),Promise.resolve(void 0)};var ew=e=>{let t="";for(let r=0;r<e.length;r+=3)r+2===e.length?t+=Ru(e[r],e[r+1],0):r+1===e.length?t+=Ru(e[r],0,0):t+=Ru(e[r],e[r+1],e[r+2]);return t},mc=e=>e<10?String.fromCharCode(48+e):(e-=10,e<26?String.fromCharCode(65+e):(e-=26,e<26?String.fromCharCode(97+e):(e-=26,e===0?"-":e===1?"_":"?"))),Ru=(e,t,r)=>{let o=e>>2,n=(e&3)<<4|t>>4,s=(t&15)<<2|r>>6,i=r&63;return mc(o&63)+mc(n&63)+mc(s&63)+mc(i&63)};var tw=async(e,t="svg")=>{let r=new Blob([new TextEncoder().encode(e)]).stream().pipeThrough(new CompressionStream("deflate")),o=new Uint8Array(await new Response(r).arrayBuffer());return`https://www.plantuml.com/plantuml/${t}/~1${ew(o)}`};var rw=async e=>{if(!("after"in e))return;let t=document.createElement("img"),r=await tw(It(e.after));t.src=r,e.render(t)};var ku=Promise.resolve({log:new Uint8Array(0)}),fc,ow=(e,t,r,o)=>(ku=(async()=>{await ku,fc??=await zC(t,r);let n=new Promise(i=>{let a=c=>{if(c.data.type==="stdout"){o(c.data.message);return}c.data.type==="compile"&&(i(c.data),fc.removeEventListener("message",a))};fc.addEventListener("message",a)}),s={type:"compile",input:e};return fc.postMessage(s),n})(),ku),zC=async(e,t)=>{let r=new Worker(e,{type:"module"}),o=new Promise(s=>{let i=a=>{a.data.type==="asset-url"&&(s(),r.removeEventListener("message",i))};r.addEventListener("message",i)}),n={type:"asset-url",url:`${t}`};return r.postMessage(n),await o,r};var nw=(e,t)=>async r=>{if(!("after"in r))return;let o=qC(),n="Compile is not started yet. Please wait...",s=l=>{n=[...n.split(`
`),l].join(`
`),o.log(n)},i=document.createElement("img"),a=setTimeout(()=>{r.render(o.div),o.log(n)},2e3),{svg:c}=await ow(It(r.after),e,t,s);if(clearTimeout(a),!c){r.render(o.div),o.log(n);return}i.src=await vs(new Blob([c],{type:"image/svg+xml"})),r.render(i)},qC=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"}),r=document.createElement("style");r.textContent='*{box-sizing:border-box;}pre{display:block;padding:9.5px;margin:0 0 10px;border:1px solid #ccc;border-radius:4px;height:20em;overflow:auto;font-size:13px;line-height:1.428571429;}pre code{padding:0;font-family:Menlo,Monaco,Consolas,"Courier New",monospace;font-size:inherit;word-break:break-all;word-wrap:break-word;white-space:pre-wrap;color:var(--code-color,#342d9c);background-color: rgba(0,0,0,0);border-radius:0;}',t.append(r);let o=document.createElement("pre"),n=document.createElement("code");return o.append(n),t.append(o),{div:e,log:s=>{n.textContent=s,o.scroll(0,o.scrollHeight)}}};var Bo=()=>/mobile/i.test(navigator.userAgent);var sw="Cannot complete the mapping as an error was thrown from an item";function vu(e,t,r){let o=new TransformStream({async transform(n,s){try{let i=await n;s.enqueue(i)}catch(i){i instanceof AggregateError&&i.message===sw&&s.error(i)}}});return(async()=>{let n=o.writable.getWriter(),s=[];try{for await(let i of t){let a=Promise.resolve().then(()=>r(i));n.write(a);let c=a.then(()=>s.splice(s.indexOf(c),1));s.push(c),s.length>=e&&await Promise.race(s)}await Promise.all(s),n.close()}catch{let i=[];for(let a of await Promise.allSettled(s))a.status==="rejected"&&i.push(a.reason);n.write(Promise.reject(new AggregateError(i,sw))).catch(()=>{})}})(),Symbol.asyncIterator in o.readable&&typeof o.readable[Symbol.asyncIterator]=="function"?o.readable[Symbol.asyncIterator]():async function*(){let n=o.readable.getReader();for(;;){let{done:s,value:i}=await n.read();if(s)break;yield i}n.releaseLock()}()}async function*iw(e,t){if(e.length===0||e.every(({before:o,after:n})=>o===n))return;let r=X(await Ve());try{let{readable:o,writable:n}=new TransformStream(void 0),s=n.getWriter(),i=vu(5,e,async l=>{let u=0,p=0;l.before===l.after&&(await s.ready,await s.write({link:l,projectCount:0,replaced:0,done:!0}));let f=vu(2,new Set(t),async m=>{let h=await KC(l,m,r);if(G(h))throw XC(Jo(h));u++,p+=X(h),await s.ready,await s.write({link:l,projectCount:u,replaced:p,done:!1})});await Array.fromAsync(f),await s.ready,await s.write({link:l,projectCount:u,replaced:p,done:!0})}),a=Array.fromAsync(i).then(async()=>{await s.ready,await s.close()}),c=o.getReader();for(;;){let{done:l,value:u}=await c.read();if(l)return;yield u}await a}finally{await rt(r)}}var KC=async(e,t,r)=>{let[o]=await Promise.all([li(t,e.before,e.after),xe(t,e.before,(n,{persistent:s})=>{if(s)return[e.after,...n.map(i=>i.text).slice(1)]},{socket:r})]);return o},Ar=e=>e.split(`
`).flatMap(t=>[...t.matchAll(/\[((?:[^\[!"#%&'()\*\+,\-\.\/\{\|\}<>_~] |.[^ ]*)[^\[\]]*)\]/g)]).map(([,t])=>t),XC=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var aw=e=>Be(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return YC(r);case"table":return JC(r);case"line":return QC(r)}}).map(r=>r).join(`
`),YC=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[`${o}code:${e}`,...t.split(`
`).map(n=>`${o} ${n}`)]},JC=({fileName:e,cells:t,indent:r})=>{let o=" ".repeat(r);return[`${o}table:${e}`,...t.map(n=>`${o} ${n.map(s=>s.map(i=>Ts(i)).join("")).join(" ")}`)]},QC=({nodes:e,indent:t})=>[`${" ".repeat(t)}${e.map(r=>`${Ts(r)}`).join("")}`],Ts=e=>{switch(e.type){case"quote":return`> ${e.nodes.map(t=>Ts(t)).join("")}`;case"strong":return`[[${e.nodes.map(t=>Ts(t)).join("")}]]`;case"decoration":{let t=e.decos.map(r=>{let o=parseInt(r.match(/\*-(\d)/)?.[1]??"0");return o>0?"*".repeat(o):r}).join("");return`[${t?`${t} `:""}${e.nodes.map(r=>Ts(r)).join("")}]`}case"hashTag":return e.href;case"link":return e.pathType==="absolute"?e.raw:e.href;default:return e.raw}};scrapbox.PopupMenu.addButton({title:e=>Ar(e).length>0?"":"",onClick:e=>{let t=aw(e);if(e!=t)return t}});var cw=e=>!e.includes(`
`)&&/\[[^\]]+\]/.test(e);scrapbox.PopupMenu.addButton({title:e=>cw(e)?"[][]":"",onClick:e=>{if(!cw(e))return;let t=e.replaceAll("[","").replaceAll("]","");return(async()=>{let{render:r,dispose:o}=Le();try{let n=scrapbox.Project.name;r({type:"spinner"},{type:"text",text:`create /${n}/${t}`}),await xe(n,t,([{text:s}],{persistent:i})=>{if(!i)return[s,e]}),r({type:"check-circle"},{type:"text",text:`create /${n}/${t}`})}catch(n){if(console.error(n),!(n instanceof Error))throw n;r({type:"exclamation-triangle"},{type:"text",text:`${n.name} ${n.message}`})}finally{await Te(2e3),o()}})(),`[${t}]`}});var pw=(e,t)=>{switch(e.type){case"title":return"";case"codeBlock":return[e.fileName,`
\`\`\`${sA(e.fileName)}`,e.content,"```\n"].join(`
`);case"table":return ZC(e);case"line":return tA(e,t)}},ZC=e=>{let t=[e.fileName],r=Math.max(...e.cells.map(o=>o.length));return e.cells.forEach((o,n)=>{t.push(`| ${o.map(s=>s.map(i=>Ln(i)).join("")).join(" | ")} |`),n===0&&t.push(`|${" -- |".repeat(r)}`)}),t.join(`
`)},eA=" ",tA=(e,t)=>{let r=e.nodes.map(n=>Ln(n,{section:e.indent===t})).join("").trim();if(r==="")return"";if(e.indent===t)return r;let o=eA.repeat(e.indent-t-1);return/^\d+\. /.test(r)||(o+="- "),o+r},Ln=(e,t)=>{let{section:r=!1}=t??{};switch(e.type){case"quote":return`> ${e.nodes.map(o=>Ln(o)).join("")}`;case"helpfeel":return`\`? ${e.text}\``;case"image":case"strongImage":return``;case"icon":case"strongIcon":return["/icons/hr","/scrapboxlab/hr"].includes(e.path)?"---":"";case"strong":return`**${e.nodes.map(o=>Ln(o)).join("")}**`;case"formula":return`$${e.formula}$`;case"decoration":{let o=e.nodes.map(n=>Ln(n)).join("");return e.decos.includes("/")&&(o=`*${o}*`),r?(e.decos.includes("*-3")&&(o=`# ${o}
`),e.decos.includes("*-2")&&(o=`## ${o}
`),e.decos.includes("*-1")&&(o=`### ${o}
`)):e.decos.some(n=>/\*-/.test(n[0]))&&(o=`**${o}**`),e.decos.includes("~")&&(o=`~~${o}~~`),o}case"code":return`\`${e.text}\``;case"commandLine":return`\`${e.symbol} ${e.text}\``;case"link":switch(e.pathType){case"root":{let[,o,...n]=e.href.split("/");return`[${e.href}](https://scrapbox.io/${o}/${lw(n.join("/"))})`}case"relative":return`[${e.href}](https://scrapbox.io/${scrapbox.Project.name}/${lw(e.href)})`;default:return e.content===""?` ${e.href} `:`[${e.content}](${e.href})`}case"googleMap":return`[${e.place}](${e.url})`;case"hashTag":return`[#${e.href}](https://scrapbox.io/${scrapbox.Project.name}/${e.href})`;case"numberList":return`${e.number}. ${e.nodes.map(o=>Ln(o)).join("")}`;case"blank":case"plain":return e.text}},lw=e=>[...e].map((t,r)=>t===" "?"_":!rA.includes(t)||r===e.length-1&&oA.includes(t)?encodeURIComponent(t):t).join(""),rA='@$&+=:;",',oA=':;",',nA=[{extensions:["javascript","js"],fileType:"javascript"},{extensions:["typescript","ts"],fileType:"typescript"},{extensions:["cpp","hpp"],fileType:"cpp"},{extensions:["c","cc","h"],fileType:"c"},{extensions:["cs","csharp"],fileType:"cs"},{extensions:["markdown","md"],fileType:"markdown"},{extensions:["htm","html"],fileType:"html"},{extensions:["json"],fileType:"json"},{extensions:["xml"],fileType:"xml"},{extensions:["yaml","yml"],fileType:"yaml"},{extensions:["toml"],fileType:"toml"},{extensions:["ini"],fileType:"ini"},{extensions:["tex","sty"],fileType:"tex"},{extensions:["svg"],fileType:"svg"}],sA=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return nA.find(r=>r.extensions.includes(t))?.fileType??""};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{(async()=>{try{let t=ic.parse(e,{hasTitle:!1}),r=Math.min(...t.map(o=>o.indent));await navigator.clipboard.writeText(t.map(o=>pw(o,r)).join(`
`))}catch(t){alert(`Failed to copy:
${JSON.stringify(t)}`)}})()}});var _u=(e,...t)=>{let r=t.reduce((o,n)=>De(o)?o:o instanceof Promise?o.then(s=>De(s)?s:n(s)):n(o),e);return r instanceof Promise?r.then(o=>`${o}`):`${e}`};var Nn=e=>e.ok?ae(e):Q({name:"HTTPError",message:`${e.status} ${e.statusText}`,response:e});var uw=e=>window.GM_fetch?.(`https://cdn.syndication.twimg.com/tweet-result?id=${e}&token=x`)?.then?.(t=>Tt(Nn(t),r=>r.json()));var dc=e=>{let{fetch:t=globalThis.fetch,...r}=e;return{fetch:t,...r}},mw=e=>typeof e=="object"&&e!==null;var Ps=class e extends Error{name="UnexpectedResponseError";status;statusText;body;path;constructor(t){super(`${t.status} ${t.statusText} when fetching ${t.path.toString()}`),this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.path=t.path,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};var hc=async e=>{let t=await e.text();if(e.ok)return ae(t);if(e.status===400)return Q({name:"BadRequestError",message:t});try{let r=JSON.parse(t);if(!mw(r)||typeof r.message!="string")throw new Ps({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)});switch(e.status){case 401:return Q({name:"UnauthorizedError",message:r.message});case 403:return Q({name:"NotPrivilegeError",message:r.message});case 404:return Q({name:"NotFoundError",message:r.message});case 422:return Q({name:"InvalidParameterError",message:r.message});case 429:return Q({name:"RateLimitError",message:r.message});default:throw new Ps({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)})}}catch(r){throw r instanceof SyntaxError?new Ps({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)}):r}};var fw=async(e,t)=>{let{title:r,description:o,metadataIsPublic:n,collectionId:s,refererURL:i,accessToken:a,created:c,app:l,fetch:u}=dc(t),p=new FormData;p.append("imagedata",e),p.append("access_token",a),i&&p.append("referer_url",i.toString()),l!==void 0&&p.append("app",l),r!==void 0&&p.append("title",r),o!=null&&p.append("desc",o),s&&p.append("collection_id",s),n&&p.append("metadata_is_public","true"),c!==void 0&&p.append("created_at",`${c}`);let f=await u("https://upload.gyazo.com/api/upload",{method:"POST",mode:"cors",credentials:"omit",body:p}),m=await hc(f);return B(m)?m:ae(JSON.parse(H(m)))};var dw=(e,t)=>{let r=new FormData;return r.append("data",e),r.append("metadata",JSON.stringify({app:"Gyazo",title:e.name})),GM_fetch(`https://gif.gyazo.com/${t?.teams?"teams":"gif"}/upload`,{method:"POST",body:r,credentials:"include",headers:{Origin:"https://gyazo.com","sec-fetch-site":"same-site"},referrer:"https://gyazo.com/"})};var gc="",hw=!1,yc=new Map,gw=async(e,t,r,o)=>{let n=yc.get(e.href);if(n)return n;if(e.hostname==="video.twimg.com"||`${e}`.endsWith(".svg")){let c=await GM_fetch(e);if(!c.ok)return;let l=c.headers.get("content-type")?.split?.(";")?.[0]??`${e}`.endsWith(".mp4")?"video/mp4":"video/webm",u=new File([await c.blob()],o||`${t}`,{type:l});if(l==="video/mp4"){let m=await dw(u);if(m.ok){let h=new URL(await m.text());return yc.set(e.href,h),h}}let p=await Bf(u,r);if(B(p))throw Error(re(p).name);let f=new URL(H(p).embedUrl);return yc.set(e.href,f),f}if(e.hostname!=="pbs.twimg.com"||!e.pathname.startsWith("/media"))return;if(hw){if(!gc)return}else{let c=await Cf();if(hw=!0,B(c)){alert("You haven't logged in Gyazo yet, so you can only upload images to scrapbox.io.");return}if(gc=H(c)||"",!gc){alert("You haven't connect Gyazo to scrapbox.io yet.");return}}let s=await GM_fetch(e);if(!s.ok)return;let i=await fw(await s.blob(),{accessToken:gc,refererURL:t,description:o});if(B(i))throw Error(re(i).name);let a=new URL(H(i).permalink_url);return yc.set(e.href,a),a};var bw=[["&","&"],["<","<"],[">",">"],['"',"""],["'","'"]],iA=Object.fromEntries([...bw.map(([e,t])=>[t,e]),["'","'"],[" "," "]]),aA=new Map(bw),IAe=new RegExp(`[${[...aA.keys()].join("")}]`,"g");var cA={entityList:iA},lA=1114111,pA=/&#([0-9]+);/g,uA=/&#x(\p{AHex}+);/gu,yw=new WeakMap;function Tu(e,t={}){let{entityList:r}={...cA,...t},o=yw.get(r);return o||(o=new RegExp(`(${Object.keys(r).sort((n,s)=>s.length-n.length).join("|")})`,"g"),yw.set(r,o)),e.replaceAll(o,n=>r[n]).replaceAll(pA,(n,s)=>xw(s,10)).replaceAll(uA,(n,s)=>xw(s,16))}function xw(e,t){let r=parseInt(e,t);return r>lA?"�":String.fromCodePoint(r)}var xc=e=>{let t={name:e.user.name,screenName:e.user.screen_name},r=new Date(e.created_at),o=[...e.entities.hashtags.map(i=>({type:"hashtag",...i})),...e.entities.symbols.map(i=>({type:"symbol",...i})),...e.entities.user_mentions.map(i=>({type:"mention",name:i.name,screenName:i.screen_name,indices:i.indices})),...e.entities.urls.map(i=>{let a={type:"url",indices:i.indices,url:new URL(i.expanded_url)};if(e.card&&e.card?.url===i.url){let{description:c,title:l}=e.card.binding_values,u="STRING";c?.type===u&&(a.description=c.string_value),l?.type===u&&(a.title=l.string_value)}return a}),...e.entities.media?.map?.(i=>({type:"media",indices:i.indices,media:e.mediaDetails?.flatMap?.(a=>a.url===i.url?[{type:a.type,url:new URL(a.video_info?.variants?.sort?.((c,l)=>(l.bitrate??0)-(c.bitrate??0))?.[0].url??a.media_url_https)}]:[])??[]}))??[]].sort((i,a)=>i.indices[0]-a.indices[0]),n=[];{let i=0,a=e.text;for(let{indices:c,...l}of o){let u=[...a].slice(0,c[0]-i).join("");n.push({type:"plain",text:Tu(u)}),n.push(l),a=[...a].slice(c[1]-i).join(""),i=c[1]}a&&n.push({type:"plain",text:Tu(a)})}let s={id:e.id_str,content:n,author:t,posted:r,replyCount:"reply_count"in e?e.reply_count:e.conversation_count};return e.self_thread&&(s.rootId=e.self_thread.id_str),e.in_reply_to_status_id_str&&(s.replyId=e.in_reply_to_status_id_str),e.parent&&(s.replyTo=xc(e.parent)),e.quoted_tweet&&(s.quote=xc(e.quoted_tweet)),s};var mA=["landing","product","enterprise","pricing","try-enterprise","contact","terms","privacy","jp-commercial-act","support","case","features","business","auth","login","logout","oauth2","_","api","app.html","assets","file","files","billing","billings","config","feed","index","io","new","opensearch","project","projects","search","setting","settings","setup-profile","slide","socket.io","stream","user","users"],bc=(e=scrapbox.Project.name,t=location.host)=>r=>{if(r.host!==t)return r;let[,o,n]=r.pathname.match(/^\/([\w\d][\w\d-]{0,22}[\w\d])(?:\/?|\/(.+))$/)??[];return!o||mA.includes(o)?r:n?o===e?`[${decodeURIComponent(n)}]`:`[/${o}/${decodeURIComponent(n)}]`:`[/${o}]`};var Ew=(e=fA)=>t=>{let[,r]=t.href.match(/^https:\/\/(?:(?:www\.|mobile\.|m\.)?twitter|x)\.com\/[\w\d_]+\/(?:status|statuses)\/(\d+)/)??[];return r?(async()=>{let o=await(uw(r)??Nf(t.href));if(B(o))throw re(o);let n=H(o);return e("images"in n?{...n,id:r}:n,t)})():t},fA=async e=>{if("images"in e)return Ss(e);let{quote:t,replyTo:r,...o}=xc(e);return[...r?[...(await Ss(r)).split(`
`).map(n=>` > ${n}`),...r.quote?(await Ss(r.quote)).split(`
`).map(n=>` > ${n}`):[]]:[],...(await Ss(o)).split(`
`).map(n=>`> ${n}`),...t?(await Ss(t)).split(`
`).map(n=>`> > ${n}`):[]].join(`
`)},Ss=async e=>{let t=new URL(`https://twitter.com/${"author"in e?e.author.screenName:e.screenName}/status/${e.id}`);if("images"in e)return[`> [@${Su(e.screenName)} ${t.origin}${t.pathname}]`,...e.description?.split?.(`
`)?.map?.(n=>`> ${Su(n)}`)??["> [/ no description provided]"],...e.images.length>0?[`> ${e.images.map(n=>`[${n}]`)}`]:[]].join(`
`);let r=e.content,o=e.author.screenName;return[`[@${Su(o)} ${t}]`,...(await Promise.all(r.map(async n=>{switch(n.type){case"plain":return n.text;case"hashtag":return` #${n.text} `;case"symbol":return` #$${n.text} `;case"mention":return`[@${n.screenName} https://twitter.com/${n.screenName}]`;case"media":{let s=[],i=1;for(;i<n.media.length;i+=2)s.push(`[${await Pu(n.media[i-1],t)}] [${await Pu(n.media[i],t)}]`);return i===n.media.length&&s.push(`[${await Pu(n.media[i-1],t)}]`),`
${s.join(`
`)}
`}case"url":return`${bc()(n.url)} `}}))).join("").split(`
`)].join(`
`)},Ec="",dA=async()=>{if(Ec)return Ec;let e=await gr(scrapbox.Project.name);if(B(e))throw new Error(re(e).name);return Ec=H(e).id,Ec},Pu=async(e,t)=>await gw(e.url,t,await dA(),"")??e.url,Su=e=>e.replace(/\b/gm,"").replace(/[\s\r\n\u2028\u2029]+/gm," ").replace(/\s*[[\]`]\s*/g," ").trim();var ww=e=>window.GM_fetch?.(`https://t.co/${e}`)?.then?.(t=>Tt(Nn(t),async r=>{let o=new DOMParser().parseFromString(await r.text(),"text/html");try{return new URL(o.title)}catch(n){if(n instanceof TypeError)return;throw n}}));var Rw=e=>{let t=window.GM_fetch;if(["bit.ly","amzn.to","amzn.asia","goo.gl","s.nikkei.com","apple.co","nico.ms","w.wiki"].includes(e.hostname)&&t)return t(e).then(o=>o.ok?new URL(o.url):e);if(e.hostname!=="t.co")return e;let r=ww(e.pathname.slice(1));return r?r.then(o=>il(o,()=>e,n=>n??e)):e};var kw=e=>{if(!e.pathname.startsWith("/wiki/"))return e;if(!/^\w+\.wikipedia\.org$/.test(e.hostname)){let[,n]=e.hostname.match(/^(\w+)\.m\.wikipedia\.org$/)??[];if(!n)return e;e.hostname=`${n}.wikipedia.org`}let t=decodeURIComponent(e.pathname.slice(6)),r=e.hash?decodeURIComponent(e.hash.slice(1)):"",o=`${e.origin}/wiki/${t}`;return r?`[${r} | ${t} - Wikipedia ${o}#${r}]`:`[${t} - Wikipedia ${o}]`};var vw=e=>{if(e.hostname!=="www.wikiwand.com")return e;let[,t,r]=e.pathname.match(/^\/([^\/]+)\/([^\/]+)/)??[];return!t||!r||(e.hostname=`${t}.wikipedia.org`,e.pathname=`/wiki/${r}`,e.hash=e.hash.startsWith("#/")?`#${e.hash.slice(2)}`:e.hash),e};var Ou=e=>{if(!e.hostname.startsWith("www.google."))return e;let t=e.searchParams.get("url");return t?new URL(decodeURIComponent(t)):e};var _w=/charset=([^;]+)/,Tw=e=>window.GM_fetch?.(`${e}`)?.then?.(t=>Tt(Nn(t),async r=>{let o=r.headers.get("content-type")?.match?.(_w)?.[1]??await hA(r.clone());return new TextDecoder(o).decode(await r.arrayBuffer())})),hA=async e=>{let t=new DOMParser().parseFromString(await e.text(),"text/html");return t.querySelector("meta[charset]")?.getAttribute?.("charset")??t.querySelector('meta[http-equiv="content-type"]')?.getAttribute?.("content")?.match?.(_w)?.[1]??"utf-8"};var Pw=(e=gA)=>async t=>e(await yA(t),t),gA=(e,t)=>{let r=(De(e)?e:e.title).replace(/\s/g," ").replaceAll("[","[").replaceAll("]","]");return r?`[${t.hash?`${decodeURIComponent(t.hash.slice(1))} | `:""}${r} ${t}]`:`${t}`},yA=async e=>{let t=Tw(e);if(!t){let o=await Lf(e);if(B(o))throw re(o);return H(o)}let r=await t;if(B(r))throw re(r);return new DOMParser().parseFromString(H(r),"text/html")};var Sw=e=>{if(!/^(?:www\.)?amazon(?:\.co|com)?\.(?:au|br|ca|fr|de|in|it|jp|mx|nl|sg|es|tr|ae|uk|cn)$/.test(e.hostname))return e;let[,t]=e.pathname.match(/\/dp\/([\w\d]+)/)??e.pathname.match(/\/gp\/product\/([\w\d]+)/)??e.pathname.match(/\/exec\/obidos\/asin\/([\w\d]+)/)??e.pathname.match(/\/o\/ASIN\/([\w\d]+)/)??[];return t&&(e.hash="",e.search="",e.pathname=`/dp/${t}`),e};var Ow=e=>{if(!/(?:[0-9a-z-]\.)?gyazo\.com/.test(e.hostname))return e;let[,t]=e.pathname.match(/^\/([0-9a-f]{32})(?:\/raw)?$/)??[];return t?`[https://gyazo.com/${t}]`:e};var Lw=(e,...t)=>{if(e instanceof URL)return _u(new URL(e),...t);let r=0,o=0,n=0,s=!1,i=e.split(/(https?:\/\/\S+)/g).map(u=>{if(!/^https?:\/\/\S+$/.test(u))return u;r++;try{let p=_u(new URL(u),...t);return De(p)?(o++,p):(s=!0,[p,u])}catch(p){return console.error(p),n++,u}});if(!s)return i.join("");let{render:a,dispose:c}=Le(),l=()=>a({type:"spinner"},{type:"text",text:`URL: ${o}/${r} converted, ${n} failed`});return l(),Promise.all(i.map(async u=>{if(De(u))return u;try{let p=await u[0];return o++,p}catch(p){return console.error(p),n++,u[1]}finally{l()}})).then(u=>(a({type:"check-circle"},{type:"text",text:`URL: ${o}/${r} converted, ${n} failed`}),u.join(""))).finally(()=>{setTimeout(c,1e3)})};var Nw=e=>{if(!/^(?:\w+\.nicovideo\.jp|nico\.ms)$/.test(e.hostname))return e;let t=e.pathname.match(/(?:sm|nm|so|ca|ax|yo|nl|ig|na|cw|z[a-e]|om|sk|yk|lv)\d{1,14}$/)?.[0];return t?`[https://nicothumb2img.vercel.app/image/${t}#.png https://nico.ms/${t}]`:e};var Cw=e=>Be(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return xA(r);case"table":return bA(r);case"line":return EA(r)}}).map(r=>r).join(`
`),xA=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[`${o}code:${e}`,...t.split(`
`).map(n=>`${o} ${n}`)]},bA=({fileName:e,cells:t,indent:r})=>{let o=" ".repeat(r);return[`${o}table:${e}`,...t.map(n=>`${o} ${n.map(s=>s.map(i=>i.raw).join("")).join(" ")}`)]},EA=({nodes:e,indent:t})=>[`${" ".repeat(t)}${e.map(r=>`${Os(r)}`).join("")}`],Os=e=>{switch(e.type){case"quote":return`> ${e.nodes.map(t=>Os(t)).join("")}`;case"helpfeel":return`[-? ${e.text}]`;case"commandLine":return`[-${e.symbol} ${e.text}]`;case"icon":case"strongIcon":case"image":case"strongImage":case"formula":case"code":case"googleMap":return e.raw;case"strong":return`[[${e.nodes.map(t=>Os(t)).join("")}]]`;case"decoration":{e.decos.includes("-")||e.decos.push("-");let t=e.decos.map(r=>{let o=parseInt(r.match(/\*-(\d)/)?.[1]??"0");return o>0?"*".repeat(o):r}).join("");return`[${t?`${t} `:""}${e.nodes.map(r=>Os(r)).join("")}]`}case"link":switch(e.pathType){case"root":case"relative":return`[- [${e.href}]]`;case"absolute":return`[- ${e.content?`${e.content} `:""}${e.href}]]`}case"hashTag":return`[- #${e.href}]`;case"numberList":return`${e.number}. ${e.nodes.map(t=>Os(t)).join("")}`;case"blank":case"plain":return`[- ${e.text}]`}};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=Cw(e);if(e!==t)return t}});var Lu=e=>{let t=e.indexOf(`
`);if(t<0)return;let r=e.slice(0,t).split(`
`).map(s=>{let[i="",a=""]=s.split(" => ",2);return[i,a]});if(r.length===0)return;let o=e.slice(t+2).split(`
`);if(o.length===0)return;for(let[s,i]of r){let a=s.match(/^\/(.*?)\/([gimy]*)$/);if(a){let c=new RegExp(a[1],a[2]);o=o.map(l=>l.replace(c,i.replaceAll("\\n",`
`)))}else o=o.map(c=>c.replaceAll(s,i.replaceAll("\\n",`
`)))}let n=`${e.slice(0,t+2)}${o.join(`
`)}`;if(e!==n)return n};scrapbox.PopupMenu.addButton({title:e=>Lu(e)?"replace":"",onClick:e=>{let t=Lu(e);if(t!==void 0)return t}});var Aw=e=>{let t=document.createElement("div"),r=t.attachShadow({mode:"open"}),o=document.createElement("style");o.textContent="dialog::backdrop{background-color:#000c}dialog{flex-direction:column;align-items:center;row-gap:10px;padding:10px;background:unset;margin-top:unset;margin-bottom:unset;border:unset;height:unset}dialog[open]{display:flex}dialog>*{color:var(--page-text-color, #4a4a4a);background-color:var(--dropdown-menu-bg, #fff);border:1px solid rgba(0,0,0,.2);border-radius:6px}@media (min-width: 768px){dialog{padding:30px 0}}.container{display:flex;padding:5px;gap:0.2em;flex-direction:column;width:100%;}.button-container{flex-direction:unset;}.button-container>*{flex:1;}",r.append(o);let n=document.createElement("dialog");n.insertAdjacentHTML("beforeend",`
<div class="container">
Replace Links:
<textarea class="editor"></textarea>
<div class="container button-container">
<button class="cancel">cancel</button>
<button class="replace">replace</button>
</div>
</div>
`),r.append(n);let s=n.querySelector(".editor");s.rows=e.length,s.value=e.join(`
`);let i=()=>{n.style.minWidth=`${Math.max(...s.value.split(`
`).map(u=>[...u].length))+6}em`};i(),s.addEventListener("input",i);let a=n.querySelector(".cancel"),c=n.querySelector(".replace"),l=new Promise(u=>{let p=()=>{u({convert:!1}),t.remove()};n.addEventListener("close",p),n.addEventListener("click",p),a.addEventListener("click",p),c.addEventListener("click",()=>{let f=s.value.split(`
`);u({convert:!0,links:e.flatMap((m,h)=>m===f[h]||m===""||!f[h]?[]:[{before:m,after:f[h]??m}])}),t.remove()}),n.querySelector(".container").addEventListener("click",f=>{f.stopPropagation()})});return document.body.append(t),n.showModal(),l};var Mw=async(e,t)=>{let r=Ar(e),o=await Aw([...new Set(r)]);if(!o.convert||o.links.length===0)return;let n=new Map(o.links.map(s=>[s.before,Le()]));for await(let{link:s,projectCount:i,replaced:a,done:c}of iw(o.links,t)){let l=n.get(s.before);if(!l)return;if(c){l.render({type:"check-circle"},{type:"text",text:`"${s.after}", ${a}l. ${i}p.`}),setTimeout(()=>l.dispose(),1e3);return}l.render({type:"spinner"},{type:"text",text:`"${s.after}", ${a}l. ${i}p.`})}};var Iw=async(e,t)=>{let r=Ar(e)[0];if(!r)return;let o=window.prompt(`Replace "${r}" to this in ${t.map(a=>`"/${a}"`).join(", ")}`,r)?.replace?.(/[\[\]\n]/g," ")??"";if(o==="")return;let{render:n,dispose:s}=Le(),i=H(await Ve());try{n({type:"spinner"},{type:"text",text:`Replacing links in ${t.length} projects...`});let a=0,l=(await Promise.all(t.map(async u=>{let[p]=await Promise.all([li(u,r,o),xe(u,r,(f,{persistent:m})=>{if(m)return[o,...f.map(h=>h.text).slice(1)]},{socket:i})]);if(B(p))throw n({type:"exclamation-triangle"},{type:"text",text:`${re(p).name} ${re(p).message}`}),wA(re(p));return a++,n({type:"spinner"},{type:"text",text:`Replacing links in ${t.length-a} projects...`}),H(p)}))).reduce((u,p)=>u+p,0);n({type:"check-circle"},{type:"text",text:`Successfully replaced ${l} links.`})}finally{await rt(i),setTimeout(s,1e3)}},wA=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var Fw=e=>{let t=[scrapbox.Project.name,...e];scrapbox.PopupMenu.addButton({title:r=>{let o=Ar(r).length;return o>1?"update links":o===1?"update a link":""},onClick:r=>{let o=Ar(r).length;o>1?Mw(r,t):o===1&&Iw(r,t)}})};scrapbox.PopupMenu.addButton({title:e=>/[\n..。]/.test(e)?"\\n":"",onClick:e=>e.replace(/(\w)\n(\w)/g,"$1 $2").replaceAll(`
`,"").replaceAll(".",`.
`).replaceAll(".",`.
`).replaceAll("。",`。
`)});scrapbox.PopupMenu.addButton({title:e=>/https:\/\/(?:thumb\.|i\.)?gyazo\.com\/[a-z0-9]+/.test(e)?globalThis.GM_fetch?"copy Gyazo OCR":"open Gyazo":"",onClick:async e=>{let t=e.match(/https:\/\/(?:thumb\.|i\.)?gyazo\.com\/([a-z0-9]+)/)?.[1];if(!t)return;if(!globalThis.GM_fetch){window.open(`https://gyazo.com/${t}`);return}let o=(await(await GM_fetch(`https://gyazo.com/${t}.json`)).json()).metadata?.ocr?.description;if(o)try{await navigator.clipboard.writeText(o)}catch(n){console.error(n),alert(`${n.name} ${n.message}`)}}});scrapbox.PopupMenu.addButton({title:e=>/https:\/\/gyazo\.com\/[a-z0-9]+/.test(e)?"":"",onClick:e=>{let t=e.match(/https:\/\/gyazo\.com\/([a-z0-9]+)/)?.[1];t&&window.open(`https://gyazo.com/${t}/transform`)}});var Uw=e=>{let t="",r=0;for(let o of e)if(o.type!=="title"){if(o.indent>r)for(let n=r;n<o.indent;n++)t+=Ls(`${n!==r?"\\item":""}\\begin{itemize}`,n*2)+`
`;if(o.indent<r)for(let n=r;n>o.indent;n--)t+=Ls("\\end{itemize}",(n-1)*2)+`
`;r=o.indent,t+=Ls(`${r>0?"\\item ":""}${RA(o)}`,r*2)+`
`}for(let o=r;o>0;o--)t+=Ls("\\end{itemize}",(o-1)*2)+`
`;return t},RA=e=>{switch(e.type){case"codeBlock":return kA(e);case"table":return vA(e);case"line":return _A(e)}},kA=e=>`\\begin{lstlisting}[language=${_t(PA(e.fileName))},caption=${_t(e.fileName)},label=lang:${e.fileName},numbers=left]
${e.content}
\\end{lstlisting}`,vA=e=>{let t=`\\caption{${_t(e.fileName)}}\\label{table:${_t(e.fileName)}}`,r=Math.max(...e.cells.map(n=>n.length)),o=e.cells.map(n=>` ${n.map(s=>s.map(i=>Cn(i)).join("")).join(" & ")}\\\\`);return`\\begin{table}[htbp]
${t}
\\centering
\\begin{tabular}{${"c".repeat(r)}}
${o.length===0?"":o.length===1?` \\toprule
${o.join(`
`)}
\\bottomrule`:` \\toprule
${o[0]}
\\midrule
${o.slice(1).join(`
`)}
\\bottomrule`}
\\end{tabular}
\\end{table}`},_A=e=>e.nodes.map(t=>Cn(t)).join(""),Cn=e=>{switch(e.type){case"quote":return`\\begin{quote}
${Ls(e.nodes.map(t=>Cn(t)).join(""),2)}
\\end{quote}`;case"image":case"strongImage":return`\\begin{figure}[hbtp]
iamge:\\url{${e.src}}
\\end{figure}`;case"icon":case"strongIcon":return`\\textit{${_t(e.path)}}`;case"strong":return`\\textbf{${e.nodes.map(t=>Cn(t)).join("")}}`;case"formula":return`$${e.formula}$`;case"decoration":{let t=e.nodes.map(r=>Cn(r)).join("");return e.decos.includes("/")&&(t=`\\textit{${t}}`),e.decos.some(r=>/\*-/.test(r[0]))&&(t=`\\textbf{${t}}`),e.decos.includes("_")&&(t=`\\uline{${t}}`),e.decos.includes("-")&&(t=`\\sout{${t}}`),t}case"numberList":return`${e.number}. ${e.nodes.map(t=>Cn(t)).join("")}`;case"helpfeel":return`\\lstinline!? ${_t(e.text)}!`;case"code":return`\\lstinline!${_t(e.text)}!`;case"commandLine":return`\\lstinline!${_t(e.symbol)} ${_t(e.text)}!`;case"link":return e.pathType==="absolute"?e.content===""?`\\url{${e.href}}`:`\\href{${e.href}}{${_t(e.content)}}`:_t(e.href);case"googleMap":return`\\href{${e.url}}{${_t(e.place)}}`;case"hashTag":return _t(`#${e.href}`);case"blank":case"plain":return _t(e.text)}},TA=[{extensions:["javascript","js"],fileType:"javascript"},{extensions:["typescript","ts"],fileType:"typescript"},{extensions:["cpp","hpp"],fileType:"C++"},{extensions:["c","cc","h"],fileType:"C"},{extensions:["cs","csharp"],fileType:"cs"},{extensions:["markdown","md"],fileType:"markdown"},{extensions:["htm","html"],fileType:"html"},{extensions:["json"],fileType:"json"},{extensions:["xml"],fileType:"xml"},{extensions:["yaml","yml"],fileType:"yaml"},{extensions:["toml"],fileType:"toml"},{extensions:["ini"],fileType:"ini"},{extensions:["tex","sty"],fileType:"tex"},{extensions:["svg"],fileType:"svg"}],PA=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return TA.find(r=>r.extensions.includes(t))?.fileType??""},_t=e=>e.replaceAll("\\","\\textbackslash ").replaceAll("#","\\#").replaceAll("%","\\%").replaceAll("$","\\$").replaceAll("&","\\&").replaceAll("~","\\textasciitilde ").replaceAll("^","\\textasciicircum ").replaceAll("_","\\_").replaceAll("{","\\{").replaceAll("}","\\}").replaceAll("|","\\textbar ").replaceAll("<","\\textless ").replaceAll(">","\\textgreater "),Ls=(e,t)=>e.split(`
`).map(r=>`${" ".repeat(t)}${r}`).join(`
`);scrapbox.PopupMenu.addButton({title:"TeX",onClick:e=>{navigator.clipboard.writeText(Uw(Be(e))).catch(t=>{console.error(t),alert(`${t.name} ${t.message}
${t.stack}`)})}});var wc="https://keicho.herokuapp.com/api/";var Dw=async(e,t)=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let r=await window.GM_fetch(`${wc}web/`,{mode:"cors",method:"POST",body:JSON.stringify({user:"nobody",talk:t,text:e}),headers:{"Content-Type":"application/json"}});if(!r.ok)return{ok:!1,value:{name:"ResponseError",res:r}};let o=await r.json();return{ok:!0,value:{text:o.text,buttons:o.buttons,canInput:o.can_input}}};var $w=()=>{let{popupMenu:e,render:t}=SA();Td()?.append?.(e);let r=$r(),o=()=>{requestAnimationFrame(()=>{let n=document.getElementsByClassName("cursor")[0];e.style.top=`${parseInt(n.style.top)+parseInt(n.style.height)+4}px`})};return r.addChangeListener(o),{render:t,visible:()=>!e.hidden,open:()=>e.hidden=!1,close:()=>e.hidden=!0,toggle:()=>e.hidden=!e.hidden,dispose:()=>{e.remove(),r.removeChangeListener(o)}}},SA=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"});t.innerHTML=`
<style>
:host {
position: absolute;
left: 0px;
width:100%;
z-index:300;
user-select:none;
font-family:"Open Sans",Helvetica,Arial,"Hiragino Sans",sans-serif;
pointer-events:none
}
.button-container {
position: relative;
display:inline-block;
max-width:70vw;
min-width:80px;
text-align:center;
background-color:#111;
padding:0 1px;
border-radius:4px;
pointer-events:auto
}
html[data-os*='android'] .button-container {
max-width:90vw
}
html[data-os*='ios'] .button-container {
max-width:90vw
}
.button {
font-size:11px;
color:#eee;
cursor:pointer;
display:inline-block;
padding:0 5px
}
.button:not(:first-of-type) {
border:0;
border-left:1px solid #eee
}
.button.selected {
background-color:#222;
text-decoration:underline
}
html[data-os*='android'] .button {
font-size:13px;
padding:6px;
min-width:12vw
}
html[data-os*='ios'] .button{
font-size:13px;
padding:6px;
min-width:12vw
}
.button div.icon {
height:2em;
max-width:10em;
display:inline-block;
overflow:hidden;
margin-left:1px;
vertical-align:top
}
.button div.icon img {
max-height:100%;
vertical-align:unset
}
</style>
<div class="button-container"></div>
`;let r=t.lastElementChild;return{popupMenu:e,render:(...o)=>{r.textContent="",r.append(...o.map(({text:n,onClick:s})=>{let i=document.createElement("div");return i.classList.add("button"),i.textContent=n,s&&i.addEventListener("click",()=>s()),i}))}}};var jw=async(e="normal")=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let t=await window.GM_fetch(`${wc}web/create/?mode=${e}`,{mode:"cors"});return t.ok?{ok:!0,value:await t.text()}:{ok:!1,value:{name:"ResponseError",res:t}}};var Bw=e=>`https://keicho.netlify.app/#talk=${e}`;var Hw=e=>{let t=e.split(`
`),r=t[1]??t[0],o=e===t[0]?"":t[0];return o?[o.trim(),r].join(`
`):r};var Rc=async(e,t,r)=>{let o=$r(),n=o.lines.findIndex(i=>i.id===t.id);n<0&&(n=o.lines.findIndex(i=>i.text===t.text)),n<0&&(n=Math.min(r,Math.max(0,o.lines.length-1)));let s=o.lines[n].text;return Ui().clear(),o.setPosition({line:n,char:[...s].length}),await Ye(`
${e}`),o.getPosition().line};var Ww=e=>Be(e,{hasTitle:!1}).map(t=>{if(t.type==="title")return t.text.trimEnd();let r=" ".repeat(t.indent);switch(t.type){case"codeBlock":return[`${r}${t.fileName}`,...t.content.split(`
`).map(o=>`${r} ${o}`)].join(`
`).trimEnd();case"table":return[`${r}${t.fileName}`,...t.cells.map(o=>`${r} ${o.flatMap(n=>n.map(s=>kc(s))).join(" ")}`)].join(`
`).trimEnd();case"line":return`${r}${t.nodes.map(o=>kc(o)).join("")}`.trimEnd()}}).join(`
`),kc=e=>{switch(e.type){case"quote":return`> ${e.nodes.map(t=>kc(t)).join("")}`;case"helpfeel":case"commandLine":return e.raw;case"strongImage":case"image":case"strongIcon":case"icon":case"googleMap":return"";case"strong":case"decoration":case"numberList":return e.nodes.map(t=>kc(t)).join("");case"formula":return`\\(${e.formula}\\)`;case"code":return` ${e.text} `;case"blank":case"plain":return e.raw;case"hashTag":return e.href;case"link":switch(e.pathType){case"absolute":return e.content?` ${e.content} `:"";case"root":return e.href.split("/").pop()??"";case"relative":return e.href}}};var An=e=>/^[((]/.test(e);var Vw=async e=>{let t=scrapbox.Page.lines;if(!t)return;let{cursor:r,selection:o}=Lt(),n=e?.entire||o.hasSelectionAll(),s=n?t.map(T=>T.text).join(`
`):o.getSelectedText(),i=e?.botIcon??"[/nishio/nisbot.icon]",{render:a,visible:c,open:l,close:u,dispose:p}=$w();u();let f=new Set,m=()=>{p();for(let T of f)T()},h=T=>f.add(T),g={text:"Exit",onClick:m},y=e?.talkId||Gw(s)||(n?"":Gw(t.slice(0,1+r.getPosition().line).map(T=>T.text).join(`
`))),x=!y;if(!y){let T=jw(e?.mode),S=setTimeout(()=>{a({text:"Start talking..."}),l();let M=0;S=setInterval(()=>{a({text:`Start talking${".".repeat(M%3)}`}),M++},1e3)},1e3),A=await T;if(clearTimeout(S),!A.ok){if(A.value.name==="GMFetchNotAvailableError"){alert("`GM_fetch` is not available. Please use Tampermonkey and install `GM_fethc`.");return}if(A.value.name==="ResponseError"){a({text:`Error: ${A.value.res.status} ${A.value.res.statusText}`},g),l(),console.error(`Error: ${A.value.res.status} ${A.value.res.statusText}`,await A.value.res.text());return}return}y=A.value}let E=y,k=o.normalizeOrder(o.getRange()),b=n?t.length-1:k.end.line,v=t[b],R=n?"":" ".repeat(Math.min(...t.slice(k.start.line,k.end.line+1).map(T=>br(T.text)))),O=async T=>{let S=await Dw(T,E);if(!S.ok)switch(S.value.name){case"ResponseError":return a({text:`Error: ${S.value.res.status} ${S.value.res.statusText}`},g),l(),console.error(`Error: ${S.value.res.status} ${S.value.res.statusText}`,await S.value.res.text()),S;case"GMFetchNotAvailableError":return alert("`GM_fetch` is not available. Please use Tampermonkey and install `GM_fethc`."),S}return S},L="",N=async T=>{let S=Ww(T).split(`
`).map(I=>I.trim()).join(`
`).trim();S.startsWith(L)&&(S=S.slice(L.length));let A=S.split(`
`);if(A.length===0)return;if(A.every(I=>An(I))&&(L=S),A.filter(I=>!An(I)).length<2){let I,z;for(let $ of A){if(z=await O($),!z.ok)return z;An($)||(I=z)}return I??z}let D=0;{let I;for(;D<A.length&&An(A[D]);D++)if(I=await O(A[D]),!I.ok)return I}{let I=await O("まず聞いて");if(!I.ok)return I}for(;D<A.length&&!An(A[D]);D++){let I=await O(A[D]);if(!I.ok)return I}return await O("おしまい")},P=async T=>{if(scrapbox.Layout!=="page"||T==="")return;let S=N(T),A=setTimeout(()=>{a({text:"Asking..."}),l();let $=0;A=setInterval(()=>{a({text:`Asking${".".repeat($%3)}`}),$++},1e3)},1e3),M=await S;if(clearTimeout(A),!M||!M.ok)return;let{text:D,buttons:I}=M.value,z=Hw(D);if(z.trim()){let $=`${R}${i}${z.includes(`
`)?`
${z.split(`
`).map(q=>` ${R}${q}`).join(`
`)}`:z}
${R}`;b=await Rc($,v,b),v=t[b]}a({text:"Send",onClick:_},{text:"🙂",onClick:()=>Ye("🙂")},{text:"🙁",onClick:()=>Ye("🙁")},...I.map($=>({text:$,onClick:async()=>{b=await Rc($,v,b),v=t[b],await P($)}})),g),l()},_=async()=>{if(scrapbox.Layout!=="page")return;let T=scrapbox.Page.lines,S=r.getPosition().line,[A,M,D]=OA(T,S,i);A!==""&&(b=D,v=T[b],R=" ".repeat(Math.min(...T.slice(M,D+1).map(I=>br(I.text)))),await P(A))};return x&&(b=await Rc(Bw(E),v,b),v=t[b]),await P(s),{ask:_,open:l,close:u,visible:c,exit:m,onExit:h}},Gw=e=>{for(let t of e.split(`
`).reverse()){let r=t.match(/https?:\/\/keicho\.netlify\.app\/#talk=(\w+)/)?.[1];if(r)return r}},OA=(e,t,r)=>{let o=Math.max(e.findLastIndex((s,i)=>i<t&&s.text.trim().startsWith(r)),1),n=o+mo(o,e)+1;return[e.slice(n,t+1).map(s=>s.text.trim()).join(`
`).trim(),n,t]};scrapbox.PopupMenu.addButton({title:"",onClick:e=>`[_ ${e}]`});scrapbox.PopupMenu.addButton({title:"",onClick:e=>`[$ ${e}]`});var zw=[ko,vo,_o];scrapbox.PopupMenu.addButton({title:e=>{let t=Rr({project:scrapbox.Project.name,mode:"noopen",hooks:zw});return!t||t.hookName.includes("default")?"":t.hookName.includes("task")?"":t.hookName.includes("split")?"":""},onClick:()=>{let e=window.prompt("Create a new page at",scrapbox.Project.name);e&&Rr({project:e,mode:"noopen",hooks:zw})?.()}});scrapbox.PopupMenu.addButton({title:e=>/(https?:\/\/[^\s]+)/g.test(e)?"":"",onClick:e=>{let t=e.replace(/(https?:\/\/[^\s]+)/g,"[$1#.jpg]");if(e!==t)return t}});scrapbox.PopupMenu.addButton({title:"S",onClick:e=>{window.open(`https://scrapbox.io/${scrapbox.Project.name}/search/page?q=${e}`)}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\[(.*)\]/g,"$1")).join(`
`);window.open(`https://www.google.com/search?q=${encodeURIComponent(t)}`)}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=o=>[...o].some(n=>n.charCodeAt(0)>255),r=e.split(/\n/).map(o=>o.replace(/\[(.*)\]/g,"$1")).join(`
`).trim().replace(/\s+/g,"+");t(r)?window.open(`https://www.ldoceonline.com/search/japanese-english/direct/?q=${encodeURIComponent(r)}`):window.open(`https://www.oxfordlearnersdictionaries.com/search/english/?q=${encodeURIComponent(r)}`)}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\[(.*)\]/g,"$1")).join(`
`);window.open(`https://www.google.com/search?q=${encodeURIComponent(t)}+site:scrapbox.io`)}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>`[" ${e}]`});scrapbox.PopupMenu.addButton({title:"🖍",onClick:e=>`[[${e}]]`});scrapbox.PopupMenu.addButton({title:e=>/\$([^$]+)\$/.test(e)?"L":"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\$([^$]+)\$/g,"[$ $1]")).join(`
`);if(e!=t)return t}});var LA=[Ou,Rw,Ou,vw,Sw,bc(),Ow,Ew(),kw,e=>{if(e.hostname!=="ekitan.com"||!/^\/transit\/(?:route|first|last)\//.test(e.pathname))return e;let t=e.searchParams.get("dt"),r=e.searchParams.get("tm"),o=e.searchParams.get("sr"),n=new URL(e);return n.search="",t&&n.searchParams.append("dt",t),n.pathname.startsWith("/transit/route/")&&(r&&n.searchParams.append("tm",r),o&&n.searchParams.append("sr",o)),n},e=>{if(e.host!==location.host||!e.pathname.startsWith("/api/code/"))return e;let t=encodeURIComponent(`${e.origin}${e.pathname}`);return`${e}`.endsWith(".svg")?`[https://svg-hosting.vercel.app/api/svg?url=${t} ${e}]`:`${e}`.endsWith(".mlt")?`[https://aa2svg.vercel.app/svg/${t}?width=1000 ${e}]`:e},e=>{if(e.hostname==="raw.githubusercontent.com")return`[https://code2svg.vercel.app/svg/${e.origin}${e.pathname}#.svg ${e}]`;if(e.hostname!=="github.com")return e;let[t,r,o]=e.pathname.match(/^\/([^\\]+)\/([^\\]+)\/blob\/(.+)$/)?.slice?.(1)??[];if(!t||!r||!o)return e;let[,n,s]=e.hash.match(/L(\d+)-L(\d+)/)??e.hash.match(/L(\d+)/)??[];return`[https://code2svg.vercel.app/svg/${n&&s?`L${n}-${s}/`:n?`L${n}/`:""}https://raw.githubusercontent.com/${t}/${r}/${o}#.svg ${e}]`},e=>e.hostname==="github.com"?`${e}`:e,Nw,Pw()];scrapbox.PopupMenu.addButton({title:e=>/https?:\/\/\S+/.test(e)?"URL":"",onClick:e=>{let t=Lw(e,...LA);if(typeof t=="string")return e===t?void 0:t;t.then(r=>{if(e!==r)return Ye(r)})}});Fw(["takker","takker-memex","takker-private","takker-books"]);if(!/mobile/i.test(navigator.userAgent)){let e=(t,r)=>{t.trim()!==""&&Vw({mode:r}).then(o=>{if(!o)return;let{ask:n,visible:s,onExit:i}=o,a=c=>{!s()||c.key!=="Enter"||!c.ctrlKey||c.altKey||c.shiftKey||(c.preventDefault(),c.stopPropagation(),n())};Xe().addEventListener("keydown",a),i(()=>Xe().removeEventListener("keydown",a))})};scrapbox.PopupMenu.addButton({title:()=>"🤖",onClick:t=>e(t)})}var Ns=(e,t)=>t.map(r=>r.replace(/@yyyy-MM-dd HH:mm:ss@/g,be(e,"yyyy-MM-dd HH:mm:ss")).replace(/@yyyy-MM-dd@/g,be(e,"yyyy-MM-dd")).replace(/@yyyy-MM-dd(?:([+-])(\d+)(w?))?(?:\((Sun|Mon|Tue|Wed|Thu|Fri|Sat)\))?@/g,(o,n,s,i,a)=>{let c=n?n==="+"?Fe(e,parseInt(s)*(i==="w"?7:1)):vr(e,parseInt(s)*(i==="w"?7:1)):e;return be(a?Fe(ft(c),NA(a)):c,"yyyy-MM-dd")}).replace(/@yyyy-ww@/g,`${yo(e)}-w${`${go(e)}`.padStart(2,"0")}`).replace(/@yyyy-ww([+-])(\d+)(w?)@/g,(o,n,s,i)=>{let a=n==="+"?Fe(e,parseInt(s)*(i==="w"?7:1)):vr(e,parseInt(s)*(i==="w"?7:1));return`${yo(a)}-w${`${go(a)}`.padStart(2,"0")}`}).replace(/@yyyy@/g,`${yo(e)}`).replace(/@yyyy([+-])(\d+)y@/g,(o,n,s)=>{let i=parseInt(s);return`${yo(e)+(n==="+"?i:-i)}`})),NA=e=>{switch(e){case"Sun":return 0;case"Mon":return 1;case"Tue":return 2;case"Wed":return 3;case"Thu":return 4;case"Fri":return 5;default:return 6}};var Kw=async(e,t,r,o=new Date(2023,1,3))=>{if(scrapbox.Project.name!==e)return()=>{};let n=scrapbox.Project.pages;await new Promise(l=>{let u=setInterval(()=>{if(n.length===0){n=scrapbox.Project.pages;return}clearInterval(u),l()},2e3)});let s=async()=>{let l=new Date,u={start:o,end:Fe(l,1)},{render:p,dispose:f}=Le(),m;try{let h=await qw(t),g=await qw(r),y=Wi(u).filter(b=>{let v=Ns(b,h)[0],R=n.find(O=>O.title===v);return!R||!R.exists}),x=Nh(u).filter(b=>{let v=Ns(b,g)[0],R=n.find(O=>O.title===v);return!R||!R.exists});if(y.length===0&&x.length===0)return;let E=y.length+x.length;p({type:"spinner"},{type:"text",text:`create ${E} review pages...`});let k=await Ve();if(B(k))throw re(k);m=H(k);for(let b of[...y.map(v=>Ns(v,h)),...x.map(v=>Ns(v,g))])await xe(e,b[0],(v,R)=>R.persistent?void 0:b,m?{socket:m}:{}),E--,p({type:"spinner"},{type:"text",text:`create ${E} review pages...`});p({type:"check-circle"},{type:"text",text:`created ${y.length+x.length} review pages.`}),o=l}catch(h){p({type:"exclamation-triangle"},{type:"text",text:h instanceof Error?`${h.name} ${h.message}`:"Unknown error! (see developper console)"}),console.error(h)}finally{m&&await rt(m),await Te(1e3),f()}},i=s(),a=new Date,c=setInterval(()=>{let l=new Date;dt(a,l)||(a=l,i.then(()=>i=s()))},1e4);return()=>(clearTimeout(c),i)},qw=async e=>{let t=await pi(e[0],e[1],e[2]);if(B(t)){let o=new Error;throw o.name=re(t).name,o.message=`${re(t).message} at fetching /${e[0]}/${e[1]}/${e[2]}`,o}let r=H(t).split(`
`);if(r.length===0)throw new Error(`template "/${e[0]}/${e[1]}/${e[2]}" is empty!`);return r};var Et=e=>`${e.getFullYear()}-${Yt(e.getMonth()+1)}-${Yt(e.getDate())}`,Cs=e=>{let[t,r,o]=e.split("-").map(n=>parseInt(n,10));return{year:t,month:r,date:o}},As=e=>`${qi(e)}-w${Yt(go(e))}`,vc=e=>{let[t,r]=e.split("-w").map(o=>parseInt(o,10));return ft(Lh(new Date(t,0,1),r))};var Xw="takker-memex",Yw=async(e=new Date(2023,0,24))=>{if(scrapbox.Project.name!==Xw)return()=>{};let t=scrapbox.Project.pages;await new Promise(i=>{let a=setInterval(()=>{if(t.length===0){t=scrapbox.Project.pages;return}clearInterval(a),i()},2e3)});let r=async()=>{let i=new Date,c=Wi({start:e,end:i}).filter(f=>{let m=Vr(f),h=t.find(g=>g.title===m);return!h||!h.exists});if(c.length===0)return;let{render:l,dispose:u}=Le(),p;try{l({type:"spinner"},{type:"text",text:`load tasks for ${c.length} diary pages`});let f=new Map,m=new Set,h=c.map(x=>Et(x));for(let{title:x,links:E,project:k}of await Pn(["takker","takker-memex"]))for(let b of[x,...E]){let v=ir(b);if(!v)continue;if(B(v)){let{name:L,message:N}=re(v);console.error(`[/${k}/${b}]: ${L} ${N}`);continue}let R=ne(b);if(m.has(R))continue;m.add(R);let O=H(v);if(O.freshness?.status!=="done")for(let L of c){let N=rs(O,L);if(!N)continue;let P=Et(N.base);h.includes(P)&&(f.set(P,[...f.get(P)??[],N]),qr(O))}}let g=await Ve();if(B(g))throw re(g);p=H(g);let y=0;l({type:"spinner"},{type:"text",text:`create 0/${c.length} diary pages...`});for(let x of c){let E=Vr(x),k=f.get(Et(x))?.map?.(R=>Pe(R))??[],b=`#${be(x,"yyyy-MM-dd")}`,v=`#${be(x,"yyyy-MM-dd HH:mm:ss")}`;await xe(Xw,E,(R,{persistent:O})=>{if(O)return;let L=[...R.map(N=>N.text),...k];return L.some(N=>N.includes(b))?wo(L):wo([...L,v])},{socket:p}),y++,l({type:"spinner"},{type:"text",text:`create ${y}/${c.length} diary pages...`})}l({type:"check-circle"},{type:"text",text:`created ${c.length} diary pages.`}),e=i}catch(f){l({type:"exclamation-triangle"},{type:"text",text:f instanceof Error?`${f.name} ${f.message}`:"Unknown error! (see developper console)"}),console.error(f)}finally{p&&await rt(p),await Te(1e3),u()}},o=r(),n=new Date,s=setInterval(()=>{let i=new Date;dt(n,i)||(n=i,o.then(()=>o=r()))},1e4);return()=>(clearTimeout(s),o)};Yw(new Date(2024,11,24));var Cu=(...e)=>{let t=e.flatMap(o=>{if(typeof o=="string")return[_c(o)];if(Array.isArray(o.type))return[Jw(o.type)];switch(o.type){case"text":return[_c(o.text)];case"group":{let n=Cu(...o.items);return n?[n]:[]}default:return[Jw(o.type)]}});if(t.length===0)return;if(t.length===1)return t[0];let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r},_c=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},Jw=e=>{if(Array.isArray(e)){let t=document.createElement("span");t.classList.add("fa-stack");let r=Nu(e[0]);r.classList.add("fa-stack-1x");let o=Nu(e[1]);return o.classList.add("fa-stack-1x"),t.append(r,o),_c(t)}return _c(Nu(e))},Nu=e=>{let t=document.createElement("i");switch(e){case"spinner":t.classList.add("fa","fa-spinner");break;case"check-circle":case"gyazo":case"ocr":case"calendar":case"trim":t.classList.add("kamon",`kamon-${e}`);break;case"markdown":case"google":t.classList.add("fab",`fa-${e}`);break;case"copy":case"clipboard":t.classList.add("far",`fa-${e}`);break;default:t.classList.add("fas",`fa-${e}`);break}return t};var{cursor:Au,selection:Mu}=Lt(),Zw=e=>{let{className:t,display:r,onClick:o,context:n="page"}=e,s=document.createElement("div");t&&s.classList.add(t),Qw(n)||(s.style.display="none");let i=(...l)=>{if(l.length===1&&l[0]===""){s.style.display="none";return}s.textContent="";let u=Cu(...l);u&&s.append(u)},a=typeof r=="function"?r({cursor:Au,selection:Mu}):r;return i(...Array.isArray(a)?a:[a]),s.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),o({cursor:Au,selection:Mu,setDisplay:i})}),{status:s,context:n,update:()=>{if(Qw(n)?s.removeAttribute("style"):s.style.display="none",typeof r=="function"){let l=r({cursor:Au,selection:Mu});i(...Array.isArray(l)?l:[l])}}}},Qw=e=>e!=="stream"?scrapbox.Layout===e:scrapbox.Layout==="list"&&location.pathname.startsWith("/stream");var eR=()=>{let e=document.createElement("style");e.textContent=`.status-bar.left {
position: absolute;
top: 0;
left: 0;
max-width: 80vw;
overflow-x: auto;
overflow-y: hidden;
}
.status-bar.left:empty {
display: none;
}
.status-bar.left > div {
border-left: unset;
}
.status-bar.left > div {
border-right: 1px solid var(--tool-light-color, #a9aaaf);
}
.status-bar.left > div:first-of-type {
border-top-left-radius: unset;
}
.status-bar.left > div:last-of-type {
border-top-right-radius: 3px;
}`,document.head.append(e);let t=document.createElement("div");return t.classList.add("status-bar","left"),document.getElementsByClassName("footer")[0].append(t),t};var Iu=new Set,{cursor:CA,selection:AA}=Lt(),MA=eR();var zt=e=>{let t=Zw(e);return Iu.add(t),MA.append(t.status),()=>{t.status.remove(),Iu.delete(t)}},Fu=()=>{for(let{update:e}of Iu)e()};CA.addChangeListener(()=>Fu());AA.addChangeListener(()=>Fu());scrapbox.addListener("layout:changed",Fu);var tR=async(e,t)=>{try{let r=t.getSelectedText()||ot(e.getPosition().line);if(!r)return;await navigator.clipboard.writeText(r)}catch(r){console.error(r),alert(`Faild to copy:
${JSON.stringify(r)}`)}},rR=async(e,t)=>{try{let r=t.hasSelection(),o=r?t.getRange().start.line:e.getPosition().line,n=r?t.getSelectedText():ot(o);if(!n)return;await navigator.clipboard.writeText(n),r||t.setRange({start:{line:o,char:0},end:{line:o,char:n.length}}),e.focus(),He("Delete")}catch(r){console.error(r),alert(`Faild to cut:
${JSON.stringify(r)}`)}},oR=async e=>{try{let t=await navigator.clipboard.readText();if(!t)return;e.focus(),await Ye(t)}catch(t){console.error(t),alert(`Faild to paste:
${JSON.stringify(t)}`)}},nR=e=>{e.getVisible()&&e.hasFocus&&e.visiblePopupMenu?e.hide():(e.focus(),e.showEditPopupMenu())};globalThis.addEventListener("keydown",e=>{if(e.key!=="i"||e.shiftKey||e.altKey||e.metaKey||!e.ctrlKey||e.isComposing)return;let t=$r();t.hasFocus||(e.preventDefault(),t.focus())});var Uu=class{get editor(){return document.getElementById("editor")}get lines(){return document.getElementsByClassName("lines")?.[0]}get computeLine(){return document.getElementById("compute-line")}get grid(){return document.getElementsByClassName("related-page-list clearfix")?.[0]?.getElementsByClassName("grid")?.[0]}get cursorLine(){return document.getElementsByClassName("cursor-line")?.[0]}get textInput(){return document.getElementById("text-input")}get cursor(){return document.getElementsByClassName("cursor")?.[0]}get selections(){return document.getElementsByClassName("selections")?.[0]}get popupMenu(){return document.getElementsByClassName("popup-menu")?.[0]}get pageMenus(){return document.getElementsByClassName("page-menu")?.[0]}get pageInfoMenu(){return document.getElementById("page-info-menu")}get pageEditMenu(){return document.getElementById("page-edit-menu")}get pageEditButtons(){return this.pageEditMenu.nextElementSibling.getElementsByTagName("a")}get randomJumpButton(){return document.getElementsByClassName("random-jump-button")?.[0]}get pageCustomButtons(){return document.getElementsByClassName("page-menu-extension")}},sR=new Uu;var iR=e=>new Promise(t=>setTimeout(t,e));async function er(e,{wait:t=1}={}){let r=sR.textInput;r.focus(),r.value=e;let o=document.createEvent("UIEvent");o.initEvent("input",!0,!1),r.dispatchEvent(o),await iR(t)}if(Bo()){let e="Timestamp";scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/add-time.png"}),scrapbox.PageMenu(e).addItem({title:"#YYYY-MM-DD HH:mm:ss ",onClick:()=>er(be(new Date,"#yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD HH:mm:ss ",onClick:()=>er(be(new Date,"yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD",onClick:()=>er(be(new Date,"yyyy-MM-dd"))}),scrapbox.PageMenu(e).addItem({title:"HH:mm:ss ",onClick:()=>er(be(new Date,"HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"⬜",onClick:()=>er("⬜")}),scrapbox.PageMenu(e).addItem({title:"🚧",onClick:()=>er("🚧")}),scrapbox.PageMenu(e).addItem({title:"⌛",onClick:()=>er("⌛")}),scrapbox.PageMenu(e).addItem({title:"📝",onClick:()=>er("📝")}),scrapbox.PageMenu(e).addItem({title:"✅",onClick:()=>er("✅")}),scrapbox.PageMenu(e).addItem({title:"❌",onClick:()=>er("❌")})}scrapbox.PageMenu.addItem({title:"Open kakeru",image:"https://i.kakeru.app/15c3b1a40b6b3c2ebd68f33f4c86b3f6-opaque.png",onClick:()=>window.open("https://kakeru.app")});var IA=()=>{let e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.right="0",e.style.textAlign="right",e},Mn=new Map,Tc,Du=()=>{for(let e of Mn.values())e.remove();if(Mn.clear(),scrapbox.Layout!=="page"||scrapbox.Project.name!=="takker-memex"){if(scrapbox.removeListener("lines:changed",Pc),!Tc)return;clearInterval(Tc),Tc=void 0;return}Pc(),scrapbox.addListener("lines:changed",Pc),Tc=setInterval(Pc,60*1e3)},Pc=()=>{let e=mt();for(let t of e){let r=at(t.text);if(!r?.record?.start){Mn.get(t.id)?.remove?.(),Mn.delete(t.id);continue}let o=Yn(r.record.end??new Date,r.record.start),n=Math.round(o/30),s=n>20?`🍅x${(o/30).toFixed(1)}`:"🍅".repeat(n),i=Mn.get(t.id)??IA();Er(t.id)?.append?.(i),Mn.set(t.id,i),i.textContent=s}};Du();scrapbox.addListener("page:changed",Du);scrapbox.addListener("lines:changed",Du);async function aR(e,{from:t,to:r,merge:o}){if(t===r)return{success:!0,dup:!1};let n=await Dt(t,e);if(B(n))return{success:!1,at:"from",name:re(n).name,message:re(n).message};let s=H(n);if(!s.persistent)return{success:!1,at:"from",name:"EmptyPageError",message:"The request page is empty."};let i=await Dt(r,e);if(B(i))return{success:!1,at:"to",name:re(i).name,message:re(i).message};let a=H(n);return a.persistent&&!o?{success:!1,at:"to",name:"NoEmptyPageError",message:`The same page already exists in "/${r}"`}:(await xe(r,e,c=>[...c,...s.lines.slice(1)].map(l=>l.text)),await _f(t,e),{success:!0,dup:a.persistent})}var $u=async()=>{let e=scrapbox.Page.title,t=scrapbox.Project.name,r=globalThis.prompt(`Take "/${t}/${e}" from "${t}" to:`,"takker");if(!r)return;let{render:o,dispose:n}=Le();o({type:"spinner"},{type:"text",text:`/${t}/${e} → /${r}/${e}`});try{let s=await aR(e,{from:t,to:r,merge:!0});if(!s.success){o({type:"exclamation-triangle"},{type:"text",text:`${s.name} ${s.message}`});return}return o({type:"check-circle"},{type:"text",text:`Moved ${s.dup?"and merged ":""}to "/${r}/${e}".`}),`https://scrapbox.io/${r}/${me(e)}`}catch(s){o({type:"exclamation-triangle"},{type:"text",text:s instanceof Error?`${s.name} ${s.message}`:"Unknown error! (see developper console)"}),console.error(s)}finally{setTimeout(()=>n(),1e3)}};scrapbox.PageMenu.addItem({title:"Transport",onClick:async()=>{await $u()}});scrapbox.PageMenu.addItem({title:"Transport and Open",onClick:async()=>{let e=await $u();e&&window.open(e)}});var ju=e=>e.replace(/[\[\]]/g,"").replace(/\s/g," "),Ho=e=>`${e}`.padStart(2,"0"),cR=e=>`${e.getFullYear()}-${Ho(e.getMonth()+1)}-${Ho(e.getDate())} ${Ho(e.getHours())}:${Ho(e.getMinutes())}:${Ho(e.getSeconds())}`,Bu=e=>`${e.getFullYear()}-${Ho(e.getMonth()+1)}-${Ho(e.getDate())}`;var lR=async(e,t,r,o)=>{let{render:n,dispose:s}=Le(),i=[],a=[];for(let l of FA(r)){if(l.type==="line"){i.push(`[${ju(l.text)}~@${Bu(new Date)}]`);continue}let u=`${ju(l.lines[0])}~@${Bu(new Date)}`;a.push([u,...l.lines.slice(1),"",`#${cR(new Date)}`]),i.push(`[${u}]`)}let c=H(await Ve(o?.socket));try{n({type:"spinner"},{type:"text",text:`Adding ${i.length} items...`}),await xe(e,t,l=>{let u=l.map(f=>f.text),p=u.flatMap((f,m)=>f.trim()==="[/icons/hr.icon]"?[m]:[]).pop()??-1;return p<0?[...u,...i]:[...u.slice(0,p),...i,...u.slice(p)]},{socket:c}),n({type:"spinner"},{type:"text",text:`Create ${a.length} pages...`}),await Promise.all(a.map(l=>xe(e,l[0],u=>[u[0].text,...u.slice(1).map(p=>p.text),...l.slice(1)],{socket:c}))),n({type:"check-circle"},{type:"text",text:"Added to the inbox."})}catch(l){n({type:"exclamation-triangle"},{type:"text",text:"Failed to add (see console). Write directory instead."}),console.error(l),Kn(e,t,[...i,...a].join(`
`))}finally{let l=Te(1e3);o?.socket&&await rt(c),await l,s()}};function*FA(e){let t=0;for(;t<e.length;){let r=jh(t,e);if(r===0){yield{type:"line",text:e[t].trim()},t++;continue}let o=zr(e[t]);yield{type:"block",lines:e.slice(t,t+r+1).map(n=>n.slice(o))},t+=r+1}}var pR=async(e,t)=>{let r=window.prompt("Type all you think of","");if(!r||r.trim()==="")return;let o=r.trim().split(/\s+/);await lR(e,t,o)};var UA="button.";document.getElementById("editor").addEventListener("click",async e=>{let t=e.target;if(t.tagName==="IMG"&&t.classList.contains("icon")&&t.title.endsWith("-button")){e.preventDefault(),e.stopImmediatePropagation();try{let r=`../${encodeURIComponent(t.title)}/${UA}`,{execute:o}=await import(r);o()}catch(r){console.log(r)}}});scrapbox.PageMenu.addItem({title:"Copy link for Markdown",onClick:()=>{let e=scrapbox.Page.title.replaceAll(" ","_").replace(/[/?#\{}^|<>]/g,t=>encodeURIComponent(t));navigator.clipboard.writeText(`[${scrapbox.Page.title}](https://${location.hostname}/${scrapbox.Project.name}/${e}${location.hash})`).catch(t=>alert(`${t.name}: ${t.message}`))}});var Ms=e=>_n(...C(()=>{let t={tasks:[],errors:[],load:async()=>{},loading:!1},r=Promise.resolve();return[o=>{t.load=()=>(r=(async()=>{await r,t={...t,loading:!0},o(),await sc(e,60),t={...t,loading:!1},o()})(),r);let n=()=>{r=(async()=>{await r,t={...t,loading:!0},o();let[s,i]=DA(await Pn(e));t={...t,tasks:s,errors:i,loading:!1},o()})()};return n(),nc(e,n)},()=>t]},e)),DA=e=>{let t=new Set,r=[],o=[];for(let{title:n,links:s,project:i}of e)for(let a of[n,...s]){let c=ne(a);if(t.has(c))continue;t.add(c);let l=ir(a);if(l){if(B(l)){o.push({project:i,title:a,...re(l)});continue}r.push({project:i,title:a,...H(l)})}}return[r,o]};var Sc=()=>{let[e,t]=Dr($A,{isOpen:!1,prevOverflowY:""}),r=qe(null),o=F(()=>{t(i=>{r?.current?.showModal?.();let a=r?.current?.open??!1,c=i.isOpen?i.prevOverflowY:document.documentElement.style.overflowY;return document.documentElement.style.overflowY="hidden",{isOpen:a,prevOverflowY:c}})},[]),n=F(()=>{t(i=>{r?.current?.close?.();let a=r?.current?.open??!1;return a?{isOpen:a,prevOverflowY:i.prevOverflowY}:(i.prevOverflowY?document.documentElement.style.overflowY=i.prevOverflowY:document.documentElement.style.removeProperty("overflow-y"),{isOpen:a})})},[]),s=C(()=>{let i;return a=>{if(!a){i?.(),r.current=null;return}let c=new AbortController;a.addEventListener("cancel",n,{signal:c.signal}),a.addEventListener("click",l=>{if(l.target!==l.currentTarget){l.stopPropagation();return}n()},{signal:c.signal}),i=()=>{c.abort()},r.current=a}},[n]);return{isOpen:e.isOpen,open:o,close:n,ref:s}},$A=(e,t)=>{let r=t(e);return e.isOpen===r.isOpen&&e.prevOverflowY===r.prevOverflowY?e:r.isOpen?r:{isOpen:!1}};var Is=String.raw`.fa,.far{font-weight:900;font-family:"Font Awesome 5 Free";-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:inline-block;font-style:normal;font-variant:normal;text-rendering:auto;line-height:1}.far{font-weight:400}.fa-spinner{animation:spin 2s infinite linear}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(359deg)}}.fa-spinner:before{content:"\f110"}.fa-sync:before{content:"\f021"}.fa-bookmark:before{content:"\f02e"}.fa-fw{text-align:center;width:1.25em}.kamon:before{font-family:AppIcons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-style:normal;font-variant:normal;font-weight:400;text-decoration:none;text-transform:none}.kamon-check-circle:before{content:"\e018"}.timeline-wrap{display:flex;flex-direction:column;height:100%;overflow-y:hidden;--timeline-bg: var(--dropdown-menu-bg, #fff);--timeline-text-color: var(--page-text-color, #4a4a4a);--timeline-link-color: var(--page-link-color, #5e8af7);--row-header-width: 40px;--timeline-border-color: #888;--timeline-border: solid 1px var(--timeline-border-color);--timeline-hour-height: 40px;background-color:var(--timeline-bg);color:var(--timeline-text-color);.column-header{flex:none;display:flex;flex-direction:row;.cell{flex:1 1 1px;h2{font-weight:400;margin:0;text-align:center;width:100%}}}.week-container{position:relative;height:100%;overflow-y:auto;scrollbar-width:none;.week{flex:auto;display:flex;width:100%;.borders{.border{height:var(--timeline-hour-height)}.border:after{content:attr(data-time);font-size:10px;text-align:right;border-top:var(--timeline-border);position:absolute;width:100%;margin-top:-1px;pointer-events:none}}.timeline{flex:auto;border-left:var(--timeline-border);position:relative;.indicator{position:absolute;top:calc(var(--start) * 40px - .5px);width:100%;height:1px;background-color:red}.copy{position:absolute;top:1.5em}.event{position:absolute;top:calc(var(--start) * 40px - 1px);height:calc(40px * var(--duration) / 60);outline:none;--event-bg2: var(--timeline-text-color);--event-bg: var(--timeline-bg);--event-bg-ratio: 50%;--event-color-ratio: 0%;--event-border-color-ratio: 0%;background-color:color-mix(in srgb,var(--event-bg) var(--event-bg-ratio),var(--event-bg2));color:color-mix(in srgb,var(--event-bg) var(--event-color-ratio),var(--timeline-text-color));border:var(--timeline-border);border-color:color-mix(in srgb,var(--event-bg) var(--event-border-color-ratio),var(--timeline-border-color));border-radius:4px;overflow:hidden;text-wrap:nowrap;max-width:100%;text-overflow:ellipsis}.event[data-status=done]{--event-bg-ratio: 90%;--event-color-ratio: 50%;--event-border-color-ratio: 50%}.event[data-status=expired]{font-weight:700}a.event{--event-bg2: var(--timeline-link-color);text-decoration:none}}.timeline:first-child{border-right:var(--timeline-border)}}}}.wedget{position:fixed;top:60px;left:10px;max-height:calc(90vh - 60px);max-width:100px;width:calc(100vw / 767 * 100 - 10px);min-width:60px;border:solid 1px #888;border-radius:4px;display:flex;flex-direction:column;background-color:var(--dropdown-menu-bg, #fff);color:var(--page-text-color, #4a4a4a);&:not(.open){display:none}}dialog{flex-direction:column;align-items:center;row-gap:10px;&::backdrop{background-color:#000c}padding:10px;background:unset;margin-top:unset;margin-bottom:unset;border:unset;height:unset;overflow-y:hidden;&[open]{display:flex}>*{color:var(--page-text-color, #4a4a4a);background-color:var(--dropdown-menu-bg, #fff);border:1px solid rgba(0,0,0,.2);border-radius:6px}}@media (min-width: 768px){dialog{padding:30px 0;--item-width: 600px}}.result{padding:15px;width:calc(var(--item-width, 100%) - 30px);overflow-y:scroll}.controller{padding:5px;width:calc(var(--item-width, 100%) - 10px);display:flex;flex-wrap:wrap;flex:none;gap:.2em}.progress{flex-grow:1;>*{padding:0 2px}}a{text-decoration:none;color:var(--page-link-color, #5e8af7);&:hover{color:var(--page-link-hover-color, #2d67f5)}}button{cursor:pointer;background:unset;color:unset;border:unset}.copy,.close,.today{font-family:"Font Awesome 5 Free"}.navi{font-family:AppIcons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-style:normal;font-variant:normal;font-weight:400;text-decoration:none;text-transform:none}.close,.today{font-weight:900}ul{list-style-type:none;word-break:break-all}.task-list li:not([data-freshness^="-"]):not([data-freshness="0"]){font-weight:700}.scheduler details li{&[data-status=done]{opacity:.4}&[data-status=expired]{font-weight:700}}.task-list li{&[data-type=deadline] .label.type{color:var(--takker-scheduler-label-deadline-color, rgb(255, 75, 0))}&[data-type=todo] .label.type{color:var(--takker-scheduler-label-todo-color, rgb(246, 170, 0))}&[data-type=note] .label.type{color:var(--takker-scheduler-label-note-color, rgb(200, 200, 203))}&[data-type=up-down] .label.type{color:var(--takker-scheduler-label-up-down-color, rgb(77, 196, 255))}}:is([data-page-no=expired],[data-page-no=errors]) li{opacity:1!important}.scheduler{--takker-scheduler-summary-meter-width: 10em;overflow-y:hidden}.label{display:inline-block;font-size:90%;padding:0 3px}.type{text-align:center;width:2.5em;border:1px solid;border-radius:3px}.freshness{text-align:right;width:2.5em}.start,.duration{text-align:right;width:3em}
`;var In=({text:e,title:t})=>{let[r,o]=J(""),n=F(async s=>{s.preventDefault(),s.stopPropagation();try{await navigator.clipboard.writeText(e),o("Copied"),await Te(1e3),o("")}catch(i){alert(`Failed to copy the code block
Error:${i instanceof Error?i.message:i}`),console.error(i)}},[e]);return d("button",{className:"copy",title:t??"Copy",onClick:n,children:r})};var jA=60*60*24*1e3,uR=(e,t)=>{let r=ge(e.refDate),o=(t.getTime()-r.getTime())/jA;switch(r.setHours(0),r.setMinutes(0),e.status){case"done":return-1/0;case"deadline":return o/(e.speed??1);case"todo":return Math.min(o/(e.speed??1),0);case"note":return t.getTime()<r.getTime()?-1/0:-o/(e.speed??1);case"up-down":{let n=e.speed??30;return n*(-1+Math.cos(Math.PI*2*o/n))}}};var fR=(e,t)=>{if(t.score!==e.score)return t.score-e.score;let r=mR(e.freshness),o=mR(t.freshness);return r!==o?o-r:jt(cr(e),cr(t))?-1:1},mR=e=>{switch(e.status){case"todo":return 3;case"note":return 2;case"deadline":return 5;case"up-down":return 1;case"done":return 0}};var Fs=({loading:e,onClick:t})=>e?d("div",{children:d("i",{className:"fa fa-spinner"})}):d("button",{className:"navi reload",onClick:t,children:""});var Fn=()=>{let[e,t]=J(new Date);return oe(()=>{let r=setInterval(()=>t(new Date),6e4);return()=>{clearInterval(r)}},[]),e};var dR=e=>{switch(e){case"todo":return"ToDo";case"note":return"覚書";case"deadline":return"締切";case"up-down":return"浮遊";case"done":return"完了"}};var hR=(e,t)=>new URL(`/${e.project}/${me(e.title)}`,t??location.href);var Oc=({children:e,project:t,title:r,className:o,...n})=>d("a",{...n,className:[o??"","page-link"].join(" "),type:"link",href:hR({project:t,title:r}).pathname,...t===scrapbox.Project.name?{rel:"route"}:{rel:"noopener noreferrer",target:"_blank"},children:e});var gR=({action:e,pActions:t})=>{let r=C(()=>dR(e.freshness.status),[e.freshness.status]),o=C(()=>sr(cr(e)).slice(11)||" ",[cr(e)]),n=C(()=>ts(e),[e]),s=Math.floor(Math.round(e.score)/7),i=Fn(),a=C(()=>e.executed!==void 0&&xo(Wr(ge(e.executed.start),e.executed.duration),i),[e.executed?.start,e.executed?.duration,i]),c=C(()=>[...t,e].map(l=>`[${l.raw}]`).join(`
`),[t,e]);return d("li",{"data-type":e.freshness.status,"data-freshness":e.score.toFixed(0),"data-level":s,...s<0?{style:{opacity:BA(e).toFixed(2)}}:{},children:[d(In,{text:c,title:"ここまでコピー"}),d("span",{className:"label type",children:r}),d("i",{className:`label far fa-fw${a?" fa-bookmark":""}`}),d("span",{className:"label freshness",children:e.score.toFixed(0)}),d("time",{className:"label start",children:o}),d("span",{className:"label duration",children:[n,"m"]}),d(Oc,{project:e.project,title:e.raw,children:e.name})]})},BA=e=>Math.max(.8*Math.exp(Math.log(8/7)/7*e.score),.05);var yR=(e=Et(new Date))=>{let[t,r]=J(e),o=F(()=>{r(s=>{switch(s){case"errors":return"expired";case"expired":return Et(new Date);default:{let i=ge(Cs(s));return i.setDate(i.getDate()+1),Et(i)}}})},[]),n=F(()=>{r(s=>{let i=Et(new Date);switch(s){case"errors":return"errors";case"expired":return"errors";case i:return"expired";default:{let a=ge(Cs(s));return a.setDate(a.getDate()-1),Et(a)}}})},[]);return{pageNo:t,next:o,prev:n}};var Lc=(e,t)=>oe(()=>(scrapbox.on(e,t),()=>scrapbox.off(e,t)),[]);var Us=(e,t)=>{let r=qe({...t});oe(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),oe(()=>{e(r.current)},[e])};var xR=e=>{let t=document.createElement("div");t.dataset.userscriptName="takker-workflow@0.0.1/next-action-viewer";let r=t.attachShadow({mode:"open"});return document.body.append(t),new Promise(o=>ut(d(HA,{getController:o,projects:e}),r))},HA=({getController:e,projects:t})=>{let{tasks:r,errors:o,load:n,loading:s}=Ms(t),{pageNo:i,next:a,prev:c}=yR(),l=C(()=>{if(i==="errors")return o.map(g=>({name:`${g.title}
name:${g.name}
message:${g.message}`,raw:g.title,freshness:{refDate:{year:9999,month:1,date:1},status:"todo"},project:g.project,generated:!0,score:0}));if(i==="expired"){let g=new Date;return r.flatMap(y=>!ar(y)&&jt(Kh(y),xt(g))&&y.freshness===void 0&&y.recurrence===void 0?[{...y,score:0,freshness:{refDate:y.executed.start,status:"todo"}}]:[]).sort((y,x)=>jt(cr(y),cr(x))?-1:0)}let h=ge(Cs(i));return r.flatMap(g=>{if(!g.freshness)return[];if(qr(g))return[];let y=uR(g.freshness,h);return y>-999?[{...g,score:y}]:[]}).sort(fR)},[r,o,i]),{ref:u,open:p,close:f}=Sc();Us(e,{open:p,close:f});let m=C(()=>[i,...l.map(h=>` [${h.raw}]`)].join(`
`),[l,i]);return Lc("page:changed",f),d(Y,{children:[d("style",{children:Is}),d("dialog",{ref:u,children:[d("div",{className:"controller",children:[d(In,{text:m,title:"Copy All Tasks"}),d("span",{children:i}),d("button",{className:"navi left",onClick:c,children:""}),d("button",{className:"navi right",onClick:a,children:""}),d(Fs,{loading:s,onClick:n}),d("button",{className:"close",onClick:f,children:""})]}),d("ul",{className:"result task-list","data-page-no":i,children:l.map((h,g)=>d(gR,{action:h,pActions:l.slice(0,g)},h.raw))})]})]})};var Cc=(e,t)=>`/${e}/${ne(t)}`,Ds=new Map,Hu=new Map,bR=(e,t)=>{Ds.set(e,t);for(let r of Hu.get(e)??[])r(t)},Nc=()=>{Wo!==void 0&&(clearInterval(Wo),Wo=void 0);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=Cc(e,t);if(!Ds.has(r))return;let o=mt().map(n=>n.text);Wo=setInterval(()=>{ne(t)===ne(o[0])&&(bR(r,o),Wo!==void 0&&(clearInterval(Wo),Wo=void 0))},1e3)},Wo;scrapbox.on("page:changed",()=>{scrapbox.off("lines:changed",Nc);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=Cc(e,t);Ds.has(r)&&scrapbox.on("lines:changed",Nc)});var WA=(e,t)=>{let r=Cc(e,t),o=Ds.get(r);return o||(Ds.set(r,[]),Dt(e,t).then(n=>{if(B(n))return[];let s=H(n).lines.map(i=>i.text);bR(r,s),t===scrapbox.Page.title&&!scrapbox.listeners("lines:changed").includes(Nc)&&scrapbox.on("lines:changed",Nc)})),o??[]},ER=(e,t)=>{let[r,o]=J(WA(e,t));return oe(()=>{let n=Cc(e,t),s=Hu.get(n)??new Set;return s.add(o),Hu.set(n,s),()=>{s.delete(o)}},[e,t]),r};var Wu=e=>e.duration===void 0?void 0:xt(Wr(ge(e.start),e.duration)),Gu=(e,t)=>{let r=ge(e.start),o=t.getTime(),n=Math.round((o-r.getTime())/(60*1e3));if(n<=0)return[void 0,e];if(e.duration<=n)return[e,void 0];let s={start:e.start,duration:n};return[s,{start:Wu(s),duration:e.duration-n}]};var Go=e=>"title"in e,GA=e=>e.record?.duration!==void 0,wR=(e,t)=>Go(e)&&e.status==="done"?e.status:GA(e)?Go(e)&&e.executed?jt(xt(t),e.executed.start)?"moved":"expired":"done":jt(Wu(e.plan),xt(t))?Go(e)?"expired":"done":"undone";var RR=(e,t)=>{let r=ir(e.title.slice(1,-1));if(!e.plan.start)return;let o={name:r&&Ne(r)?H(r).name:e.title,plan:{start:xt(e.plan.start),duration:(e.plan.duration??0)/60}};if(e.record.start&&(o.record={start:xt(e.record.start)},e.record.end&&(o.record.duration=Yn(e.record.end,e.record.start))),!r||B(r))return o;let n=H(r),s={...o,title:n.raw,project:t};return n.freshness&&(s.status=n.freshness.status),ar(n)||(s.executed=n.executed),s},Vu=(e,t)=>{let r=Ji(e);return r!==void 0?{name:e.name,project:t,title:r,executed:e.executed,plan:e.executed,status:e.freshness?.status}:{name:e.name,plan:e.executed}};var kR=(e,t,r)=>{let o=[zu(e,vr(t,1),r),zu(e,t,r),zu(e,Fe(t,1),r)],n=C(()=>o.flat(),o);return C(()=>{let s=jr(t),i=Ph(t);return n.flatMap(a=>{let[,c]=Gu(a.plan,s);if(!c)return[];let[l]=Gu(c,i);if(!l)return[];let{plan:u,...p}=a;return[{plan:l,...p}]}).sort((a,c)=>jt(a.plan.start,c.plan.start)?-1:0)},[n,t])},zu=(e,t,r)=>{let o=ER(e,Vr(t)),n=C(()=>zA(o,e),[o,e]);return C(()=>n.length!==0?n:VA(t,r),[n,t,r])},VA=(e,t)=>t.flatMap(r=>{if(r.freshness?.status==="done")return[];if(ar(r))return[];if(qr(r)){let n=Yi(r,e);return n?[Vu(n,r.project)]:[]}let o=ge(r.executed.start);return dt(o,e)?[Vu(r,r.project)]:[]}),zA=(e,t)=>{let r=[];for(let o of bo(e)){if(Gr(o))continue;let n=RR(o,t);n&&r.push(n)}return r};var vR=({event:e})=>{let t=C(()=>e.plan.start.hours+e.plan.start.minutes/60,[e.plan.start]),r=C(()=>`--start: ${t}; --duration: ${e.plan.duration};`,[t,e.plan.duration]),o=Fn(),n=C(()=>wR(e,o),[e,o]);return Go(e)?d(Oc,{className:"event","data-status":n,style:r,title:e.title,project:e.project,children:e.name}):d("div",{className:"event","data-status":n,title:e.name,style:r,children:e.name})};var _R=({project:e,date:t,tasks:r})=>{let o=kR(e,t,r),n=C(()=>o.flatMap(a=>Go(a)?[`[${a.title}]`]:[]).join(`
`),[o]),s=Fn(),i=C(()=>dt(s,t)?d("div",{className:"indicator",style:`--start: ${_h(s)+Rh(s)/60}`}):d(Y,{}),[s,t]);return d("div",{className:"timeline",role:"gridcell",children:[o.map(a=>d(vR,{event:a},a.name)),i,d(In,{text:n})]})};var qu=({dateList:e,tasks:t,project:r,hasColumn:o})=>d("div",{className:"timeline-wrap",role:"grid",children:[(o??!0)&&d("div",{className:"column-header",role:"row",children:e.map(n=>d("div",{className:"cell",role:"columnheader",children:d("h2",{children:zi(n)})},Et(n)))}),d("div",{className:"week-container",role:"presentation",children:d("div",{className:"week",role:"presentation",children:[d("div",{className:"borders",children:[...Array(24).keys()].map(n=>d("div",{className:"border","data-time":`${Yt(n)}:00`},n))}),e.map(n=>d(_R,{project:r,date:n,tasks:t},Et(n)))]})})]});var Ku=(e,t,r)=>{let[o,n]=J(e),s=F(()=>n(t),[t]),i=F(()=>n(r),[t]),a=F(c=>n(c),[]);return{pageNo:o,next:s,prev:i,jump:a}};var TR=e=>{let t=qe(new Set),[r,o]=J(e),n=F(()=>{for(let l of t.current)l()},[]),s=F(()=>{o(!0),n()},[]),i=F(()=>o(!1),[]),a=F(()=>o(l=>(l||n(),!l)),[]),c=F(l=>(t.current.add(l),()=>t.current.delete(l)),[]);return{isOpen:r,open:s,close:i,toggle:a,onOpen:c}};var OR=e=>{let t=document.createElement("div");t.dataset.userscriptName="takker-scheduler/weekly-scheduler";let r=t.attachShadow({mode:"open"});return document.body.append(t),new Promise(o=>ut(d(qA,{getController:o,projects:e,mainProject:e[0]}),r))},LR=(e,t)=>{let r=document.createElement("div");r.dataset.userscriptName="takker-scheduler/timeline-wedget";let o=r.attachShadow({mode:"open"});return document.body.append(r),new Promise(n=>ut(d(KA,{getController:n,projects:e,mainProject:e[0],open:t}),o))},PR=!1,qA=({getController:e,projects:t,mainProject:r})=>{let{tasks:o,load:n,loading:s}=Ms(t),{pageNo:i,next:a,prev:c,jump:l}=Ku(As(new Date),XA,YA),u=C(()=>{let y=vc(i);return[0,1,2,3,4,5,6].map(x=>Fe(y,x))},[i]),{ref:p,open:f,close:m,isOpen:h}=Sc();PR||=h,Us(e,{open:f,close:m,isOpen:h}),Lc("page:changed",m);let g=F(()=>l(As(new Date)),[l]);return d(Y,{children:[d("style",{children:Is}),d("dialog",{ref:p,children:[d("div",{className:"controller",children:[d("span",{children:i}),d("button",{className:"navi left",onClick:c,children:""}),d("button",{className:"navi right",onClick:a,children:""}),d("button",{className:"today",onClick:g,children:""}),d(Fs,{loading:s,onClick:n}),d("button",{className:"close",onClick:m,children:""})]}),PR&&d("div",{ref:NR,className:"result scheduler","data-page-no":i,children:d(qu,{dateList:u,tasks:o,project:r})})]})]})},SR=!1,KA=({projects:e,mainProject:t,getController:r,open:o})=>{let{tasks:n,load:s,loading:i}=Ms(e),{pageNo:a,next:c,prev:l,jump:u}=Ku(new Date,JA,QA),p=C(()=>[a],[a]),f=F(()=>u(new Date),[u]),{isOpen:m,open:h,close:g}=TR(o);return SR||=m,Us(r,{open:h,close:g,isOpen:m}),d(Y,{children:[d("style",{children:Is}),SR&&d("div",{className:`wedget${m?" open":""}`,ref:NR,children:[d("div",{className:"controller",children:[d("span",{children:Et(a)}),d("button",{className:"navi left",onClick:l,children:""}),d("button",{className:"navi right",onClick:c,children:""}),d("button",{className:"today",onClick:f,children:""}),d(Fs,{loading:i,onClick:s})]}),d(qu,{dateList:p,tasks:n,project:t,hasColumn:!1})]})]})},XA=e=>As(rn(vc(e),1)),YA=e=>As(Oh(vc(e),1)),JA=e=>Fe(e,1),QA=e=>vr(e,1),NR=e=>{let t=e?.getElementsByClassName?.("indicator")?.[0];if(!t)return;let r=globalThis.scrollY;t.scrollIntoView({block:"center"}),globalThis.scroll(0,r)};Xf({project:"takker-dist"});gi(!0);Jd().then(e=>{scrapbox.PageMenu.addItem({title:"Fulltext Search",onClick:()=>{e.toggle()}})});var ZA="https://scrapbox.io/files/67344295032adf96d1e4c276.wasm",e1="/api/code/takker-dist/for-any-project-min/esbuild-worker.js";(async()=>{let e=new Request(ZA),t=await tn(e);t||(t=await fetch(e),await Fi(e,t)),await yb(await WebAssembly.compileStreaming(t),e1)})();(async()=>{let e=[scrapbox.Project.name,"takker","takker-memex","takker-books","takker-private","villagepump","hub","arpla","work4ai","unnamedcamp","unnamed-project","nishio","enchi","rashitamemo","motoso","shokai","masui","rakusai","yuiseki","akiroom","c4j","miyamonz","mrsekut-p","masuilab","kidaaam-92022284","nwtgck","juneboku","marshmallow-rm","sushitecture","sno2wman","inteltank","issac-37765679","blu3mo","yosider","Mijinko","Mijinko-other","scrapbox-drinkup","nota-techconf","customize","scrapboxlab","scrasobox","programming-notes","tus-alpine","tus-alpine-private","guiland"],t=await AE({projects:e,mark:{...Object.fromEntries([["takker","takker"],["takker-memex","takker"],["takker-books","takker-books"],["takker-private","takker-private"],["nishio","nishio"],["rashitamemo","rashita"],["enchi","雑談_2022-04-12~"],["rakusai","rakusai"],["masui","概要"],["shokai","shokai"],["yuiseki","yuiseki"],["akiroom","はじめに"],["inteltank","sawachin"],["motoso","もとそのもと"],["villagepump","井戸端"],["hub","scrapbox.io%2Fhub_について"],["masuilab","増井研に入ったらまずやること"],["marshmallow-rm","読書猿マシュマロ全質問回答"],["miyamonz","miyamonz"],["mrsekut-p","mrsekut"],["kidaaam-92022284","kidooom"],["c4j","Code_for_Japan"],["suto3","suto3"],["blu3mo","blu3mo"],["nwtgck","nwtgck"],["juneboku","juneboku"],["jigsaw","jgs"],["sno2wman","SnO2WMaN"],["sushitecture","hashrock"],["unnamedcamp","知を営む"],["unnamed-project","unnamed-project"],["issac-37765679","cFQ2f7LRuLYP"],["blu3mo","blu3mo"],["yosider","yosider"],["Mijinko","Mijinko_SD"],["Mijinko-other","Mijinko_SD"],["customize","みんなのカスタマイズ"],["scrapboxlab","入会手続き"],["scrasobox","Scrapboxとあそぶ"],["programming-notes","参加する"],["guiland","概要と参加方法"],["work4ai","work4ai"]].map(([n,s])=>[n,`https://scrapbox.io/api/pages/${n}/${s}/icon`])),"NDLSH-SB":"📚","scrapbox-drinkup":"https://scrapbox.io/assets/img/page-icon/scrapbox_beaver.png","nota-techconf":"https://i.gyazo.com/727f42bbd9e2534d99d70e6ea90705b3.jpg","plurality-japanese":"⿻"},enableSelfProjectOnStart:!0}),r=n=>{n.preventDefault(),n.stopPropagation()},o=()=>document.querySelector(".line .popup-menu")!==null;zl.bind({"<Tab>":n=>{o()||t.selectNext?.({cyclic:!0})&&r(n)},"<S-Tab>":n=>{o()||t.selectPrev?.({cyclic:!0})&&r(n)},"<Enter>":n=>{o()||t.confirm?.()&&r(n)},"<Esc>":n=>{o()||t.cancel?.()&&r(n)}})})();UE({previewers:[{when:/(?:^|\.)svg$/,preview:DE},{when:/(?:^|\.)glsl$/,preview:ZE},{when:/(?:^|\.)(?:plantuml|puml|pu)$/,preview:rw},{when:/(?:^|\.)tikz\(tex\)$/,preview:nw("/api/code/takker-dist/for-any-project-min/tex-worker.js","https://scrapbox.io/files/65d1645c19cd8e002433c3df")}]});Kw("takker",["takker","振り返り(takker-workflow@0.0.1)のtemplate","txt"],["takker","1週間の振り返り(takker-workflow@0.0.1)のtemplate","txt"],new Date(2024,11,24));Bo()&&(zt({display:{type:"caret-left"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Ci():Si()}}),zt({display:{type:"caret-right"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Ni():Pi()}}),zt({display:{type:"caret-up"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Ai():Oi()}}),zt({display:{type:"caret-down"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Mi():Li()}}),zt({display:{type:"copy"},onClick:async({cursor:e,selection:t})=>await tR(e,t)}),zt({display:{type:"cut"},onClick:async({cursor:e,selection:t})=>await rR(e,t)}),zt({display:{type:"clipboard"},onClick:async({cursor:e})=>await oR(e)}),zt({display:{type:"undo"},onClick:()=>Dd()}),zt({display:{type:"redo"},onClick:()=>$d()}),zt({display:({cursor:e})=>e.getVisible()&&e.hasFocus&&e.visiblePopupMenu?{type:["i-cursor","slash"]}:{type:"i-cursor"},onClick:({cursor:e})=>nR(e)}));if(Bo()&&scrapbox.Project.name!=="takker-memex"){let e="task";scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/todo-list--v2.png"}),scrapbox.PageMenu(e).addItem({title:"Book starting",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:Jn}),scrapbox.PageMenu(e).addItem({title:"Transport",onClick:()=>Zn({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"})})}if(Bo()){let e="New Page",t=[ko,vo,_o];scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/cut-paper.png"}),scrapbox.PageMenu(e).addItem({title:"New Page",onClick:()=>{let r=window.prompt("Create a new page at",scrapbox.Project.name);r&&Rr({project:r,mode:"noopen",hooks:t})?.()}}),scrapbox.PageMenu(e).addItem({title:"New Page and Open",onClick:()=>{let r=window.prompt("Create a new page at",scrapbox.Project.name);r&&Rr({project:r,mode:"self",hooks:t})?.()}})}scrapbox.PageMenu.addMenu({title:"Add to inbox",image:"https://img.icons8.com/ios/180/FFFFFF/inbox.png",onClick:()=>pR("takker-memex","メモ帳")});(async()=>{let e="next-action",t=`head style[data-userscript-name="${e}"]`;document.querySelector(t)?.remove?.();let r=document.createElement("style");r.dataset.userscriptName=e,r.textContent=`
button:is(#${e}, #scheduler).tool-btn::before {
position: absolute;
font: 900 20px/46px "Font Awesome 5 Free";
}
button#${e}.tool-btn::before {
content: "\\f0ae";
}
button#scheduler.tool-btn::before {
content: "\\f073";
font-weight: 400;
}
button:is(#${e}, #scheduler).tool-btn img {
opacity: 0;
}`,document.head.append(r);let o=["takker-memex","takker"],{open:n}=await xR(o);scrapbox.PageMenu.addMenu({title:e,image:"/assets/img/favicon/apple-touch-icon.png",onClick:n});let s=await OR(o);scrapbox.PageMenu.addMenu({title:"scheduler",image:"/assets/img/favicon/apple-touch-icon.png",onClick:s.open});{let i="takker-scheduler/wedget",a=JSON.parse(localStorage.getItem(i)??"{}"),c=scrapbox.Project.name;a[c]??=!1;let l=await LR(o,a[c]),u=()=>{a[c]=!l.isOpen,l.isOpen?l.close():l.open?.(),localStorage.setItem(i,JSON.stringify(a))};Bo()?zt({display:{type:"calendar"},onClick:u}):scrapbox.PageMenu.addItem({title:"toggle wedget",onClick:u})}})();export{zt as addButton,Ye as insertText,zl as scrapBindings};
/** @license
* esbuild-wasm@v0.24.0
*
* MIT License
*
* Copyright (c) 2020 Evan Wallace
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
takker-memex.jsvar Bk=Object.defineProperty;var co=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var zs=(e,t)=>{for(var r in t)Bk(e,r,{get:t[r],enumerable:!0})};function _e(e){if(e)return Hk(e)}function Hk(e){for(var t in _e.prototype)e[t]=_e.prototype[t];return e}_e.prototype.on=_e.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};_e.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};_e.prototype.off=_e.prototype.removeListener=_e.prototype.removeAllListeners=_e.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var r=this._callbacks["$"+e];if(!r)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var o,n=0;n<r.length;n++)if(o=r[n],o===t||o.fn===t){r.splice(n,1);break}return r.length===0&&delete this._callbacks["$"+e],this};_e.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],o=1;o<arguments.length;o++)t[o-1]=arguments[o];if(r){r=r.slice(0);for(var o=0,n=r.length;o<n;++o)r[o].apply(this,t)}return this};_e.prototype.emitReserved=_e.prototype.emit;_e.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};_e.prototype.hasListeners=function(e){return!!this.listeners(e).length};var nr=Object.create(null);nr.open="0";nr.close="1";nr.ping="2";nr.pong="3";nr.message="4";nr.upgrade="5";nr.noop="6";var Xs=Object.create(null);Object.keys(nr).forEach(e=>{Xs[nr[e]]=e});var Hc={type:"error",data:"parser error"},rm=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",om=typeof ArrayBuffer=="function",nm=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Ys=({type:e,data:t},r,o)=>rm&&t instanceof Blob?r?o(t):Zu(t,o):om&&(t instanceof ArrayBuffer||nm(t))?r?o(t):Zu(new Blob([t]),o):o(nr[e]+(t||"")),Zu=(e,t)=>{let r=new FileReader;return r.onload=function(){let o=r.result.split(",")[1];t("b"+(o||""))},r.readAsDataURL(e)};function em(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var jc;function Wk(e,t){if(rm&&e.data instanceof Blob)return e.data.arrayBuffer().then(em).then(t);if(om&&(e.data instanceof ArrayBuffer||nm(e.data)))return t(em(e.data));Ys(e,!1,r=>{jc||(jc=new TextEncoder),t(jc.encode(r))})}var tm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Hn=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<tm.length;e++)Hn[tm.charCodeAt(e)]=e;var Gk=e=>{let t=e.length*.75,r=e.length,o,n=0,s,i,a,c;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(o=0;o<r;o+=4)s=Hn[e.charCodeAt(o)],i=Hn[e.charCodeAt(o+1)],a=Hn[e.charCodeAt(o+2)],c=Hn[e.charCodeAt(o+3)],u[n++]=s<<2|i>>4,u[n++]=(i&15)<<4|a>>2,u[n++]=(a&3)<<6|c&63;return l},Vk=typeof ArrayBuffer=="function",Js=(e,t)=>{if(typeof e!="string")return{type:"message",data:sm(e,t)};let r=e.charAt(0);return r==="b"?{type:"message",data:zk(e.substring(1),t)}:Xs[r]?e.length>1?{type:Xs[r],data:e.substring(1)}:{type:Xs[r]}:Hc},zk=(e,t)=>{if(Vk){let r=Gk(e);return sm(r,t)}else return{base64:!0,data:e}},sm=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},im="",am=(e,t)=>{let r=e.length,o=new Array(r),n=0;e.forEach((s,i)=>{Ys(s,!1,a=>{o[i]=a,++n===r&&t(o.join(im))})})},cm=(e,t)=>{let r=e.split(im),o=[];for(let n=0;n<r.length;n++){let s=Js(r[n],t);if(o.push(s),s.type==="error")break}return o};function lm(){return new TransformStream({transform(e,t){Wk(e,r=>{let o=r.length,n;if(o<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,o);else if(o<65536){n=new Uint8Array(3);let s=new DataView(n.buffer);s.setUint8(0,126),s.setUint16(1,o)}else{n=new Uint8Array(9);let s=new DataView(n.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(o))}e.data&&typeof e.data!="string"&&(n[0]|=128),t.enqueue(n),t.enqueue(r)})}})}var Bc;function qs(e){return e.reduce((t,r)=>t+r.length,0)}function Ks(e,t){if(e[0].length===t)return e.shift();let r=new Uint8Array(t),o=0;for(let n=0;n<t;n++)r[n]=e[0][o++],o===e[0].length&&(e.shift(),o=0);return e.length&&o<e[0].length&&(e[0]=e[0].slice(o)),r}function pm(e,t){Bc||(Bc=new TextDecoder);let r=[],o=0,n=-1,s=!1;return new TransformStream({transform(i,a){for(r.push(i);;){if(o===0){if(qs(r)<1)break;let c=Ks(r,1);s=(c[0]&128)===128,n=c[0]&127,n<126?o=3:n===126?o=1:o=2}else if(o===1){if(qs(r)<2)break;let c=Ks(r,2);n=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),o=3}else if(o===2){if(qs(r)<8)break;let c=Ks(r,8),l=new DataView(c.buffer,c.byteOffset,c.length),u=l.getUint32(0);if(u>Math.pow(2,21)-1){a.enqueue(Hc);break}n=u*Math.pow(2,32)+l.getUint32(4),o=3}else{if(qs(r)<n)break;let c=Ks(r,n);a.enqueue(Js(s?c:Bc.decode(c),t)),o=0}if(n===0||n>e){a.enqueue(Hc);break}}}})}var Wc=4;var Wn=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Ft=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),qk="arraybuffer";function mm(e,...t){return t.reduce((r,o)=>(e.hasOwnProperty(o)&&(r[o]=e[o]),r),{})}var Kk=Ft.setTimeout,Xk=Ft.clearTimeout;function Gn(e,t){t.useNativeTimers?(e.setTimeoutFn=Kk.bind(Ft),e.clearTimeoutFn=Xk.bind(Ft)):(e.setTimeoutFn=Ft.setTimeout.bind(Ft),e.clearTimeoutFn=Ft.clearTimeout.bind(Ft))}var Yk=1.33;function Jk(e){return typeof e=="string"?Qk(e):Math.ceil((e.byteLength||e.size)*Yk)}function Qk(e){let t=0,r=0;for(let o=0,n=e.length;o<n;o++)t=e.charCodeAt(o),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(o++,r+=4);return r}function fm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Zk(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}function eR(e){let t={},r=e.split("&");for(let o=0,n=r.length;o<n;o++){let s=r[o].split("=");t[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return t}var tR=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},zc=class extends _e{constructor(e){super(),this.writable=!1,Gn(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new tR(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=Js(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=Zk(e);return t.length?"?"+t:""}},rR=class extends zc{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||t()})),this.writable||(r++,this.once("drain",function(){--r||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};cm(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){let e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,am(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=fm()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},dm=!1;try{dm=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var oR=dm;function nR(){}var sR=class extends rR{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",r=location.port;r||(r=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(o,n)=>{this.onError("xhr post error",o,n)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,r)=>{this.onError("xhr poll error",t,r)}),this.pollXhr=e}},Yo=class Qs extends _e{constructor(t,r,o){super(),this.createRequest=t,Gn(this,o),this._opts=o,this._method=o.method||"GET",this._uri=r,this._data=o.data!==void 0?o.data:null,this._create()}_create(){var t;let r=mm(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;let o=this._xhr=this.createRequest(r);try{o.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){o.setDisableHeaderCheck&&o.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&o.setRequestHeader(n,this._opts.extraHeaders[n])}}catch{}if(this._method==="POST")try{o.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{o.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(o),"withCredentials"in o&&(o.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(o.timeout=this._opts.requestTimeout),o.onreadystatechange=()=>{var n;o.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.parseCookies(o.getResponseHeader("set-cookie"))),o.readyState===4&&(o.status===200||o.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof o.status=="number"?o.status:0)},0))},o.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=Qs.requestsCount++,Qs.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=nR,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Qs.requests[this._index],this._xhr=null}}_onLoad(){let t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};Yo.requestsCount=0;Yo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",um);else if(typeof addEventListener=="function"){let e="onpagehide"in Ft?"pagehide":"unload";addEventListener(e,um,!1)}}function um(){for(let e in Yo.requests)Yo.requests.hasOwnProperty(e)&&Yo.requests[e].abort()}var iR=function(){let e=hm({xdomain:!1});return e&&e.responseType!==null}(),qc=class extends sR{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=iR&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Yo(hm,this.uri(),e)}};function hm(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||oR))return new XMLHttpRequest}catch{}if(!t)try{return new Ft[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var gm=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",aR=class extends zc{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=gm?{}:mm(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],o=t===e.length-1;Ys(r,this.supportsBinary,n=>{try{this.doWrite(r,n)}catch{}o&&Wn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=fm()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Gc=Ft.WebSocket||Ft.MozWebSocket,Kc=class extends aR{createSocket(e,t,r){return gm?new Gc(e,t,r):t?new Gc(e,t):new Gc(e)}doWrite(e,t){this.ws.send(t)}},ym=class extends zc{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=pm(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),o=lm();o.readable.pipeTo(e.writable),this._writer=o.writable.getWriter();let n=()=>{r.read().then(({done:i,value:a})=>{i||(this.onPacket(a),n())}).catch(i=>{})};n();let s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],o=t===e.length-1;this._writer.write(r).then(()=>{o&&Wn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}},cR={websocket:Kc,webtransport:ym,polling:qc},lR=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,pR=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ri(e){if(e.length>8e3)throw"URI too long";let t=e,r=e.indexOf("["),o=e.indexOf("]");r!=-1&&o!=-1&&(e=e.substring(0,r)+e.substring(r,o).replace(/:/g,";")+e.substring(o,e.length));let n=lR.exec(e||""),s={},i=14;for(;i--;)s[pR[i]]=n[i]||"";return r!=-1&&o!=-1&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=uR(s,s.path),s.queryKey=mR(s,s.query),s}function uR(e,t){let r=/\/{2,9}/g,o=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&o.splice(0,1),t.slice(-1)=="/"&&o.splice(o.length-1,1),o}function mR(e,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(o,n,s){n&&(r[n]=s)}),r}var Vc=typeof addEventListener=="function"&&typeof removeEventListener=="function",Zs=[];Vc&&addEventListener("offline",()=>{Zs.forEach(e=>e())},!1);var ei=class ti extends _e{constructor(t,r){if(super(),this.binaryType=qk,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){let o=ri(t);r.hostname=o.host,r.secure=o.protocol==="https"||o.protocol==="wss",r.port=o.port,o.query&&(r.query=o.query)}else r.host&&(r.hostname=ri(r.host).host);Gn(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(o=>{let n=o.prototype.name;this.transports.push(n),this._transportsByName[n]=o}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=eR(this.opts.query)),Vc&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Zs.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){let r=Object.assign({},this.opts.query);r.EIO=Wc,r.transport=t,this.id&&(r.sid=this.id);let o=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](o)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let t=this.opts.rememberUpgrade&&ti.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){this.readyState="open",ti.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let r=0;r<this.writeBuffer.length;r++){let o=this.writeBuffer[r].data;if(o&&(t+=Jk(o)),r>0&&t>this._maxPayload)return this.writeBuffer.slice(0,r);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Wn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,o){return this._sendPacket("message",t,r,o),this}send(t,r,o){return this._sendPacket("message",t,r,o),this}_sendPacket(t,r,o,n){if(typeof r=="function"&&(n=r,r=void 0),typeof o=="function"&&(n=o,o=null),this.readyState==="closing"||this.readyState==="closed")return;o=o||{},o.compress=o.compress!==!1;let s={type:t,data:r,options:o};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){let t=()=>{this._onClose("forced close"),this.transport.close()},r=()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},o=()=>{this.once("upgrade",r),this.once("upgradeError",r)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?o():t()}):this.upgrading?o():t()),this}_onError(t){if(ti.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Vc&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let o=Zs.indexOf(this._offlineEventListener);o!==-1&&Zs.splice(o,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};ei.protocol=Wc;var fR=class extends ei{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),r=!1;ei.priorWebsocketSuccess=!1;let o=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",u=>{if(!r)if(u.type==="pong"&&u.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ei.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let p=new Error("probe error");p.transport=t.name,this.emitReserved("upgradeError",p)}}))};function n(){r||(r=!0,l(),t.close(),t=null)}let s=u=>{let p=new Error("probe error: "+u);p.transport=t.name,n(),this.emitReserved("upgradeError",p)};function i(){s("transport closed")}function a(){s("socket closed")}function c(u){t&&u.name!==t.name&&n()}let l=()=>{t.removeListener("open",o),t.removeListener("error",s),t.removeListener("close",i),this.off("close",a),this.off("upgrading",c)};t.once("open",o),t.once("error",s),t.once("close",i),this.once("close",a),this.once("upgrading",c),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}},Xc=class extends fR{constructor(e,t={}){let r=typeof e=="object"?e:t;(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(o=>cR[o]).filter(o=>!!o)),super(e,r)}};var v1=Xc.protocol;var Zc={};zs(Zc,{Decoder:()=>kR,Encoder:()=>wR,PacketType:()=>se,protocol:()=>Em});var dR=typeof ArrayBuffer=="function",hR=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,bm=Object.prototype.toString,gR=typeof Blob=="function"||typeof Blob<"u"&&bm.call(Blob)==="[object BlobConstructor]",yR=typeof File=="function"||typeof File<"u"&&bm.call(File)==="[object FileConstructor]";function Qc(e){return dR&&(e instanceof ArrayBuffer||hR(e))||gR&&e instanceof Blob||yR&&e instanceof File}function oi(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,o=e.length;r<o;r++)if(oi(e[r]))return!0;return!1}if(Qc(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return oi(e.toJSON(),!0);for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&oi(e[r]))return!0;return!1}function xR(e){let t=[],r=e.data,o=e;return o.data=Yc(r,t),o.attachments=t.length,{packet:o,buffers:t}}function Yc(e,t){if(!e)return e;if(Qc(e)){let r={_placeholder:!0,num:t.length};return t.push(e),r}else if(Array.isArray(e)){let r=new Array(e.length);for(let o=0;o<e.length;o++)r[o]=Yc(e[o],t);return r}else if(typeof e=="object"&&!(e instanceof Date)){let r={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=Yc(e[o],t));return r}return e}function bR(e,t){return e.data=Jc(e.data,t),delete e.attachments,e}function Jc(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Jc(e[r],t);else if(typeof e=="object")for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Jc(e[r],t));return e}var ER=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Em=5,se;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(se||(se={}));var wR=class{constructor(e){this.replacer=e}encode(e){return(e.type===se.EVENT||e.type===se.ACK)&&oi(e)?this.encodeAsBinary({type:e.type===se.EVENT?se.BINARY_EVENT:se.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===se.BINARY_EVENT||e.type===se.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=xR(e),r=this.encodeAsString(t.packet),o=t.buffers;return o.unshift(r),o}};function xm(e){return Object.prototype.toString.call(e)==="[object Object]"}var kR=class wm extends _e{constructor(t){super(),this.reviver=t}add(t){let r;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");r=this.decodeString(t);let o=r.type===se.BINARY_EVENT;o||r.type===se.BINARY_ACK?(r.type=o?se.EVENT:se.ACK,this.reconstructor=new RR(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(Qc(t)||t.base64)if(this.reconstructor)r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,super.emitReserved("decoded",r));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let r=0,o={type:Number(t.charAt(0))};if(se[o.type]===void 0)throw new Error("unknown packet type "+o.type);if(o.type===se.BINARY_EVENT||o.type===se.BINARY_ACK){let s=r+1;for(;t.charAt(++r)!=="-"&&r!=t.length;);let i=t.substring(s,r);if(i!=Number(i)||t.charAt(r)!=="-")throw new Error("Illegal attachments");o.attachments=Number(i)}if(t.charAt(r+1)==="/"){let s=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););o.nsp=t.substring(s,r)}else o.nsp="/";let n=t.charAt(r+1);if(n!==""&&Number(n)==n){let s=r+1;for(;++r;){let i=t.charAt(r);if(i==null||Number(i)!=i){--r;break}if(r===t.length)break}o.id=Number(t.substring(s,r+1))}if(t.charAt(++r)){let s=this.tryParse(t.substr(r));if(wm.isPayloadValid(o.type,s))o.data=s;else throw new Error("invalid payload")}return o}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case se.CONNECT:return xm(r);case se.DISCONNECT:return r===void 0;case se.CONNECT_ERROR:return typeof r=="string"||xm(r);case se.EVENT:case se.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&ER.indexOf(r[0])===-1);case se.ACK:case se.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},RR=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=bR(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function vR(e,t="",r){let o=e;r=r||typeof location<"u"&&location,e==null&&(e=r.protocol+"//"+r.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=r.protocol+e:e=r.host+e),/^(https?|wss?):\/\//.test(e)||(typeof r<"u"?e=r.protocol+"//"+e:e="https://"+e),o=ri(e)),o.port||(/^(http|ws)$/.test(o.protocol)?o.port="80":/^(http|ws)s$/.test(o.protocol)&&(o.port="443")),o.path=o.path||"/";let n=o.host.indexOf(":")!==-1?"["+o.host+"]":o.host;return o.id=o.protocol+"://"+n+":"+o.port+t,o.href=o.protocol+"://"+n+(r&&r.port===o.port?"":":"+o.port),o}function Kt(e,t,r){return e.on(t,r),function(){e.off(t,r)}}var TR=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),km=class extends _e{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[Kt(e,"open",this.onopen.bind(this)),Kt(e,"packet",this.onpacket.bind(this)),Kt(e,"error",this.onerror.bind(this)),Kt(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,o,n;if(TR.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let s={type:se.EVENT,data:t};if(s.options={},s.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let c=this.ids++,l=t.pop();this._registerAckCallback(c,l),s.id=c}let i=(o=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||o===void 0?void 0:o.writable,a=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!i||(a?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(e,t){var r;let o=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(o===void 0){this.acks[e]=t;return}let n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let i=0;i<this.sendBuffer.length;i++)this.sendBuffer[i].id===e&&this.sendBuffer.splice(i,1);t.call(this,new Error("operation has timed out"))},o),s=(...i)=>{this.io.clearTimeoutFn(n),t.apply(this,i)};s.withError=!0,this.acks[e]=s}emitWithAck(e,...t){return new Promise((r,o)=>{let n=(s,i)=>s?o(s):r(i);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((o,...n)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(o)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:se.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case se.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case se.EVENT:case se.BINARY_EVENT:this.onevent(e);break;case se.ACK:case se.BINARY_ACK:this.onack(e);break;case se.DISCONNECT:this.ondisconnect();break;case se.CONNECT_ERROR:this.destroy();let t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,r=!1;return function(...o){r||(r=!0,t.packet({type:se.ACK,id:e,data:o}))}}onack(e){let t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:se.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let r of t)r.apply(this,e.data)}}};function Qo(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Qo.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+r:e-r}return Math.min(e,this.max)|0};Qo.prototype.reset=function(){this.attempts=0};Qo.prototype.setMin=function(e){this.ms=e};Qo.prototype.setMax=function(e){this.max=e};Qo.prototype.setJitter=function(e){this.jitter=e};var el=class extends _e{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,Gn(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((r=t.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Qo({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let o=t.parser||Zc;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Xc(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let o=Kt(t,"open",function(){r.onopen(),e&&e()}),n=i=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",i),e?e(i):this.maybeReconnectOnOpen()},s=Kt(t,"error",n);if(this._timeout!==!1){let i=this._timeout,a=this.setTimeoutFn(()=>{o(),n(new Error("timeout")),t.close()},i);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}return this.subs.push(o),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(Kt(e,"ping",this.onping.bind(this)),Kt(e,"data",this.ondata.bind(this)),Kt(e,"error",this.onerror.bind(this)),Kt(e,"close",this.onclose.bind(this)),Kt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){Wn(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new km(this,e,t),this.nsps[e]=r),r}_destroy(e){let t=Object.keys(this.nsps);for(let r of t)if(this.nsps[r].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(o=>{o?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",o)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}},Vn={};function Jo(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};let r=vR(e,t.path||"/socket.io"),o=r.source,n=r.id,s=r.path,i=Vn[n]&&s in Vn[n].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||i,c;return a?c=new el(o,t):(Vn[n]||(Vn[n]=new el(o,t)),c=Vn[n]),r.query&&!t.query&&(t.query=r.queryKey),c.socket(r.path,t)}Object.assign(Jo,{Manager:el,Socket:km,io:Jo,connect:Jo});function at(e){return e.val}function yt(e){return e.err}var Rm=" must not return ",_R="`transformer`",PR="`recoverer`",SR="`defaultValue`",Zo=_R+Rm,hr="called with ",en=SR+" must not be ",tn=PR+Rm;var OR="`Ok`",vm="`Err`",Tm=hr+vm,_m=hr+OR,LR="Carrying `E` in "+vm+" instead of throwing it directly. See `.cause`",tl="an instance of `Error` of the current realm.",mM="The thrown value is not "+tl,fM="The contained E should be "+tl,NR="This `.cause` is not "+tl;function Ae(e){return e.ok}function te(e){return{ok:!0,val:e,err:null}}function G(e){return!e.ok}function fe(e){return{ok:!1,val:null,err:e}}function X(e){return Pm(e,Tm)}function rn(e){return Sm(e,_m)}function Pm(e,t){if(G(e))throw new TypeError(t);return e.val}function Sm(e,t){if(Ae(e))throw new TypeError(t);return e.err}async function rl(e,t){if(G(e))return e;let r=at(e);return await t(r)}function lo(e,t){if(G(e))return e;let r=at(e),o=t(r);return te(o)}async function Re(e,t){if(G(e))return e;let r=at(e),o=await t(r);return te(o)}async function Te(e,t){if(Ae(e))return e;let r=yt(e),o=await t(r);return fe(o)}async function ni(e,t){if(Ae(e))return e;let r=yt(e);return await t(r)}var si="`null`",bI=Zo+si,MR=hr+si,EI=en+si,wI=tn+si;var ii="`undefined`",_I=Zo+ii,IR=hr+ii,PI=en+ii,SI=tn+ii;var ve=e=>e.ok?te(e):fe({name:"HTTPError",message:`${e.status} ${e.statusText}`,response:e});var Lm=async(e,t)=>{let r=new Request(e,t);try{return te(await globalThis.fetch(r))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return fe({name:"AbortError",message:o.message,request:r});if(o instanceof TypeError)return fe({name:"NetworkError",message:o.message,request:r});throw o}};var le=e=>{let{fetch:t=Lm,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var Nm=e=>{let{sid:t,hostName:r}=le(e??{});return new Request(`https://${r}/api/users/me`,t?{headers:{Cookie:de(t)}}:void 0)},Cm=e=>Re(ve(e),async t=>await t.json()),ai=(()=>{let e=async t=>{let{fetch:r,...o}=le(t??{}),n=await r(Nm(o));return G(n)?n:Cm(X(n))};return e.toRequest=Nm,e.fromResponse=Cm,e})();var de=e=>`connect.sid=${e}`,sr=async e=>{let t=e?.csrf??globalThis._csrf;return t?te(t):lo(await ai(e),r=>r.csrfToken)};var Ve=(e,t)=>{if(e?.connected)return Promise.resolve(te(e));e??=Jo("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"],...t?{rejectUnauthorized:!1,extraHeaders:{Cookie:de(t),Host:"scrapbox.io",Referer:"https://scrapbox.io/"}}:{}});let r=new Promise(o=>{let n=s=>o(fe(s));e.once("connect",()=>{e.off("disconnect",n),o(te(e))}),e.once("disconnect",n)});return e.connect(),r},ot=e=>{if(e.disconnected)return Promise.resolve(te(void 0));let t=new Promise(r=>{let o=n=>{if(n!=="io client disconnect"){r(fe(n));return}r(te(void 0)),e.off("disconnect",o)};e.on("disconnect",o)});return e.disconnect(),t};var Am=e=>UR.includes(e.name),UR=["SocketIOError","DuplicateTitleError","NotFastForwardError"];var Mm=(e,t,r,o)=>{if(t==="cursor")return e.emit(t,r),Promise.resolve(te(void 0));let{resolve:n,promise:s,reject:i}=Promise.withResolvers(),a=()=>{e.off("disconnect",c),clearTimeout(u)},c=f=>{if(f==="io client disconnect"){a(),i(new Error("io client disconnect"));return}if(f==="io server disconnect"){a(),n(fe({name:"SocketIOError"}));return}};e.on("disconnect",c);let l=o?.timeout??9e4,u=setTimeout(()=>{a(),n(fe({name:"TimeoutError",message:`exceeded ${l} (ms)`}))},l),p=t==="commit"?{method:"commit",data:r}:{method:"room:join",data:r};return e.emit("socket.io-request",p,f=>{if(a(),"error"in f){n(fe(Am(f.error)?f.error:{name:"UnexpectedRequestError",...f}));return}n(te(f.data))}),s};function ci(e,t={}){if(e===null)return"null";if(Array.isArray(e))return DR(e,t);switch(typeof e){case"string":return JSON.stringify(e);case"bigint":return`${e}n`;case"object":return e.constructor?.name!=="Object"?e.constructor?.name:$R(e,t);case"function":return e.name||"(anonymous)"}return e?.toString()??"undefined"}function DR(e,t){let{threshold:r=20}=t,o=e.map(i=>ci(i,t)),n=o.join(", ");if(n.length<=r)return`[${n}]`;let s=o.join(`,
`);return`[
${Im(2,s)}
]`}function $R(e,t){let{threshold:r=20}=t,o=[...Object.keys(e),...Object.getOwnPropertySymbols(e)].map(i=>`${i.toString()}: ${ci(e[i],t)}`),n=o.join(", ");if(n.length<=r)return`{${n}}`;let s=o.join(`,
`);return`{
${Im(2,s)}
}`}function Im(e,t){let r=" ".repeat(e);return t.split(`
`).map(o=>`${r}${o}`).join(`
`)}function ze(e,t,...r){let o;return Object.defineProperties(e,{name:{get:()=>o||(o=`${t}(${r.map(n=>ci(n)).join(", ")})`,o)}})}function gr(e){return Array.isArray(e)}function ol(e){return ze(t=>gr(t)&&t.every(r=>e(r)),"isArrayOf",e)}function li(e){let t=new Set(e);return ze(r=>t.has(r),"isLiteralOneOf",e)}function zn(e){return e!=null&&!Array.isArray(e)&&typeof e=="object"}function $e(e){return typeof e=="string"}var Fe=async(e,t)=>{let r=e.response.clone(),o=li(t);try{let n=await r.json();if(!zn(n))return;if(r.status===422){if(!$e(n.message))return;for(let s of["NoQueryError","InvalidURLError"])if(t.includes(s))return{name:s,message:n.message}}return!o(n.name)||!$e(n.message)?void 0:n.name==="NotLoggedInError"?!zn(n.detals)||!$e(n.detals.project)||!ol(jR)(n.detals.loginStrategies)?void 0:{name:n.name,message:n.message,details:{project:n.detals.project,loginStrategies:n.detals.loginStrategies}}:{name:n.name,message:n.message}}catch(n){if(n instanceof SyntaxError)return;throw n}},jR=li(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var ne=e=>e.replaceAll(" ","_").toLowerCase();var me=e=>[...e].map((t,r)=>t===" "?"_":!BR.includes(t)||r===e.length-1&&HR.includes(t)?encodeURIComponent(t):t).join(""),BR='@$&+=:;",',HR=':;",';var pi="`null` or `undefined`",on=Zo+pi,WR=hr+pi,ui=en+pi,mi=tn+pi;function Ut(e){return e!=null}function ir(e){return e==null}function Xt(e,t){if(Ut(e))return e;throw new TypeError(t)}function fi(e){return ir(e)?fe(void 0):te(e)}function nl(e,t){return Ut(e)?e:Xt(t,ui)}var Fm=(e,t,r)=>{let{sid:o,hostName:n,followRename:s,projects:i}=le(r??{}),a=new URLSearchParams([["followRename",`${s??!0}`],...i?.map?.(c=>["projects",c])??[]]);return new Request(`https://${n}/api/pages/${e}/${me(t)}?${a}`,o?{headers:{Cookie:de(o)}}:void 0)},Um=async e=>Te(await Re(ve(e),t=>t.json()),async t=>t.response.status===414?{name:"TooLongURIError",message:"project ids may be too much."}:nl(await Fe(t,["NotFoundError","NotLoggedInError","NotMemberError"]),t)),Dt=(()=>{let e=async(t,r,o)=>rl(await le(o??{}).fetch(Fm(t,r,o)),n=>Um(n));return e.toRequest=Fm,e.fromResponse=Um,e})();var Dm=(e,t)=>{let{sid:r,hostName:o}=le(t??{});return new Request(`https://${o}/api/projects/${e}`,r?{headers:{Cookie:de(r)}}:void 0)},$m=async e=>Re(await Te(ve(e),async t=>await Fe(t,["NotFoundError","NotLoggedInError","NotMemberError"])??t),t=>t.json()),yr=(()=>{let e=async(t,r)=>{let{fetch:o}=le(r??{}),n=Dm(t,r),s=await o(n);return G(s)?s:$m(X(s))};return e.toRequest=Dm,e.fromResponse=$m,e})(),jm=(e,t)=>{let{sid:r,hostName:o}=le(t??{}),n=new URLSearchParams(e.map(s=>["ids",s]));return new Request(`https://${o}/api/projects?${n}`,r?{headers:{Cookie:de(r)}}:void 0)},Bm=async e=>Re(await Te(ve(e),async t=>await Fe(t,["NotLoggedInError"])??t),t=>t.json()),di=(()=>{let e=async(t,r)=>{let{fetch:o}=le(r??{}),n=await o(jm(t,r));return G(n)?n:Bm(X(n))};return e.toRequest=jm,e.fromResponse=Bm,e})();var il=async(e,t,r)=>{let[o,n,s]=await Promise.all([Dt(e,t,r),GR(r),VR(e,r)]);return G(o)?o:G(n)?n:G(s)?s:te({...X(o),projectId:X(s),userId:X(n)})},sl,GR=async e=>{if(sl)return te(sl);let t=await ai(e);if(G(t))return t;let r=X(t);return"id"in r?(sl=r.id,te(r.id)):fe({name:"NotLoggedInError",message:"This script cannot be used without login"})},Hm=new Map,VR=async(e,t)=>{let r=Hm.get(e);return r?te(r):lo(await yr(e,t),({id:o})=>(Hm.set(e,o),o))};function Pe(e,t={}){let{signal:r,persistent:o=!0}=t;return r?.aborted?Promise.reject(r.reason):new Promise((n,s)=>{let i=()=>{clearTimeout(c),s(r?.reason)},c=setTimeout(()=>{r?.removeEventListener("abort",i),n()},e);if(r?.addEventListener("abort",i,{once:!0}),o===!1)try{Deno.unrefTimer(c)}catch(l){if(!(l instanceof ReferenceError))throw l;console.error("`persistent` option is only available in Deno")}})}var po=async(e,t,r,o)=>{let n=await Ve(o?.socket,o?.sid);if(G(n))return fe({name:"UnexpectedRequestError",error:rn(n)});let s=X(n),i=await il(e,t,o);if(G(i))return i;let a=X(i);try{let c=0,l=[],u;for(;o?.maxAttempts===void 0||c<o.maxAttempts;){let p=r(a,c,l,u);if(l=p instanceof Promise?await p:p,c++,l.length===0)return te(a.commitId);let f={kind:"page",projectId:a.projectId,pageId:a.id,parentId:a.commitId,userId:a.userId,changes:l,cursor:null,freeze:!0};for(;;){let m=await Mm(s,"commit",f);if(Ae(m))return a.commitId=X(m).commitId,te(a.commitId);let h=rn(m),g=h.name;if(g==="SocketIOServerDisconnectError"||g==="UnexpectedRequestError")return fe(h);if(g==="TimeoutError"||g==="SocketIOError"){await Pe(3e3);continue}if(g==="NotFastForwardError"){await Pe(1e3);let y=await il(e,t,o);if(G(y))return y;a=X(y)}u=g;break}}return fe({name:"RetryError",attempts:c,message:`Retrying exceeded the maxAttempts (${c}).`})}finally{o?.socket||await ot(s)}};var al=(e,t)=>{let r=e.length>t.length,o=r?t:e,n=r?e:t,s=o.length+1,i=o.length+n.length+3,a=new Array(i);a.fill(-1);let c=[];function l(g,y,x){let E=Math.max(y,x),R=E-g;for(;R<o.length&&E<n.length&&o[R]===n[E];)++R,++E;return a[g+s]=c.length,c.push([{x:R,y:E},a[g+(y>x?-1:1)+s]]),E}let u=new Array(i);u.fill(-1);let p=-1,f=n.length-o.length;do{++p;for(let g=-p;g<=f-1;++g)u[g+s]=l(g,u[g-1+s]+1,u[g+1+s]);for(let g=f+p;g>=f+1;--g)u[g+s]=l(g,u[g-1+s]+1,u[g+1+s]);u[f+s]=l(f,u[f-1+s]+1,u[f+1+s])}while(u[f+s]!==n.length);let m=[],h=a[f+s];for(;h!==-1;)m.push(c[h][0]),h=c[h][1];return{from:e,to:t,editDistance:f+p*2,buildSES:function*(){let g=0,y=0;for(let{x,y:E}of zR(m))for(;g<x||y<E;)E-x>y-g?(yield{value:n[y],type:r?"deleted":"added"},++y):E-x<y-g?(yield{value:o[g],type:r?"added":"deleted"},++g):(yield{value:o[g],type:"common"},++g,++y)}}};function*cl(e){let t=[],r=[];function*o(){if(t.length>r.length){for(let n=0;n<r.length;n++)yield Wm(t[n],r[n]);for(let n=r.length;n<t.length;n++)yield t[n]}else{for(let n=0;n<t.length;n++)yield Wm(t[n],r[n]);for(let n=t.length;n<r.length;n++)yield r[n]}t=[],r=[]}for(let n of e)switch(n.type){case"added":t.push(n);break;case"deleted":r.push(n);break;case"common":yield*o(),yield n;break}yield*o()}var Wm=(e,t)=>({value:e.value,oldValue:t.value,type:"replaced"});function*zR(e){for(let t=e.length-1;t>=0;t--)yield e[t]}var Gm=e=>e.padStart(8,"0"),ll=e=>{let t=Math.floor(new Date().getTime()/1e3).toString(16),r=Math.floor(16777214*Math.random()).toString(16);return`${Gm(t).slice(-8)}${e.slice(-6)}0000${Gm(r)}`};function*pl(e,t,{userId:r}){let{buildSES:o}=al(e.map(({text:i})=>i),t),n=0,s=e[0].id;for(let i of cl(o())){switch(i.type){case"added":yield{_insert:s,lines:{id:ll(r),text:i.value}};continue;case"deleted":yield{_delete:s,lines:-1};break;case"replaced":yield{_update:s,lines:{text:i.value}};break}n++,s=e[n]?.id??"_end"}}var qR=(e,t)=>(e.type==="codeBlock"||e.type==="table")&&t.indent>(e.rows[0]?.indent??0),Vm=(e,t)=>{let r=e[e.length-1];return r!==void 0&&qR(r,t)?(r.rows.push(t),e):(e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e)},zm=(e,t)=>{if(t.hasTitle??!0){let[r,...o]=e;return r===void 0?[]:[{type:"title",rows:[r]},...o.reduce(Vm,[])]}return e.reduce(Vm,[])};var qm=e=>e.split(`
`).map(t=>({indent:/^\s+/.exec(t)?.[0]?.length??0,text:t}));var Km=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*code:/,"");return{indent:o,type:"codeBlock",fileName:s,content:r.map(i=>i.text.substring(o+1)).join(`
`)}};var ie=(e,{parseOnNested:t,parseOnQuoted:r,patterns:o})=>(n,s,i)=>{if(!t&&s.nested)return i?.()??[];if(!r&&s.quoted)return i?.()??[];for(let a of o){let c=a.exec(n);if(c===null)continue;let l=n.substring(0,c.index),u=n.substring(c.index+(c[0]?.length??0)),p=e(c[0]??"",s);return[...xt(l,s),...p,...xt(u,s)]}return i?.()??[]};var ue=e=>[{type:"plain",raw:e,text:e}],Xm=ie(ue,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]});var KR=/\[\s+\]/,XR=(e,t)=>t.context==="table"?ue(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],Ym=ie(XR,{parseOnNested:!1,parseOnQuoted:!0,patterns:[KR]});var YR=/`.*?`/,JR=(e,t)=>t.context==="table"?ue(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],Jm=ie(JR,{parseOnNested:!1,parseOnQuoted:!0,patterns:[YR]});var QR=/^[$%] .+$/,ZR=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e[0]??"",o=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:o}]},Qm=ie(ZR,{parseOnNested:!1,parseOnQuoted:!1,patterns:[QR]});var ev=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,tv=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.indexOf(" "),o=e.substring(1,r),n=e.substring(r+1,e.length-1),s=new Set(o);if(s.has("*")){let i=o.split("*").length-1;s.delete("*"),s.add(`*-${Math.min(i,10)}`)}return[{type:"decoration",raw:e,rawDecos:o,decos:Array.from(s),nodes:xt(n,{...t,nested:!0})}]},Zm=ie(tv,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ev]});var rv=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,ov=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,nv=/\[https?:\/\/[^\s\]]+\]/,sv=/https?:\/\/[^\s]+/,iv=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.startsWith("[")&&e.endsWith("]")?e.substring(1,e.length-1):e,o=/^https?:\/\/[^\s\]]/.test(r),n=(o?/^https?:\/\/[^\s\]]+/:/https?:\/\/[^\s\]]+$/).exec(r);if(n?.[0]===void 0)return[];let s=o?r.substring(n[0].length):r.substring(0,n.index-1);return[{type:"link",raw:e,pathType:"absolute",href:n[0],content:s.trim()}]},ef=ie(iv,{parseOnNested:!0,parseOnQuoted:!0,patterns:[rv,ov,nv,sv]});var av=/\[\$ .+? \]/,cv=/\[\$ [^\]]+\]/,lv=(e,t)=>t.context==="table"?ue(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],tf=ie(lv,{parseOnNested:!1,parseOnQuoted:!0,patterns:[av,cv]});var rf=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,of=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,pv=e=>{let[t="",r="",o=""]=e.split(","),n=Number.parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),s=Number.parseFloat(r.replace(/^E/,"").replace(/^W/,"-")),i=/^Z\d+$/.test(o)?Number.parseInt(o.replace(/^Z/,""),10):14;return{latitude:n,longitude:s,zoom:i}},uv=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.match(rf)??e.match(of);if(r===null)return[];let o=e.startsWith("[N")||e.startsWith("[S"),[,n="",s=""]=o?r:[r[0],r[2],r[1]],{latitude:i,longitude:a,zoom:c}=pv(n),l=s!==""?`https://www.google.com/maps/place/${encodeURIComponent(s)}/@${i},${a},${c}z`:`https://www.google.com/maps/@${i},${a},${c}z`;return[{type:"googleMap",raw:e,latitude:i,longitude:a,zoom:c,place:s,url:l}]},nf=ie(uv,{parseOnNested:!1,parseOnQuoted:!0,patterns:[rf,of]});var mv=/(?:^|\s)#\S+/,fv=(e,t)=>{if(t.context==="table")return ue(e,t);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),o=e.substring(1);return[...ue(r,t),{type:"hashTag",raw:o,href:o.substring(1)}]},sf=ie(fv,{parseOnNested:!0,parseOnQuoted:!0,patterns:[mv]});var dv=/^\? .+$/,hv=(e,t)=>t.context==="table"?ue(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],af=ie(hv,{parseOnNested:!1,parseOnQuoted:!1,patterns:[dv]});var gv=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/,yv=e=>{let t=e.substring(1,e.length-1),r=t.lastIndexOf(".icon"),o=t.substring(0,r),n=o.startsWith("/")?"root":"relative",s=t.substring(r+5,t.length),i=s.startsWith("*")?Number.parseInt(s.substring(1),10):1;return new Array(i).fill({}).map(()=>({path:o,pathType:n,type:"icon",raw:e}))},cf=ie(yv,{parseOnNested:!0,parseOnQuoted:!0,patterns:[gv]});var xv=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,bv=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?\]/i,Ev=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,wv=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,kv=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg|webp)(\?[^\]\s]+)?$/i.test(e)||Rv(e),Rv=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),vv=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.search(/\s/),o=r!==-1?e.substring(1,r):e.substring(1,e.length-1),n=r!==-1?e.substring(r,e.length-1).replace(/^\s+/,""):"",[s,i]=kv(n)?[n,o]:[o,n];return[{type:"image",raw:e,src:/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(s)?`${s}/thumb/1000`:s,link:i}]},lf=ie(vv,{parseOnNested:!0,parseOnQuoted:!0,patterns:[xv,bv,Ev,wv]});var Tv=/\[\/?[^[\]]+\]/,_v=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},pf=ie(_v,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Tv]});var Pv=/^[0-9]+\. .*$/,Sv=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.indexOf(" "),o=e.substring(0,r-1),n=Number.parseInt(o,10),s=e.substring(r+1,e.length);return[{type:"numberList",raw:e,rawNumber:o,number:n,nodes:xt(s,{...t,nested:!1})}]},uf=ie(Sv,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Pv]});var Ov=/^>.*$/,Lv=(e,t)=>t.context==="table"?ue(e,t):[{type:"quote",raw:e,nodes:xt(e.substring(1),{...t,quoted:!0})}],mf=ie(Lv,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Ov]});var Nv=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,Cv=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.substring(2,e.length-2),o=r.lastIndexOf(".icon"),n=r.substring(0,o),s=n.startsWith("/")?"root":"relative",i=r.substring(o+5,r.length),a=i.startsWith("*")?Number.parseInt(i.substring(1),10):1;return new Array(a).fill({}).map(()=>({path:n,pathType:s,type:"strongIcon",raw:e}))},ff=ie(Cv,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Nv]});var Av=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)\]\]/i,Mv=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,Iv=(e,t)=>{if(t.context==="table")return ue(e,t);let r=e.substring(2,e.length-2),o=/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(r);return[{type:"strongImage",raw:e,src:o?`${r}/thumb/1000`:r}]},df=ie(Iv,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Av,Mv]});var Fv=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,Uv=(e,t)=>t.context==="table"?ue(e,t):[{type:"strong",raw:e,nodes:xt(e.substring(2,e.length-2),{...t,nested:!0})}],hf=ie(Uv,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Fv]});var Dv=(e,t,r)=>e===""?[]:r?.()??[],$v=(...e)=>(t,r)=>e.reduceRight((o,n)=>()=>n(t,r,o),()=>Xm(t,r))(),xt=$v(Dv,mf,af,uf,Jm,Qm,tf,Ym,Zm,df,ff,hf,lf,ef,cf,nf,pf,sf);var gf=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:xt(r.substring(t),{nested:!1,quoted:!1,context:"line"})}};var yf=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*table:/,"");return{indent:o,type:"table",fileName:s,cells:r.map(i=>i.text.substring(o+1)).map(i=>i.split(" ").map(a=>xt(a,{nested:!1,quoted:!1,context:"table"})))}};var xf=e=>({type:"title",text:e.rows[0].text});var bf=e=>{switch(e.type){case"title":return xf(e);case"codeBlock":return Km(e);case"table":return yf(e);case"line":return gf(e)}};var He=(e,t)=>{let r=qm(e);return zm(r,{hasTitle:t?.hasTitle??!0}).map(bf)},Ef=e=>/^\s*\S.*$/m.exec(e)?.[0]?.trim()??"Untitled";var jv=/https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/,Bv=/https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/,Hv=/https?:\/\/(?:www\.|)youtube\.com\/shorts\/([a-zA-Z\d_-]+)(?:\?([^\s]+)|)/,Wv=/https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/,hi=e=>{if(jv.test(e)){let t=new URL(e).searchParams,r=t.get("v");if(r)return{pathType:"com",videoId:r,params:t}}{let t=e.match(Bv);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"dotbe"}}}{let t=e.match(Hv);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"short"}}}{let t=e.match(Wv);if(t){let[,r,o]=t;return{listId:o,params:new URLSearchParams(r),pathType:"list"}}}};var Rf=e=>{let t=He(e,{hasTitle:!0}),r="",o=new Map,n=[],s=new Set,i=[],a=new Set,c=[],l=null,u=[],p=new Set,f=new Set,m=new RegExp(`${globalThis.location?.origin??"https://scrapbox.io"}/files/([a-z0-9]{24})(?:|\\.[a-zA-Z0-9]+)(?:|\\?[^\\s]*)$`),h=x=>{switch(x.type){case"hashTag":if(o.has(ne(x.href)))return;o.set(ne(x.href),!1),n.push(x.href);return;case"link":switch(x.pathType){case"relative":{let E=kf(x.href);if(o.get(ne(E)))return;o.set(ne(E),!0),n.push(E);return}case"root":{let E=kf(x.href);if(/^\/[\w\d-]+\/?$/.test(E)||s.has(ne(E)))return;s.add(ne(E)),i.push(E);return}case"absolute":{if(x.content)return;let E=hi(x.href);if(E&&E.pathType!=="list"){l??=`https://i.ytimg.com/vi/${E.videoId}/mqdefault.jpg`;return}let R=x.href.match(m)?.[1];R&&p.add(R);return}default:return}case"icon":case"strongIcon":{if(x.pathType==="root"||a.has(ne(x.path)))return;a.add(ne(x.path)),c.push(x.path);return}case"image":case"strongImage":{l??=x.src.endsWith("/thumb/1000")?x.src.replace(/\/thumb\/1000$/,"/raw"):x.src;{let E=x.src.match(m)?.[1];E&&p.add(E)}if(x.type==="image"){let E=x.link.match(m)?.[1];E&&p.add(E)}return}case"helpfeel":f.add(x.text);return;case"numberList":case"strong":case"quote":case"decoration":{for(let E of x.nodes)h(E);return}default:return}},g=[];for(let x of t)switch(x.type){case"title":{r=x.text;continue}case"line":u.length<5&&x.nodes.length>0&&u.push(x.nodes[0].type==="helpfeel"||x.nodes[0].type==="commandLine"?wf(x.nodes[0].raw):x.nodes.map(E=>E.raw).join("").trim().slice(0,200));for(let E of x.nodes)h(E);continue;case"codeBlock":u.length<5&&u.push(wf(x.content));continue;case"table":{for(let E of x.cells)for(let R of E)for(let b of R)h(b);if(!["infobox","cosense"].includes(x.fileName))continue;g.push(...x.cells.map(E=>E.map(R=>R.map(b=>b.raw).join("")).join(" ").trim()));continue}}let y=e.split(`
`);return[r,n,i,c,l,u,[...p],[...f],g,y.length,y.reduce((x,E)=>x+[...E].length,0)]},wf=e=>`\`${e.trim().replaceAll("`","\\`").slice(0,198)}\``,kf=e=>e.replace(/#[a-f\d]{24,32}$/,""),vf=e=>e.flatMap(({text:t})=>/^\s*\? .*$/.test(t)?[t.trimStart().slice(2)]:[]);var Fr=(e,t)=>e.length===t.length&&e.every(r=>t.includes(r));function*Tf(e,t,r){let o=t.flatMap(g=>($e(g)?g:g.text).split(`
`));for(let g of pl(e.lines,o,{userId:r}))yield g;let[n,s,i,a,c,l,u,p,f,m,h]=Rf(o.join(`
`));(e.title!==n||!e.persistent)&&(yield{title:n}),Fr(e.links,s)||(yield{links:s}),Fr(e.projectLinks,i)||(yield{projectLinks:i}),Fr(e.icons,a)||(yield{icons:a}),e.image!==c&&(yield{image:c}),Fr(e.descriptions,l)||(yield{descriptions:l}),Fr(e.files,u)||(yield{files:u}),Fr(vf(e.lines),p)||(yield{helpfeels:p}),Fr(e.infoboxDefinition,f)||(yield{infoboxDefinition:f}),yield{linesCount:m},yield{charsCount:h}}var _f=e=>{let t=e.match(/(.+?)(?:_(\d+))?$/),r=t?.[1]??e,o=t?.[2]?parseInt(t[2])+1:2;return`${r}_${o}`};var Pf=()=>Number.MAX_SAFE_INTEGER-Math.floor(Date.now()/1e3);var xe=(e,t,r,o)=>po(e,t,async(n,s,i,a)=>{if(a==="DuplicateTitleError"){let m=_f(t);return i.map(h=>("title"in h&&(h.title=m),h))}let c=r(n.lines,{...n,attempts:s}),l=c instanceof Promise?await c:c;if(l===void 0)return[];let[u,p]=Array.isArray(l)?[l,void 0]:[l.lines,l.pin];if(u.length===0)return[{deleted:!0}];let f=n.lines===u?[]:[...Tf(n,u,n.userId)];return p!==void 0&&(p&&n.pin===0||!p&&n.pin>0)&&f.push({pin:p?Pf():0}),f},o);var Sf=(e,t,r)=>po(e,t,o=>o.persistent?[{deleted:!0}]:[],r);var gi=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i}=le(o??{}),a=await sr(o);if(G(a))return a;let c=new Request(`https://${s}/api/pages/${e}/replace/links`,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":X(a),...n?{Cookie:de(n)}:{}},body:JSON.stringify({from:t,to:r})}),l=await i(c);return G(l)?l:Re(await Te(ve(X(l)),async u=>await Fe(u,["NotFoundError","NotLoggedInError","NotMemberError"])??u),async u=>{let{message:p}=await u.json();return parseInt(p.match(/\d+/)?.[0]??"0")})};var Of=(e,t)=>{let{sid:r,hostName:o,followingId:n}=le(t??{});return new Request(`https://${o}/api/pages/${e}/search/titles${n?`?followingId=${n}`:""}`,r?{headers:{Cookie:de(r)}}:void 0)},Lf=async e=>Re(await Te(ve(e),async t=>t.response.status===422?{name:"InvalidFollowingIdError",message:await t.response.text()}:await Fe(t,["NotFoundError","NotLoggedInError"])??t),t=>t.json().then(r=>({pages:r,followingId:t.headers.get("X-following-id")??""}))),zv=(()=>{let e=async(t,r)=>{let o=await le(r??{}).fetch(Of(t,r));return G(o)?o:Lf(X(o))};return e.toRequest=Of,e.fromResponse=Lf,e})();async function*Nf(e,t){let r;do{let o=await zv(e,{followingId:r,...t});if(G(o)){yield o;return}let n=X(o);yield te(n.pages),r=n.followingId}while(r)}var Cf=async(e,t,r)=>{let{sid:o,hostName:n,fetch:s}=le(r??{}),i=new Request(`https://${n}/api/pages/${t}/search/query?q=${encodeURIComponent(e)}`,o?{headers:{Cookie:de(o)}}:void 0),a=await s(i);return G(a)?a:Re(await Te(ve(X(a)),async c=>await Fe(c,["NotFoundError","NotLoggedInError","NotMemberError","NoQueryError"])??c),c=>c.json())};var Af=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=le(t??{}),s=await sr(t);if(G(s))return s;let i=new Request(`https://${o}/api/embed-text/url?url=${encodeURIComponent(`${e}`)}`,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":X(s),...r?{Cookie:de(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return G(a)?a:Re(await Te(ve(X(a)),async c=>await Fe(c,["SessionError","BadRequestError","InvalidURLError"])??c),async c=>{let{title:l}=await c.json();return l})};var Mf=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=le(t??{}),s=await sr(t);if(G(s))return s;let i=new Request(`https://${o}/api/embed-text/twitter?url=${encodeURIComponent(`${e}`)}`,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":X(s),...r?{Cookie:de(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return G(a)?a:Te(await Re(ve(X(a)),c=>c.json()),async c=>c.response.status===422?{name:"InvalidURLError",message:(await c.response.json()).message}:await Fe(c,["SessionError","BadRequestError"])??c)};var If=async e=>{let{fetch:t,sid:r,hostName:o,gyazoTeamsName:n}=le(e??{}),s=new Request(`https://${o}/api/login/gyazo/oauth-upload/token${n?`?gyazoTeamsName=${n}`:""}`,r?{headers:{Cookie:de(r)}}:void 0),i=await t(s);return G(i)?i:Re(await Te(ve(X(i)),async a=>await Fe(a,["NotLoggedInError"])??a),a=>a.json().then(c=>c.token))};var Ff=(e,t,r,o)=>{let{sid:n,hostName:s}=le(o??{});return new Request(`https://${s}/api/code/${e}/${me(t)}/${me(r)}`,n?{headers:{Cookie:de(n)}}:void 0)},Uf=async e=>Re(await Te(ve(e),async t=>t.response.status===404&&t.response.headers.get("Content-Type")?.includes?.("text/plain")?{name:"NotFoundError",message:"Code block is not found"}:await Fe(t,["NotLoggedInError","NotMemberError"])??t),t=>t.text()),yi=(()=>{let e=async(t,r,o,n)=>{let s=Ff(t,r,o,n),i=await le(n??{}).fetch(s);return G(i)?i:Uf(X(i))};return e.toRequest=Ff,e.fromResponse=Uf,e})();var jf=e=>{let t=typeof e=="string"?new TextEncoder().encode(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),r=[1732584193,4023233417,2562383102,271733878],o=new Uint8Array(ul),n=0,s=0,i=0;[r,o,n,s,i]=$f(r,o,n,s,i,t);let a=ul-n;a<9&&(a+=ul);let c=new Uint8Array(a);c[0]=128,[s,i]=[s<<3,i<<3|s>>>29],c[c.length-8]=s&255,c[c.length-7]=s>>>8&255,c[c.length-6]=s>>>16&255,c[c.length-5]=s>>>24&255,c[c.length-4]=i&255,c[c.length-3]=i>>>8&255,c[c.length-2]=i>>>16&255,c[c.length-1]=i>>>24&255,[r,o,n,s,i]=$f(r,o,n,s,i,new Uint8Array(c.buffer));let l=new ArrayBuffer(16),u=new DataView(l);return u.setUint32(0,r[0],!0),u.setUint32(4,r[1],!0),u.setUint32(8,r[2],!0),u.setUint32(12,r[3],!0),l},ul=64,j=(e,t)=>e<<t|e>>>32-t,pt=(e,t)=>e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,Df=(e,t)=>{let[r,o,n,s]=e,i=pt(t,0),a=pt(t,4),c=pt(t,8),l=pt(t,12),u=pt(t,16),p=pt(t,20),f=pt(t,24),m=pt(t,28),h=pt(t,32),g=pt(t,36),y=pt(t,40),x=pt(t,44),E=pt(t,48),R=pt(t,52),b=pt(t,56),v=pt(t,60);return r=o+j(((n^s)&o^s)+r+i+3614090360,7),s=r+j(((o^n)&r^n)+s+a+3905402710,12),n=s+j(((r^o)&s^o)+n+c+606105819,17),o=n+j(((s^r)&n^r)+o+l+3250441966,22),r=o+j(((n^s)&o^s)+r+u+4118548399,7),s=r+j(((o^n)&r^n)+s+p+1200080426,12),n=s+j(((r^o)&s^o)+n+f+2821735955,17),o=n+j(((s^r)&n^r)+o+m+4249261313,22),r=o+j(((n^s)&o^s)+r+h+1770035416,7),s=r+j(((o^n)&r^n)+s+g+2336552879,12),n=s+j(((r^o)&s^o)+n+y+4294925233,17),o=n+j(((s^r)&n^r)+o+x+2304563134,22),r=o+j(((n^s)&o^s)+r+E+1804603682,7),s=r+j(((o^n)&r^n)+s+R+4254626195,12),n=s+j(((r^o)&s^o)+n+b+2792965006,17),o=n+j(((s^r)&n^r)+o+v+1236535329,22),r=o+j(((o^n)&s^n)+r+a+4129170786,5),s=r+j(((r^o)&n^o)+s+f+3225465664,9),n=s+j(((s^r)&o^r)+n+x+643717713,14),o=n+j(((n^s)&r^s)+o+i+3921069994,20),r=o+j(((o^n)&s^n)+r+p+3593408605,5),s=r+j(((r^o)&n^o)+s+y+38016083,9),n=s+j(((s^r)&o^r)+n+v+3634488961,14),o=n+j(((n^s)&r^s)+o+u+3889429448,20),r=o+j(((o^n)&s^n)+r+g+568446438,5),s=r+j(((r^o)&n^o)+s+b+3275163606,9),n=s+j(((s^r)&o^r)+n+l+4107603335,14),o=n+j(((n^s)&r^s)+o+h+1163531501,20),r=o+j(((o^n)&s^n)+r+R+2850285829,5),s=r+j(((r^o)&n^o)+s+c+4243563512,9),n=s+j(((s^r)&o^r)+n+m+1735328473,14),o=n+j(((n^s)&r^s)+o+E+2368359562,20),r=o+j((o^n^s)+r+p+4294588738,4),s=r+j((r^o^n)+s+h+2272392833,11),n=s+j((s^r^o)+n+x+1839030562,16),o=n+j((n^s^r)+o+b+4259657740,23),r=o+j((o^n^s)+r+a+2763975236,4),s=r+j((r^o^n)+s+u+1272893353,11),n=s+j((s^r^o)+n+m+4139469664,16),o=n+j((n^s^r)+o+y+3200236656,23),r=o+j((o^n^s)+r+R+681279174,4),s=r+j((r^o^n)+s+i+3936430074,11),n=s+j((s^r^o)+n+l+3572445317,16),o=n+j((n^s^r)+o+f+76029189,23),r=o+j((o^n^s)+r+g+3654602809,4),s=r+j((r^o^n)+s+E+3873151461,11),n=s+j((s^r^o)+n+v+530742520,16),o=n+j((n^s^r)+o+c+3299628645,23),r=o+j((n^(o|~s))+r+i+4096336452,6),s=r+j((o^(r|~n))+s+m+1126891415,10),n=s+j((r^(s|~o))+n+b+2878612391,15),o=n+j((s^(n|~r))+o+p+4237533241,21),r=o+j((n^(o|~s))+r+E+1700485571,6),s=r+j((o^(r|~n))+s+l+2399980690,10),n=s+j((r^(s|~o))+n+y+4293915773,15),o=n+j((s^(n|~r))+o+a+2240044497,21),r=o+j((n^(o|~s))+r+h+1873313359,6),s=r+j((o^(r|~n))+s+v+4264355552,10),n=s+j((r^(s|~o))+n+f+2734768916,15),o=n+j((s^(n|~r))+o+R+1309151649,21),r=o+j((n^(o|~s))+r+u+4149444226,6),s=r+j((o^(r|~n))+s+x+3174756917,10),n=s+j((r^(s|~o))+n+c+718787259,15),o=n+j((s^(n|~r))+o+g+3951481745,21),[e[0]+r>>>0,e[1]+o>>>0,e[2]+n>>>0,e[3]+s>>>0]},$f=(e,t,r,o,n,s)=>{let i=64-r;if(s.length<i)t.set(s,r),r+=s.length;else{t.set(s.slice(0,i),r),e=Df(e,t);let a=i;for(;a+64<=s.length;)e=Df(e,s.slice(a,a+64)),a+=64;t.fill(0).set(s.slice(a),0),r=s.length-a}return[o,n]=qv(o,n,s.length),[e,t,r,o,n]},qv=(e,t,r)=>(e+=r,e>4294967295&&(t+=1),[e>>>0,t]);var Kv=new TextEncoder;function Xv(e){let t=typeof e;return t!=="object"?t:e===null?"null":e?.constructor?.name??"object"}function Bf(e){if(typeof e=="string")return Kv.encode(e);if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new TypeError(`Cannot validate the input as it must be a Uint8Array, a string, or an ArrayBuffer: received a value of the type ${Xv(e)}`)}var Hf=new TextEncoder().encode("0123456789abcdef"),c3=new TextEncoder,Yv=new TextDecoder;function Wf(e){let t=Bf(e),r=new Uint8Array(t.length*2);for(let o=0;o<t.length;o++){let n=t[o];r[o*2]=Hf[n>>4],r[o*2+1]=Hf[n&15]}return Yv.decode(r)}var Gf=async(e,t,r)=>{let o=`${Wf(jf(await e.arrayBuffer()))}`,n=await Jv(e,t,o,r);if(G(n))return n;let s=X(n);if("embedUrl"in s)return te(s);let i=await Qv(s.signedUrl,e,r);return G(i)?i:Zv(t,s.fileId,o,r)},Jv=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=le(o??{}),c={md5:r,size:e.size,contentType:e.type,name:e.name},l=await ni(fi(a),()=>sr(o));if(G(l))return l;let u=new Request(`https://${s}/api/gcs/${t}/upload-request`,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":X(l),...n?{Cookie:de(n)}:{}}}),p=await i(u);return G(p)?p:Re(await Te(ve(X(p)),async f=>f.response.status===402?{name:"FileCapacityError",message:(await f.response.json()).message}:f),f=>f.json())},Qv=async(e,t,r)=>{let{sid:o,fetch:n}=le(r??{}),s=await n(e,{method:"PUT",body:t,headers:{"Content-Type":t.type,...o?{Cookie:de(o)}:{}}});return G(s)?s:lo(await Te(ve(X(s)),async i=>i.response.headers.get("Content-Type")?.includes?.("/xml")?{name:"GCSError",message:await i.response.text()}:i),()=>{})},Zv=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=le(o??{}),c=await ni(fi(a),()=>sr(o));if(G(c))return c;let l=new Request(`https://${s}/api/gcs/${e}/verify`,{method:"POST",body:JSON.stringify({md5:r,fileId:t}),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":X(c),...n?{Cookie:de(n)}:{}}}),u=await i(l);return G(u)?u:Re(await Te(ve(X(u)),async p=>p.response.status===404?{name:"NotFoundError",message:(await p.response.json()).message}:p),p=>p.json())};function ut(e){return e.val}function kt(e){return e.err}var Vf=" must not return ",eT="`transformer`",tT="`recoverer`",rT="`defaultValue`",xi=eT+Vf,uo="called with ",bi=rT+" must not be ",Ei=tT+Vf;var oT="`Ok`",zf="`Err`",qf=uo+zf,Kf=uo+oT,nT="Carrying `E` in "+zf+" instead of throwing it directly. See `.cause`",ml="an instance of `Error` of the current realm.",W3="The thrown value is not "+ml,G3="The contained E should be "+ml,sT="This `.cause` is not "+ml;function Ne(e){return e.ok}function ae(e){return{ok:!0,val:e,err:null}}function B(e){return!e.ok}function Q(e){return{ok:!1,val:null,err:e}}function H(e){return Xf(e,qf)}function re(e){return Yf(e,Kf)}function Xf(e,t){if(B(e))throw new TypeError(t);return e.val}function Yf(e,t){if(Ne(e))throw new TypeError(t);return e.err}async function _t(e,t){if(B(e))return e;let r=ut(e),o=await t(r);return ae(o)}function fl(e,t,r){if(Ne(e)){let n=ut(e);return r(n)}let o=kt(e);return t(o)}var wi="`null`",YG=xi+wi,cT=uo+wi,JG=bi+wi,QG=Ei+wi;var ki="`undefined`",oV=xi+ki,lT=uo+ki,nV=bi+ki,sV=Ei+ki;var Qf=async e=>{let t=e.title??".watchlistrc",r="projectsLastAccessed.json",o=await yi(e.project,t,r),n=B(o)?{}:JSON.parse(H(o)||"{}"),s=JSON.parse(localStorage.getItem("projectsLastAccessed")??"{}"),i=new Set([...Object.keys(n),...Object.keys(s)]),a=Object.fromEntries([...i].map(l=>[l,Math.max(n[l]??0,s[l]??0)]).sort((l,u)=>u[1]-l[1])),c=JSON.stringify(a);localStorage.setItem("projectsLastAccessed",c),await xe(e.project,t,()=>[t,"This page is automatically generated. DO NOT EDIT ANYTHING, WHITCH WILL BE OVERWRITTEN.","",`code:${r}`,` ${c}`,""])};var Pt=!1,Ri=e=>{Pt=typeof e=="boolean"?e:new Set(e)},Ur=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...o)=>r(`%c${e}`,dl,...o)];case"log":case"info":case"debug":return[t,(...o)=>{Pt!==!0&&(!Pt||!Pt.has(e))||r(`%c${e}`,dl,...o)}];case"assert":return[t,(o,...n)=>{Pt!==!0&&(!Pt||!Pt.has(e))||r(o,`%c${e}`,dl,...n)}];case"time":case"timeEnd":return[t,o=>{Pt!==!0&&(!Pt||!Pt.has(e))||r(`${e} ${o}`)}];default:return[t,(...o)=>{if(!(Pt!==!0&&(!Pt||!Pt.has(e))))return r(...o)}]}})),dl="color: gray";scrapbox.PageMenu.addMenu({title:"Gyazo",image:"https://i.gyazo.com/503a911fea542532aa5aba0a88eb7b60.png",onClick:()=>window.open("https://gyazo.com/captures")});var Pi,Z,rd,uT,mo,Zf,od,hl,nd,bl,gl,yl,sd,qn={},id=[],mT=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Si=Array.isArray;function Dr(e,t){for(var r in t)e[r]=t[r];return e}function El(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function xr(e,t,r){var o,n,s,i={};for(s in t)s=="key"?o=t[s]:s=="ref"?n=t[s]:i[s]=t[s];if(arguments.length>2&&(i.children=arguments.length>3?Pi.call(arguments,2):r),typeof e=="function"&&e.defaultProps!=null)for(s in e.defaultProps)i[s]===void 0&&(i[s]=e.defaultProps[s]);return Ti(e,i,o,n,null)}function Ti(e,t,r,o,n){var s={type:e,props:t,key:r,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:n??++rd,__i:-1,__u:0};return n==null&&Z.vnode!=null&&Z.vnode(s),s}function Y(e){return e.children}function Yt(e,t){this.props=e,this.context=t}function nn(e,t){if(t==null)return e.__?nn(e.__,e.__i+1):null;for(var r;t<e.__k.length;t++)if((r=e.__k[t])!=null&&r.__e!=null)return r.__e;return typeof e.type=="function"?nn(e):null}function ad(e){var t,r;if((e=e.__)!=null&&e.__c!=null){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if((r=e.__k[t])!=null&&r.__e!=null){e.__e=e.__c.base=r.__e;break}return ad(e)}}function xl(e){(!e.__d&&(e.__d=!0)&&mo.push(e)&&!_i.__r++||Zf!==Z.debounceRendering)&&((Zf=Z.debounceRendering)||od)(_i)}function _i(){var e,t,r,o,n,s,i,a;for(mo.sort(hl);e=mo.shift();)e.__d&&(t=mo.length,o=void 0,s=(n=(r=e).__v).__e,i=[],a=[],r.__P&&((o=Dr({},n)).__v=n.__v+1,Z.vnode&&Z.vnode(o),wl(r.__P,o,n,r.__n,r.__P.namespaceURI,32&n.__u?[s]:null,i,s??nn(n),!!(32&n.__u),a),o.__v=n.__v,o.__.__k[o.__i]=o,pd(i,o,a),o.__e!=s&&ad(o)),mo.length>t&&mo.sort(hl));_i.__r=0}function cd(e,t,r,o,n,s,i,a,c,l,u){var p,f,m,h,g,y,x=o&&o.__k||id,E=t.length;for(c=fT(r,t,x,c,E),p=0;p<E;p++)(m=r.__k[p])!=null&&(f=m.__i===-1?qn:x[m.__i]||qn,m.__i=p,y=wl(e,m,f,n,s,i,a,c,l,u),h=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&kl(f.ref,null,m),u.push(m.ref,m.__c||h,m)),g==null&&h!=null&&(g=h),4&m.__u||f.__k===m.__k?c=ld(m,c,e):typeof m.type=="function"&&y!==void 0?c=y:h&&(c=h.nextSibling),m.__u&=-7);return r.__e=g,c}function fT(e,t,r,o,n){var s,i,a,c,l,u=r.length,p=u,f=0;for(e.__k=new Array(n),s=0;s<n;s++)(i=t[s])!=null&&typeof i!="boolean"&&typeof i!="function"?(c=s+f,(i=e.__k[s]=typeof i=="string"||typeof i=="number"||typeof i=="bigint"||i.constructor==String?Ti(null,i,null,null,null):Si(i)?Ti(Y,{children:i},null,null,null):i.constructor===void 0&&i.__b>0?Ti(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):i).__=e,i.__b=e.__b+1,a=null,(l=i.__i=dT(i,r,c,p))!==-1&&(p--,(a=r[l])&&(a.__u|=2)),a==null||a.__v===null?(l==-1&&f--,typeof i.type!="function"&&(i.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,i.__u|=4))):e.__k[s]=null;if(p)for(s=0;s<u;s++)(a=r[s])!=null&&!(2&a.__u)&&(a.__e==o&&(o=nn(a)),ud(a,a));return o}function ld(e,t,r){var o,n;if(typeof e.type=="function"){for(o=e.__k,n=0;o&&n<o.length;n++)o[n]&&(o[n].__=e,t=ld(o[n],t,r));return t}e.__e!=t&&(t&&e.type&&!r.contains(t)&&(t=nn(e)),r.insertBefore(e.__e,t||null),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function $r(e,t){return t=t||[],e==null||typeof e=="boolean"||(Si(e)?e.some(function(r){$r(r,t)}):t.push(e)),t}function dT(e,t,r,o){var n,s,i=e.key,a=e.type,c=t[r];if(c===null||c&&i==c.key&&a===c.type&&!(2&c.__u))return r;if(o>(c!=null&&!(2&c.__u)?1:0))for(n=r-1,s=r+1;n>=0||s<t.length;){if(n>=0){if((c=t[n])&&!(2&c.__u)&&i==c.key&&a===c.type)return n;n--}if(s<t.length){if((c=t[s])&&!(2&c.__u)&&i==c.key&&a===c.type)return s;s++}}return-1}function ed(e,t,r){t[0]=="-"?e.setProperty(t,r??""):e[t]=r==null?"":typeof r!="number"||mT.test(t)?r:r+"px"}function vi(e,t,r,o,n){var s;e:if(t=="style")if(typeof r=="string")e.style.cssText=r;else{if(typeof o=="string"&&(e.style.cssText=o=""),o)for(t in o)r&&t in r||ed(e.style,t,"");if(r)for(t in r)o&&r[t]===o[t]||ed(e.style,t,r[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(nd,"$1")),t=t.toLowerCase()in e||t=="onFocusOut"||t=="onFocusIn"?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=r,r?o?r.u=o.u:(r.u=bl,e.addEventListener(t,s?yl:gl,s)):e.removeEventListener(t,s?yl:gl,s);else{if(n=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=r??"";break e}catch{}typeof r=="function"||(r==null||r===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&r==1?"":r))}}function td(e){return function(t){if(this.l){var r=this.l[t.type+e];if(t.t==null)t.t=bl++;else if(t.t<r.u)return;return r(Z.event?Z.event(t):t)}}}function wl(e,t,r,o,n,s,i,a,c,l){var u,p,f,m,h,g,y,x,E,R,b,v,k,O,L,N,P,T=t.type;if(t.constructor!==void 0)return null;128&r.__u&&(c=!!(32&r.__u),s=[a=t.__e=r.__e]),(u=Z.__b)&&u(t);e:if(typeof T=="function")try{if(x=t.props,E="prototype"in T&&T.prototype.render,R=(u=T.contextType)&&o[u.__c],b=u?R?R.props.value:u.__:o,r.__c?y=(p=t.__c=r.__c).__=p.__E:(E?t.__c=p=new T(x,b):(t.__c=p=new Yt(x,b),p.constructor=T,p.render=gT),R&&R.sub(p),p.props=x,p.state||(p.state={}),p.context=b,p.__n=o,f=p.__d=!0,p.__h=[],p._sb=[]),E&&p.__s==null&&(p.__s=p.state),E&&T.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Dr({},p.__s)),Dr(p.__s,T.getDerivedStateFromProps(x,p.__s))),m=p.props,h=p.state,p.__v=t,f)E&&T.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),E&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(E&&T.getDerivedStateFromProps==null&&x!==m&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(x,b),!p.__e&&(p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(x,p.__s,b)===!1||t.__v==r.__v)){for(t.__v!=r.__v&&(p.props=x,p.state=p.__s,p.__d=!1),t.__e=r.__e,t.__k=r.__k,t.__k.some(function(_){_&&(_.__=t)}),v=0;v<p._sb.length;v++)p.__h.push(p._sb[v]);p._sb=[],p.__h.length&&i.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(x,p.__s,b),E&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(m,h,g)})}if(p.context=b,p.props=x,p.__P=e,p.__e=!1,k=Z.__r,O=0,E){for(p.state=p.__s,p.__d=!1,k&&k(t),u=p.render(p.props,p.state,p.context),L=0;L<p._sb.length;L++)p.__h.push(p._sb[L]);p._sb=[]}else do p.__d=!1,k&&k(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++O<25);p.state=p.__s,p.getChildContext!=null&&(o=Dr(Dr({},o),p.getChildContext())),E&&!f&&p.getSnapshotBeforeUpdate!=null&&(g=p.getSnapshotBeforeUpdate(m,h)),a=cd(e,Si(N=u!=null&&u.type===Y&&u.key==null?u.props.children:u)?N:[N],t,r,o,n,s,i,a,c,l),p.base=t.__e,t.__u&=-161,p.__h.length&&i.push(p),y&&(p.__E=p.__=null)}catch(_){if(t.__v=null,c||s!=null)if(_.then){for(t.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;s[s.indexOf(a)]=null,t.__e=a}else for(P=s.length;P--;)El(s[P]);else t.__e=r.__e,t.__k=r.__k;Z.__e(_,t,r)}else s==null&&t.__v==r.__v?(t.__k=r.__k,t.__e=r.__e):a=t.__e=hT(r.__e,t,r,o,n,s,i,c,l);return(u=Z.diffed)&&u(t),128&t.__u?void 0:a}function pd(e,t,r){for(var o=0;o<r.length;o++)kl(r[o],r[++o],r[++o]);Z.__c&&Z.__c(t,e),e.some(function(n){try{e=n.__h,n.__h=[],e.some(function(s){s.call(n)})}catch(s){Z.__e(s,n.__v)}})}function hT(e,t,r,o,n,s,i,a,c){var l,u,p,f,m,h,g,y=r.props,x=t.props,E=t.type;if(E=="svg"?n="http://www.w3.org/2000/svg":E=="math"?n="http://www.w3.org/1998/Math/MathML":n||(n="http://www.w3.org/1999/xhtml"),s!=null){for(l=0;l<s.length;l++)if((m=s[l])&&"setAttribute"in m==!!E&&(E?m.localName==E:m.nodeType==3)){e=m,s[l]=null;break}}if(e==null){if(E==null)return document.createTextNode(x);e=document.createElementNS(n,E,x.is&&x),a&&(Z.__m&&Z.__m(t,s),a=!1),s=null}if(E===null)y===x||a&&e.data===x||(e.data=x);else{if(s=s&&Pi.call(e.childNodes),y=r.props||qn,!a&&s!=null)for(y={},l=0;l<e.attributes.length;l++)y[(m=e.attributes[l]).name]=m.value;for(l in y)if(m=y[l],l!="children"){if(l=="dangerouslySetInnerHTML")p=m;else if(!(l in x)){if(l=="value"&&"defaultValue"in x||l=="checked"&&"defaultChecked"in x)continue;vi(e,l,null,m,n)}}for(l in x)m=x[l],l=="children"?f=m:l=="dangerouslySetInnerHTML"?u=m:l=="value"?h=m:l=="checked"?g=m:a&&typeof m!="function"||y[l]===m||vi(e,l,m,y[l],n);if(u)a||p&&(u.__html===p.__html||u.__html===e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),cd(e,Si(f)?f:[f],t,r,o,E=="foreignObject"?"http://www.w3.org/1999/xhtml":n,s,i,s?s[0]:r.__k&&nn(r,0),a,c),s!=null)for(l=s.length;l--;)El(s[l]);a||(l="value",E=="progress"&&h==null?e.removeAttribute("value"):h!==void 0&&(h!==e[l]||E=="progress"&&!h||E=="option"&&h!==y[l])&&vi(e,l,h,y[l],n),l="checked",g!==void 0&&g!==e[l]&&vi(e,l,g,y[l],n))}return e}function kl(e,t,r){try{if(typeof e=="function"){var o=typeof e.__u=="function";o&&e.__u(),o&&t==null||(e.__u=e(t))}else e.current=t}catch(n){Z.__e(n,r)}}function ud(e,t,r){var o,n;if(Z.unmount&&Z.unmount(e),(o=e.ref)&&(o.current&&o.current!==e.__e||kl(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){Z.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(n=0;n<o.length;n++)o[n]&&ud(o[n],t,r||typeof e.type!="function");r||El(e.__e),e.__c=e.__=e.__e=void 0}function gT(e,t,r){return this.constructor(e,r)}function mt(e,t,r){var o,n,s,i;t==document&&(t=document.documentElement),Z.__&&Z.__(e,t),n=(o=typeof r=="function")?null:r&&r.__k||t.__k,s=[],i=[],wl(t,e=(!o&&r||t).__k=xr(Y,null,[e]),n||qn,qn,t.namespaceURI,!o&&r?[r]:n?null:t.firstChild?Pi.call(t.childNodes):null,s,!o&&r?r:n?n.__e:t.firstChild,o,i),pd(s,e,i)}function Kn(e,t){var r={__c:t="__cC"+sd++,__:e,Consumer:function(o,n){return o.children(n)},Provider:function(o){var n,s;return this.getChildContext||(n=new Set,(s={})[t]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){n=null},this.shouldComponentUpdate=function(i){this.props.value!==i.value&&n.forEach(function(a){a.__e=!0,xl(a)})},this.sub=function(i){n.add(i);var a=i.componentWillUnmount;i.componentWillUnmount=function(){n&&n.delete(i),a&&a.call(i)}}),o.children}};return r.Provider.__=r.Consumer.contextType=r}Pi=id.slice,Z={__e:function(e,t,r,o){for(var n,s,i;t=t.__;)if((n=t.__c)&&!n.__)try{if((s=n.constructor)&&s.getDerivedStateFromError!=null&&(n.setState(s.getDerivedStateFromError(e)),i=n.__d),n.componentDidCatch!=null&&(n.componentDidCatch(e,o||{}),i=n.__d),i)return n.__E=n}catch(a){e=a}throw e}},rd=0,uT=function(e){return e!=null&&e.constructor==null},Yt.prototype.setState=function(e,t){var r;r=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=Dr({},this.state),typeof e=="function"&&(e=e(Dr({},r),this.props)),e&&Dr(r,e),e!=null&&this.__v&&(t&&this._sb.push(t),xl(this))},Yt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),xl(this))},Yt.prototype.render=Y,mo=[],od=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,hl=function(e,t){return e.__v.__b-t.__v.__b},_i.__r=0,nd=/(PointerCapture)$|Capture$/i,bl=0,gl=td(!1),yl=td(!0),sd=0;var fo,Ce,Rl,md,Xn=0,Ed=[],je=Z,fd=je.__b,dd=je.__r,hd=je.diffed,gd=je.__c,yd=je.unmount,xd=je.__;function Yn(e,t){je.__h&&je.__h(Ce,e,Xn||t),Xn=0;var r=Ce.__H||(Ce.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function J(e){return Xn=1,jr(wd,e)}function jr(e,t,r){var o=Yn(fo++,2);if(o.t=e,!o.__c&&(o.__=[r?r(t):wd(void 0,t),function(a){var c=o.__N?o.__N[0]:o.__[0],l=o.t(c,a);c!==l&&(o.__N=[l,o.__[1]],o.__c.setState({}))}],o.__c=Ce,!Ce.u)){var n=function(a,c,l){if(!o.__c.__H)return!0;var u=o.__c.__H.__.filter(function(f){return!!f.__c});if(u.every(function(f){return!f.__N}))return!s||s.call(this,a,c,l);var p=o.__c.props!==a;return u.forEach(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(p=!0)}}),s&&s.call(this,a,c,l)||p};Ce.u=!0;var s=Ce.shouldComponentUpdate,i=Ce.componentWillUpdate;Ce.componentWillUpdate=function(a,c,l){if(this.__e){var u=s;s=void 0,n(a,c,l),s=u}i&&i.call(this,a,c,l)},Ce.shouldComponentUpdate=n}return o.__N||o.__}function oe(e,t){var r=Yn(fo++,3);!je.__s&&Tl(r.__H,t)&&(r.__=e,r.i=t,Ce.__H.__h.push(r))}function Li(e,t){var r=Yn(fo++,4);!je.__s&&Tl(r.__H,t)&&(r.__=e,r.i=t,Ce.__h.push(r))}function qe(e){return Xn=5,C(function(){return{current:e}},[])}function C(e,t){var r=Yn(fo++,7);return Tl(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function F(e,t){return Xn=8,C(function(){return e},t)}function br(e){var t=Ce.context[e.__c],r=Yn(fo++,9);return r.c=e,t?(r.__==null&&(r.__=!0,t.sub(Ce)),t.props.value):e.__}function yT(){for(var e;e=Ed.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Oi),e.__H.__h.forEach(vl),e.__H.__h=[]}catch(t){e.__H.__h=[],je.__e(t,e.__v)}}je.__b=function(e){Ce=null,fd&&fd(e)},je.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),xd&&xd(e,t)},je.__r=function(e){dd&&dd(e),fo=0;var t=(Ce=e.__c).__H;t&&(Rl===Ce?(t.__h=[],Ce.__h=[],t.__.forEach(function(r){r.__N&&(r.__=r.__N),r.i=r.__N=void 0})):(t.__h.forEach(Oi),t.__h.forEach(vl),t.__h=[],fo=0)),Rl=Ce},je.diffed=function(e){hd&&hd(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Ed.push(t)!==1&&md===je.requestAnimationFrame||((md=je.requestAnimationFrame)||xT)(yT)),t.__H.__.forEach(function(r){r.i&&(r.__H=r.i),r.i=void 0})),Rl=Ce=null},je.__c=function(e,t){t.some(function(r){try{r.__h.forEach(Oi),r.__h=r.__h.filter(function(o){return!o.__||vl(o)})}catch(o){t.some(function(n){n.__h&&(n.__h=[])}),t=[],je.__e(o,r.__v)}}),gd&&gd(e,t)},je.unmount=function(e){yd&&yd(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.forEach(function(o){try{Oi(o)}catch(n){t=n}}),r.__H=void 0,t&&je.__e(t,r.__v))};var bd=typeof requestAnimationFrame=="function";function xT(e){var t,r=function(){clearTimeout(o),bd&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(r,100);bd&&(t=requestAnimationFrame(r))}function Oi(e){var t=Ce,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),Ce=t}function vl(e){var t=Ce;e.__c=e.__(),Ce=t}function Tl(e,t){return!e||e.length!==t.length||t.some(function(r,o){return r!==e[o]})}function wd(e,t){return typeof t=="function"?t(e):t}function Ke(e){return typeof e=="number"}var bT=(e,t,r)=>{let o=t.name||"anonymous predicate",n=typeof e,s=JSON.stringify(e,null,2);return`Expected ${r??"a value"} that satisfies the predicate ${o}, got ${n}: ${s}`},ET=bT,_l=class e extends Error{constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.name=this.constructor.name}};function kd(e,t,r={}){if(!t(e))throw new _l(r.message??ET(e,t,r.name))}function Rd(e,t,r={}){return kd(e,t,r),e}function St(e){return typeof e>"u"}var Ni=!1,vd=null,Td=()=>{scrapbox.addListener("lines:changed",()=>Ni=!1),scrapbox.addListener("layout:changed",()=>Ni=!1),Td=void 0},_d=()=>(Td?.(),Ni||(vd=scrapbox.Page.lines,Ni=!0),vd);var Pd=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError(`"${t}" must be HTMLDivElememt but actual is "${e}"`)};var Sd=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError(`"${t}" must be HTMLTextAreaElement but actual is "${e}"`)};var Od=()=>Ci(document.getElementById("editor"),"div#editor"),Jn=()=>Ci(document.getElementsByClassName("lines").item(0),"div.lines");var Xe=()=>{let e=document.getElementById("text-input");if(e)return Sd(e,"textarea#text-input"),e};var Ld=()=>Ci(document.getElementsByClassName("popup-menu")?.[0],"div.popup-menu");var Nd=()=>Ci(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),Ci=(e,t)=>{if(e)return Pd(e,t),e};var ft=()=>{let e=Jn();if(!e)throw Error("div.lines is not found.");let t=Object.keys(e).find(r=>r.startsWith("__reactFiber"));if(!t)throw Error('div.lines must has the property whose name starts with "__reactFiber"');return e[t].return.stateNode.props.lines};var Er=e=>e.match(/^(\s*)/)?.[1]?.length??0,ho=(e,t)=>{let r=Er(Cd(e,t)),o=0;for(;e+o+1<t.length&&Er(Cd(e+o+1,t))>r;)o++;return o},Cd=(e,t)=>{let r=t[e];return $e(r)?r:r.text};var Pl=e=>{if(St(e))return;if(Ke(e))return Ai(e)?.id;if($e(e))return e.startsWith("L")?e.slice(1):e;if(e.classList.contains("line"))return e.id.slice(1);let t=e.closest(".line");if(t)return t.id.slice(1)},Ad=e=>{if(St(e))return;if(Ke(e))return e;let t=Pl(e);return t?ft().findIndex(r=>r.id===t):-1};var Ai=e=>{if(St(e))return;if(Ke(e))return ft()[e];let t=Pl(e);return t?ft().find(r=>r.id===t):void 0},wr=e=>{if(Md(e))return e;let t=Pl(e);if(St(t))return t;let r=document.getElementById(`L${t}`);if(!St(r))return r},Md=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var Jt=()=>Rd(_d(),gr),Ye=e=>{if(St(e))return;if(Ke(e)||$e(e))return Ai(e)?.text;if(!(e instanceof HTMLElement))return;if(Md(e))return Ai(e)?.text;if(e.classList.contains("char-index"))return e.textContent??void 0;if(e.classList.contains("line")||e.getElementsByClassName("lines")?.[0])return ft().map(({text:o})=>o).join(`
`);let t=[],r=Ai(e);if(!St(r)){for(let o of kT(e))t.push(RT(o));return r.text.slice(Math.min(...t),Math.max(...t)+1)}};var Id=()=>{let e=Jn()?.firstElementChild;if(!St(e))return e},Fd=()=>{let e=Jn()?.lastElementChild;if(!St(e))return e};var Sl=e=>{let t=Ad(e);if(!St(t))return ho(t,Jt())};function*kT(e){let t=e.getElementsByClassName("char-index");for(let r=0;r<t.length;r++)yield t[0]}var Ol=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index"),RT=e=>{if(!Ol(e))throw Error("A char DOM is required.");let t=e.className.match(/c-(\d+)/)?.[1];if(St(t))throw Error('.char-index must have ".c-{\\d}"');return parseInt(t)},Ud=e=>{let t=e?.getElementsByClassName?.("c-0")?.[0];return Ol(t)?t:void 0};var Qn=(e,t)=>{let r=wr(e)?.getElementsByClassName?.(`c-${t}`)?.[0];return Ol(r)?r:void 0};var We=(e,t)=>{let{noModifiedKeys:r=!1,...o}=t??{},n={bubbles:!0,cancelable:!0,keyCode:vT[e],...r?{}:{...o}},s=Xe();if(!s)throw Error("#text-input must exist.");s.dispatchEvent(new KeyboardEvent("keydown",n)),s.dispatchEvent(new KeyboardEvent("keyup",n))},vT={Backspace:8,Tab:9,Enter:13,Delete:46,Escape:27," ":32,PageUp:33,PageDown:34,End:35,Home:36,ArrowLeft:37,ArrowUp:38,ArrowRight:39,ArrowDown:40,a:65,A:65,b:66,B:66,c:67,C:67,d:68,D:68,e:69,E:69,f:70,F:70,g:71,G:71,h:72,H:72,i:73,I:73,j:74,J:74,k:75,K:75,l:76,L:76,m:77,M:77,n:78,N:78,o:79,O:79,p:80,P:80,q:81,Q:81,r:82,R:82,s:83,S:83,t:84,T:84,u:85,U:85,v:86,V:86,w:87,W:87,x:88,X:88,y:89,Y:89,z:90,Z:90,0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,F1:113,F2:114,F3:115,F4:116,F5:117,F6:118,F7:119,F8:120,F9:121,F10:122,F11:123,F12:124,":":186,"*":186,";":187,"+":187,"-":189,"=":189,".":190,">":190,"/":191,"?":191,"@":192,"`":192,"[":219,"{":219,"\\":220,"|":220,"]":221,"}":221,"^":222,"~":222,_:226};var Ll=async(e,t)=>{let r={button:t.button??0,clientX:t.X,clientY:t.Y,bubbles:!0,cancelable:!0,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,view:window};e.dispatchEvent(new MouseEvent("mousedown",r)),e.dispatchEvent(new MouseEvent("mouseup",r)),e.dispatchEvent(new MouseEvent("click",r)),await Pe(10)};var Me=()=>{let e=Xe();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(r=>r.startsWith("__reactFiber"));if(!t)throw Error('div.cursor must has the property whose name starts with "__reactFiber"');return e[t].return.return.stateNode.props};var Nl=e=>{let{top:t,bottom:r}=e.getBoundingClientRect();return t>=0&&r<=globalThis.innerHeight};function*Ot(e,t){for(let r=e;r<t;r++)yield r}var Cl=()=>{We("Home"),We("Home")};var Dd=async()=>{let e=Id();if(!e)throw Error(".line:first-of-type can't be found.");Nl(e)||e.scrollIntoView({block:"center"});let t=Ud(e);if(!t)throw Error(".line:first-of-type .c-0 can't be found.");let{left:r,top:o}=t.getBoundingClientRect();await Ll(e,{X:r,Y:o})},$d=async()=>{await jd(Fd())},Al=async e=>{await jd(wr(e))},jd=async e=>{if(!e)throw Error("The target line DOM is failed to find.");Nl(e)||e.scrollIntoView({block:"center"});let{right:t,top:r,height:o}=e.getElementsByClassName("text")[0].getBoundingClientRect();await Ll(e,{X:t+1,Y:r+o/2})};var Bd=(e=1)=>{for(let t of Ot(0,e))We("z",{ctrlKey:!0})},Hd=(e=1)=>{for(let t of Ot(0,e))We("z",{shiftKey:!0,ctrlKey:!0})};var Wd=async(e,t)=>{await Al(e),Cl(),We("Enter"),We("ArrowUp"),await Je(t)},ct=async(e,t,r)=>{await Al(e),Cl();for(let o of Ot(e,t))We("ArrowDown",{shiftKey:!0});We("End",{shiftKey:!0}),await Je(r)};var Mi=(e=1)=>{for(let t of Ot(0,e))We("ArrowRight",{ctrlKey:!0})},Ii=(e=1)=>{for(let t of Ot(0,e))We("ArrowLeft",{ctrlKey:!0})};var Fi=(e=1)=>{for(let t of Ot(0,e))We("ArrowUp",{ctrlKey:!0})},Ui=(e=1)=>{for(let t of Ot(0,e))We("ArrowDown",{ctrlKey:!0})},Di=(e=1)=>{for(let t of Ot(0,e))We("ArrowRight",{altKey:!0})},$i=(e=1)=>{for(let t of Ot(0,e))We("ArrowLeft",{altKey:!0})};var ji=(e=1)=>{for(let t of Ot(0,e))We("ArrowUp",{altKey:!0})},Bi=(e=1)=>{for(let t of Ot(0,e))We("ArrowDown",{altKey:!0})},Je=async e=>{let t=Xe();if(!t)throw Error("#text-input is not ditected.");t.focus(),t.value=e;let r=new InputEvent("input",{bubbles:!0});t.dispatchEvent(r),await Pe(1)};var Le=()=>{let e=Nd();if(!e)throw new Error("div.status-bar can't be found");let t=document.createElement("div");return e.append(t),{render:(...r)=>{t.textContent="";let o=Gd(...r);o&&t.append(o)},dispose:()=>t.remove()}},Gd=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":return[_T()];case"check-circle":return[PT()];case"exclamation-triangle":return[ST()];case"text":return[Hi(o.text)];case"group":{let n=Gd(...o.items);return n?[n]:[]}}});if(t.length===0)return;if(t.length===1)return t[0];let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r},Hi=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},_T=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),Hi(e)},PT=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),Hi(e)},ST=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),Hi(e)};var sn=e=>{let t=JSON.parse(localStorage.getItem("pageTransitionContext")??""),r=e.type==="page"?e.from.project===e.to.project?e.from.title===e.to.title?{titleHint:e.to.title}:{linkFrom:e.from.title}:{linkFrom:`/${e.from.project}/${e.from.title}`}:{searchQuery:e.query};t[`page_${ne(e.to.title)}`]=r,localStorage.setItem("pageTransitionContext",JSON.stringify(t))};var OT=(e,t,r)=>{let o=new URL(`/${e}/${me(t)}`,location.href);if(r?.body&&(o.search=`?body=${encodeURIComponent(r.body)}`),r?.id&&(o.hash=`#${r.id}`),r?.context&&sn({...r?.context,to:{project:e,title:t}}),r?.newTab!==!1&&(r?.newTab===!0||e!==scrapbox.Project.name)){globalThis.open(o);return}if(r?.reload!==!1&&(r?.reload===!0||e!==scrapbox.Project.name)){globalThis.open(o,"_self");return}let n=document.createElement("a");n.href=o.toString(),document.body.append(n),n.click(),n.remove()},Zn=(e,t,r)=>OT(e,t,{newTab:!1,reload:!1,body:r});var an=async(e,t)=>{let r=await globalThis.caches.keys();for(let o of r.sort().reverse()){let s=await(await caches.open(o)).match(e,t);if(s)return s}},Wi=async(e,t)=>{let r=t.clone();return await(await caches.open(LT(new Date))).put(e,r)},LT=e=>`api-${e.getFullYear()}-${`${e.getMonth()+1}`.padStart(2,"0")}-${`${e.getDate()}`.padStart(2,"0")}`;var Lt=()=>{let e=Xe();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(s=>s.startsWith("__reactFiber"));if(!t)throw Error('#text-input must has the property whose name starts with "__reactFiber"');let r=e[t].return.return.stateNode._stores,o=r.find(s=>s.constructor.name==="Cursor");if(!o)throw Error('#text-input must has a "Cursor" store.');let n=r.find(s=>s.constructor.name==="Selection");if(!n)throw Error('#text-input must has a "Selection" store.');return{cursor:o,selection:n}};var Br=()=>Lt().cursor;var Gi=()=>Lt().selection;var es=e=>e===void 0?0:typeof e=="boolean"?Number(e):(e.capture?1:0)|(e.once?2:0)|(e.passive?4:0),Vd=e=>{if(e===0)return;let t={};return e&1&&(t.capture=!0),e&2&&(t.once=!0),e&4&&(t.passive=!0),t};var Vi=new Map,Ml=new Map,Il=()=>{scrapbox.on("layout:changed",()=>{let e=Xe();if(e)for(let[t,r]of Vi)for(let[o,n]of r)for(let s of n)e.addEventListener(t,o,Vd(s))}),Il=void 0},zd=(e,t,r)=>{Il?.();let o=Vi.get(e)??new Map,n=o.get(t)??new Set;if(n.has(es(r)))return;if(n.add(es(r)),o.set(t,n),Vi.set(e,o),typeof r=="object"&&r?.once){let i=Ml.get(t)??new Map,a=es(r),c=function(u){return Fl(e,t,r),i.delete(a),t.call(this,u)};i.set(a,c),Ml.set(t,i);let l=Xe();if(!l)return;l.addEventListener(e,c,r)}let s=Xe();s&&s.addEventListener(e,t,r)},Fl=(e,t,r)=>{Il?.();let o=Vi.get(e);if(!o)return;let n=o.get(t);if(!n)return;let s=es(r);if(n.delete(s),typeof r=="object"&&r?.once){let a=Ml.get(t);if(!a)return;let c=a.get(s);if(!c)return;let l=Xe();if(!l)return;l.removeEventListener(e,c,r),a.delete(s);return}let i=Xe();i&&i.removeEventListener(e,t,r)};var qd={"&":"\\x26","!":"\\x21","#":"\\x23",$:"\\$","%":"\\x25","*":"\\*","+":"\\+",",":"\\x2c",".":"\\.",":":"\\x3a",";":"\\x3b","<":"\\x3c","=":"\\x3d",">":"\\x3e","?":"\\?","@":"\\x40","^":"\\^","`":"\\x60","~":"\\x7e","(":"\\(",")":"\\)","[":"\\[","]":"\\]","{":"\\{","}":"\\}","/":"\\/","-":"\\x2d","\\":"\\\\","|":"\\|"},NT=new RegExp(`[${Object.values(qd).join("")}]`,"gu");function Kd(e){return e.replaceAll(NT,t=>qd[t]).replace(/^[0-9a-zA-Z]/,t=>`\\x${t.codePointAt(0).toString(16)}`)}var CT=0,g8=Array.isArray;function d(e,t,r,o,n,s){t||(t={});var i,a,c=t;if("ref"in c)for(a in c={},t)a=="ref"?i=t[a]:c[a]=t[a];var l={type:e,props:c,key:r,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--CT,__i:-1,__u:0,__source:n,__self:s};if(typeof e=="function"&&(i=e.defaultProps))for(a in i)c[a]===void 0&&(c[a]=i[a]);return Z.vnode&&Z.vnode(l),l}var Xd=({project:e,title:t,words:r,lines:o,query:n,close:s})=>{let i=F(c=>{sn({type:"search",query:n,to:{project:e,title:t}}),!(c.metaKey||c.ctrlKey||c.altKey||c.shiftKey)&&s()},[e,t,n,s]),a=C(()=>{let c=new RegExp(`(${r.map(l=>Kd(l)).join("|")})`,"i");return o.flatMap(l=>{let u=l.split(c);return d("span",{children:u.map((p,f)=>f%2===0?p:d("strong",{children:p}))})})},[o,r]);return d("a",{href:`/${e}/${me(t)}`,target:`${e===scrapbox.Project.name?"":"_blank"}`,rel:`${e===scrapbox.Project.name?"route":"noopener noreferrer"}`,onClick:i,children:[t,d("div",{className:"description",children:a})]})};var Yd=e=>{let[t,r]=J(e),o=F(()=>r(!0),[]),n=F(()=>r(!1),[]),s=F(()=>r(i=>!i),[]);return[t,{open:o,close:n,toggle:s}]};var Jd=(e,t)=>{let[r,o]=J(),[n,s]=J(!1),i=qe(Promise.resolve());return oe(()=>{if(t===""){o(void 0);return}let a=!1;return i.current=(async()=>{if(await i.current,!a){s(!0);try{let c=await Cf(t,e);if(a)return;o(Ae(c)?X(c):void 0)}finally{s(!1)}}})(),()=>a=!0},[t,e]),{loading:n,result:r}};var Qd=()=>d("style",{children:`.modal {
position:fixed;
inset:0;
z-index:1050;
background-color:#000c;
display: flex;
flex-direction: column;
align-items: center;
row-gap: 10px;
padding: 10px;
}
.closed {
display: none;
}
.modal > * {
color: var(--page-text-color, #4a4a4a);
background-color: var(--page-bg, #fefefe);
border: 2px solid var(--body-bg, #dcdde0);
border-radius: 4px;
padding: 5px;
width: calc(var(--item-width, 100%) - 10px);
}
@media (min-width: 768px) {
.modal {
padding: 30px;
}
}
.controller {
display: flex;
gap: 0.2em;
flex-direction: column;
}
input {
border-radius: 5px;
padding: 0 10px;
height: 32px;
border: transparent;
box-shadow: none;
color: var(--search-form-text-color, rgba(255, 255, 255, 0.35));
background-color: var(--search-form-bg, rgba(255, 255, 255, 0.15))
}
.result {
flex-direction: column;
width: 100%;
padding: 5px 0;
margin: 2px 0 0;
list-style: none;
font-size: 14px;
font-weight: normal;
line-height: 28px;
text-align: left;
border: 1px solid rgba(0,0,0,0.15);
border-radius: 4px;
background-clip: padding-box;
white-space: nowrap;
overflow-x: hidden;
overflow-y: auto;
}
a {
display: block;
padding: 3px 20px;
clear: both;
align-items: center;
user-select: none;
text-decoration: none;
overflow: hidden;
text-overflow: ellipsis;
color: inherit;
}
.description {
margin-top: 0.5em;
color: var(--incremental-fulltext-search-description-text-color, #c4c4c4);
font-size: 12px;
line-height: 14px;
max-height: 28px;
overflow: hidden;
text-overflow: ellipsis;
}
.description strong {
background-color: #ff0;
color: #666;
}
.spinner::before {
display: inline-block;
font-style: normal;
font-variant: normal;
text-rendering: auto;
line-height: 1;
content: "\f110";
font-family: "Font Awesome 5 Free";
font-weight: 900;
margin: 0;
padding: 0;
box-sizing: border-box;
animation: fa-spin 2s linear infinite;
}`});var AT=()=>d("i",{className:"spinner"}),Zd=({exportOps:e})=>{let[t,r]=J(""),o=scrapbox.Project.name,{loading:n,result:s}=Jd(o,t),i=F(m=>{r(m.currentTarget.value)},[]),[a,{open:c,close:l,toggle:u}]=Yd(!1),p=qe({open:c,close:l,toggle:u});oe(()=>{Object.assign(p.current,{open:c,close:l,toggle:u})},[]),oe(()=>e(p.current),[e]);let f=F(m=>{m.target instanceof HTMLElement&&m.target.id==="background"&&l()},[]);return d(Y,{children:[d(Qd,{}),d("div",{id:"background",className:`modal${a?"":" closed"}`,onClick:f,children:[d("div",{className:"controller",children:[d("input",{type:"text",value:t,onInput:i}),d("div",{className:"info",children:[n&&d(AT,{}),`${s?.pages?.length??0} pages`]})]}),s?.pages&&s.pages.length>0&&d("ul",{className:"result",children:s.pages.map(m=>d("li",{children:d(Xd,{...m,project:o,query:t,close:l})},m.title))})]})]})};var eh=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"});return document.body.append(e),new Promise(r=>{mt(d(Zd,{exportOps:r}),t)})};var zi=(e,t)=>Object.hasOwn(e,t),th={left:"ArrowLeft",right:"ArrowRight",up:"ArrowUp",down:"ArrowDown",bs:"Backspace",menu:"ContextMenu",apps:"ContextMenu",del:"Delete",return:"Enter",cr:"Enter",esc:"Escape",pgup:"PageUp",pgdn:"PageDown",lt:"<",less:"<",lesser:"<",gt:">",greater:">"},sh=e=>{let t=e.toLowerCase();return zi(th,t)?th[t]:e},rh={Backquote:["`","~"],Digit1:["1","!"],Digit2:["2","@"],Digit3:["3","#"],Digit4:["4","$"],Digit5:["5","%"],Digit6:["6","^"],Digit7:["7","&"],Digit8:["8","*"],Digit9:["9","("],Digit0:["0",")"],Minus:["-","_"],Equal:["=","+"],Backslash:["\\","|"],BracketLeft:["[","{"],BracketRight:["]","}"],Semicolon:[";",":"],Quote:["'",'"'],Comma:[",","<"],Period:[".",">"],Slash:["/","?"]},MT=(e,t)=>{if(e.startsWith("Key")){let r=e.slice(3);return t||(r=r.toLowerCase()),r}return zi(rh,e)?rh[e][t?1:0]:e},oh={"<":"lt",">":"gt"},IT=/^($|Unidentified$|Process$|Dead$|Alt|Control|Hyper|Meta|Shift|Super|OS)/,Ul=e=>{let t=e.shiftKey,r=e.key||"Unidentified";if(r==="Unidentified"?r=MT(e.code||"",t):(r=sh(r),r===" "&&(r="Space")),IT.test(r))return"";r.length===1?t=!1:r=r.toLowerCase();let o="";return e.altKey&&(o+="a-"),e.ctrlKey&&(o+="c-"),e.metaKey&&(o+="m-"),t&&(o+="s-"),zi(oh,r)&&(r=oh[r]),o||r.length>1?`<${o}${r}>`:r},nh={a:"altKey",c:"ctrlKey",m:"metaKey",s:"shiftKey"},FT=e=>{if(e.length===1)return/\s/.test(e)?{ok:!1,value:{name:"InvalidKeyError",key:e,message:`Invalid key: ${e}`}}:{ok:!0,value:{key:e}};let t=e.match(/^<((?:[a-z]-)*)([a-z\d]+|[^<>\s])>$/i);if(!t)return{ok:!1,value:{name:"InvalidKeyError",key:e,message:`Invalid key: ${e}`}};let[,r,o]=t,n={key:sh(o)};for(let s of r.split("-").slice(0,-1)){let i=s.toLowerCase();if(!zi(nh,i))return{ok:!1,value:{name:"UnknownModifierError",modifier:s,context:e,message:`${e}: Unknown modifier: ${s}`}};let a=nh[i];if(n[a]!==void 0)return{ok:!1,value:{name:"DuplicateModifierError",modifier:s,context:e,message:`${e}: Duplicate modifier: ${s}`}};if(n[a]=!0,n.key.length===1&&n.shiftKey)return{ok:!1,value:{name:"DisallowedModifierError",modifier:s,context:e,message:`${e}: Unusable modifier with single-character keys: ${s}`}}}return{ok:!0,value:n}},ih=e=>{let t=FT(e);return t.ok?{ok:!0,value:Ul(t.value)}:t},ah=e=>e.match(/<[^<>\s]+>|[\s\S]|^$/g);var $t=!1;var ch=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...o)=>r(`%c${e}`,"color: gray",...o)];case"log":case"info":case"debug":return[t,(...o)=>{$t!==!0&&(!$t||!$t.has(e))||r(`%c${e}`,"color: gray",...o)}];case"assert":return[t,(o,...n)=>{$t!==!0&&(!$t||!$t.has(e))||r(o,`%c${e}`,"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{$t!==!0&&(!$t||!$t.has(e))||r(`${e} ${o}`)}];default:return[t,(...o)=>{if(!($t!==!0&&(!$t||!$t.has(e))))return r(...o)}]}}));var go=ch("ScrapBindings:mod.ts"),qi=class{constructor(t,r){this.target=t;this.onSequenceUpdate=r?.onSequenceUpdate,this.flushInterval=r?.flushInterval??1e3}bind(t,r){let o=new Map,n=[];for(let[s,i]of t instanceof Map?t.entries():typeof t=="string"?[[t,r]]:Object.entries(t)){let a=lh(s);if(!a.ok){for(let l of a.value)go.error(`${s}: ${l.message}`);o.set(s,a.value);continue}let c=a.value;this.bindings.set(c,i),c.startsWith(this.currentSequence)&&this.filtered.add(c),n.push(c)}return go.debug("Binded the following commands:",n),this.emitChange(),o}unbind(...t){for(let r of t){let o=lh(r);if(!o.ok)continue;let n=o.value;this.bindings.delete(n),this.filtered.delete(n)}this.emitChange()}reset(){this.bindings.clear(),this.emitChange()}bindings=new Map;onSequenceUpdate;flushInterval;_sequence="";set currentSequence(t){let r=this._sequence!==t;this._sequence=t,r&&this.onSequenceUpdate?.(t)}get currentSequence(){return this._sequence}prevBestMatchCommand;filtered=new Set;timer;backToInitial=()=>{clearTimeout(this.timer),this.currentSequence="",this.prevBestMatchCommand=void 0,this.filtered=new Set(this.bindings.keys()),go.debug("reset the sequence")};handleKeydown=t=>{if(!t.isTrusted)return;let r=Ul(t);if(!r)return;if(clearTimeout(this.timer),t.isComposing){this.backToInitial();return}this.currentSequence+=r,go.debug("sequence",this.currentSequence);let o;for(let s of this.filtered){if(s.startsWith(this.currentSequence)||this.filtered.delete(s),this.currentSequence!==s)continue;let i=this.bindings.get(s);if(!i){this.filtered.delete(s);continue}o=()=>{go.debug(`run ${s}`);try{i(t)}catch(a){go.error(a)}finally{this.backToInitial()}}}let n=this.filtered.size;if(go.debug(`${n} candidates: ${[...this.filtered.keys()].join(", ")}`),n>0&&(this.prevBestMatchCommand=o),this.prevBestMatchCommand&&n<2){if(this.prevBestMatchCommand(),n===0){this.handleKeydown(t);return}return}if(n===0){this.backToInitial();return}t.preventDefault(),t.stopPropagation(),this.timer=setTimeout(this.prevBestMatchCommand??this.backToInitial,this.flushInterval)};emitChange=()=>{if(this.bindings.size===0){this.backToInitial(),this.target.removeEventListener("keydown",this.handleKeydown);return}this.target.addEventListener("keydown",this.handleKeydown)}},UT={name:"InvalidSequenceError",message:"cannot parse the sequence"},lh=e=>{let t=ah(e);if(!t)return{ok:!1,value:[UT]};let r="",o=[];for(let n of t){let s=ih(n);if(!s.ok){o.push(s.value);continue}r+=s.value}return o.length>0?{ok:!1,value:o}:{ok:!0,value:r}};var ph=()=>{if(scrapbox.Layout!=="page")return{selectionRange:{start:{line:0,char:0},end:{line:0,char:0}},selectedText:""};let{selectionRange:e,selectedText:t,position:r}=Me();if(!t){let u=Sl(r.line)??0,p={start:{line:r.line,char:0},end:{line:r.line+u,char:Ye(r.line+u)?.length??0}};return{selectionRange:p,selectedText:scrapbox.Page.lines.slice(p.start.line,p.end.line+1).map(f=>f.text).join(`
`)}}let{start:o,end:n}=e,s=o.line>n.line,i=s?n.line:o.line,a=s?n.char:o.char,c=s?o.line:n.line,l=s?o.char:n.char;return{selectedText:t,selectionRange:{start:{line:i,char:a},end:{line:c,char:l}}}};var Dl=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(`
`),i=n.replaceAll("[","").replaceAll("]","").trim(),a=Math.min(...[n,...s].map(l=>Er(l))),c=[`from [${t}]`,n.slice(a),...s.map(l=>l.slice(a))];return{text:`[${i}]`,pages:[{project:r,title:i,lines:c,mode:o}]}};Dl.hookName="default-hook";var kr=e=>{let{project:t=scrapbox.Project.name,mode:r="newtab"}=e??{},o=[...e?.hooks??[],Dl],{selectionRange:{start:n,end:s},selectedText:i}=ph();if(!i||scrapbox.Layout!=="page")return;let a=(()=>{for(let p of o){let f=p(i,{title:scrapbox.Page.title,projectFrom:scrapbox.Project.name,projectTo:t,lines:ft().slice(n.line,s.line+1),mode:r});if(f)return[p.hookName,f]}})();if(!a)return;let[c,l]=a,u=async()=>{let p=l instanceof Promise?await l:l;if(p.pages.length===0&&p.text===i)return;let f,{render:m,dispose:h}=Le();try{if(p.pages.length>0){let y=p.pages.length;m({type:"spinner"},{type:"text",text:`Create new ${y} pages...`});let x=await Ve(e?.socket);if(B(x))throw re(x);f=H(x);let E=0;await Promise.all(p.pages.map(async R=>{let b=Array.isArray(R.lines)?v=>[...v.map(k=>k.text),...R.lines]:R.lines;await xe(R.project,R.title,b,{socket:f}),m({type:"spinner"},{type:"text",text:`Create ${y-++E} pages...`})}))}m({type:"spinner"},{type:"text",text:`${p.pages.length>0?"Created. ":""}Removing cut text...`});let g=p.text;if(i===g)return;await xe(scrapbox.Project.name,scrapbox.Page.title,y=>{let x=y.map(E=>E.text);return[...x.slice(0,n.line),...`${x[n.line].slice(0,n.char)}${g}${x.slice(s.line).join(`
`).slice(s.char)}`.split(`
`)]}),m({type:"check-circle"},{type:"text",text:"Removed."});for(let y of p.pages)switch(y.mode){case"self":y.project===scrapbox.Project.name?Zn(y.project,y.title):globalThis.open(`https://scrapbox.io/${y.project}/${me(y.title)}`,"_self");break;case"newtab":globalThis.open(`https://scrapbox.io/${y.project}/${me(y.title)}`);break}}catch(g){m({type:"exclamation-triangle"},{type:"text",text:"Failed to create new pages (see console)."}),console.error(g)}finally{let g=Pe(1e3);f&&await ot(f),await g,h()}};return u.hookName=c,u};var DT=Math.pow(10,8)*24*60*60*1e3,qK=-DT,uh=6048e5,mh=864e5,Ki=6e4,fh=36e5;var $T=3600;var dh=$T*24,KK=dh*7,jT=dh*365.2425,BT=jT/12,XK=BT*3,$l=Symbol.for("constructDateFrom");function he(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&$l in e?e[$l](t):e instanceof Date?new e.constructor(t):new Date(t)}function W(e,t){return he(t||e,e)}var HT={};function yo(){return HT}function dt(e,t){let r=yo(),o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=W(e,t?.in),s=n.getDay(),i=(s<o?7:0)+s-o;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}function Hr(e,t){let r=W(e,t?.in);return r.setHours(0,0,0,0),r}function Wr(e,...t){let r=he.bind(null,e||t.find(o=>typeof o=="object"));return t.map(r)}function Xi(e,t){let[r,o]=Wr(e,t.start,t.end);return{start:r,end:o}}function Yi(e,t){let{start:r,end:o}=Xi(t?.in,e),n=+r>+o,s=n?+r:+o,i=n?o:r;i.setHours(0,0,0,0);let a=t?.step??1;if(!a)return[];a<0&&(a=-a,n=!n);let c=[];for(;+i<=s;)c.push(he(r,i)),i.setDate(i.getDate()+a),i.setHours(0,0,0,0);return n?c.reverse():c}function ht(e,t,r){let[o,n]=Wr(r?.in,e,t);return+Hr(o)==+Hr(n)}function Rr(e,t){let r=e<0?"-":"",o=Math.abs(e).toString().padStart(t,"0");return r+o}var hh={y(e,t){let r=e.getFullYear(),o=r>0?r:1-r;return Rr(t==="yy"?o%100:o,t.length)},M(e,t){let r=e.getMonth();return t==="M"?String(r+1):Rr(r+1,2)},d(e,t){return Rr(e.getDate(),t.length)},a(e,t){let r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(e,t){return Rr(e.getHours()%12||12,t.length)},H(e,t){return Rr(e.getHours(),t.length)},m(e,t){return Rr(e.getMinutes(),t.length)},s(e,t){return Rr(e.getSeconds(),t.length)},S(e,t){let r=t.length,o=e.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return Rr(n,t.length)}};function gh(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Gr(e){return!(!gh(e)&&typeof e!="number"||isNaN(+W(e)))}var WT=/(\w)\1*|''|'(''|[^'])+('|$)|./g,GT=/^'([^]*?)'?$/,VT=/''/g,zT=/[a-zA-Z]/;function be(e,t){let r=W(e);if(!Gr(r))throw new RangeError("Invalid time value");let o=t.match(WT);return o?o.map(n=>{if(n==="''")return"'";let s=n[0];if(s==="'")return qT(n);let i=hh[s];if(i)return i(r,n);if(s.match(zT))throw new RangeError("Format string contains an unescaped latin alphabet character `"+s+"`");return n}).join(""):""}function qT(e){let t=e.match(GT);return t?t[1].replace(VT,"'"):e}function Ue(e,t,r){let o=W(e,r?.in);return isNaN(t)?he(r?.in||e,NaN):(t&&o.setDate(o.getDate()+t),o)}function vr(e,t,r){return Ue(e,-t,r)}function Ji(e,t,r){return he(r?.in||e,+W(e)+t)}function Qi(e,t,r){return Ji(e,t*1e3,r)}function cn(e,t,r){return Ue(e,t*7,r)}function Zi(e,t){return W(e,t?.in).getDate()}function ea(e,t){let r=W(e,t?.in),o=r.getFullYear(),n=yo(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=he(t?.in||e,0);i.setFullYear(o+1,0,s),i.setHours(0,0,0,0);let a=dt(i,t),c=he(t?.in||e,0);c.setFullYear(o,0,s),c.setHours(0,0,0,0);let l=dt(c,t);return+r>=+a?o+1:+r>=+l?o:o-1}function yh(e,t){let r=yo(),o=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=ea(e,t),s=he(t?.in||e,0);return s.setFullYear(n,0,o),s.setHours(0,0,0,0),dt(s,t)}function xo(e,t){let r=W(e,t?.in),o=+dt(r,t)-+yh(r,t);return Math.round(o/uh)+1}function xh(e,t){return W(e,t?.in).getMonth()}function bo(e,t){return W(e,t?.in).getFullYear()}var bh=e=>{let t=new Map;for(let r of e){let o=`${bo(r)}-${xh(r)}-${Zi(r)}`,n=t.get(o);n&&n.getTime()>r.getTime()||t.set(o,r)}return[...t.values()]};function Eh(e,t,r){let o=W(e,r?.in);if(isNaN(t))return he(r?.in||e,NaN);if(!t)return o;let n=o.getDate(),s=he(r?.in||e,o.getTime());s.setMonth(o.getMonth()+t+1,0);let i=s.getDate();return n>=i?s:(o.setFullYear(s.getFullYear(),s.getMonth(),n),o)}function wh(e,t,r){let{years:o=0,months:n=0,weeks:s=0,days:i=0,hours:a=0,minutes:c=0,seconds:l=0}=t,u=W(e,r?.in),p=n||o?Eh(u,n+o*12):u,f=i||s?Ue(p,i+s*7):p,m=c+a*60,h=(l+m*60)*1e3;return he(r?.in||e,+f+h)}function kh(e,t){let r=W(e,t?.in),o=r.getFullYear(),n=r.getMonth(),s=he(r,0);return s.setFullYear(o,n+1,0),s.setHours(0,0,0,0),s.getDate()}function Rh(e,t,r){let o=W(e,r?.in),n=o.getFullYear(),s=o.getDate(),i=he(r?.in||e,0);i.setFullYear(n,t,15),i.setHours(0,0,0,0);let a=kh(i);return o.setMonth(t,Math.min(s,a)),o}function vh(e,t,r){let o=W(e,r?.in);return isNaN(+o)?he(r?.in||e,NaN):(t.year!=null&&o.setFullYear(t.year),t.month!=null&&(o=Rh(o,t.month)),t.date!=null&&o.setDate(t.date),t.hours!=null&&o.setHours(t.hours),t.minutes!=null&&o.setMinutes(t.minutes),t.seconds!=null&&o.setSeconds(t.seconds),t.milliseconds!=null&&o.setMilliseconds(t.milliseconds),o)}function Th(e,t){return W(e,t?.in).getMinutes()}function Vr(e,t,r){let o=W(e,r?.in);return o.setTime(o.getTime()+t*Ki),o}function _h(e){return t=>{let r=(e?Math[e]:Math.trunc)(t);return r===0?0:r}}function Ph(e,t){return+W(e)-+W(t)}function ts(e,t,r){let o=Ph(e,t)/Ki;return _h(r?.roundingMethod)(o)}function Sh(e,t){return W(e,t?.in).getHours()}function Oh(e,t,r){return Ji(e,t*fh,r)}function Lh(e,t){let r=W(e,t?.in);return r.setHours(23,59,59,999),r}function jl(e){let t=W(e),r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return r.setUTCFullYear(t.getFullYear()),+e-+r}function Nh(e,t,r){let[o,n]=Wr(r?.in,e,t),s=Hr(o),i=Hr(n),a=+s-jl(s),c=+i-jl(i);return Math.round((a-c)/mh)}function Ch(e,t,r){return cn(e,-t,r)}function Ah(e,t,r){let o=W(e,r?.in),n=xo(o,r)-t;return o.setDate(o.getDate()-n*7),W(o,r?.in)}function Mh(e,t){let{start:r,end:o}=Xi(t?.in,e),n=+r>+o,s=n?dt(o,t):dt(r,t),i=n?dt(r,t):dt(o,t);s.setHours(15),i.setHours(15);let a=+i.getTime(),c=s,l=t?.step??1;if(!l)return[];l<0&&(l=-l,n=!n);let u=[];for(;+c<=a;)c.setHours(0),u.push(he(r,c)),c=cn(c,l),c.setHours(15);return n?u.reverse():u}function Ih(e,t,r){let[o,n]=Wr(r?.in,e,t),s=o.getFullYear()-n.getFullYear(),i=o.getMonth()-n.getMonth();return s*12+i}function Fh(e,t){let r=+W(e)-+W(t);return r<0?-1:r>0?1:r}function Eo(e,t){return+W(e)>+W(t)}var Uh=e=>e==null,zr=e=>typeof e=="string";async function*Dh(e){let t=[],r,o=i=>{if(!r){t.push(i);return}r(i),r=void 0},n=()=>t.length>0?Promise.resolve(t.pop()):new Promise(i=>r=i),s=0;for(let i of e)i.then(a=>o({state:"fulfilled",value:a})).catch(a=>o({state:"rejected",reason:a})),s++;for(let i=0;i<s;i++)yield await n()}var nt=e=>{let t=e.match(/^`(\d{4})-(\d{2})-(\d{2}) (?: {5}|(\d{2}):(\d{2})) (?: {4}|(\d{4})) (?: {8}|(\d{2}):(\d{2}):(\d{2})) (?: {8}|(\d{2}):(\d{2}):(\d{2}))`([^\n]*)$/);if(!t)return;let[,r,o,n,s,i,a,c,l,u,p,f,m,h]=t,g={title:h,base:new Date(parseInt(r),parseInt(o)-1,parseInt(n)),plan:{},record:{}};if(s){let y=new Date(g.base);y.setHours(parseInt(s)),y.setMinutes(parseInt(i)),g.plan.start=y}if(a&&(g.plan.duration=parseInt(a)*60),c){let y=new Date(g.base);y.setHours(parseInt(c)),y.setMinutes(parseInt(l)),y.setSeconds(parseInt(u)),g.record.start=y}if(p){let y=new Date(g.base);y.setHours(parseInt(p)),y.setMinutes(parseInt(f)),y.setSeconds(parseInt(m)),g.record.start&&Eo(g.record.start,y)&&y.setDate(y.getDate()+1),g.record.end=y}return g};var ln=e=>e.record?.start??e.plan?.start??e.base,$h=e=>e.record?.end??(Uh(e.plan?.duration)?e.base:Qi(ln(e),e.plan.duration));var Ee=({title:e,base:t,plan:r,record:o})=>["`",be(t,"yyyy-MM-dd")," ",r?.start?be(r.start,"HH:mm"):" ".repeat(5)," ",r?.duration?`${r.duration/60}`.padStart(4,"0"):" ".repeat(4)," ",o?.start?be(o?.start,"HH:mm:ss"):" ".repeat(8)," ",o?.end?be(o?.end,"HH:mm:ss"):" ".repeat(8),"`",e].join("");function*jh(e){for(let t of wo(e))zr(t)||(yield t)}function*wo(e){for(let t=0;t<e.length;t++){let r=e[t],o=zr(r)?r:r.text,n=ho(t,e),s=nt(o);if(!s){yield o;continue}yield{...s,lines:e.slice(t+1,t+1+n).map(i=>zr(i)?i:i.text)},t+=n}}var KT=5*60,rs=async()=>{let e=Me().position.line,t=nt(Ye(e)??""),r=t?.base??new Date,o={start:t?.plan?.start?Qi(t.plan.start,KT+(t.plan.duration??0)):void 0,duration:t?.plan?.duration};await Wd(e+1,Ee({title:"",base:r,plan:o,record:{}}))};var ko=async()=>{let e=Me().position.line,t=nt(Ye(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;o||await ct(e,e,Ee({record:{start:r?void 0:new Date},...n}))};var Tr=async()=>{let e=Me().position.line,t=nt(Ye(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;r&&await ct(e,e,Ee({record:{start:r,end:o?void 0:new Date},...n}))};var Bl=async()=>{let e=Me().position.line,t=nt(Ye(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;if(!r){await ko();return}if(!o){await Tr();return}await ct(e,e,Ee({record:{},...n}))};var os=async()=>{let e=Me().position.line,t=nt(Ye(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;if(r){if(o)return;await Tr();return}if(o)return;let s;for(let{text:a}of Jt().slice(0,(e??0)+1).reverse()){let{record:c}=nt(a)??{};if(c?.end){s=c.end;break}}let i=new Date;await ct(e,e,Ee({record:{start:s??i,end:i},...n}))};var Ro=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=Me();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var Hl=(e,t=7)=>new Date((e+2592e3*((t+1)**1.5-1)/5221.154823442138)*1e3);var Wl=(e,t)=>{let r,o,n,s,i=null;if(i=e.match(/^(.*?)(s|e):([^\s]+)\s+d:(\d+)/))[,o,s,n,r]=i;else if(i=e.match(/^(.*?)d:(\d+)\s+(s|e):([^\s]+)/))[,o,r,s,n]=i;else if(i=e.match(/^(.*?)(s|e):([^\s]+)/))[,o,s,n]=i;else return(i=e.match(/^(.*?)d:(\d+)/))?([,o,r]=i,{name:o.trimEnd(),duration:parseInt(r)*60}):void 0;for(let{test:a,parse:c}of XT){let l=n.match(a);if(!l)continue;let u=c(l),p=u.isDuration?wh(t,u):vh(t,u);return s==="s"?{name:o.trimEnd(),start:p,...r!==void 0?{duration:parseInt(r)*60}:{}}:{name:o.trimEnd(),start:Hl(t.getTime()/1e3,(p.getTime()-t.getTime())/(24*60*60*1e3)),...r!==void 0?{duration:parseInt(r)*60}:{}}}},XT=[{test:/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3]),hours:parseInt(e[4]),minutes:parseInt(e[5])})},{test:/(\d{4})-(\d{2})-(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3]),hours:parseInt(e[4])})},{test:/(\d{4})-(\d{2})-(\d{2})T?$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3])})},{test:/(\d{2})-(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2]),hours:parseInt(e[3]),minutes:parseInt(e[4])})},{test:/(\d{2})-(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2]),hours:parseInt(e[3])})},{test:/(\d{2})-(\d{2})T?$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2])})},{test:/(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,date:parseInt(e[1]),hours:parseInt(e[2]),minutes:parseInt(e[3])})},{test:/(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,date:parseInt(e[1]),hours:parseInt(e[2])})},{test:/T?(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,hours:parseInt(e[1]),minutes:parseInt(e[2])})},{test:/T?(\d{2})$/i,parse:e=>({isDuration:!1,hours:parseInt(e[1])})},{test:/P(\d+)Y(\d+)M(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3]),hours:parseInt(e[4]),minutes:parseInt(e[5])})},{test:/P(\d+)Y(\d+)M(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3]),hours:parseInt(e[4])})},{test:/P(\d+)Y(\d+)M(\d+)D$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3])})},{test:/P(\d+)M(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2]),hours:parseInt(e[3]),minutes:parseInt(e[4])})},{test:/P(\d+)M(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2]),hours:parseInt(e[3])})},{test:/P(\d+)M(\d+)D$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2])})},{test:/P(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,days:parseInt(e[1]),hours:parseInt(e[2]),minutes:parseInt(e[3])})},{test:/P(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,days:parseInt(e[1]),hours:parseInt(e[2])})},{test:/P(\d+)D$/i,parse:e=>({isDuration:!0,days:parseInt(e[1])})},{test:/PT?(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,hours:parseInt(e[1]),minutes:parseInt(e[2])})},{test:/PT?(\d+)H$/i,parse:e=>({isDuration:!0,hours:parseInt(e[1])})},{test:/PT?(\d+)M$/i,parse:e=>({isDuration:!0,minutes:parseInt(e[1])})},{test:/P(\d+)W$/i,parse:e=>({isDuration:!0,weeks:parseInt(e[1])})}];var vo=async()=>{let e=new Date,[t,r]=Ro(),o=Jt().slice(t,r+1).map(s=>s.text),n=o.flatMap(s=>{let i=s.trimEnd();if(i==="")return s;let{name:a,start:c,duration:l}=Wl(i,e)??{};return!a||!c&&!l?s:[Ee({title:a.trim(),base:c??e,plan:{start:c,duration:l},record:{}})]}).join(`
`);o.join(`
`)!==n&&await ct(t,r,n)};var ta=async(e,t,r)=>{let o=[];for(let n=e;n<=t;n++){let s=Ye(n)??"",i=nt(s);if(!i){o.push(s);continue}o.push(Ee(r(i,n)))}await ct(e,t,o.join(`
`))};var ns=async(e=1)=>{let[t,r]=Ro();await ta(t,r,o=>(o.base=Ue(o.base,e),o))};var ss=async()=>{let[e,t]=Ro(),r=new Date;await ta(e,t,o=>(ht(o.base,r)||(o.base=r),o))};var YT="日刊記録sheet",JT=/日刊記録sheet (\d{4})-(\d{2})-(\d{2})/,is=["[** 00:00 - 03:00] 未明","[** 03:00 - 06:00] 明け方","[** 06:00 - 09:00] 朝","[** 09:00 - 12:00] 昼前","[** 12:00 - 15:00] 昼過ぎ","[** 15:00 - 18:00] 夕方","[** 18:00 - 21:00] 夜のはじめ頃","[** 21:00 - 00:00] 夜遅く"];var Gl=e=>{let t=e.match(JT);if(!t)return;let[,r,o,n]=t,s=new Date(parseInt(r),parseInt(o)-1,parseInt(n));return Gr(s)?s:void 0},qr=e=>be(e,`'${YT}' yyyy-MM-dd`),To=e=>{let t=Gl(e[0]);if(!t)return e;let r=QT(t),o=[],n=[];for(let a of wo(e.slice(1))){if(typeof a=="string"){if(is.includes(a)||r!==""&&r===a)continue;n.push(a);continue}o.push(a)}let s=o.sort((a,c)=>Fh(ln(a),ln(c)));if(s.length===0)return[e[0],r,...is,...n];let i=[0,0,0,0,0,0,0,0];for(let a=1;a<is.length;a++){let c=Oh(new Date(t.getFullYear(),t.getMonth(),t.getDate()),3*a),l=s.findIndex(m=>Eo(ln(m),c));if(l<0){i[a]=-1;continue}if(l===0)continue;let u=s[l-1],p=ln(u),f=$h(u);i[a]=(f.getTime()-p.getTime())/2<c.getTime()-p.getTime()?l:l-1}return[e[0],r,...s.flatMap((a,c)=>[...i.flatMap((l,u)=>l===c?[is[u]]:[]),Ee(a),...a.lines]),...i.flatMap((a,c)=>a===-1?[is[c]]:[]),...n]},QT=e=>`yesterday: [${qr(vr(e,1))}]`;var as=async(e,t)=>{let r=()=>{},o=setTimeout(()=>{let{render:n,dispose:s}=Le();r=s,n({type:"spinner"},{type:"text",text:"formatting..."})},500);await xe(e,t,n=>To(n.map(s=>s.text))),clearTimeout(o),r()};async function*Vl(e,t,r){let o=[...t],n=[];for(;o.length>0;){let s=o.shift();if(!s)break;let i=s.base,a=[s];for(let c=0;c<o.length;c++)ht(o[c].base,i)&&(a.push(...o.splice(c,1)),c--);n.push((async()=>(await xe(e,qr(i),c=>To([...c.map(l=>l.text),...a.flatMap(l=>[Ee(l),...l.lines??[]])]),r),{date:i,size:a.length}))())}yield*Dh(n)}var _o=async({from:{project:e,title:t},to:r})=>{let o=await Dt(e,t);if(B(o))throw re(o);let n=Gl(t),{lines:s}=H(o),i=[];for(let p of jh(s))n&&ht(p.base,n)||i.push(p);let{render:a,dispose:c}=Le();a({type:"spinner"},{type:"text",text:`copying ${i.length} tasks...`});let l=await Ve();if(B(l))throw re(l);let u=H(l);try{let p=0,f=!1;for await(let m of Vl(r,i,{socket:u})){if(m.state!=="fulfilled"){console.error(m.reason),f=!0;continue}p+=m.value.size,a({type:"spinner"},{type:"text",text:`copying ${i.length-p} tasks...`})}if(f){a({type:"exclamation-triangle"},{type:"text",text:"Some tasks failed to be written"});return}a({type:"spinner"},{type:"text",text:`Copied. removing ${i.length} original tasks...`}),await xe(e,t,m=>{let h=[];for(let g of wo(m)){if(zr(g)){h.push(g);continue}n&&ht(g.base,n)&&h.push(Ee(g),...g.lines)}return h},{socket:u}),a({type:"check-circle"},{type:"text",text:"Moved"})}finally{await ot(u),await Pe(1e3),c()}};var Bh=e=>typeof e=="string";var Kr=e=>e.match(/^(\s*)/)?.[1]?.length??0,Wh=(e,t)=>{let r=Kr(Hh(e,t)),o=0;for(;e+o+1<t.length&&Kr(Hh(e+o+1,t))>r;)o++;return o},Hh=(e,t)=>{let r=t[e];return Bh(r)?r:r.text};var Qt=e=>`${e}`.padStart(2,"0");var Po=e=>"hours"in e,jt=(e,t)=>e.year!==t.year?e.year<t.year:e.month!==t.month?e.month<t.month:e.date!==t.date?e.date<t.date:"hours"in t?"hours"in e?e.hours*60+e.minutes<t.hours*60+t.minutes:0<t.hours*60+t.minutes:!1,ar=e=>`${`${e.year}`.padStart(4,"0")}-${Qt(e.month)}-${Qt(e.date)}${"hours"in e?`T${Qt(e.hours)}:${Qt(e.minutes)}`:""}`,ge=e=>{let t=ar(e);return new Date(t.includes("T")?t:`${t}T00:00`)},bt=e=>({year:e.getFullYear(),month:e.getMonth()+1,date:e.getDate(),hours:e.getHours(),minutes:e.getMinutes()});var Vh=e=>{switch(e.toLowerCase()){case"y":return"yearly";case"m":return"monthly";case"w":return"weekly";case"d":return"daily";default:return}};var zh=e=>{switch(e){case"+":return"todo";case"-":return"note";case"!":return"deadline";case".":return"done";case"~":return"up-down";default:return}},qh=e=>{switch(e){case"todo":return"+";case"note":return"-";case"deadline":return"!";case"done":return".";case"up-down":return"~"}};var Bt=e=>{let t=e.match(/(?:([\+\-!~.])(\d+)?)?@(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}))?(?:\/(\d{2}):(\d{2})|\/(?:(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)|D(\d+))?(?:R([YMWD])?(\d+))?(?:@(?:(\d{2}):(\d{2})|(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)?(?:\/(\d{2}):(\d{2})|\/(?:(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)|D(\d+))?)?/i);if(!t)return;let[r,o,n,s,i,a,c,l,u,p,f,m,h,g,y,x,E,R,b,v,k,O,L,N,P,T,_,S,A,M,D,I,z]=t,$=`${e.slice(0,t.index).trim()}${e.slice((t.index??0)+r.length).trim()}`,q=Kh(s,i,a,c,l);if(!Gr(ge(q)))return Q({name:"InvalidDateError",message:`The reference point of the task "${ar(q)}" is an invalid date.`});let K=Xh(q,f,m,h,u||g,p||y,x);if(K!==void 0){if(Ke(K)&&isNaN(K)||!Ke(K)&&!Gr(ge(K)))return Q({name:"InvalidDateError",message:`The estimated end of the task${Ke(K)?"":` "${ar(K)}"`} is an invalid date.`});if(Ke(K)&&K<0||!Ke(K)&&jt(K,q))return Q({name:"TaskRangeError",message:`The reference point of an task cannot be after its estimated end.
reference point:${ar(q)}
estimated end:${ar(Ke(K)?bt(Vr(ge(q),K)):K)}`})}let ce=/^[\uFE00-\uFE0F]*[✅❌]/.test(e)?"done":zh(o),ee=ce?{status:ce,refDate:q}:void 0;ee&&n&&(ee.speed=parseInt(n));let rt=Kh(k||s,O||i,L||a,b||N||c,v||P||l);if(!Gr(ge(rt)))return Q({name:"InvalidDateError",message:`The start of the task/event "${ar(rt)}" is an invalid date.`});let Oe=Xh(rt,S||f,A||m,M||h,T||D||u||g,_||I||p||y,z||x),U=Po(rt)&&Ke(Oe)?{start:rt,duration:Oe}:void 0;if(U){let lt={name:$,executed:U,generated:!1,raw:e};return ee&&(lt.freshness=ee),(E||R)&&(lt.recurrence={frequency:Vh(E??"D")??"daily",count:R?parseInt(R):1}),ae(lt)}if(!ee)return Q({name:"InvalidDateError",message:"Task requires freshness to be spec"});let ke={name:$,freshness:ee,generated:!1,raw:e};return K&&(ke.estimated=K),ae(U?{...ke,executed:U}:ke)},cr=e=>!("executed"in e),Xr=e=>"recurrence"in e,Yh=e=>!("executed"in e||"freshness"in e&&Po(e.freshness.refDate)&&e.estimated&&(Ke(e.estimated)||Po(e.estimated))),ls=e=>"executed"in e?e.executed.duration:Ke(e.estimated)?e.estimated:void 0,lr=e=>cr(e)?e.freshness.refDate:e.executed.start,Jh=e=>{if(!cr(e)){let r=ge(e.executed.start);return bt(Vr(r,e.executed.duration))}if(Ke(e.estimated)&&Po(e.freshness.refDate)){let r=ge(e.freshness.refDate);return bt(Vr(r,e.estimated))}let t=ge(Ke(e.estimated)?e.freshness.refDate:e.estimated??e.freshness.refDate);return t.setHours(0),t.setMinutes(0),bt(Ue(t,1))},n_=e=>{let t=e.freshness?`${qh(e.freshness.status)}${e.freshness.speed??""}`:"",r=`${ar(lr(e))}`,o=ls(e);return`${t}@${r}${o===void 0?"":`D${o}`}${e.name}`},ra=(e,t)=>{let r=bt(t),{recurrence:o,executed:n}=e;switch(o.frequency){case"yearly":{if(Math.abs(r.year-n.start.year)%(o.count??1)!==0||n.start.month!==r.month||n.start.date!==r.date)return;break}case"monthly":{if(Ih(ge(r),ge(n.start))%(o.count??1)!==0)return;break}case"weekly":case"daily":{let a=o.frequency==="weekly"?7:1;if(Nh(ge(r),ge(n.start))%((o.count??1)*a)!==0)return;break}}let s={...n.start};s.year=r.year,s.month=r.month,s.date=r.date;let i={name:e.name,executed:{start:s,duration:n.duration},generated:!0,raw:e.raw};return e.freshness&&(i.freshness=e.freshness),i},oa=e=>e.freshness?e.generated?n_(e):e.raw:e.generated?void 0:e.raw,Kh=(e,t,r,o,n)=>{let s=parseInt(e),i=parseInt(t),a=parseInt(r),c=o?parseInt(o):void 0,l=n?parseInt(n):void 0;return c!==void 0&&l!==void 0?{year:s,month:i,date:a,hours:c,minutes:l}:{year:s,month:i,date:a}},Xh=(e,t,r,o,n,s,i)=>{if(!t&&!r&&!o&&!n&&!s&&!i)return;if(i)return parseInt(i);let a=t?parseInt(t):e.year,c=r?parseInt(r):e.month,l=o?parseInt(o):e.date,u=n?parseInt(n):void 0,p=s?parseInt(s):void 0,f=u!==void 0&&p!==void 0?{year:a,month:c,date:l,hours:u,minutes:p}:{year:a,month:c,date:l};return!Po(e)||!Po(f)?f:Math.round((ge(f).getTime()-ge(e).getTime())/(60*1e3))};var So=(e,t)=>{if(!e.generated&&Xr(e)){let s=ra(e,t);return s?So(s,t):void 0}let r=ge(cr(e)?e.freshness.refDate:e.executed.start),o=ls(e),n=oa(e);return{title:n!==void 0?`[${n}]`:e.name,base:r,plan:{start:Yh(e)?void 0:r,duration:o!==void 0?o*60:void 0},record:{}}};var zl={あさごはん:"#log-breakfast",ひるごはん:"#log-lunch",よるごはん:"#log-dinner"},Oo=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(`
`),i=nt(n);if(!i)return;if(s.length===0)return{text:e,pages:[]};let{title:a,base:c,record:l,...u}=i,p=s_(a,c,l),f=Ee({title:`[${p}]`,base:c,record:l,...u}),m=Math.min(...s.map(g=>Kr(g))),h=[.../[\[\]]/.test(a)&&a!==`[${p}]`?[a]:[],...t in zl?[...s.map(g=>g.slice(m)),"",zl[t],"#log-eatenfood"]:[...s.map(g=>` ${g.slice(m)}`),""]];return{text:f,pages:[{project:r,title:p,lines:Qh(t,h,[l.start??c]),mode:o}]}};Oo.hookName="task-hook";var s_=(e,t,r)=>{let o=be(r.start??t,"yyyy-MM-dd");if(e in zl)return`${o} ${e}`;if(Bt(e.slice(1,-1)))return e.slice(1,-1);let n=e.replace(/[\[\]]/g,"").trim();return`${n}${n.endsWith(o)?"":` ${o}`}`},Lo=(e,{title:t,projectTo:r,mode:o,lines:n})=>{let[s,...i]=e.split(`
`);if(i.length===0)return;let a=s.replace(/[\[\]]/g,"").trim(),c=Math.min(...i.map(p=>Kr(p))),l=r.startsWith("takker")?bh([new Date,...n.map(({updated:p})=>new Date(p*1e3))]).sort((p,f)=>f.getTime()-p.getTime()):[],u=["",.../[\[\]]/.test(s)?[s.trimStart()]:[],...i.map(p=>p.slice(c))];return{text:`${" ".repeat(Kr(s))}[${a}]`,pages:[{project:r,title:a,lines:Qh(t,u,l),mode:o}]}};Lo.hookName="new-page-hook";var No=(e,{projectTo:t,mode:r})=>{if(e.includes(`
`)||!/\[[^\]]+\]/.test(e))return;let[o,n]=e.match(/^(\s*)(.*)$/)?.slice?.(1)??["",e],s=[...n.matchAll(/\[([^\]])\]/g)].map(a=>ne(a[1])),i=n.replaceAll("[","").replaceAll("]","");return{text:`${o}[${i}]`,pages:[{project:t,title:i,lines:(a,{links:c})=>{let l=c.map(u=>ne(u));if(!s.every(u=>l.includes(u)))return[...a.map(u=>u.text),n]},mode:r}]}};No.hookName="splitted-link-hook";var Qh=(e,t,r)=>(o,{links:n})=>{let s=n.map(p=>ne(p)),i=s.includes(ne(e))?[]:[`from [${e}]`],a=r.flatMap(p=>{let f=be(p,"yyyy-MM-dd");if(s.includes(f))return[];let m=be(p,"HH:mm:ss");return[`#${f} ${m}`]}),c=o.map(p=>p.text),l=c.findIndex(p=>/^#\d{4}-\d{2}-\d{2}/.test(p)),u=l<0?c.length:l;return[...c.slice(0,u),...i,...t,"",...a,...c.slice(u)]};var Zh=e=>e.preventDefault(),eg=e=>e.stopPropagation(),tg={"<A-a><A-c>":async e=>{Zh(e),eg(e);let[t,r]=i_(),o=Jt().slice(t,r+1).map(n=>{let s=n.text,i=n.text.match(/\[([^\]]+)\]/)?.[1];if(!i)return s;let a=Bt(i);if(!a||G(a))return s;let c=X(a);if(c.freshness?.status==="done")return s;let l=So(c,new Date);return l?(l.title=`[${i}]`,Ee(l)):s}).join(`
`);await ct(t,r,o),await vo()},"<A-a><A-m>":e=>{scrapbox.Layout==="page"&&(Zh(e),eg(e),_o({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"}))}},i_=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=Me();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var Co=e=>e.preventDefault(),Ao=e=>e.stopPropagation(),ql={"<A-a><A-a>":e=>{Co(e),Ao(e),rs()},"<A-a><A-s>":e=>{Co(e),Ao(e),ko()},"<A-a><A-e>":e=>{Co(e),Ao(e),Tr()},"<A-a><A-0>":e=>{Co(e),Ao(e),os()},"<A-a><A-1>":e=>{Co(e),Ao(e),ns(1)},"<A-a><A-t>":e=>{Co(e),Ao(e),ss()},"<A-a><A-S>":e=>{scrapbox.Layout==="page"&&(Co(e),Ao(e),as(scrapbox.Project.name,scrapbox.Page.title))}};var Qe=e=>e.preventDefault(),Ze=e=>e.stopPropagation(),Mo=(e,t)=>{let r=Ld()?.getElementsByClassName?.("button");if(!r)return;let o=[...r].find(n=>t instanceof RegExp?t.test(n.textContent??""):n.textContent===t);o instanceof HTMLDivElement&&e.target===document.activeElement&&(Qe(e),Ze(e),o.click())},a_={"-":e=>Mo(e,""),"]":e=>Mo(e,""),c:e=>Mo(e,"Copy plain"),$:e=>Mo(e,""),"{":e=>Mo(e,/{{c\d+}}/),"}":e=>Mo(e,"reset cloze"),n:e=>Mo(e,"make note")},c_={"<C-]>":e=>{let{position:{line:t,char:r}}=Me(),o=Qn(t,r)?.closest("a.page-link")??wr(t)?.querySelector?.("a.page-link");o instanceof HTMLAnchorElement&&(Qe(e),Ze(e),o.click())},"<C-o>":e=>{Qe(e),Ze(e),history.back()}},l_={"<C-home>":e=>{Qe(e),Ze(e),Dd()},"<C-end>":e=>{Qe(e),Ze(e),$d()}},rg=[Oo,Lo,No],p_={"<C-X>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(Qe(e),Ze(e),kr({project:t,mode:"self",hooks:rg})?.())},"<C-D>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(Qe(e),Ze(e),kr({project:t,mode:"noopen",hooks:rg})?.())},"<C-h>":e=>{Qe(e),Ze(e),Ii()},"<C-j>":e=>{Qe(e),Ze(e),Ui()},"<C-k>":e=>{Qe(e),Ze(e),Fi()},"<C-l>":e=>{Qe(e),Ze(e),Mi()},"<A-h>":e=>{Qe(e),Ze(e),$i()},"<A-j>":e=>{Qe(e),Ze(e),Bi()},"<A-k>":e=>{Qe(e),Ze(e),ji()},"<A-l>":e=>{Qe(e),Ze(e),Di()}};scrapbox.TimeStamp.removeAllFormats();var u_={"<A-t><A-t>":e=>{Qe(e),Ze(e),Je(be(new Date,"#yyyy-MM-dd HH:mm:ss "))},"<A-t><A-j>":e=>{Qe(e),Ze(e),Je(be(new Date,"yyyy-MM-dd HH:mm:ss "))},"<A-t><A-k>":e=>{Qe(e),Ze(e),Je(be(new Date,"HH:mm:ss "))},"<A-t><A-l>":e=>{Qe(e),Ze(e),Je(be(new Date,"yyyy-MM-dd"))}},og={...a_,...c_,...l_,...p_,...u_,...tg};var{render:m_}=Le(),Kl,f_=e=>{Kl!==void 0&&cancelAnimationFrame(Kl),Kl=requestAnimationFrame(()=>m_({type:"text",text:e}))},Xl=new qi({addEventListener:zd,removeEventListener:Fl},{onSequenceUpdate:f_}),ng=Xl.bind({...og,...scrapbox.Project.name==="takker-memex"?ql:{}});ng.size>0&&alert([...ng.entries()].map(([e,t])=>`${e}:
${t.map(r=>`- ${r}`).join(`
`)}`).join(`
`));var d_=/https?:\/\/vimeo\.com\/([0-9]+)/i,sg=e=>{let t=e.match(d_);if(t)return t[1]};var h_=/https?:\/\/open\.spotify\.com\/(track|artist|playlist|album|episode|show)\/([a-zA-Z\d_-]+)(?:\?[^\s]{0,100}|)/,ig=e=>{let t=e.match(h_);if(!t)return;let[,r,o]=t;return{videoId:o,pathType:r}};var g_=/https?:\/\/anchor\.fm\/[a-zA-Z\d_-]+\/episodes\/([a-zA-Z\d_-]+(?:\/[a-zA-Z\d_-]+)?)(?:\?[^\s]{0,100}|)/,ag=e=>{let t=e.match(g_);if(!t)return;let[,r]=t;return r};var cg=e=>{let{type:t,pathType:r,content:o,href:n,...s}=e;if(o===""){let i=hi(n);if(i)return{type:"youtube",href:n,...i,...s};let a=sg(n);if(a)return{type:"vimeo",videoId:a,href:n,...s};let c=ig(n);if(c)return{type:"spotify",href:n,...c,...s};let l=ag(n);if(l)return{type:"anchor-fm",videoId:l,href:n,...s};if(x_(n))return{type:"video",href:n,...s}}return y_(n)?{type:"audio",content:o,href:n,...s}:{type:"absoluteLink",content:o,href:n,...s}},y_=e=>/\.(?:mp3|ogg|wav|aac)$/.test(e),x_=e=>/\.(?:mp4|webm)$/.test(e);var lg=async()=>{let e=localStorage.getItem("projectsLastAccessed");if(!e)return[];try{let t=JSON.parse(e),r=Object.entries(t).sort(([,s],[,i])=>i-s).map(([s])=>s),o=await di([]);if(B(o))return r;let n=H(o).projects.map(s=>s.id);return r.filter(s=>!n.includes(s))}catch(t){if(!(t instanceof SyntaxError))throw t;return[]}};var b_;(e=>{})(b_||={});var E_="0.13.3",Yl,Jl,pg=(e=E_)=>{let t=`https://cdnjs.cloudflare.com/ajax/libs/KaTeX/${e}/katex.min.js`;if(Jl)throw Jl;if(!document.querySelector(`script[src="${t}"]`)){let r=document.createElement("script");r.src=t,Yl=new Promise((o,n)=>{r.onload=()=>o(window.katex),r.onerror=s=>{Jl=s,n(s)},document.head.append(r)})}return Yl||new Promise(r=>{let o=setInterval(()=>{window.katex&&(clearInterval(o),r(window.katex))},500)})};var na=(e,t)=>{let[r,o]=J("");return{ref:F(s=>{if(!s){o("");return}pg().then(i=>{try{i.render(e,s,t),o("")}catch(a){if(a instanceof Error&&a.name==="ParseError")o(a.message.slice(19));else throw a}})},[e,...Object.values(t??{})]),error:r}};var ug=e=>{let t=[],r=new Set,o=n=>{r.delete(n);let s=t.pop();if(!s)return;let i=s[0]().finally(()=>o(i)).then(a=>s[1](a)).catch(a=>s[2](a));r.add(i)};return n=>{if(r.size<e){let s=n().finally(()=>o(s));return r.add(s),s}return new Promise((s,i)=>{t.push([n,s,i])})}};var w_="0.6.5",dg=`ScrapBubble-${w_}`,mg=await globalThis.caches.open(dg);(async()=>{for(let e of await globalThis.caches.keys())e.startsWith("ScrapBubble-")&&e!==dg&&(await globalThis.caches.delete(e),console.log(`[ScrapBubble] deleted old cache :"${e}"`))})();var fg=ug(3);async function*sa(e,t){let r=((t?.saveFailedResponse?mg.match(e):void 0)??an(e,t)).then(i=>["cache",i]);{let i=Pe(1e3).then(()=>"timeout"),a=await Promise.race([r,i]);if(a!=="timeout"){a[1]&&(yield["cache",a[1]]);let c=await fg(()=>fetch(e));!c.ok&&t?.saveFailedResponse&&await mg.put(e,c.clone()),yield["network",c]}}let o=fg(()=>fetch(e)).then(i=>["network",i]),[n,s]=await Promise.race([r,o]);if(n==="network"){yield[n,s];return}s&&(yield[n,s]),yield await o}var hg=(e,t)=>new Date(e.headers.get("Date")??0).getTime()/1e3+t<new Date().getTime()/1e3;var ia=()=>{let e=new Map;return{dispatch:(t,r)=>{let o=e.get(t);if(o)for(let n of o)n(r)},on:(t,r)=>{let o=e.get(t)??new Set;o.add(r),e.set(t,o)},off:(t,r)=>{let o=e.get(t);o&&o.delete(r)}}};var Nt=!1,gg=e=>{Nt=typeof e=="boolean"?e:new Set(e)},Yr=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...o)=>r(`%c${e}`,"color: gray",...o)];case"log":case"info":case"debug":return[t,(...o)=>{Nt!==!0&&(!Nt||!Nt.has(e))||r(`%c${e}`,"color: gray",...o)}];case"assert":return[t,(o,...n)=>{Nt!==!0&&(!Nt||!Nt.has(e))||r(o,`%c${e}`,"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{Nt!==!0&&(!Nt||!Nt.has(e))||r(`${e} ${o}`)}];default:return[t,(...o)=>{if(!(Nt!==!0&&(!Nt||!Nt.has(e))))return r(...o)}]}}));var Ql=ia(),aa=new Map,k_=Yr("ScrapBubble:useProject.ts"),yg=e=>{let[t,r]=J();return oe(()=>{Ql.on(e,r);let o=aa.get(e);return o?r(o.loading?void 0:o.value):(aa.set(e,{loading:!0}),r(void 0),(async()=>{try{let n=yr.toRequest(e);for await(let[,s]of sa(n)){let i=await yr.fromResponse(s);aa.set(e,{loading:!1,value:i}),Ql.dispatch(e,i);break}}catch(n){k_.error(n),aa.delete(e)}})()),()=>Ql.off(e,r)},[e]),t};var R_=["default-light","default-dark","default-minimal"],v_=["paper-light","paper-dark-dark","paper-dark"],xg=["blue","purple","green","orange","red"],T_=["hacker1","hacker2"],bg=["winter","spring","summer","automn"],Eg=["tropical"],wg=["kyoto","newyork","paris"],kg=["mred","lgreen"],_ie=["default-light","default-minimal","paper-light",...xg,...bg,...Eg,...wg,...kg];var __=[...R_,...v_,...xg,...T_,...bg,...Eg,...wg,...kg];function Rg(e){return __.includes(e)}var vg="default-light",Io=e=>{let t=yg(e);return C(()=>{if(!t||B(t))return vg;let r=H(t).theme;return Rg(r)?r:vg},[t])};var pn=(e,t)=>new Promise(r=>{let o=!1,n=()=>{o=!0,r(!1)};e.addEventListener("click",n),e.addEventListener("pointerleave",n),setTimeout(()=>{o||r(!0),e.removeEventListener("click",n),e.removeEventListener("pointerleave",n),r(!1)},t)});var un=e=>{let{top:t,right:r,left:o,bottom:n}=e.getBoundingClientRect(),s=document.body.getBoundingClientRect(),i=(o-s.left)/s.width>.5;return{top:Math.round(n-s.top),bottom:Math.round(globalThis.innerHeight-globalThis.scrollY-t),...i?{right:Math.round(s.right-r)}:{left:Math.round(o-s.left)},maxWidth:i?r-10:document.documentElement.clientWidth-o-10}};var Tg=({project:e,title:t,descriptions:r,thumbnail:o,linkTo:n,bubble:s,delay:i,prefetch:a})=>{let c=C(()=>o?[]:He(r.join(`
`),{hasTitle:!1}),[o,r]),l=Io(e),u=F(async({currentTarget:f})=>{a(e,t),await pn(f,i)&&s({project:e,title:t,linkTo:n,type:"link",position:un(f)})},[e,t,i,n?.project,n?.titleLc]),p=C(()=>n?()=>{sn({type:"page",from:{project:n.project??e,title:n.titleLc},to:{project:e,title:t}})}:()=>{},[e,t,n?.project,n?.titleLc]);return d("a",{className:"related-page-card page-link",type:"link","data-theme":l,href:`/${e}/${me(t)}`,rel:e===scrapbox.Project.name?"route":"noopner noreferrer",target:e!==scrapbox.Project.name?"_blank":"",onPointerEnter:u,onClick:p,children:[d("div",{class:"hover"}),d("div",{class:"content",children:[d("div",{class:"header",children:d("div",{class:"title",children:t})}),o?d("div",{class:"thumbnail",children:d("img",{src:o})}):d("div",{class:"description",children:c.flatMap((f,m)=>f.type==="line"?[d("p",{children:f.nodes.map(h=>d(_g,{node:h,project:e}))},m)]:[])})]})]})},_g=({node:e,project:t})=>{switch(e.type){case"code":return d("code",{children:e.text});case"formula":return d(P_,{node:e});case"commandLine":return d("code",{children:[e.symbol," $",e.text]});case"helpfeel":return d("code",{children:["? ",e.text]});case"quote":case"strong":case"decoration":return d(Y,{children:e.nodes.map(r=>d(_g,{node:r,project:t}))});case"icon":case"strongIcon":return d(S_,{node:e,project:t});case"hashTag":return d(O_,{node:e});case"link":return d(L_,{node:e});case"plain":case"blank":return d(Y,{children:e.text});default:return d(Y,{})}},P_=({node:{formula:e}})=>{let{ref:t,error:r}=na(e);return d("span",{className:`formula ${r?" error":""}`,children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},S_=({node:{pathType:e,path:t},project:r})=>{let[o,n]=e==="relative"?[r,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[r,t];return d("img",{class:"icon",src:`/api/pages/${o}/${me(n)}/icon`})},O_=({node:{href:e}})=>d("span",{class:"page-link",children:["#",e]}),L_=({node:{pathType:e,href:t,content:r}})=>e!=="absolute"?d("span",{class:"page-link",children:t}):d("span",{class:"link",children:r||t});var we=(e,t)=>`/${e.toLowerCase()}/${ne(t)}`,ca=e=>{let t=e.match("/([^/]+)/(.+)");if(!t)throw SyntaxError(`"${e}" cannnot match "/([^/]+)/(.+)"`);return{project:t[1],titleLc:t[2]}};var Cg=Symbol.for("immer-nothing"),Pg=Symbol.for("immer-draftable"),ye=Symbol.for("immer-state");function Ht(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var mn=Object.getPrototypeOf;function fn(e){return!!e&&!!e[ye]}function Pr(e){return e?Ag(e)||Array.isArray(e)||!!e[Pg]||!!e.constructor?.[Pg]||fa(e)||da(e):!1}var N_=Object.prototype.constructor.toString();function Ag(e){if(!e||typeof e!="object")return!1;let t=mn(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===N_}function ps(e,t){ma(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,o)=>t(o,r,e))}function ma(e){let t=e[ye];return t?t.type_:Array.isArray(e)?1:fa(e)?2:da(e)?3:0}function tp(e,t){return ma(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Mg(e,t,r){let o=ma(e);o===2?e.set(t,r):o===3?e.add(r):e[t]=r}function C_(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function fa(e){return e instanceof Map}function da(e){return e instanceof Set}function st(e){return e.copy_||e.base_}function rp(e,t){if(fa(e))return new Map(e);if(da(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Ag(e);if(t===!0||t==="class_only"&&!r){let o=Object.getOwnPropertyDescriptors(e);delete o[ye];let n=Reflect.ownKeys(o);for(let s=0;s<n.length;s++){let i=n[s],a=o[i];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(o[i]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[i]})}return Object.create(mn(e),o)}else{let o=mn(e);if(o!==null&&r)return{...e};let n=Object.create(o);return Object.assign(n,e)}}function ip(e,t=!1){return ha(e)||fn(e)||!Pr(e)||(ma(e)>1&&(e.set=e.add=e.clear=e.delete=A_),Object.freeze(e),t&&Object.entries(e).forEach(([r,o])=>ip(o,!0))),e}function A_(){Ht(2)}function ha(e){return Object.isFrozen(e)}var op={};function Fo(e){let t=op[e];return t||Ht(0,e),t}function M_(e,t){op[e]||(op[e]=t)}var us;function la(){return us}function I_(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Sg(e,t){t&&(Fo("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function np(e){sp(e),e.drafts_.forEach(F_),e.drafts_=null}function sp(e){e===us&&(us=e.parent_)}function Og(e){return us=I_(us,e)}function F_(e){let t=e[ye];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Lg(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[ye].modified_&&(np(t),Ht(4)),Pr(e)&&(e=pa(t,e),t.parent_||ua(t,e)),t.patches_&&Fo("Patches").generateReplacementPatches_(r[ye].base_,e,t.patches_,t.inversePatches_)):e=pa(t,r,[]),np(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Cg?e:void 0}function pa(e,t,r){if(ha(t))return t;let o=t[ye];if(!o)return ps(t,(n,s)=>Ng(e,o,t,n,s,r)),t;if(o.scope_!==e)return t;if(!o.modified_)return ua(e,o.base_,!0),o.base_;if(!o.finalized_){o.finalized_=!0,o.scope_.unfinalizedDrafts_--;let n=o.copy_,s=n,i=!1;o.type_===3&&(s=new Set(n),n.clear(),i=!0),ps(s,(a,c)=>Ng(e,o,n,a,c,r,i)),ua(e,n,!1),r&&e.patches_&&Fo("Patches").generatePatches_(o,r,e.patches_,e.inversePatches_)}return o.copy_}function Ng(e,t,r,o,n,s,i){if(fn(n)){let a=s&&t&&t.type_!==3&&!tp(t.assigned_,o)?s.concat(o):void 0,c=pa(e,n,a);if(Mg(r,o,c),fn(c))e.canAutoFreeze_=!1;else return}else i&&r.add(n);if(Pr(n)&&!ha(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;pa(e,n),(!t||!t.scope_.parent_)&&typeof o!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,o)&&ua(e,n)}}function ua(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ip(t,r)}function U_(e,t){let r=Array.isArray(e),o={type_:r?1:0,scope_:t?t.scope_:la(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=o,s=ap;r&&(n=[o],s=ms);let{revoke:i,proxy:a}=Proxy.revocable(n,s);return o.draft_=a,o.revoke_=i,a}var ap={get(e,t){if(t===ye)return e;let r=st(e);if(!tp(r,t))return D_(e,r,t);let o=r[t];return e.finalized_||!Pr(o)?o:o===Zl(e.base_,t)?(ep(e),e.copy_[t]=fs(o,e)):o},has(e,t){return t in st(e)},ownKeys(e){return Reflect.ownKeys(st(e))},set(e,t,r){let o=Ig(st(e),t);if(o?.set)return o.set.call(e.draft_,r),!0;if(!e.modified_){let n=Zl(st(e),t),s=n?.[ye];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(C_(r,n)&&(r!==void 0||tp(e.base_,t)))return!0;ep(e),_r(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Zl(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,ep(e),_r(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=st(e),o=Reflect.getOwnPropertyDescriptor(r,t);return o&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:o.enumerable,value:r[t]}},defineProperty(){Ht(11)},getPrototypeOf(e){return mn(e.base_)},setPrototypeOf(){Ht(12)}},ms={};ps(ap,(e,t)=>{ms[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ms.deleteProperty=function(e,t){return ms.set.call(this,e,t,void 0)};ms.set=function(e,t,r){return ap.set.call(this,e[0],t,r,e[0])};function Zl(e,t){let r=e[ye];return(r?st(r):e)[t]}function D_(e,t,r){let o=Ig(t,r);return o?"value"in o?o.value:o.get?.call(e.draft_):void 0}function Ig(e,t){if(!(t in e))return;let r=mn(e);for(;r;){let o=Object.getOwnPropertyDescriptor(r,t);if(o)return o;r=mn(r)}}function _r(e){e.modified_||(e.modified_=!0,e.parent_&&_r(e.parent_))}function ep(e){e.copy_||(e.copy_=rp(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var $_=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,o)=>{if(typeof t=="function"&&typeof r!="function"){let s=r;r=t;let i=this;return function(a=s,...c){return i.produce(a,l=>r.call(this,l,...c))}}typeof r!="function"&&Ht(6),o!==void 0&&typeof o!="function"&&Ht(7);let n;if(Pr(t)){let s=Og(this),i=fs(t,void 0),a=!0;try{n=r(i),a=!1}finally{a?np(s):sp(s)}return Sg(s,o),Lg(n,s)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===Cg&&(n=void 0),this.autoFreeze_&&ip(n,!0),o){let s=[],i=[];Fo("Patches").generateReplacementPatches_(t,n,s,i),o(s,i)}return n}else Ht(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...i)=>this.produceWithPatches(s,a=>t(a,...i));let o,n;return[this.produce(t,r,(s,i)=>{o=s,n=i}),o,n]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Pr(e)||Ht(8),fn(e)&&(e=j_(e));let t=Og(this),r=fs(e,void 0);return r[ye].isManual_=!0,sp(t),r}finishDraft(e,t){let r=e&&e[ye];(!r||!r.isManual_)&&Ht(9);let{scope_:o}=r;return Sg(o,t),Lg(void 0,o)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let n=t[r];if(n.path.length===0&&n.op==="replace"){e=n.value;break}}r>-1&&(t=t.slice(r+1));let o=Fo("Patches").applyPatches_;return fn(e)?o(e,t):this.produce(e,n=>o(n,t))}};function fs(e,t){let r=fa(e)?Fo("MapSet").proxyMap_(e,t):da(e)?Fo("MapSet").proxySet_(e,t):U_(e,t);return(t?t.scope_:la()).drafts_.push(r),r}function j_(e){return fn(e)||Ht(10,e),Fg(e)}function Fg(e){if(!Pr(e)||ha(e))return e;let t=e[ye],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=rp(e,t.scope_.immer_.useStrictShallowCopy_)}else r=rp(e,!0);return ps(r,(o,n)=>{Mg(r,o,Fg(n))}),t&&(t.finalized_=!1),r}function Ug(){class e extends Map{constructor(c,l){super(),this[ye]={type_:2,parent_:l,scope_:l?l.scope_:la(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:c,draft_:this,isManual_:!1,revoked_:!1}}get size(){return st(this[ye]).size}has(c){return st(this[ye]).has(c)}set(c,l){let u=this[ye];return i(u),(!st(u).has(c)||st(u).get(c)!==l)&&(r(u),_r(u),u.assigned_.set(c,!0),u.copy_.set(c,l),u.assigned_.set(c,!0)),this}delete(c){if(!this.has(c))return!1;let l=this[ye];return i(l),r(l),_r(l),l.base_.has(c)?l.assigned_.set(c,!1):l.assigned_.delete(c),l.copy_.delete(c),!0}clear(){let c=this[ye];i(c),st(c).size&&(r(c),_r(c),c.assigned_=new Map,ps(c.base_,l=>{c.assigned_.set(l,!1)}),c.copy_.clear())}forEach(c,l){let u=this[ye];st(u).forEach((p,f,m)=>{c.call(l,this.get(f),f,this)})}get(c){let l=this[ye];i(l);let u=st(l).get(c);if(l.finalized_||!Pr(u)||u!==l.base_.get(c))return u;let p=fs(u,l);return r(l),l.copy_.set(c,p),p}keys(){return st(this[ye]).keys()}values(){let c=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{let l=c.next();return l.done?l:{done:!1,value:this.get(l.value)}}}}entries(){let c=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{let l=c.next();if(l.done)return l;let u=this.get(l.value);return{done:!1,value:[l.value,u]}}}}[Symbol.iterator](){return this.entries()}}function t(a,c){return new e(a,c)}function r(a){a.copy_||(a.assigned_=new Map,a.copy_=new Map(a.base_))}class o extends Set{constructor(c,l){super(),this[ye]={type_:3,parent_:l,scope_:l?l.scope_:la(),modified_:!1,finalized_:!1,copy_:void 0,base_:c,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return st(this[ye]).size}has(c){let l=this[ye];return i(l),l.copy_?!!(l.copy_.has(c)||l.drafts_.has(c)&&l.copy_.has(l.drafts_.get(c))):l.base_.has(c)}add(c){let l=this[ye];return i(l),this.has(c)||(s(l),_r(l),l.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let l=this[ye];return i(l),s(l),_r(l),l.copy_.delete(c)||(l.drafts_.has(c)?l.copy_.delete(l.drafts_.get(c)):!1)}clear(){let c=this[ye];i(c),st(c).size&&(s(c),_r(c),c.copy_.clear())}values(){let c=this[ye];return i(c),s(c),c.copy_.values()}entries(){let c=this[ye];return i(c),s(c),c.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(c,l){let u=this.values(),p=u.next();for(;!p.done;)c.call(l,p.value,p.value,this),p=u.next()}}function n(a,c){return new o(a,c)}function s(a){a.copy_||(a.copy_=new Set,a.base_.forEach(c=>{if(Pr(c)){let l=fs(c,a);a.drafts_.set(c,l),a.copy_.add(l)}else a.copy_.add(c)}))}function i(a){a.revoked_&&Ht(3,JSON.stringify(st(a)))}M_("MapSet",{proxyMap_:t,proxySet_:n})}var Ct=new $_,ga=Ct.produce,Xie=Ct.produceWithPatches.bind(Ct),Yie=Ct.setAutoFreeze.bind(Ct),Jie=Ct.setUseStrictShallowCopy.bind(Ct),Qie=Ct.applyPatches.bind(Ct),Zie=Ct.createDraft.bind(Ct),eae=Ct.finishDraft.bind(Ct);Ug();var Dg=e=>{let t=0;for(let r of e)if(r&&(r.exists||(t+=(r.linked?.length??0)+(r.projectLinked?.length??0),t>1)))return!1;return t<2},$g=(e,t)=>ga(e,r=>{if(!r)return t;if(r.updated<t.updated){let{lines:o,linked:n,projectLinked:s,...i}=t;Object.assign(r,i),cp(t)||(r.lines=o),n&&(r.linked??=n),s&&(r.projectLinked??=s);return}cp(r)&&!cp(t)&&(r.lines=t.lines),t.linked&&(t.isLinkedCorrect||!r.isLinkedCorrect&&(r.linked?.length??0)<=t.linked.length)&&(r.linked=t.linked),t.projectLinked&&(r.projectLinked=t.projectLinked)}),cp=e=>e.lines[0].id==="dummy";var jg=(e,t)=>{let r=new Map,o=ne(t.title);for(let c of t.links){let l=lp(e,c);l.linked=[o],r.set(we(e,c),l)}let n=we(e,o),s=t.projectLinks.map(c=>{let l=ca(c);return we(l.project,l.titleLc)}),i={...ya(e,t),linked:[],projectLinked:[]};r.set(n,i);let a=t.links.map(c=>ne(c));for(let c of t.relatedPages.links1hop){c.linksLc.includes(o)&&i.linked.push(c.titleLc);for(let f of c.linksLc.filter(m=>a.includes(m))){let m=we(e,f),h=r.get(m)??lp(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=we(e,c.titleLc),u=ya(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}for(let c of t.relatedPages.projectLinks1hop){let l=we(c.projectName,c.titleLc);s.includes(l)||i.projectLinked.push(l);let u=ya(c.projectName,c),p=r.get(l)?.projectLinked;p&&(u.projectLinked=p),r.set(l,u)}i.isLinkedCorrect=!0;for(let c of t.relatedPages.links2hop){for(let f of c.linksLc){let m=we(e,f),h=r.get(m)??lp(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=we(e,c.titleLc),u=ya(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}return r},ya=(e,t)=>({project:e,titleLc:"titleLc"in t?t.titleLc:ne(t.title),exists:"persistent"in t?t.persistent:!0,descriptions:t.descriptions,image:t.image,lines:"lines"in t?t.lines:[t.title,...t.descriptions].map(r=>({text:r,id:"dummy",userId:"dummy",updated:t.updated,created:t.updated})),updated:t.updated,isLinkedCorrect:!1}),lp=(e,t)=>({project:e,titleLc:ne(t),exists:!1,descriptions:[],image:null,lines:[{text:t,id:"dummy",userId:"dummy",updated:0,created:0}],updated:0,isLinkedCorrect:!1});var xa=Yr("ScrapBubble:bubble.ts"),pp=new Map,ba=new Set,up=ia();function*Hg(e){for(let t of e)yield pp.get(t)}var Wg=(e,t)=>up.on(e,t),Gg=(e,t)=>up.off(e,t),Vg=async(e,t,r,o)=>{let n=[];for(let s of[...t].reverse()){let i=we(s,e);ba.has(i)||n.push(B_(s,e,r,o))}await Promise.all(n)},Bg=0,B_=async(e,t,r,o)=>{let n=we(e,t);if(ba.has(n))return;ba.add(n);let s=Bg++,i=`[${s}] Check update ${n}`;xa.time(i);try{let a=Dt.toRequest(e,t,{followRename:!0,projects:[...r]});for await(let[c,l]of sa(a,{ignoreSearch:!0,saveFailedResponse:!0})){xa.debug(`[${s}]${c} ${n}`);let u=await Dt.fromResponse(l);if(Ne(u)){let p=jg(e,H(u));for(let[f,m]of p){let h=pp.get(f),g=$g(h,m);g&&h!==g&&(pp.set(f,g),up.dispatch(f,m))}}if(o?.ignoreFetch===!0||c==="cache"&&!hg(l,o?.maxAge??60))break}}catch(a){xa.error(a)}finally{ba.delete(n),xa.timeEnd(i),Bg--}};var zg=Yr("ScrapBubble:useBubbleData.ts"),dn=e=>{let[t,r]=J(mp(e));return oe(()=>{r(mp(e));let o,n=()=>{clearTimeout(o),o=setTimeout(()=>{zg.debug(`Update ${e.length} pages`),r(mp(e))},10)};return e.forEach(s=>Wg(s,n)),()=>e.forEach(s=>Gg(s,n))},e),t},mp=e=>{let t=[...Hg(e)].flatMap(r=>r?[r]:[]);return zg.debug(`Required: ${e.length} pages, ${t.length} found`,t),t};var qg=({source:e,linked:t,externalLinked:r,projectsForSort:o,...n})=>{let s=C(()=>[...t.keys(),...r.keys()],[t,r]),i=dn(s),a=C(()=>[...o],[o]),c=C(()=>{let u=(p,f)=>{let m=a.indexOf(p.project),h=a.indexOf(f.project);return m===h?f.updated-p.updated:m<0?1:h<0?-1:m-h};return[...i].sort(u)},[i,a]),l=C(()=>({bottom:`${e.position.bottom}px`,maxWidth:`${e.position.maxWidth}px`,..."left"in e.position?{left:`${e.position.left}px`}:{right:`${e.position.right}px`}}),[e.position]);return d("ul",{className:"card-bubble",style:l,onClick:n.onClick,children:c.map(({project:u,titleLc:p,lines:[{text:f}],descriptions:m,image:h})=>{let g=we(u,p),y=t.get(g)??r.get(g);return d("li",{children:d(Tg,{project:u,title:f,linkTo:y,descriptions:m,thumbnail:h??"",...n})},g)})})};var hn=e=>{e:if(e.pathType==="root"){let[,r="",o=""]=e.href.match(/\/([\w\-]+)(?:\/?|\/(.*))$/)??["","",""];if(r==="")break e;let[,n]=o?.match?.(/#([a-f\d]{24,32})$/)??["",""];return o===""?{project:r}:n===""?{project:r,title:o}:{project:r,title:o.slice(0,-1-n.length),hash:n}}let[,t]=e.href.match(/#([a-f\d]{24,32})$/)??["",""];return t===""?{title:e.href}:{title:e.href.slice(0,-1-t.length),hash:t}};var fp=(e,t)=>t.some(r=>{let o=!e.project;switch(r.type){case"hashTag":return o&&ne(r.href)===e.titleLc;case"link":{if(r.pathType=="absolute"||r.pathType==="relative"!==o)return!1;let{project:n,title:s=""}=hn({pathType:r.pathType,href:r.href});return o?!n&&ne(s)===e.titleLc:n===e.project&&ne(s)===e.titleLc}case"quote":case"strong":case"decoration":return fp(e,r.nodes)}});var Jr=Kn({title:"",project:"",whiteList:new Set,bubble:()=>{},hide:()=>{},delay:0,prefetch:()=>{}}),Xg=({lines:e,project:t,title:r,whiteList:o,noIndent:n,hash:s,linkTo:i,...a})=>{let c=C(()=>e.flatMap(m=>typeof m=="string"?[]:[m.id]),[e]),l=C(()=>{let m=0;return He(e.map(h=>typeof h=="string"?h:h.text).join(`
`),{hasTitle:!0}).map(h=>{switch(h.type){case"title":case"line":return{...h,id:c[m++]};case"codeBlock":{let g=m;return m+=h.content.split(`
`).length+1,{...h,ids:c.slice(g,m)}}case"table":{let g=m;return m+=h.cells.length+1,{...h,ids:c.slice(g,m)}}}})},[e,c]),u=C(()=>{if(s&&c.includes(s))return s;if(i)return l.find(m=>m.type!=="line"?!1:fp(i,m.nodes))?.id},[l,c,s,i?.project,i?.titleLc]),p=qe(null);oe(()=>{if(!u)return;let m=p.current?.querySelector(`[data-id="${u}"]`),h=globalThis.scrollY;m?.scrollIntoView?.({block:"center"}),globalThis.scroll(0,h)},[u]);let f=Io(t);return d("div",{className:"lines","data-theme":f,ref:p,children:d(Jr.Provider,{value:{project:t,title:r,whiteList:o,...a},children:l.map(m=>{switch(m.type){case"title":return d(Y,{children:[d(yn,{index:m.id,indent:0,noIndent:n,permalink:m.id===u,children:d("a",{className:"page-link",type:"link",href:`/${t}/${me(m.text)}`,rel:t===scrapbox.Project.name?"route":"noopener noreferrer",target:t===scrapbox.Project.name?"":"_blank",children:m.text})},m.id),d("hr",{})]});case"codeBlock":return d(H_,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"table":return d(W_,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"line":return d(yn,{index:m.id,indent:m.indent,noIndent:n,permalink:m.id===u,children:m.nodes.length>0?m.nodes.map(h=>d(gn,{node:h})):d("br",{})},m.id)}})})})},yn=({index:e,indent:t,noIndent:r,children:o,permalink:n})=>d("div",{className:`line${n?" permalink":""}`,"data-id":e,"data-indent":t,style:{"margin-left":r?"":`${1*t}em`},children:o}),H_=({block:{fileName:e,content:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=br(Jr),[a,c]=J(""),l=F(async u=>{u.preventDefault(),u.stopPropagation();try{await navigator.clipboard.writeText(t),c("Copied"),await Pe(1e3),c("")}catch(p){alert(`Failed to copy the code block
Error: ${p}`)}},[t]);return d(Y,{children:[d(yn,{index:o[0],indent:r,permalink:o[0]===n,children:d("span",{className:"code-block",children:[d("span",{className:"code-block-start",children:d("a",{href:`/api/code/${s}/${me(i)}/${e}`,target:"_blank",children:e})}),d("span",{className:"copy",title:"Copy",onClick:l,children:a})]})}),d(Y,{children:t.split(`
`).map((u,p)=>d(yn,{index:o[p+1],indent:r,permalink:o[p+1]===n,children:d("code",{className:"code-block",children:u})}))})]})},W_=({block:{fileName:e,cells:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=br(Jr);return d(Y,{children:[d(yn,{index:o[0],indent:r,permalink:o[0]===n,children:d("span",{className:"table-block",children:d("span",{className:"table-block-start",children:d("a",{href:`/api/table/${s}/${me(i)}/${e}.csv`,target:"_blank",children:e})})})}),d(Y,{children:t.map((a,c)=>d(yn,{index:o[c+1],indent:r,permalink:o[c+1]===n,children:d("span",{className:"table-block table-block-row",children:a.map((l,u)=>d("span",{className:`cell col-${u}`,children:l.map(p=>d(gn,{node:p}))}))})}))})]})},gn=({node:e})=>{switch(e.type){case"code":return d("code",{className:"code",children:e.text});case"formula":return d(G_,{node:e});case"commandLine":return d(z_,{node:e});case"helpfeel":return d("code",{className:"helpfeel",children:[d("span",{className:"prefix",children:"?"})," ",d("span",{className:"entry",children:e.text})]});case"quote":return d("blockquote",{className:"quote",children:e.nodes.map(t=>d(gn,{node:t}))});case"strong":return d("strong",{children:e.nodes.map(t=>d(gn,{node:t}))});case"decoration":return d(V_,{node:e});case"plain":case"blank":return d(Y,{children:e.text});case"hashTag":return d(X_,{node:e});case"link":return d(Y_,{node:e});case"googleMap":return d(q_,{node:e});case"icon":return d(Kg,{node:e});case"strongIcon":return d(Kg,{node:e,strong:!0});case"image":return d(K_,{node:e});case"strongImage":return d("img",{className:"image strong-image",src:e.src});case"numberList":return d(Y,{children:[`${e.number}. `,e.nodes.map(t=>d(gn,{node:t}))]})}},G_=({node:{formula:e}})=>{let{ref:t,error:r}=na(e);return d("span",{className:`formula ${r?" error":""}`,children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},V_=({node:{decos:e,nodes:t}})=>d("span",{className:e.map(r=>`deco-${r}`).join(" "),children:t.map(r=>d(gn,{node:r}))}),z_=({node:e})=>{let[t,r]=J(""),o=F(async n=>{n.preventDefault(),n.stopPropagation();try{await navigator.clipboard.writeText(e.text),r("Copied"),await Pe(1e3),r("")}catch(s){alert(`Failed to copy the code block
Error: ${s}`)}},[e.text]);return d(Y,{children:[d("code",{className:"cli",children:[d("span",{className:"prefix",children:e.symbol})," ",d("span",{className:"command",children:e.text})]}),d("span",{className:"tool-buttons",children:d("span",{title:"Copy",className:"copy",onClick:o,children:t})})]})},q_=({node:{place:e,latitude:t,longitude:r,zoom:o}})=>d("span",{className:"pointing-device-map",children:d("a",{href:`https://www.google.com/maps/search/${e}/@${t},${r},${o}z`,rel:"noopner noreferrer",target:"_blank",children:d("img",{className:"google-map",src:`/api/google-map/static-map?center=${t}%2C${r}&markers=${e}&zoom=${o}&_csrf=${globalThis._csrf}`})})}),Kg=({node:{pathType:e,path:t},strong:r})=>{let{project:o}=br(Jr),[n,s]=e==="relative"?[o,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[o,t],i=me(s);return d("a",{href:`/${n}/${i}`,rel:n===scrapbox.Project.name?"route":"noopener noreferrer",target:n===scrapbox.Project.name?"":"_blank",children:d("img",{className:r?"icon strong-icon":"icon",alt:s,src:`/api/pages/${n}/${i}/icon`,children:s})})},K_=({node:{link:e,src:t}})=>{let r=e||(/https:\/\/gyazo\.com\/[^\/]+\/thumb\/1000/.test(t)?t.slice(0,-11):t);return d("a",{className:e?"link":"",href:r,rel:"noopner noreferrer",target:"_blank",children:d("img",{className:"image",src:t})})},X_=({node:{href:e}})=>{let{project:t}=br(Jr),r=Yg(t,e),o=Jg(t,e,"hashtag");return d("a",{href:`/${t}/${me(e)}`,className:`page-link${r?" empty-page-link":""}`,type:"hashTag",rel:t===scrapbox.Project.name?"route":"noopener noreferrer",target:t===scrapbox.Project.name?"":"_blank",onPointerEnter:o,children:["#",e]})},Y_=({node:{pathType:e,...t}})=>{switch(e){case"relative":case"root":return d(J_,{pathType:e,href:t.href});case"absolute":{let r=cg({pathType:e,...t});switch(r.type){case"youtube":return d(Q_,{...r});case"vimeo":return d(Z_,{...r});case"spotify":return d(e0,{...r});case"anchor-fm":return d(t0,{...r});case"audio":return d(r0,{...r});case"video":return d(n0,{...r});case"absoluteLink":return d("a",{className:"link",href:r.href,rel:"noopener noreferrer",target:"_blank",children:r.content||r.href})}}}},J_=({pathType:e,href:t})=>{let{project:r}=br(Jr),{project:o=r,title:n,hash:s=""}=hn({pathType:e,href:t}),i=Jg(o,n,"link",s),a=Yg(o,n??"");return d("a",{className:`page-link${n!==void 0&&a?" empty-page-link":""}`,type:"link",href:`/${o}${n===void 0?"":`/${me(n)}${s===""?"":`#${s}`}`}`,rel:o===scrapbox.Project.name?"route":"noopener noreferrer",target:o===scrapbox.Project.name?"":"_blank",onPointerEnter:i,children:t})},Q_=e=>{e.params.append("autoplay","0");let t=e.pathType==="list"?`https://www.youtube.com/embed/?${e.params.toString()}&list=${e.listId}`:`https://www.youtube.com/embed/${e.videoId}?${e.params.toString()}`;return d("div",{className:"iframe-video-player",children:d("iframe",{src:t,allowFullScreen:!0})})},Z_=({videoId:e})=>d("div",{className:"iframe-video-player",children:d("iframe",{src:`https://player.vimeo.com/video/${e}`,allowFullScreen:!0})}),e0=e=>d("div",{className:"iframe-video-player",children:d("iframe",{className:`spotify type-${e.pathType}`,src:`https://open.spotify.com/embed/${e.pathType}/${e.videoId}`,allowFullScreen:!0})}),t0=e=>d("div",{className:"iframe-video-player",children:d("iframe",{className:"anchor-fm",src:e.href.replace("/episodes/","/embed/episodes/"),allowFullScreen:!0})}),r0=e=>e.content===""?d("audio",{className:"audio-player",preload:"none",controls:!0,src:e.href}):d(o0,{...e}),o0=({href:e,content:t})=>{let r=qe(null),o=F(()=>{r.current?.paused?(r.current.currentTime=0,r.current.play()):r.current?.pause?.()},[]);return d("span",{className:"audio-link",children:[d("a",{href:e,rel:"noopener noreferrer",target:"_blank",children:t}),d("span",{className:"play",onClick:o,children:"♬"}),d("audio",{preload:"none",src:e,ref:r})]})},n0=({href:e})=>d("div",{className:"video-player",children:d("video",{class:"video",style:{display:"inline-block"},controls:!0,loop:!0,src:e})}),Yg=(e,t)=>{let{whiteList:r}=br(Jr),o=C(()=>(r.has(e)?[...r]:[e,...r]).map(s=>we(s,t)),[r,e]),n=dn(o);return C(()=>Dg(n),n)},Jg=(e,t,r,o)=>{let{delay:n,bubble:s,prefetch:i}=br(Jr);return F(async({currentTarget:a})=>{t&&(i(e,t),await pn(a,n)&&s({project:e,title:t,hash:o,type:r,position:un(a)}))},[e,t,o,r,n,i,s])};var Qg=({pages:e,onClick:t,source:r,whiteList:o,...n})=>{let[s,i]=J(we(e[0].project,e[0].titleLc)),a=C(()=>({top:`${r.position.top}px`,maxWidth:`${r.position.maxWidth}px`,..."left"in r.position?{left:`${r.position.left}px`}:{right:`${r.position.right}px`}}),[r.position]);return d("div",{className:"text-bubble",style:a,onClick:t,children:[e.length>1&&d("div",{role:"tablist",children:e.map(c=>d(s0,{project:c.project,titleLc:c.titleLc,selected:s===we(c.project,c.titleLc),tabSelector:i},we(c.project,c.titleLc)))}),e.map(c=>d(i0,{selected:s===we(c.project,c.titleLc),...c,title:c.lines[0].text,hash:r.hash,linkTo:r.linkTo,whiteList:o,...n},we(c.project,c.titleLc)))]})},s0=({project:e,titleLc:t,tabSelector:r,selected:o})=>{let n=F(()=>r(we(e,t)),[e,t]),s=Io(e);return d("button",{role:"tab","aria-selected":o,"data-theme":s,tabIndex:-1,onClick:n,children:e})},i0=({selected:e,...t})=>{let r=Io(t.project);return d("div",{role:"tabpanel","data-theme":r,hidden:!e,children:d(Xg,{...t})})};var Zg=Yr("ScrapBubble:Bubble.tsx"),ey=({source:e,parentTitles:t,whiteList:r,...o})=>{let n=C(()=>r.has(e.project)?new Set([e.project,...r]):new Set([e.project]),[r,e.project]),[s,i,a]=c0(e,n,r,t);return d(Y,{children:[a0(a)&&d(Qg,{pages:a,source:e,whiteList:r,onClick:o.hide,...o}),d(qg,{linked:s,externalLinked:i,onClick:o.hide,source:e,projectsForSort:n,...o})]})},a0=e=>e.length>0,c0=(e,t,r,o)=>{let[[n,s,i],a]=J([new Map,new Map,[]]),c=C(()=>{let p=[...t].map(f=>we(f,e.title));return Zg.debug("projects",p),p},[t,e.title]),l=dn(c),u=C(()=>o.map(p=>ne(p)),[o]);return Li(()=>{let p=new Map,f=new Map,m=[];for(let h of l){let g={project:h.project,titleLc:h.titleLc};for(let x of h.projectLinked??[]){let{project:E,titleLc:R}=ca(x);u.includes(R)&&r.has(E)||f.has(x)||f.set(x,g)}if(!r.has(h.project))continue;let y={titleLc:h.titleLc};for(let x of h.linked??[]){if(u.includes(x))continue;let E=we(h.project,x);p.has(E)||p.set(E,y)}u.includes(h.titleLc)||h.exists&&m.push(h)}a(ga(h=>{Zg.debug(`depth: ${u.length}, bubbled from ${we(e.project,e.title)}, bubbles,`,l,"before",h[0],"internal cards,",p,"external cards",f);for(let g of h[0].keys())p.has(g)||h[0].delete(g);for(let[g,y]of p)h[0].set(g,y);for(let g of h[1].keys())f.has(g)||h[1].delete(g);for(let[g,y]of f)h[1].set(g,y);h[2]=m}))},[l,r,u]),[n,s,i]};var ty=(e,t)=>{if(e instanceof URL)return e;try{return new URL(e)}catch(r){if(!(r instanceof TypeError))throw r;if(!t||!/^\.\/|^\.\.\/|^\//.test(e))return e;try{return new URL(e,t)}catch(o){if(!(o instanceof TypeError))throw o;return e}}};var ry=e=>{let t=C(()=>ty(e.style,import.meta.url),[e.style]);return d(Y,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var oy=String.raw`*{box-sizing:border-box}a{background-color:transparent;text-decoration:none;cursor:pointer}img{display:inline-block;max-width:100%;max-height:100px}code{font-family:var(--code-text-font, Menlo, Monaco, Consolas, "Courier New", monospace);font-size:90%;color:var(--code-color, #342d9c);background-color:var(--code-bg, rgba(0,0,0,.04));padding:0;white-space:pre-wrap;word-wrap:break-word}blockquote{background-color:var(--quote-bg-color, rgba(0,0,0,.05));display:block;border-left:solid 4px #a0a0a0;padding-left:4px;margin:0}strong{font-weight:700}iframe{display:inline-block;margin:3px 0;vertical-align:middle;max-width:100%;width:640px;height:360px;border:0}audio{display:inline-block;vertical-align:middle;white-space:initial;max-width:100%}.formula{margin:auto 6px}.formula.error code{color:#fd7373}.katex-display{display:inline-block!important;margin:0!important;text-align:inherit!important}.error .katex-display{display:none}.cli{border-radius:4px}.cli .prefix{color:#9c6248}.helpfeel{background-color:#fbebdd;border-radius:4px;padding:3px!important}.helpfeel .prefix{color:#f17c00}.helpfeel .entry{color:#cc5020}.code-block{display:block;line-height:1.7em;background-color:var(--code-bg, rgba(0,0,0,.04))}.code-block-start{font-family:Menlo,Monaco,Consolas,Courier New,monospace;color:#342d9c;background-color:#ffcfc6;font-size:.9em;padding:1px 2px}.code-block-start a{color:#342d9c;text-decoration:underline}code.code-block,.table-block.table-block-row{padding-left:1em}.copy{font-family:"Font Awesome 5 Free";cursor:pointer}.table-block{white-space:nowrap}.table-block-start{padding:1px 2px;font-size:.9em;background-color:#ffcfc6}.table-block-start a{color:#342d9c;text-decoration:underline}.cell{margin:0;padding:0 2px 0 8px;box-sizing:content-box;display:inline-block;white-space:pre}.cell:nth-child(odd){background-color:#0000000a}.cell:nth-child(2n){background-color:#0000000f}.strong-image{max-height:100%}.icon{height:11px;vertical-align:middle}.strong-icon{height:13.2px}.tool-button{margin-left:1em;cursor:pointer;font-size:.9em}.deco-\/{font-style:italic}.deco-\*-1{font-weight:700}.deco-\*-2{font-weight:700;font-size:1.2em}.deco-\*-3{font-weight:700;font-size:1.44em}.deco-\*-4{font-weight:700;font-size:1.73em}.deco-\*-5{font-weight:700;font-size:2.07em}.deco-\*-6{font-weight:700;font-size:2.49em}.deco-\*-7{font-weight:700;font-size:3em}.deco-\*-8{font-weight:700;font-size:3.58em}.deco-\*-9{font-weight:700;font-size:4.3em}.deco-\*-10{font-weight:700;font-size:5.16em}.deco--{text-decoration:line-through}.deco-_{text-decoration:underline}.page-link{color:var(--page-link-color, #5e8af7)}a.page-link:hover{color:var(--page-link-hover-color, #2d67f5)}.empty-page-link{color:var(--empty-page-link-color, #fd7373)}a.empty-page-link:hover{color:var(--empty-page-link-hover-color, #fd7373)}.link{color:var(--page-link-color, #5e8af7);text-decoration:underline}a.link:hover{color:var(--page-link-color-hover-color, #2d67f5)}.link img{padding-bottom:3px;border-style:none none solid;border-width:1.5px;border-color:#8fadf9}.permalink{background-color:var(--line-permalink-color, rgba(234,218,74,.75))}.status-bar{display:inline-block;position:absolute;background-color:var(--page-bg, #fefefe);cursor:default}.status-bar>*{border:1px solid var(--status-bar-border-color, #a9aaaf)}.status-bar.top-left{top:0;left:0}.status-bar.top-left>*{border-top:none;border-left:none}.status-bar.top-left :last-of-type{border-bottom-right-radius:3px}.status-bar.top-right{top:0;right:0}.status-bar.top-right>*{border-top:none;border-right:none}.status-bar.top-right :last-of-type{border-bottom-left-radius:3px}.status-bar.bottom-right{bottom:0;right:0}.status-bar.bottom-right>*{border-bottom:none;border-right:none}.status-bar.bottom-right :last-of-type{border-top-left-radius:3px}.status-bar.bottom-left{bottom:0;left:0}.status-bar.bottom-left>*{border-bottom:none;border-left:none}.status-bar.bottom-left :last-of-type{border-top-right-radius:3px}.text-bubble{font-size:11px;line-height:1.42857;user-select:text;position:absolute;color:var(--page-text-color, #4a4a4a);box-shadow:0 6px 12px #0000002d;display:flex;flex-direction:column;z-index:9000;&.no-scroll{overflow-y:hidden}[data-theme=default-dark]{--text-bubble-border-color: hsl(0, 0%, 39%)}[data-theme=default-minimal]{--text-bubble-border-color: hsl(0, 0%, 89%)}[data-theme=paper-light]{--text-bubble-border-color: hsl(53, 8%, 58%)}[data-theme=paper-dark-dark]{--text-bubble-border-color: hsl(203, 42%, 17%)}[data-theme=blue]{--text-bubble-border-color: hsl(227, 68%, 62%)}[data-theme=purple]{--text-bubble-border-color: hsl(267, 39%, 60%)}[data-theme=green]{--text-bubble-border-color: hsl(136, 29%, 50%)}[data-theme=orange]{--text-bubble-border-color: hsl(43, 71%, 51%)}[data-theme=red]{--text-bubble-border-color: hsl(4, 58%, 56%)}[data-theme=spring]{--text-bubble-border-color: hsl(72, 64%, 57%)}[data-theme=kyoto]{--text-bubble-border-color: hsl(331, 21%, 26%)}[data-theme=newyork]{--text-bubble-border-color: hsl(176, 29%, 67%)}[role=tabpanel]{padding:5px 0 5px 5px;border-radius:4px;background-color:var(--page-bg, #fefefe);max-height:80vh;overflow-y:auto}[role=tabpanel],button{border:1px solid var(--text-bubble-border-color, hsl(221, 15%, 25%))}button{cursor:default;color:inherit;font-size:inherit;line-height:inherit;background-color:var(--page-bg, #fefefe);border-radius:4px 4px 0 0}button[aria-selected=true]{background-color:var(--text-bubble-border-color, hsl(221, 15%, 25%))}}.project-badge{text-decoration:none;color:var(--tool-text-color, #363c49)}.related-page-card[data-theme=default-dark]{--card-title-bg: hsl(0, 0%, 39%)}.related-page-card[data-theme=default-minimal]{--card-title-bg: hsl(0, 0%, 89%)}.related-page-card[data-theme=paper-light]{--card-title-bg: hsl(53, 8%, 58%)}.related-page-card[data-theme=paper-dark-dark]{--card-title-bg: hsl(203, 42%, 17%)}.related-page-card[data-theme=blue]{--card-title-bg: hsl(227, 68%, 62%)}.related-page-card[data-theme=purple]{--card-title-bg: hsl(267, 39%, 60%)}.text-bubble[data-theme=green]{--card-title-bg: hsl(136, 29%, 50%)}.related-page-card[data-theme=orange]{--card-title-bg: hsl(43, 71%, 51%)}.related-page-card[data-theme=red]{--card-title-bg: hsl(4, 58%, 56%)}.related-page-card[data-theme=spring]{--card-title-bg: hsl(72, 64%, 57%)}.related-page-card[data-theme=kyoto]{--card-title-bg: hsl(331, 21%, 26%)}.related-page-card[data-theme=newyork]{--card-title-bg: hsl(176, 29%, 67%)}.related-page-card{display:block;position:relative;height:inherit;width:inherit;overflow:hidden;text-overflow:ellipsis;font-family:Roboto,Helvetica,Arial,Hiragino Sans,sans-serif;background-color:var(--card-bg, #fff);color:var(--card-title-color, #555);word-break:break-word;text-decoration:none}.related-page-card:hover{box-shadow:var(--card-box-hover-shadow, 0 2px 0 rgba(0,0,0,.23))}.related-page-card:focus{outline:0;box-shadow:0 0 0 3px #66afe999;border-color:#66afe9;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.related-page-card.hover{opacity:0;position:absolute;width:100%;height:100%;top:0;left:0;background-color:var(--card-hover-bg, rgba(0,0,0,.05));mix-blend-mode:multiply;z-index:1;transition:background-color .1s}.related-page-card:hover .hover{opacity:1}.related-page-card:active .hover{opacity:1;background-color:var(--card-active-bg, rgba(0,0,0,.1))}.related-page-card .content{height:calc(100% - 5px);width:inherit;display:flex;flex-direction:column;overflow:hidden}.related-page-card .content .header{width:100%;color:#396bdd;text-overflow:ellipsis;border-top:var(--card-title-bg, #f2f2f3) solid 10px;padding:8px 10px}.related-page-card .content .header .title{font-size:11px;line-height:16px;font-weight:700;max-height:48px;color:var(--card-title-color, #363c49);margin:0;overflow:hidden;display:block;-webkit-line-clamp:3;-webkit-box-orient:vertical;text-overflow:ellipsis}.related-page-card .content .description{line-height:16px;padding:8px 10px 0;font-size:10px;white-space:pre-line;column-count:1;column-gap:2em;column-width:10em;height:inherit;color:var(--card-description-color, gray);flex-shrink:16;overflow:hidden}.related-page-card .content .thumbnail{display:block;width:100%;margin:0 auto;padding:0 5px}.related-page-card .content .description p{margin:0;display:block}.related-page-card .content .description code{font-family:Menlo,Monaco,Consolas,Courier New,monospace;font-size:90%;color:var(--code-color, #342d9c);background-color:var(--code-bg, rgba(0,0,0,.04));padding:0;white-space:pre-wrap;word-wrap:break-word}.related-page-card .content .description .icon{height:9px;vertical-align:middle}.related-page-card .content .description .page-link{background-color:transparent;text-decoration:none;cursor:pointer;color:var(--page-link-color, #5e8af7)}.card-bubble{background-color:var(--page-bg, #FFF);box-shadow:0 2px 2px #00000024,0 3px 1px -2px #0003,0 1px 5px #0000001f;position:absolute;max-width:80vw;box-sizing:content-box;z-index:9000;font-size:11px;line-height:1.42857;display:flex;padding:0;margin:0;list-style:none;overflow-x:auto;overflow-y:visible}.card-bubble li{display:block;position:relative;float:none;margin:5px;box-sizing:border-box;box-shadow:var(--card-box-shadow, 0 2px 0 rgba(0,0,0,.12));border-radius:2px;width:120px;height:120px}
`;var ny=()=>{let[e,t]=J([{bubble:o=>r(0,o),hide:()=>r(0)}]),r=F((o,n)=>{t(([s,...i])=>[s,...n?[...i.slice(0,o),n===i.at(o)?.source?i.at(o):{source:n,parentTitles:[scrapbox.Page.title??"",...i.slice(0,o).map(a=>a.source.title)],bubble:a=>r(o+1,a),hide:()=>r(o+1)}]:[...i.slice(0,o)]])},[]);return e};var dp=(e,t,r,o,n)=>{oe(()=>(e.addEventListener(t,r,o),()=>e.removeEventListener(t,r,o)),[e,t,o,...n??[]])};var sy=e=>e instanceof HTMLSpanElement&&e.matches(".line-title .text"),Ea=e=>e instanceof HTMLAnchorElement&&e.classList.contains("page-link");var hp="scrap-bubble",iy=({delay:e,whiteList:t,watchList:r,style:o})=>{let[{bubble:n,hide:s},...i]=ny(),a=F((c,l)=>Vg(l,t.has(c)?t:new Set([c]),r),[t,r]);return dp(document,"pointerenter",async c=>{let l=c.target;if(!Ea(l)&&!sy(l))return;let{project:u=scrapbox.Project.name,title:p,hash:f=""}=Ea(l)?hn({pathType:"root",href:`${new URL(l.href).pathname}${new URL(l.href).hash}`}):{project:scrapbox.Project.name,title:scrapbox.Page.title};if(u==="")return;let m=decodeURIComponent(p??"");a(u,m),await pn(l,e)&&n({project:u,title:m,hash:f,position:un(l),type:l0(l)})},{capture:!0},[e,t,r]),dp(document,"click",c=>{c.target.dataset.userscriptName!==hp&&s()},{capture:!0},[s]),oe(()=>(scrapbox.addListener("page:changed",s),()=>scrapbox.removeListener("page:changed",s)),[s]),d(Y,{children:[d("link",{rel:"stylesheet",href:"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.12.0/katex.min.css"}),d("style",{children:oy}),d(ry,{style:o}),i.map(c=>d(ey,{...c,whiteList:t,delay:e,prefetch:a},we(c.source.project,c.source.title)))]})},l0=e=>Ea(e)?e.type==="link"?"link":"hashtag":"title";var ay=async e=>{let{delay:t=500,whiteList:r=[],watchList:o=(await lg()).slice(0,100),style:n="",debug:s=!1}=e??{};gg(s);let i=document.createElement("div");i.dataset.userscriptName=hp,document.body.append(i);let a=i.attachShadow({mode:"open"});mt(d(iy,{delay:t,whiteList:new Set([scrapbox.Project.name,...r]),watchList:new Set(o),style:n}),a)};var p0=["takker-memex","takker-private","takker","takker-books","villagepump"],Uo=[];switch(scrapbox.Project.name){case"hub":case"villagepump":case"verbalizing-community":Uo.push("villagepump","hub","verbalizing-community");break;case"programming-notes":case"customize":case"scrapboxlab":Uo.push("programming-notes","customize","scrapboxlab");break;case"sta":Uo.push("sta-taskmanagement");break;case"sta-taskmanagement":case"taskmanagement":Uo.push("sta-taskmanagement","taskmanagement");break;case"plurality-japanese":Uo.push("nishio","tkgshn");case"takker-books":Uo.push("work4ai");break}ay({delay:/mobile/i.test(navigator.userAgent)?300:500,whiteList:[...p0,...Uo],style:`@import "/api/code/takker/kakeruの背景を白にするUserCSS/style.css";
@import "/api/code/takker/アイコン記法を画像記法っぽくするUserCSS/style2.css";`});var cy=e=>{{let r=e.match(/^([^(]+)\(([^)]+)\)$/);if(r)return{fileName:r[1],lang:r[2]}}let t=e.split(".").pop();return t===void 0?{fileName:e,lang:e}:{fileName:e,lang:t}};var ly=(e,t,r)=>{if(r.length===0)return[];let o=r.map(a=>a.text).join(`
`),n=He(o,{hasTitle:!0}),s=new Map,i=0;for(let a of n)switch(a.type){case"title":case"line":{i++;break}case"table":i+=a.cells.length+1;break;case"codeBlock":{let{fileName:c,lang:l}=cy(a.fileName),u=s.get(c);s.set(c,{path:u?.path??`https://scrapbox.io/api/code/${e}/${me(t)}/${me(c)}`,lang:u?.lang??l,startIds:[...u?.startIds??[],r[i].id]}),i+=a.content.split(`
`).length+1;break}}return s.values()};function yp(e){let t=o=>{if(o===null)r.write8(0);else if(typeof o=="boolean")r.write8(1),r.write8(+o);else if(typeof o=="number")r.write8(2),r.write32(o|0);else if(typeof o=="string")r.write8(3),r.write(Zt(o));else if(o instanceof Uint8Array)r.write8(4),r.write(o);else if(o instanceof Array){r.write8(5),r.write32(o.length);for(let n of o)t(n)}else{let n=Object.keys(o);r.write8(6),r.write32(n.length);for(let s of n)r.write(Zt(s)),t(o[s])}},r=new wa;return r.write32(0),r.write32(e.id<<1|+!e.isRequest),t(e.value),gp(r.buf,r.len-4,0),r.buf.subarray(0,r.len)}function py(e){let t=()=>{switch(r.read8()){case 0:return null;case 1:return!!r.read8();case 2:return r.read32();case 3:return xn(r.read());case 4:return r.read();case 5:{let i=r.read32(),a=[];for(let c=0;c<i;c++)a.push(t());return a}case 6:{let i=r.read32(),a={};for(let c=0;c<i;c++)a[xn(r.read())]=t();return a}default:throw new Error("Invalid packet")}},r=new wa(e),o=r.read32(),n=(o&1)===0;o>>>=1;let s=t();if(r.ptr!==e.length)throw new Error("Invalid packet");return{id:o,isRequest:n,value:s}}var wa=class{constructor(t=new Uint8Array(1024)){this.buf=t}len=0;ptr=0;_write(t){if(this.len+t>this.buf.length){let r=new Uint8Array((this.len+t)*2);r.set(this.buf),this.buf=r}return this.len+=t,this.len-t}write8(t){let r=this._write(1);this.buf[r]=t}write32(t){let r=this._write(4);gp(this.buf,t,r)}write(t){let r=this._write(4+t.length);gp(this.buf,t.length,r),this.buf.set(t,r+4)}_read(t){if(this.ptr+t>this.buf.length)throw new Error("Invalid packet");return this.ptr+=t,this.ptr-t}read8(){return this.buf[this._read(1)]}read32(){return xp(this.buf,this._read(4))}read(){let t=this.read32(),r=new Uint8Array(t),o=this._read(r.length);return r.set(this.buf.subarray(o,o+t)),r}},Zt,xn,uy;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let e=new TextEncoder,t=new TextDecoder;Zt=r=>e.encode(r),xn=r=>t.decode(r),uy='new TextEncoder().encode("")'}else throw new Error("No UTF-8 codec found");if(!(Zt("")instanceof Uint8Array))throw new Error(`Invariant violation: "${uy} instanceof Uint8Array" is incorrectly false
This indicates that your JavaScript environment is broken. You cannot use
esbuild in this environment because esbuild relies on this invariant. This
is not a problem with esbuild. You need to fix your environment instead.
`);function xp(e,t){return e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}function gp(e,t,r){e[r++]=t,e[r++]=t>>8,e[r++]=t>>16,e[r++]=t>>24}var ds="0.24.0";var Ge=JSON.stringify,my="warning",fy="silent";function dy(e){if(it(e,"target"),e.indexOf(",")>=0)throw new Error(`Invalid target: ${e}`);return e}var va=()=>null,Ie=e=>typeof e=="boolean"?null:"a boolean",V=e=>typeof e=="string"?null:"a string",Ta=e=>e instanceof RegExp?null:"a RegExp object",$o=e=>typeof e=="number"&&e===(e|0)?null:"an integer",yy=e=>typeof e=="function"?null:"a function",De=e=>Array.isArray(e)?null:"an array",Wt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"an object",m0=e=>typeof e=="object"&&e!==null?null:"an array or an object";var hy=e=>typeof e=="object"&&!Array.isArray(e)?null:"an object or null",xy=e=>typeof e=="string"||typeof e=="boolean"?null:"a string or a boolean",f0=e=>typeof e=="string"||typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"a string or an object",d0=e=>typeof e=="string"||Array.isArray(e)?null:"a string or an array",by=e=>typeof e=="string"||e instanceof Uint8Array?null:"a string or a Uint8Array";function w(e,t,r,o){let n=e[r];if(t[r+""]=!0,n===void 0)return;let s=o(n);if(s!==null)throw new Error(`${Ge(r)} must be ${s}`);return n}function et(e,t,r){for(let o in e)if(!(o in t))throw new Error(`Invalid option ${r}: ${Ge(o)}`)}function Ey(e){let t;if(e!==void 0){t=Object.create(null);for(let r in e){let o=e[r];if(typeof o=="string"||o===!1)t[r]=o;else throw new Error(`Expected ${Ge(r)} in mangle cache to map to either a string or false`)}}return t}function _a(e,t,r,o,n){let s=w(t,r,"color",Ie),i=w(t,r,"logLevel",V),a=w(t,r,"logLimit",$o);s!==void 0?e.push(`--color=${s}`):o&&e.push("--color=true"),e.push(`--log-level=${i||n}`),e.push(`--log-limit=${a||0}`)}function it(e,t,r){if(typeof e!="string")throw new Error(`Expected value for ${t}${r!==void 0?" "+Ge(r):""} to be a string, got ${typeof e} instead`);return e}function wy(e,t,r){let o=w(t,r,"legalComments",V),n=w(t,r,"sourceRoot",V),s=w(t,r,"sourcesContent",Ie),i=w(t,r,"target",d0),a=w(t,r,"format",V),c=w(t,r,"globalName",V),l=w(t,r,"mangleProps",Ta),u=w(t,r,"reserveProps",Ta),p=w(t,r,"mangleQuoted",Ie),f=w(t,r,"minify",Ie),m=w(t,r,"minifySyntax",Ie),h=w(t,r,"minifyWhitespace",Ie),g=w(t,r,"minifyIdentifiers",Ie),y=w(t,r,"lineLimit",$o),x=w(t,r,"drop",De),E=w(t,r,"dropLabels",De),R=w(t,r,"charset",V),b=w(t,r,"treeShaking",Ie),v=w(t,r,"ignoreAnnotations",Ie),k=w(t,r,"jsx",V),O=w(t,r,"jsxFactory",V),L=w(t,r,"jsxFragment",V),N=w(t,r,"jsxImportSource",V),P=w(t,r,"jsxDev",Ie),T=w(t,r,"jsxSideEffects",Ie),_=w(t,r,"define",Wt),S=w(t,r,"logOverride",Wt),A=w(t,r,"supported",Wt),M=w(t,r,"pure",De),D=w(t,r,"keepNames",Ie),I=w(t,r,"platform",V),z=w(t,r,"tsconfigRaw",f0);if(o&&e.push(`--legal-comments=${o}`),n!==void 0&&e.push(`--source-root=${n}`),s!==void 0&&e.push(`--sources-content=${s}`),i&&(Array.isArray(i)?e.push(`--target=${Array.from(i).map(dy).join(",")}`):e.push(`--target=${dy(i)}`)),a&&e.push(`--format=${a}`),c&&e.push(`--global-name=${c}`),I&&e.push(`--platform=${I}`),z&&e.push(`--tsconfig-raw=${typeof z=="string"?z:JSON.stringify(z)}`),f&&e.push("--minify"),m&&e.push("--minify-syntax"),h&&e.push("--minify-whitespace"),g&&e.push("--minify-identifiers"),y&&e.push(`--line-limit=${y}`),R&&e.push(`--charset=${R}`),b!==void 0&&e.push(`--tree-shaking=${b}`),v&&e.push("--ignore-annotations"),x)for(let $ of x)e.push(`--drop:${it($,"drop")}`);if(E&&e.push(`--drop-labels=${Array.from(E).map($=>it($,"dropLabels")).join(",")}`),l&&e.push(`--mangle-props=${l.source}`),u&&e.push(`--reserve-props=${u.source}`),p!==void 0&&e.push(`--mangle-quoted=${p}`),k&&e.push(`--jsx=${k}`),O&&e.push(`--jsx-factory=${O}`),L&&e.push(`--jsx-fragment=${L}`),N&&e.push(`--jsx-import-source=${N}`),P&&e.push("--jsx-dev"),T&&e.push("--jsx-side-effects"),_)for(let $ in _){if($.indexOf("=")>=0)throw new Error(`Invalid define: ${$}`);e.push(`--define:${$}=${it(_[$],"define",$)}`)}if(S)for(let $ in S){if($.indexOf("=")>=0)throw new Error(`Invalid log override: ${$}`);e.push(`--log-override:${$}=${it(S[$],"log override",$)}`)}if(A)for(let $ in A){if($.indexOf("=")>=0)throw new Error(`Invalid supported: ${$}`);let q=A[$];if(typeof q!="boolean")throw new Error(`Expected value for supported ${Ge($)} to be a boolean, got ${typeof q} instead`);e.push(`--supported:${$}=${q}`)}if(M)for(let $ of M)e.push(`--pure:${it($,"pure")}`);D&&e.push("--keep-names")}function h0(e,t,r,o,n){let s=[],i=[],a=Object.create(null),c=null,l=null;_a(s,t,a,r,o),wy(s,t,a);let u=w(t,a,"sourcemap",xy),p=w(t,a,"bundle",Ie),f=w(t,a,"splitting",Ie),m=w(t,a,"preserveSymlinks",Ie),h=w(t,a,"metafile",Ie),g=w(t,a,"outfile",V),y=w(t,a,"outdir",V),x=w(t,a,"outbase",V),E=w(t,a,"tsconfig",V),R=w(t,a,"resolveExtensions",De),b=w(t,a,"nodePaths",De),v=w(t,a,"mainFields",De),k=w(t,a,"conditions",De),O=w(t,a,"external",De),L=w(t,a,"packages",V),N=w(t,a,"alias",Wt),P=w(t,a,"loader",Wt),T=w(t,a,"outExtension",Wt),_=w(t,a,"publicPath",V),S=w(t,a,"entryNames",V),A=w(t,a,"chunkNames",V),M=w(t,a,"assetNames",V),D=w(t,a,"inject",De),I=w(t,a,"banner",Wt),z=w(t,a,"footer",Wt),$=w(t,a,"entryPoints",m0),q=w(t,a,"absWorkingDir",V),K=w(t,a,"stdin",Wt),ce=w(t,a,"write",Ie)??n,ee=w(t,a,"allowOverwrite",Ie),rt=w(t,a,"mangleCache",Wt);if(a.plugins=!0,et(t,a,`in ${e}() call`),u&&s.push(`--sourcemap${u===!0?"":`=${u}`}`),p&&s.push("--bundle"),ee&&s.push("--allow-overwrite"),f&&s.push("--splitting"),m&&s.push("--preserve-symlinks"),h&&s.push("--metafile"),g&&s.push(`--outfile=${g}`),y&&s.push(`--outdir=${y}`),x&&s.push(`--outbase=${x}`),E&&s.push(`--tsconfig=${E}`),L&&s.push(`--packages=${L}`),R){let U=[];for(let ke of R){if(it(ke,"resolve extension"),ke.indexOf(",")>=0)throw new Error(`Invalid resolve extension: ${ke}`);U.push(ke)}s.push(`--resolve-extensions=${U.join(",")}`)}if(_&&s.push(`--public-path=${_}`),S&&s.push(`--entry-names=${S}`),A&&s.push(`--chunk-names=${A}`),M&&s.push(`--asset-names=${M}`),v){let U=[];for(let ke of v){if(it(ke,"main field"),ke.indexOf(",")>=0)throw new Error(`Invalid main field: ${ke}`);U.push(ke)}s.push(`--main-fields=${U.join(",")}`)}if(k){let U=[];for(let ke of k){if(it(ke,"condition"),ke.indexOf(",")>=0)throw new Error(`Invalid condition: ${ke}`);U.push(ke)}s.push(`--conditions=${U.join(",")}`)}if(O)for(let U of O)s.push(`--external:${it(U,"external")}`);if(N)for(let U in N){if(U.indexOf("=")>=0)throw new Error(`Invalid package name in alias: ${U}`);s.push(`--alias:${U}=${it(N[U],"alias",U)}`)}if(I)for(let U in I){if(U.indexOf("=")>=0)throw new Error(`Invalid banner file type: ${U}`);s.push(`--banner:${U}=${it(I[U],"banner",U)}`)}if(z)for(let U in z){if(U.indexOf("=")>=0)throw new Error(`Invalid footer file type: ${U}`);s.push(`--footer:${U}=${it(z[U],"footer",U)}`)}if(D)for(let U of D)s.push(`--inject:${it(U,"inject")}`);if(P)for(let U in P){if(U.indexOf("=")>=0)throw new Error(`Invalid loader extension: ${U}`);s.push(`--loader:${U}=${it(P[U],"loader",U)}`)}if(T)for(let U in T){if(U.indexOf("=")>=0)throw new Error(`Invalid out extension: ${U}`);s.push(`--out-extension:${U}=${it(T[U],"out extension",U)}`)}if($)if(Array.isArray($))for(let U=0,ke=$.length;U<ke;U++){let lt=$[U];if(typeof lt=="object"&<!==null){let fr=Object.create(null),dr=w(lt,fr,"in",V),or=w(lt,fr,"out",V);if(et(lt,fr,"in entry point at index "+U),dr===void 0)throw new Error('Missing property "in" for entry point at index '+U);if(or===void 0)throw new Error('Missing property "out" for entry point at index '+U);i.push([or,dr])}else i.push(["",it(lt,"entry point at index "+U)])}else for(let U in $)i.push([U,it($[U],"entry point",U)]);if(K){let U=Object.create(null),ke=w(K,U,"contents",by),lt=w(K,U,"resolveDir",V),fr=w(K,U,"sourcefile",V),dr=w(K,U,"loader",V);et(K,U,'in "stdin" object'),fr&&s.push(`--sourcefile=${fr}`),dr&&s.push(`--loader=${dr}`),lt&&(l=lt),typeof ke=="string"?c=Zt(ke):ke instanceof Uint8Array&&(c=ke)}let Oe=[];if(b)for(let U of b)U+="",Oe.push(U);return{entries:i,flags:s,write:ce,stdinContents:c,stdinResolveDir:l,absWorkingDir:q,nodePaths:Oe,mangleCache:Ey(rt)}}function g0(e,t,r,o){let n=[],s=Object.create(null);_a(n,t,s,r,o),wy(n,t,s);let i=w(t,s,"sourcemap",xy),a=w(t,s,"sourcefile",V),c=w(t,s,"loader",V),l=w(t,s,"banner",V),u=w(t,s,"footer",V),p=w(t,s,"mangleCache",Wt);return et(t,s,`in ${e}() call`),i&&n.push(`--sourcemap=${i===!0?"external":i}`),a&&n.push(`--sourcefile=${a}`),c&&n.push(`--loader=${c}`),l&&n.push(`--banner=${l}`),u&&n.push(`--footer=${u}`),{flags:n,mangleCache:Ey(p)}}function ky(e){let t={},r={didClose:!1,reason:""},o={},n=0,s=0,i=new Uint8Array(16*1024),a=0,c=R=>{let b=a+R.length;if(b>i.length){let k=new Uint8Array(b*2);k.set(i),i=k}i.set(R,a),a+=R.length;let v=0;for(;v+4<=a;){let k=xp(i,v);if(v+4+k>a)break;v+=4,h(i.subarray(v,v+k)),v+=k}v>0&&(i.copyWithin(0,v,a),a-=v)},l=R=>{r.didClose=!0,R&&(r.reason=": "+(R.message||R));let b="The service was stopped"+r.reason;for(let v in o)o[v](b,null);o={}},u=(R,b,v)=>{if(r.didClose)return v("The service is no longer running"+r.reason,null);let k=n++;o[k]=(O,L)=>{try{v(O,L)}finally{R&&R.unref()}},R&&R.ref(),e.writeToStdin(yp({id:k,isRequest:!0,value:b}))},p=(R,b)=>{if(r.didClose)throw new Error("The service is no longer running"+r.reason);e.writeToStdin(yp({id:R,isRequest:!1,value:b}))},f=async(R,b)=>{try{if(b.command==="ping"){p(R,{});return}if(typeof b.key=="number"){let v=t[b.key];if(!v)return;let k=v[b.command];if(k){await k(R,b);return}}throw new Error("Invalid command: "+b.command)}catch(v){let k=[Do(v,e,null,void 0,"")];try{p(R,{errors:k})}catch{}}},m=!0,h=R=>{if(m){m=!1;let v=String.fromCharCode(...R);if(v!==ds)throw new Error(`Cannot start service: Host version "${ds}" does not match binary version ${Ge(v)}`);return}let b=py(R);if(b.isRequest)f(b.id,b.value);else{let v=o[b.id];delete o[b.id],b.value.error?v(b.value.error,{}):v(null,b.value)}};return{readFromStdout:c,afterClose:l,service:{buildOrContext:({callName:R,refs:b,options:v,isTTY:k,defaultWD:O,callback:L})=>{let N=0,P=s++,T={},_={ref(){++N===1&&b&&b.ref()},unref(){--N===0&&(delete t[P],b&&b.unref())}};t[P]=T,_.ref(),y0(R,P,u,p,_,e,T,v,k,O,(S,A)=>{try{L(S,A)}finally{_.unref()}})},transform:({callName:R,refs:b,input:v,options:k,isTTY:O,fs:L,callback:N})=>{let P=Ry(),T=_=>{try{if(typeof v!="string"&&!(v instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:S,mangleCache:A}=g0(R,k,O,fy),M={command:"transform",flags:S,inputFS:_!==null,input:_!==null?Zt(_):typeof v=="string"?Zt(v):v};A&&(M.mangleCache=A),u(b,M,(D,I)=>{if(D)return N(new Error(D),null);let z=bn(I.errors,P),$=bn(I.warnings,P),q=1,K=()=>{if(--q===0){let ce={warnings:$,code:I.code,map:I.map,mangleCache:void 0,legalComments:void 0};"legalComments"in I&&(ce.legalComments=I?.legalComments),I.mangleCache&&(ce.mangleCache=I?.mangleCache),N(null,ce)}};if(z.length>0)return N(hs("Transform failed",z,$),null);I.codeFS&&(q++,L.readFile(I.code,(ce,ee)=>{ce!==null?N(ce,null):(I.code=ee,K())})),I.mapFS&&(q++,L.readFile(I.map,(ce,ee)=>{ce!==null?N(ce,null):(I.map=ee,K())})),K()})}catch(S){let A=[];try{_a(A,k,{},O,fy)}catch{}let M=Do(S,e,P,void 0,"");u(b,{command:"error",flags:A,error:M},()=>{M.detail=P.load(M.detail),N(hs("Transform failed",[M],[]),null)})}};if((typeof v=="string"||v instanceof Uint8Array)&&v.length>1024*1024){let _=T;T=()=>L.writeFile(v,_)}T(null)},formatMessages:({callName:R,refs:b,messages:v,options:k,callback:O})=>{if(!k)throw new Error(`Missing second argument in ${R}() call`);let L={},N=w(k,L,"kind",V),P=w(k,L,"color",Ie),T=w(k,L,"terminalWidth",$o);if(et(k,L,`in ${R}() call`),N===void 0)throw new Error(`Missing "kind" in ${R}() call`);if(N!=="error"&&N!=="warning")throw new Error(`Expected "kind" to be "error" or "warning" in ${R}() call`);let _={command:"format-msgs",messages:Sr(v,"messages",null,"",T),isWarning:N==="warning"};P!==void 0&&(_.color=P),T!==void 0&&(_.terminalWidth=T),u(b,_,(S,A)=>{if(S)return O(new Error(S),null);O(null,A.messages)})},analyzeMetafile:({callName:R,refs:b,metafile:v,options:k,callback:O})=>{k===void 0&&(k={});let L={},N=w(k,L,"color",Ie),P=w(k,L,"verbose",Ie);et(k,L,`in ${R}() call`);let T={command:"analyze-metafile",metafile:v};N!==void 0&&(T.color=N),P!==void 0&&(T.verbose=P),u(b,T,(_,S)=>{if(_)return O(new Error(_),null);O(null,S.result)})}}}}function y0(e,t,r,o,n,s,i,a,c,l,u){let p=Ry(),f=e==="context",m=(y,x)=>{let E=[];try{_a(E,a,{},c,my)}catch{}let R=Do(y,s,p,void 0,x);r(n,{command:"error",flags:E,error:R},()=>{R.detail=p.load(R.detail),u(hs(f?"Context failed":"Build failed",[R],[]),null)})},h;if(typeof a=="object"){let y=a.plugins;if(y!==void 0){if(!Array.isArray(y))return m(new Error('"plugins" must be an array'),"");h=y}}if(h&&h.length>0){if(s.isSync)return m(new Error("Cannot use plugins in synchronous API calls"),"");x0(t,r,o,n,s,i,a,h,p).then(y=>{if(!y.ok)return m(y.error,y.pluginName);try{g(y.requestPlugins,y.runOnEndCallbacks,y.scheduleOnDisposeCallbacks)}catch(x){m(x,"")}},y=>m(y,""));return}try{g(null,(y,x)=>x([],[]),()=>{})}catch(y){m(y,"")}function g(y,x,E){let R=s.hasFS,{entries:b,flags:v,write:k,stdinContents:O,stdinResolveDir:L,absWorkingDir:N,nodePaths:P,mangleCache:T}=h0(e,a,c,my,R);if(k&&!s.hasFS)throw new Error('The "write" option is unavailable in this environment');let _={command:"build",key:t,entries:b,flags:v,write:k,stdinContents:O,stdinResolveDir:L,absWorkingDir:N||l,nodePaths:P,context:f};y&&(_.plugins=y),T&&(_.mangleCache=T);let S=(D,I)=>{let z={errors:bn(D.errors,p),warnings:bn(D.warnings,p),outputFiles:void 0,metafile:void 0,mangleCache:void 0},$=z.errors.slice(),q=z.warnings.slice();D.outputFiles&&(z.outputFiles=D.outputFiles.map(E0)),D.metafile&&(z.metafile=JSON.parse(D.metafile)),D.mangleCache&&(z.mangleCache=D.mangleCache),D.writeToStdout!==void 0&&console.log(xn(D.writeToStdout).replace(/\n$/,"")),x(z,(K,ce)=>{if($.length>0||K.length>0){let ee=hs("Build failed",$.concat(K),q.concat(ce));return I(ee,null,K,ce)}I(null,z,K,ce)})},A,M;f&&(i["on-end"]=(D,I)=>new Promise(z=>{S(I,($,q,K,ce)=>{let ee={errors:K,warnings:ce};M&&M($,q),A=void 0,M=void 0,o(D,ee),z()})})),r(n,_,(D,I)=>{if(D)return u(new Error(D),null);if(!f)return S(I,(q,K)=>(E(),u(q,K)));if(I.errors.length>0)return u(hs("Context failed",I.errors,I.warnings),null);let z=!1,$={rebuild:()=>(A||(A=new Promise((q,K)=>{let ce;M=(rt,Oe)=>{ce||(ce=()=>rt?K(rt):q(Oe))};let ee=()=>{r(n,{command:"rebuild",key:t},(Oe,U)=>{Oe?K(new Error(Oe)):ce?ce():ee()})};ee()})),A),watch:(q={})=>new Promise((K,ce)=>{if(!s.hasFS)throw new Error('Cannot use the "watch" API in this environment');et(q,{},"in watch() call"),r(n,{command:"watch",key:t},Oe=>{Oe?ce(new Error(Oe)):K(void 0)})}),serve:(q={})=>new Promise((K,ce)=>{if(!s.hasFS)throw new Error('Cannot use the "serve" API in this environment');let ee={},rt=w(q,ee,"port",$o),Oe=w(q,ee,"host",V),U=w(q,ee,"servedir",V),ke=w(q,ee,"keyfile",V),lt=w(q,ee,"certfile",V),fr=w(q,ee,"fallback",V),dr=w(q,ee,"onRequest",yy);et(q,ee,"in serve() call");let or={command:"serve",key:t,onRequest:!!dr};rt!==void 0&&(or.port=rt),Oe!==void 0&&(or.host=Oe),U!==void 0&&(or.servedir=U),ke!==void 0&&(or.keyfile=ke),lt!==void 0&&(or.certfile=lt),fr!==void 0&&(or.fallback=fr),r(n,or,(Qu,Dk)=>{if(Qu)return ce(new Error(Qu));dr&&(i["serve-request"]=($k,jk)=>{dr(jk.args),o($k,{})}),K(Dk)})}),cancel:()=>new Promise(q=>{if(z)return q();r(n,{command:"cancel",key:t},()=>{q()})}),dispose:()=>new Promise(q=>{if(z)return q();z=!0,r(n,{command:"dispose",key:t},()=>{q(),E(),n.unref()})})};n.ref(),u(null,$)})}}var x0=async(e,t,r,o,n,s,i,a,c)=>{let l=[],u=[],p={},f={},m=[],h=0,g=0,y=[],x=!1;a=[...a];for(let b of a){let v={};if(typeof b!="object")throw new Error(`Plugin at index ${g} must be an object`);let k=w(b,v,"name",V);if(typeof k!="string"||k==="")throw new Error(`Plugin at index ${g} is missing a name`);try{let O=w(b,v,"setup",yy);if(typeof O!="function")throw new Error("Plugin is missing a setup function");et(b,v,`on plugin ${Ge(k)}`);let L={name:k,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};g++;let P=O({initialOptions:i,resolve:(T,_={})=>{if(!x)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof T!="string")throw new Error("The path to resolve must be a string");let S=Object.create(null),A=w(_,S,"pluginName",V),M=w(_,S,"importer",V),D=w(_,S,"namespace",V),I=w(_,S,"resolveDir",V),z=w(_,S,"kind",V),$=w(_,S,"pluginData",va),q=w(_,S,"with",Wt);return et(_,S,"in resolve() call"),new Promise((K,ce)=>{let ee={command:"resolve",path:T,key:e,pluginName:k};if(A!=null&&(ee.pluginName=A),M!=null&&(ee.importer=M),D!=null&&(ee.namespace=D),I!=null&&(ee.resolveDir=I),z!=null)ee.kind=z;else throw new Error('Must specify "kind" when calling "resolve"');$!=null&&(ee.pluginData=c.store($)),q!=null&&(ee.with=b0(q,"with")),t(o,ee,(rt,Oe)=>{rt!==null?ce(new Error(rt)):K({errors:bn(Oe.errors,c),warnings:bn(Oe.warnings,c),path:Oe.path,external:Oe.external,sideEffects:Oe.sideEffects,namespace:Oe.namespace,suffix:Oe.suffix,pluginData:c.load(Oe.pluginData)})})})},onStart(T){let _='This error came from the "onStart" callback registered here:',S=ka(new Error(_),n,"onStart");l.push({name:k,callback:T,note:S}),L.onStart=!0},onEnd(T){let _='This error came from the "onEnd" callback registered here:',S=ka(new Error(_),n,"onEnd");u.push({name:k,callback:T,note:S}),L.onEnd=!0},onResolve(T,_){let S='This error came from the "onResolve" callback registered here:',A=ka(new Error(S),n,"onResolve"),M={},D=w(T,M,"filter",Ta),I=w(T,M,"namespace",V);if(et(T,M,`in onResolve() call for plugin ${Ge(k)}`),D==null)throw new Error("onResolve() call is missing a filter");let z=h++;p[z]={name:k,callback:_,note:A},L.onResolve.push({id:z,filter:D.source,namespace:I||""})},onLoad(T,_){let S='This error came from the "onLoad" callback registered here:',A=ka(new Error(S),n,"onLoad"),M={},D=w(T,M,"filter",Ta),I=w(T,M,"namespace",V);if(et(T,M,`in onLoad() call for plugin ${Ge(k)}`),D==null)throw new Error("onLoad() call is missing a filter");let z=h++;f[z]={name:k,callback:_,note:A},L.onLoad.push({id:z,filter:D.source,namespace:I||""})},onDispose(T){m.push(T)},esbuild:n.esbuild});P&&await P,y.push(L)}catch(O){return{ok:!1,error:O,pluginName:k}}}s["on-start"]=async(b,v)=>{c.clear();let k={errors:[],warnings:[]};await Promise.all(l.map(async({name:O,callback:L,note:N})=>{try{let P=await L();if(P!=null){if(typeof P!="object")throw new Error(`Expected onStart() callback in plugin ${Ge(O)} to return an object`);let T={},_=w(P,T,"errors",De),S=w(P,T,"warnings",De);et(P,T,`from onStart() callback in plugin ${Ge(O)}`),_!=null&&k.errors.push(...Sr(_,"errors",c,O,void 0)),S!=null&&k.warnings.push(...Sr(S,"warnings",c,O,void 0))}}catch(P){k.errors.push(Do(P,n,c,N&&N(),O))}})),r(b,k)},s["on-resolve"]=async(b,v)=>{let k={},O="",L,N;for(let P of v.ids)try{({name:O,callback:L,note:N}=p[P]);let T=await L({path:v.path,importer:v.importer,namespace:v.namespace,resolveDir:v.resolveDir,kind:v.kind,pluginData:c.load(v.pluginData),with:v.with});if(T!=null){if(typeof T!="object")throw new Error(`Expected onResolve() callback in plugin ${Ge(O)} to return an object`);let _={},S=w(T,_,"pluginName",V),A=w(T,_,"path",V),M=w(T,_,"namespace",V),D=w(T,_,"suffix",V),I=w(T,_,"external",Ie),z=w(T,_,"sideEffects",Ie),$=w(T,_,"pluginData",va),q=w(T,_,"errors",De),K=w(T,_,"warnings",De),ce=w(T,_,"watchFiles",De),ee=w(T,_,"watchDirs",De);et(T,_,`from onResolve() callback in plugin ${Ge(O)}`),k.id=P,S!=null&&(k.pluginName=S),A!=null&&(k.path=A),M!=null&&(k.namespace=M),D!=null&&(k.suffix=D),I!=null&&(k.external=I),z!=null&&(k.sideEffects=z),$!=null&&(k.pluginData=c.store($)),q!=null&&(k.errors=Sr(q,"errors",c,O,void 0)),K!=null&&(k.warnings=Sr(K,"warnings",c,O,void 0)),ce!=null&&(k.watchFiles=Ra(ce,"watchFiles")),ee!=null&&(k.watchDirs=Ra(ee,"watchDirs"));break}}catch(T){k={id:P,errors:[Do(T,n,c,N&&N(),O)]};break}r(b,k)},s["on-load"]=async(b,v)=>{let k={},O="",L,N;for(let P of v.ids)try{({name:O,callback:L,note:N}=f[P]);let T=await L({path:v.path,namespace:v.namespace,suffix:v.suffix,pluginData:c.load(v.pluginData),with:v.with});if(T!=null){if(typeof T!="object")throw new Error(`Expected onLoad() callback in plugin ${Ge(O)} to return an object`);let _={},S=w(T,_,"pluginName",V),A=w(T,_,"contents",by),M=w(T,_,"resolveDir",V),D=w(T,_,"pluginData",va),I=w(T,_,"loader",V),z=w(T,_,"errors",De),$=w(T,_,"warnings",De),q=w(T,_,"watchFiles",De),K=w(T,_,"watchDirs",De);et(T,_,`from onLoad() callback in plugin ${Ge(O)}`),k.id=P,S!=null&&(k.pluginName=S),A instanceof Uint8Array?k.contents=A:A!=null&&(k.contents=Zt(A)),M!=null&&(k.resolveDir=M),D!=null&&(k.pluginData=c.store(D)),I!=null&&(k.loader=I),z!=null&&(k.errors=Sr(z,"errors",c,O,void 0)),$!=null&&(k.warnings=Sr($,"warnings",c,O,void 0)),q!=null&&(k.watchFiles=Ra(q,"watchFiles")),K!=null&&(k.watchDirs=Ra(K,"watchDirs"));break}}catch(T){k={id:P,errors:[Do(T,n,c,N&&N(),O)]};break}r(b,k)};let E=(b,v)=>v([],[]);u.length>0&&(E=(b,v)=>{(async()=>{let k=[],O=[];for(let{name:L,callback:N,note:P}of u){let T,_;try{let S=await N(b);if(S!=null){if(typeof S!="object")throw new Error(`Expected onEnd() callback in plugin ${Ge(L)} to return an object`);let A={},M=w(S,A,"errors",De),D=w(S,A,"warnings",De);et(S,A,`from onEnd() callback in plugin ${Ge(L)}`),M!=null&&(T=Sr(M,"errors",c,L,void 0)),D!=null&&(_=Sr(D,"warnings",c,L,void 0))}}catch(S){T=[Do(S,n,c,P&&P(),L)]}if(T){k.push(...T);try{b.errors.push(...T)}catch{}}if(_){O.push(..._);try{b.warnings.push(..._)}catch{}}}v(k,O)})()});let R=()=>{for(let b of m)setTimeout(()=>b(),0)};return x=!0,{ok:!0,requestPlugins:y,runOnEndCallbacks:E,scheduleOnDisposeCallbacks:R}};function Ry(){let e=new Map,t=0;return{clear(){e.clear()},load(r){return e.get(r)},store(r){if(r===void 0)return-1;let o=t++;return e.set(o,r),o}}}function ka(e,t,r){let o,n=!1;return()=>{if(n)return o;n=!0;try{let s=(e.stack+"").split(`
`);s.splice(1,1);let i=vy(t,s,r);if(i)return o={text:e.message,location:i},o}catch{}}}function Do(e,t,r,o,n){let s="Internal error",i=null;try{s=(e&&e.message||e)+""}catch{}try{i=vy(t,(e.stack+"").split(`
`),"")}catch{}return{id:"",pluginName:n,text:s,location:i,notes:o?[o]:[],detail:r?r.store(e):-1}}function vy(e,t,r){let o=" at ";if(e.readFileSync&&!t[0].startsWith(o)&&t[1].startsWith(o))for(let n=1;n<t.length;n++){let s=t[n];if(s.startsWith(o))for(s=s.slice(o.length);;){let i=/^(?:new |async )?\S+ \((.*)\)$/.exec(s);if(i){s=i[1];continue}if(i=/^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(s),i){s=i[1];continue}if(i=/^(\S+):(\d+):(\d+)$/.exec(s),i){let a;try{a=e.readFileSync(i[1],"utf8")}catch{break}let c=a.split(/\r\n|\r|\n|\u2028|\u2029/)[+i[2]-1]||"",l=+i[3]-1,u=c.slice(l,l+r.length)===r?r.length:0;return{file:i[1],namespace:"file",line:+i[2],column:Zt(c.slice(0,l)).length,length:Zt(c.slice(l,l+u)).length,lineText:c+`
`+t.slice(1).join(`
`),suggestion:""}}break}}return null}function hs(e,t,r){let o=5;e+=t.length<1?"":` with ${t.length} error${t.length<2?"":"s"}:`+t.slice(0,o+1).map((s,i)=>{if(i===o)return`
...`;if(!s.location)return`
error: ${s.text}`;let{file:a,line:c,column:l}=s.location,u=s.pluginName?`[plugin: ${s.pluginName}] `:"";return`
${a}:${c}:${l}: ERROR: ${u}${s.text}`}).join("");let n=new Error(e);for(let[s,i]of[["errors",t],["warnings",r]])Object.defineProperty(n,s,{configurable:!0,enumerable:!0,get:()=>i,set:a=>Object.defineProperty(n,s,{configurable:!0,enumerable:!0,value:a})});return n}function bn(e,t){for(let r of e)r.detail=t.load(r.detail);return e}function gy(e,t,r){if(e==null)return null;let o={},n=w(e,o,"file",V),s=w(e,o,"namespace",V),i=w(e,o,"line",$o),a=w(e,o,"column",$o),c=w(e,o,"length",$o),l=w(e,o,"lineText",V),u=w(e,o,"suggestion",V);if(et(e,o,t),l){let p=l.slice(0,(a&&a>0?a:0)+(c&&c>0?c:0)+(r&&r>0?r:80));!/[\x7F-\uFFFF]/.test(p)&&!/\n/.test(l)&&(l=p)}return{file:n||"",namespace:s||"",line:i||0,column:a||0,length:c||0,lineText:l||"",suggestion:u||""}}function Sr(e,t,r,o,n){let s=[],i=0;for(let a of e){let c={},l=w(a,c,"id",V),u=w(a,c,"pluginName",V),p=w(a,c,"text",V),f=w(a,c,"location",hy),m=w(a,c,"notes",De),h=w(a,c,"detail",va),g=`in element ${i} of "${t}"`;et(a,c,g);let y=[];if(m)for(let x of m){let E={},R=w(x,E,"text",V),b=w(x,E,"location",hy);et(x,E,g),y.push({text:R||"",location:gy(b,g,n)})}s.push({id:l||"",pluginName:u||o,text:p||"",location:gy(f,g,n),notes:y,detail:r?r.store(h):-1}),i++}return s}function Ra(e,t){let r=[];for(let o of e){if(typeof o!="string")throw new Error(`${Ge(t)} must be an array of strings`);r.push(o)}return r}function b0(e,t){let r=Object.create(null);for(let o in e){let n=e[o];if(typeof n!="string")throw new Error(`key ${Ge(o)} in object ${Ge(t)} must be a string`);r[o]=n}return r}function E0({path:e,contents:t,hash:r}){let o=null;return{path:e,contents:t,hash:r,get text(){let n=this.contents;return(o===null||n!==t)&&(t=n,o=xn(n)),o}}}var _y=ds,Sa=e=>Oa().build(e),Py=(e,t)=>Oa().transform(e,t),Sy=(e,t)=>Oa().formatMessages(e,t),Oy=(e,t)=>Oa().analyzeMetafile(e,t);var jo,Ty,Pa,Oa=()=>{if(Pa)return Pa;throw jo?new Error('You need to wait for the promise returned from "initialize" to be resolved before calling this'):new Error('You need to call "initialize" before calling this')},La=e=>{let t=e.wasm,r=e.worker;if(jo)throw new Error('Cannot call "initialize" more than once');return jo=w0(t,r),jo.catch(()=>{jo=void 0}),jo},w0=async(e,t)=>{let r=new Worker(t.toString(),{type:"module"}),o,n,s=new Promise((c,l)=>{o=c,n=l});r.onmessage=({data:c})=>{r.onmessage=({data:l})=>i(l),c?n(c):o()},r.postMessage(e);let{readFromStdout:i,service:a}=ky({writeToStdin(c){r.postMessage(c)},isSync:!1,hasFS:!1,esbuild:{build:Sa,transform:Py,formatMessages:Sy,analyzeMetafile:Oy,version:_y,initialize:La}});await s,Ty=()=>{r.terminate(),jo=void 0,Ty=void 0,Pa=void 0},Pa={build:c=>new Promise((l,u)=>a.buildOrContext({callName:"build",refs:null,options:c,isTTY:!1,defaultWD:"/",callback:(p,f)=>p?u(p):l(f)})),transform:(c,l)=>new Promise((u,p)=>a.transform({callName:"transform",refs:null,input:c,options:l||{},isTTY:!1,fs:{readFile(f,m){m(new Error("Internal error"),null)},writeFile(f,m){m(null)}},callback:(f,m)=>f?p(f):u(m)})),formatMessages:(c,l)=>new Promise((u,p)=>a.formatMessages({callName:"formatMessages",refs:null,messages:c,options:l,callback:(f,m)=>f?p(f):u(m)})),analyzeMetafile:(c,l)=>new Promise((u,p)=>a.analyzeMetafile({callName:"analyzeMetafile",refs:null,metafile:typeof c=="string"?c:JSON.stringify(c),options:l,callback:(f,m)=>f?p(f):u(m)}))}};self.Deno||(self.Deno={build:{os:"linux"},errors:{AlreadyExists:Error},env:{get:()=>{}},permissions:{query:()=>Promise.resolve("denied")},cwd:()=>location.href});function gt(e){if(typeof e!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(e)}`)}function pr(e){return e===47||e===92}function Or(e){return e>=97&&e<=122||e>=65&&e<=90}function Aa(e){if(e=e instanceof URL?e:new URL(e),e.protocol!=="file:")throw new TypeError("Must be a file URL.");return e}function Ly(e){e=Aa(e);let t=decodeURIComponent(e.pathname.replace(/\//g,"\\").replace(/%(?![0-9A-Fa-f]{2})/g,"%25")).replace(/^\\*([A-Za-z]:)(\\|$)/,"$1\\");return e.hostname!==""&&(t=`\\\\${e.hostname}${t}`),t}function Ep(e){gt(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return pr(r)?!0:!!(Or(r)&&t>2&&e.charCodeAt(1)===58&&pr(e.charCodeAt(2)))}var Ma=class extends Error{constructor(t){super(t),this.name="AssertionError"}};function Ia(e,t=""){if(!e)throw new Ma(t)}var M0={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function Fa(e){return e.replaceAll(/[\s]/g,t=>M0[t]??t)}function Ay(e){if(!Ep(e))throw new TypeError("Must be an absolute path.");let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),o=new URL("file:///");if(o.pathname=Fa(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(o.hostname=t,!o.hostname))throw new TypeError("Invalid hostname.");return o}function Lr(e){return e===47}function Iy(e){return e=Aa(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function kp(e){return gt(e),e.length>0&&Lr(e.charCodeAt(0))}function Uy(e){if(!kp(e))throw new TypeError("Must be an absolute path.");let t=new URL("file:///");return t.pathname=Fa(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}var z0=(()=>{let{Deno:e}=globalThis;if(typeof e?.build?.os=="string")return e.build.os;let{navigator:t}=globalThis;return t?.appVersion?.includes?.("Win")?"windows":"linux"})(),Be=z0==="windows";var En=Be?"\\":"/";function Ua(e){return Be?Ly(e):Iy(e)}function ys(e){return Be?Ay(e):Uy(e)}function Da(e){return typeof e=="object"&&e!==null&&e.constructor===Object}function $a(e){let t={},r=Object.keys(e).sort((o,n)=>n.length-o.length);for(let o of r)t[o]=e[o];return t}function Dy(e){return Da(e)&&(e.imports!==void 0?Rp(e.imports):!0)&&(e.scopes!==void 0?vp(e.scopes):!0)}function Rp(e){return Da(e)}function vp(e){return Da(e)&&Object.values(e).every(t=>Tp(t))}function Tp(e){return Da(e)}function ja(e){try{return new URL(e),!0}catch{return!1}}function jy(e,t){let r={};for(let[o,n]of Object.entries(e)){let s=K0(o,t);if(s===null)continue;if(typeof n!="string"){console.warn("addresses need to be strings."),r[s]=null;continue}let i=_p(n,t);if(i===null){console.warn("the address was invalid."),r[s]=null;continue}if(o.endsWith("/")&&!ur(i).endsWith("/")){console.warn("an invalid address was given for the specifier key specifierKey; since specifierKey ended in a slash, the address needs to as well."),r[s]=null;continue}r[s]=ur(i)}return $a(r)}function ur(e){return e.href}function q0(e,t){let r={};for(let[n,s]of Object.entries(e)){if(!Tp(s))throw new TypeError("the value of the scope with prefix scopePrefix needs to be an object.");let i;try{i=new URL(n,t)}catch{console.warn("the scope prefix URL was not parseable.");continue}let a=ur(i);r[a]=jy(s,t)}let o={};for(let n of Object.keys(r))o[n]=$a(r[n]);return $a(o)}function K0(e,t){if(!e.length)return console.warn("specifier key cannot be an empty string."),null;let r=_p(e,t);return r!==null?ur(r):e}function _p(e,t){if(t&&(e.startsWith("/")||e.startsWith("./")||e.startsWith("../")))try{return new URL(e,t)}catch{return null}try{return new URL(e)}catch{return null}}var X0=["ftp","file","http","https","ws","wss"];function Y0(e){return X0.some(t=>ur(e).startsWith(t))}function $y(e,t,r){for(let[o,n]of Object.entries(r))if(o===e){if(n===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!ja(n))throw new TypeError("resolutionResult must be an URL.");return n}else if(o.endsWith("/")&&e.startsWith(o)&&(t===null||Y0(t))){if(n===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!ja(n))throw new TypeError("resolutionResult must be an URL.");let s=e.slice(o.length);if(!n.endsWith("/"))throw new TypeError('resolutionResult does not end with "/"');try{let i=new URL(s,n);if(!ja(i))throw new TypeError("url must be an URL.");if(!ur(i).startsWith(n))throw new TypeError("resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.");return ur(i)}catch{throw new TypeError("resolution of normalizedSpecifier was blocked since the afterPrefix portion could not be URL-parsed relative to the resolutionResult mapped to by the specifierKey prefix.")}}return null}function Pp(e,t){let r={};if(!Dy(e))throw new TypeError("the top-level value needs to be a JSON object.");let{imports:o,scopes:n}=e;if(o!==void 0){if(!Rp(o))throw new TypeError('"imports" top-level key needs to be an object.');r=jy(o,t)}let s={};if(n!==void 0){if(!vp(n))throw new TypeError('"scopes" top-level key needs to be an object.');s=q0(n,t)}return Object.keys(e).find(i=>i!=="imports"&&i!=="scopes")&&console.warn("an invalid top-level key was present in the import map."),{imports:r,scopes:s}}function By(e,{imports:t={},scopes:r={}},o){let n=ur(o),s=_p(e,o),i=s!==null?ur(s):e;for(let[c,l]of Object.entries(r))if(c===n||c.endsWith("/")&&n.startsWith(c)){let u=$y(i,s,l);if(u!==null)return u}let a=$y(i,s,t);if(a!==null)return a;if(s!==null)return ur(s);throw new TypeError("specifier was a bare specifier, but was not remapped to anything by importMap.")}function Wy(e,{allowTrailingComma:t=!0}={}){if(new.target)throw new TypeError("parse is not a constructor");return new Sp(e,{allowTrailingComma:t}).parse()}var Hy=globalThis.JSON.parse,Sp=class{#i=new Set(` \r
`);#o=new Set([..."[]{}:,/",...this.#i]);#t;#e;#s;#a;constructor(t,r){this.#t=`${t}`,this.#e=this.#t.length,this.#s=this.#m(),this.#a=r}parse(){let t=this.#n(),r=this.#p(t),{done:o,value:n}=this.#s.next();if(!o)throw new SyntaxError(Zr(n));return r}#n(){let{done:t,value:r}=this.#s.next();if(t)throw new SyntaxError("Unexpected end of JSONC input");return r}*#m(){for(let t=0;t<this.#e;t++)if(!this.#i.has(this.#t[t])){if(this.#t[t]==="/"&&this.#t[t+1]==="*"){t+=2;let r=!1;for(;t<this.#e;t++)if(this.#t[t]==="*"&&this.#t[t+1]==="/"){r=!0;break}if(!r)throw new SyntaxError("Unexpected end of JSONC input");t++;continue}if(this.#t[t]==="/"&&this.#t[t+1]==="/"){for(t+=2;t<this.#e&&!(this.#t[t]===`
`||this.#t[t]==="\r");t++);continue}switch(this.#t[t]){case"{":yield{type:"BeginObject",position:t};break;case"}":yield{type:"EndObject",position:t};break;case"[":yield{type:"BeginArray",position:t};break;case"]":yield{type:"EndArray",position:t};break;case":":yield{type:"NameSeparator",position:t};break;case",":yield{type:"ValueSeparator",position:t};break;case'"':{let r=t,o=!1;for(t++;t<this.#e&&!(this.#t[t]==='"'&&!o);t++)o=this.#t[t]==="\\"&&!o;yield{type:"String",sourceText:this.#t.substring(r,t+1),position:r};break}default:{let r=t;for(;t<this.#e&&!this.#o.has(this.#t[t]);t++);t--,yield{type:"NullOrTrueOrFalseOrNumber",sourceText:this.#t.substring(r,t+1),position:r}}}}}#p(t){switch(t.type){case"BeginObject":return this.#f();case"BeginArray":return this.#r();case"NullOrTrueOrFalseOrNumber":return this.#g(t);case"String":return this.#h(t);default:throw new SyntaxError(Zr(t))}}#f(){let t={};for(let r=!0;;r=!1){let o=this.#n();if((r||this.#a.allowTrailingComma)&&o.type==="EndObject")return t;if(o.type!=="String")throw new SyntaxError(Zr(o));let n=this.#h(o),s=this.#n();if(s.type!=="NameSeparator")throw new SyntaxError(Zr(s));let i=this.#n();Object.defineProperty(t,n,{value:this.#p(i),writable:!0,enumerable:!0,configurable:!0});let a=this.#n();if(a.type==="EndObject")return t;if(a.type!=="ValueSeparator")throw new SyntaxError(Zr(a))}}#r(){let t=[];for(let r=!0;;r=!1){let o=this.#n();if((r||this.#a.allowTrailingComma)&&o.type==="EndArray")return t;t.push(this.#p(o));let n=this.#n();if(n.type==="EndArray")return t;if(n.type!=="ValueSeparator")throw new SyntaxError(Zr(n))}}#h(t){let r;try{r=Hy(t.sourceText)}catch{throw new SyntaxError(Zr(t))}return Ia(typeof r=="string"),r}#g(t){if(t.sourceText==="null")return null;if(t.sourceText==="true")return!0;if(t.sourceText==="false")return!1;let r;try{r=Hy(t.sourceText)}catch{throw new SyntaxError(Zr(t))}return Ia(typeof r=="number"),r}};function Zr({type:e,sourceText:t,position:r}){let o="";switch(e){case"BeginObject":o="{";break;case"EndObject":o="}";break;case"BeginArray":o="[";break;case"EndArray":o="]";break;case"NameSeparator":o=":";break;case"ValueSeparator":o=",";break;case"NullOrTrueOrFalseOrNumber":case"String":o=30<t.length?`${t.slice(0,30)}...`:t;break;default:throw new Error("unreachable")}return`Unexpected token ${o} in JSONC at position ${r}`}function Ha(e){if(e.protocol==="file:")return{path:Ua(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}}async function Op(e){let t=await Deno.readTextFile(e),r=Wy(t);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`Deno config at ${e} must be an object`);if("imports"in r&&(typeof r.imports!="object"||r.imports===null||Array.isArray(r.imports)))throw new Error(`Deno config at ${e} has invalid "imports" key`);if("scopes"in r&&(typeof r.scopes!="object"||r.scopes===null||Array.isArray(r.scopes)))throw new Error(`Deno config at ${e} has invalid "scopes" key`);if("lock"in r&&typeof r.lock!="boolean"&&typeof r.lock!="string")throw new Error(`Deno config at ${e} has invalid "lock" key`);if("importMap"in r&&typeof r.importMap!="string")throw new Error(`Deno config at ${e} has invalid "importMap" key`);return r}function Gy(e){if(e.imports!==void 0){let t=[];for(let[r,o]of Object.entries(e.imports))if(t.push([r,o]),!r.endsWith("/")&&o&&(o.startsWith("jsr:")||o.startsWith("npm:"))&&!e.imports[r+"/"]){let n=r+"/",s=o.slice(0,4)+"/"+o.slice(o[4]==="/"?5:4)+"/";t.push([n,s])}e.imports=Object.fromEntries(t)}}var Q0=`${En}node_modules${En}`,Z0=`${En}node_modules`;function Ba(e){return e.includes(Q0)||e.endsWith(Z0)}function Lp(e){return(e.namespace===""||e.namespace==="file")&&(Ba(e.resolveDir)||Ba(e.path)||Ba(e.importer))}function Np(e={}){return{name:"deno-resolver",setup(t){let r=null,o=(t.initialOptions.external??[]).map(n=>new RegExp("^"+n.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*")+"$"));t.onStart(async function(){let s;if(e.importMapURL===void 0&&e.configPath!==void 0){let i=await Op(e.configPath);if(i.imports!==void 0||i.scopes!==void 0){let a={imports:i.imports,scopes:i.scopes};Gy(a),r=Pp(a,ys(e.configPath))}else i.importMap!==void 0&&(s=new URL(i.importMap,ys(e.configPath)).href)}else e.importMapURL!==void 0&&(s=e.importMapURL);if(s){let i=await fetch(s),a=await i.json();r=Pp(a,new URL(i.url))}}),t.onResolve({filter:/.*/},async function(s){if(Lp(s))return;let i;if(s.importer!==""){if(s.namespace==="")throw new Error("[assert] namespace is empty");i=new URL(`${s.namespace}:${s.importer}`)}else if(s.resolveDir!=="")i=new URL(`${ys(s.resolveDir).href}/`);else return;let a;if(r!==null){let p=By(s.path,r,new URL(i));a=new URL(p)}else a=new URL(s.path,i);for(let p of o)if(p.test(a.href))return{path:a.href,external:!0};let{path:c,namespace:l}=Ha(a);return await t.resolve(c,{namespace:l,kind:s.kind})})}}}var Ghe=new TextEncoder;var eP=[],tP=[],Cp="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";for(let e=0,t=Cp.length;e<t;++e)eP[e]=Cp[e],tP[Cp.charCodeAt(e)]=e;var uge=Deno.env.get("DENO_REGISTRY_URL")??"https://jsr.io";var lP=await Deno.permissions.query({name:"run"}).then(e=>e.state!=="granted")?"portable":"native";var Vy=Np;var zy=" must not return ",pP="`transformer`",uP="`recoverer`",mP="`defaultValue`",wn=pP+zy,Nr="called with ",kn=mP+" must not be ",Rn=uP+zy;var Wa="`null` or `undefined`",vn=wn+Wa,fP=Nr+Wa,Ap=kn+Wa,Ga=Rn+Wa;function er(e){return e!=null}var dP="`Ok`",qy="`Err`",Ky=Nr+qy,Xy=Nr+dP,hP="Carrying `E` in "+qy+" instead of throwing it directly. See `.cause`",Mp="an instance of `Error` of the current realm.",iye="The thrown value is not "+Mp,aye="The contained E should be "+Mp,gP="This `.cause` is not "+Mp;function tt(e){return e.ok}function Et(e){return{ok:!0,val:e,err:null}}function Rt(e){return!e.ok}function At(e){return{ok:!1,val:null,err:e}}function Bo(e){return Yy(e,Ky)}function Tn(e){return Jy(e,Xy)}function Yy(e,t){if(Rt(e))throw new TypeError(t);return e.val}function Jy(e,t){if(tt(e))throw new TypeError(t);return e.err}function Ip(e,t){if(er(e))return Et(e);let r=t();return At(r)}var Qy=e=>!!(yP.includes(e.hostname)||e.hostname.endsWith(".openai.azure.com")),yP=["i.gyazo.com","t.gyazo.com","scrapbox.io","api.openai.com","*.openai.azure.com","maps.googleapis.com","upload.gyazo.com","storage.googleapis.com","sentry.io"];function to(e){if(typeof e!="string")throw new TypeError(`Path must be a string, received "${JSON.stringify(e)}"`)}function Ho(e){return e===47}function Zy(e){to(e);let t=-1,r=0,o=-1,n=!0,s=0;for(let i=e.length-1;i>=0;--i){let a=e.charCodeAt(i);if(Ho(a)){if(!n){r=i+1;break}continue}o===-1&&(n=!1,o=i+1),a===46?t===-1?t=i:s!==1&&(s=1):t!==-1&&(s=-1)}return t===-1||o===-1||s===0||s===1&&t===o-1&&t===r+1?"":e.slice(t,o)}function ex(e,t){if(t.length>=e.length)return e;let r=e.length-t.length;for(let o=t.length-1;o>=0;--o)if(e.charCodeAt(r+o)!==t.charCodeAt(o))return e;return e.slice(0,-t.length)}function tx(e,t,r=0){let o=!1,n=e.length;for(let s=e.length-1;s>=r;--s)if(t(e.charCodeAt(s))){if(o){r=s+1;break}}else o||(o=!0,n=s+1);return e.slice(r,n)}function rx(e,t){if(to(e),e.length===0)return e;if(typeof t!="string")throw new TypeError(`Suffix must be a string, received "${JSON.stringify(t)}"`)}function ox(e,t){if(e.length<=1)return e;let r=e.length;for(let o=e.length-1;o>0&&t(e.charCodeAt(o));o--)r=o;return e.slice(0,r)}function nx(e,t=""){rx(e,t);let r=tx(e,Ho),o=ox(r,Ho);return t?ex(o,t):o}var Va=globalThis.Deno?.build.os==="windows"||globalThis.navigator?.platform?.startsWith("Win")||globalThis.process?.platform?.startsWith("win")||!1;function za(e){if(e=e instanceof URL?e:new URL(e),e.protocol!=="file:")throw new TypeError(`URL must be a file URL: received "${e.protocol}"`);return e}function sx(e){return e=za(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function ix(e){e=za(e);let t=decodeURIComponent(e.pathname.replace(/\//g,"\\").replace(/%(?![0-9A-Fa-f]{2})/g,"%25")).replace(/^\\*([A-Za-z]:)(\\|$)/,"$1\\");return e.hostname!==""&&(t=`\\\\${e.hostname}${t}`),t}function ax(e){return Va?ix(e):sx(e)}var bP={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function qa(e){return e.replaceAll(/[\s]/g,t=>bP[t]??t)}function cx(e){return to(e),e.length>0&&Ho(e.charCodeAt(0))}function lx(e){if(!cx(e))throw new TypeError(`Path must be absolute: received "${e}"`);let t=new URL("file:///");return t.pathname=qa(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}function Up(e){return e===47||e===92}function px(e){return e>=97&&e<=122||e>=65&&e<=90}function ux(e){to(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return Up(r)?!0:!!(px(r)&&t>2&&e.charCodeAt(1)===58&&Up(e.charCodeAt(2)))}function mx(e){if(!ux(e))throw new TypeError(`Path must be absolute: received "${e}"`);let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),o=new URL("file:///");if(o.pathname=qa(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(o.hostname=t,!o.hostname))throw new TypeError(`Invalid hostname: "${o.hostname}"`);return o}function fx(e){return Va?mx(e):lx(e)}var dx=e=>{if(e.protocol==="file:")return{path:ax(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}},Dp=e=>e.namespace==="file"?fx(e.path):new URL(`${e.namespace}:${e.path}`);var hx=(e,t)=>{let r=Ip(_P(e),()=>({name:"NotFoundError",message:"Source map URL is not found"}));if(B(r))return r;let{url:o,start:n,end:s}=H(r);return URL.canParse(o,t)?ae({url:new URL(o,t),start:n,end:s}):Q({name:"InvalidURLError",message:`Invalid URL: ${o}`})},_P=e=>{for(let t of e.matchAll(/\/([*/])[#@] *sourceMappingURL=/g)){let r=t.index+t[0].length,o=e.length,n=r;for(;n<o&&e.charCodeAt(n)>32;)n++;if(n!==r&&(t[1]==="/"||e.indexOf("*/",n)>0))return{url:e.slice(r,n),start:r,end:n}}};var PP=["base64","binary","copy","css","dataurl","default","empty","file","js","json","jsx","local-css","text","ts","tsx"],gx=e=>PP.includes(e),yx=e=>/^js|^ts|css$/.test(e),xx=e=>{let t=e.url,r=nx(t);if(gx(r))return r;if(r==="mjs")return"js";let o=new URL(t);o.search="",o.hash="";let n=Zy(o.href).slice(1);if(gx(n))return n;if(n==="mjs")return"js";let i=(e.headers.get("Content-Type")??"text/plain").split(";")[0]?.trim?.()??"text/plain";return SP(i)},SP=e=>{let t=e.split("/")[1]??"plain";if(/(?:^plain$|^xml|^svg|^x?html)/.test(t))return"text";if(t.startsWith("json"))return"json";switch(t){case"javascript":return"js";case"typescript":return"ts";case"css":return"css";default:return"text"}};function Ka(e,t){if(isNaN(e)||isNaN(t))throw new Error("Cannot compare against non-numbers");return e===t?0:e<t?-1:1}function wx(e=[],t=[]){return e.length&&!t.length?-1:!e.length&&t.length?1:0}function jp(e=[],t=[]){let r=Math.max(e.length,t.length);for(let o=0;o<r;o++){let n=e[o],s=t[o];if(n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(typeof n=="string"&&typeof s=="number")return 1;if(typeof n=="number"&&typeof s=="string"||n<s)return-1;if(n>s)return 1}return 0}var _n="0|[1-9]\\d*",OP="\\d*[a-zA-Z-][a-zA-Z0-9-]*",LP=`(?<major>${_n})\\.(?<minor>${_n})\\.(?<patch>${_n})`,bx=`(?:${_n}|${OP})`,kx=`(?:-(?<prerelease>${bx}(?:\\.${bx})*))`,Ex="[0-9A-Za-z-]+",Rx=`(?:\\+(?<buildmetadata>${Ex}(?:\\.${Ex})*))`,vx=`v?${LP}${kx}?${Rx}?`,Tx=new RegExp(`^${vx}$`),_x="(?:<|>)?=?",NP="x|X|\\*",$p=`${_n}|${NP}`,Xa=`[v=\\s]*(?<major>${$p})(?:\\.(?<minor>${$p})(?:\\.(?<patch>${$p})${kx}?${Rx}?)?)?`,Px=new RegExp(`^(?<operator>~>?|\\^|${_x})\\s*${Xa}$`),Sx=new RegExp(`^(?<operator>${_x})\\s*(${vx})$|^$`);function Bp(e){return typeof e=="number"&&!Number.isNaN(e)&&(!Number.isFinite(e)||0<=e&&e<=Number.MAX_SAFE_INTEGER)}var Hp=256;var CP=new RegExp(`^${_n}$`);function vt(e){return e.split(".").filter(Boolean).map(t=>{if(CP.test(t)){let r=Number(t);if(Bp(r))return r}return t})}function mr(e){return e.split(".").filter(Boolean)}function ro(e,t){let r=Number(e);if(!Bp(r))throw new TypeError(t);return r}function Wo(e){return Number.isNaN(e.major)&&Number.isNaN(e.minor)&&Number.isNaN(e.patch)&&(e.prerelease===void 0||e.prerelease.length===0)&&(e.build===void 0||e.build.length===0)}function Gt(e,t){return e===t?0:Ka(e.major,t.major)||Ka(e.minor,t.minor)||Ka(e.patch,t.patch)||wx(e.prerelease,t.prerelease)||jp(e.prerelease,t.prerelease)}function Wp(e){return e.toFixed(0)}function Go(e){let t=Wp(e.major),r=Wp(e.minor),o=Wp(e.patch),n=e.prerelease?.join(".")??"",s=e.build?.join(".")??"";return[[`${t}.${r}.${o}`,n].filter(c=>c).join("-"),s].filter(c=>c).join("+")}function AP(e,t){if(Wo(t))return!0;let r=Gt(e,t);switch(t.operator){case"=":case void 0:return r===0;case"!=":return r!==0;case">":return r>0;case"<":return r<0;case">=":return r>=0;case"<=":return r<=0}}function Ya(e,t){for(let r of t)if(!AP(e,r))return!1;if(e.prerelease&&e.prerelease.length>0){for(let r of t){if(Wo(r))continue;let{major:o,minor:n,patch:s,prerelease:i}=r;if(i&&i.length>0&&e.major===o&&e.minor===n&&e.patch===s)return!0}return!1}return!0}function Ja(e,t){return t.some(r=>Ya(e,r))}var Qa={major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]},Pn={operator:void 0,...Qa};function Ox(e,t){return Gt(e,t)>0}function xs(e,t){let r;for(let o of e)Ja(o,t)&&(r=r&&Ox(r,o)?r:o);return r}function MP(e){let r=e.match(Sx)?.groups;if(!r)return null;let{operator:o,prerelease:n,buildmetadata:s}=r,i=r.major?{major:ro(r.major,`Cannot parse comparator ${e}: invalid major version`),minor:ro(r.minor,`Cannot parse comparator ${e}: invalid minor version`),patch:ro(r.patch,`Cannot parse comparator ${e}: invalid patch version`),prerelease:n?vt(n):[],build:s?mr(s):[]}:Qa;return{operator:o||void 0,...i}}function Se(e){return!e||e.toLowerCase()==="x"||e==="*"}function IP(e){if(!Se(e.major))return Se(e.minor)?{operator:">=",major:+e.major,minor:0,patch:0,prerelease:[],build:[]}:Se(e.patch)?{operator:">=",major:+e.major,minor:+e.minor,patch:0,prerelease:[],build:[]}:{operator:">=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:e.prerelease?vt(e.prerelease):[],build:[]}}function FP(e){if(!Se(e.major))return Se(e.minor)?{operator:"<",major:+e.major+1,minor:0,patch:0,prerelease:[],build:[]}:Se(e.patch)?{operator:"<",major:+e.major,minor:+e.minor+1,patch:0,prerelease:[],build:[]}:e.prerelease?{operator:"<=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:vt(e.prerelease),build:[]}:{operator:"<=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:e.prerelease?vt(e.prerelease):[],build:[]}}function UP(e){let t=e.match(new RegExp(`^${Xa}`)),r=t?.groups;if(!r)return;let o=t[0].length,n=e.slice(o).match(/^\s+-\s+/);if(!n)return;let s=n[0].length,a=e.slice(o+s).match(new RegExp(`^${Xa}\\s*$`))?.groups;if(!a)return;let c=IP(r),l=FP(a);return[c,l].filter(Boolean)}function DP(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[Pn];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return n===0?[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}]:[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];let a=vt(e.prerelease??"");return n===0?s===0?[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s,patch:i+1}]:[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s+1,patch:0}]:[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n+1,minor:0,patch:0}]}function $P(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[Pn];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}];let a=vt(e.prerelease??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s+1,patch:0}]}function jP(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return o?[{operator:"<",major:n,minor:0,patch:0}]:[{operator:"<",major:n,minor:s,patch:0}];if(o)return[{operator:"<",major:n,minor:s,patch:0}];let a=vt(e.prerelease??""),c=mr(e.build??"");return[{operator:"<",major:n,minor:s,patch:i,prerelease:a,build:c}]}function BP(e){let t=Se(e.minor),r=Se(e.patch),o=+e.major,n=+e.minor,s=+e.patch;if(t)return r?[{operator:"<",major:o+1,minor:0,patch:0}]:[{operator:"<",major:o,minor:n+1,patch:0}];if(r)return[{operator:"<",major:o,minor:n+1,patch:0}];let i=vt(e.prerelease??""),a=mr(e.build??"");return[{operator:"<=",major:o,minor:n,patch:s,prerelease:i,build:a}]}function HP(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return[{operator:">=",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s+1,patch:0}];let a=vt(e.prerelease??""),c=mr(e.build??"");return[{operator:">",major:n,minor:s,patch:i,prerelease:a,build:c}]}function WP(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[Pn];if(r)return o?[{operator:">=",major:n,minor:0,patch:0}]:[{operator:">=",major:n,minor:s,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0}];let a=vt(e.prerelease??""),c=mr(e.build??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a,build:c}]}function GP(e){let t=Se(e.major),r=Se(e.minor),o=Se(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[Pn];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}];let a=vt(e.prerelease??""),c=mr(e.build??"");return[{operator:void 0,major:n,minor:s,patch:i,prerelease:a,build:c}]}function VP(e){let t=e.match(Px)?.groups;if(!t)return MP(e);switch(t.operator){case"^":return DP(t);case"~":case"~>":return $P(t);case"<":return jP(t);case"<=":return BP(t);case">":return HP(t);case">=":return WP(t);case"=":case"":return GP(t);default:throw new Error(`Cannot parse version range: '${t.operator}' is not a valid operator`)}}function zP(e){return e.split(/\s+/).flatMap(VP)}function Lx(e){let t=e.replaceAll(/(?<=<|>|=|~|\^)(\s+)/g,"").split(/\s*\|\|\s*/).map(r=>UP(r)||zP(r));if(t.some(r=>r.includes(null)))throw new TypeError(`Cannot parse version range: range "${e}" is invalid`);return t}function Gp(e){if(typeof e!="string")throw new TypeError(`Cannot parse version as version must be a string: received ${typeof e}`);if(e.length>Hp)throw new TypeError(`Cannot parse version as version length is too long: length is ${e.length}, max length is ${Hp}`);e=e.trim();let t=e.match(Tx)?.groups;if(!t)throw new TypeError(`Cannot parse version: ${e}`);let r=ro(t.major,`Cannot parse version ${e}: invalid major version`),o=ro(t.minor,`Cannot parse version ${e}: invalid minor version`),n=ro(t.patch,`Cannot parse version ${e}: invalid patch version`),s=t.prerelease?vt(t.prerelease):[],i=t.buildmetadata?mr(t.buildmetadata):[];return{major:r,minor:o,patch:n,prerelease:s,build:i}}function Vp(e){try{return Lx(e)}catch{return}}function zp(e){try{return Gp(e)}catch{return}}var bs={operator:void 0,major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]};var oo=async e=>{try{let t=await fetch(e);return t.ok?ae([t,!1]):Q({name:"HTTPError",message:`${t.status} ${t.statusText}`,response:t})}catch(t){if(t instanceof TypeError)return Q({name:"NetworkError",message:t.message,request:e});if(t instanceof DOMException)return Q({name:"AbortError",message:t.message,request:e});throw t}};var qp="https://jsr.io",Nx=async(e,t)=>{let r=await(t?.fetch??oo)(new Request(`${t?.endpoint??qp}/${e}/meta.json`),t?.cacheFirst);return _t(r,([o])=>o.json())};var Cx=async(e,t,r)=>{let o=await(r?.fetch??oo)(new Request(`${r?.endpoint??qp}/${e}/${t}_meta.json`),r?.cacheFirst);return _t(o,([n])=>n.json())};var Ax=async(e,t)=>{let r=await(t?.fetch??oo)(new Request(`${t?.endpoint??"https://registry.npmjs.org"}/${e}`),t?.cacheFirst);return _t(r,([o])=>o.json())};var Fx=(e,t)=>({name:"InvalidPackageVersionError",message:`No version of ${e.name} satisfies "${e.tag??"*"}" (available: ${t.slice(0,10).join(", ")}${t.length>10?`, ... (${t.length-10} more versions)`:""})`,packageName:e.name,range:e.range,tag:e.tag,entryPoint:e.entryPoint,availableVersions:t}),Za=(e,t)=>({name:"InvalidEntryPointError",message:`${e.entryPoint} is not a valid entry point for ${e.name}@${e.tag??"*"} (available: ${t.join(", ")})`,packageName:e.name,range:e.range,tag:e.tag,entryPoint:e.entryPoint,availableEntryPoints:t}),Ux=async(e,t)=>{if(t?.resolvedVersions){let c=new Map(t.resolvedVersions.get(e.name)??[]),l=xs([...c.keys()],e.range);if(l){let u=c.get(l)??Es,p=u[e.entryPoint];return typeof p!="string"&&console.log(p),p?ae(Mx(e.name,Go(l),p)):Q(Za(e,Object.keys(u)))}}let r=await Ax(e.name,t);if(B(r))return r;let o=H(r),n=new Map(Object.entries(o.versions).flatMap(([c,{exports:l}])=>{let u=zp(c);return u?[[u,l??Es]]:[]})),s=xs([...n.keys()],e.range);if(!s)return Q(Fx(e,Object.keys(o.versions)));let i={...Es};for(let c of Object.keys(n.get(s)??Es))i[c]=c;let a=i[e.entryPoint];return a?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[s,i]]),ae(Mx(e.name,Go(s),a))):Q(Za(e,Object.keys(i)))},Mx=(e,t,r)=>new URL(r,`https://esm.sh/${e}@${t}/`),Dx=async(e,t)=>{if(t?.resolvedVersions){let a=new Map(t.resolvedVersions.get(e.name)??[]),c=xs([...a.keys()],e.range);if(c){let l=a.get(c)??Es,u=l[e.entryPoint];return u?ae(Ix(e.name,Go(c),u)):Q(Za(e,Object.keys(l)))}}let r=await qP(e,t);if(B(r))return r;let o=H(r),n=await Cx(e.name,Go(o),t);if(B(n))return n;let s=H(n).exports,i=s[e.entryPoint];return i?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[o,s]]),ae(Ix(e.name,Go(o),i))):Q(Za(e,Object.keys(H(n).exports)))},Ix=(e,t,r)=>new URL(r,`https://jsr.io/${e}/${t}/`),qP=async(e,t)=>{let r=await Nx(e.name,t);if(B(r))return r;let o=H(r),n=Object.keys(o.versions).flatMap(i=>{let a=zp(i);return a?[a]:[]}),s=xs(n,e.range);return s?ae(s):Q(Fx(e,Object.keys(o.versions)))},Es={".":"./"};var KP=e=>({name:"OnlyScopeProvidedError",specifier:e}),$x=e=>({name:"PackageNotFoundError",specifier:e}),jx=e=>{if(e.protocol!=="npm:")return Q({name:"NotNpmProtocolError",specifier:e});let t=e.pathname,r=t[0]==="/"?1:0,o,n;if(t[r]==="@"){let p=t.indexOf("/",r);if(p===-1)return Q(KP(e));o=t.indexOf("/",p+1),n=t.indexOf("@",p+1)}else o=t.indexOf("/",r),n=t.indexOf("@",r);if(o===-1&&(o=t.length),n===-1&&(n=t.length),n=Math.min(n,o),r===n)return Q($x(e));let s=t.slice(r,n),i=decodeURIComponent(t.slice(n+1,o)),a=i?Vp(i)??[[bs]]:[[bs]],c=t.slice(o+1),l=c?`./${c}`:".",u={name:s,range:a,entryPoint:l};return i&&(u.tag=i),ae(u)},Bx=e=>{if(e.protocol!=="jsr:")return Q({name:"NotJsrProtocolError",specifier:e});let t=e.pathname,r=t[0]==="/"?1:0;if(t[r]!=="@")return Q({name:"ScopeNotFoundError",specifier:e});let o=t.indexOf("/",r);if(o===-1)return Q($x(e));let n=t.indexOf("/",o+1),s=t.indexOf("@",o+1);n===-1&&(n=t.length),s===-1&&(s=t.length),s=Math.min(s,n);let i=t.slice(r,s),a=decodeURIComponent(t.slice(s+1,n)),c=a?Vp(a)??[[bs]]:[[bs]],l=t.slice(n+1),u=l?`./${l}`:".",p={name:i,range:c,entryPoint:u};return a&&(p.tag=a),ae(p)};var Hx=e=>new Promise((t,r)=>{let o=new FileReader;o.addEventListener("load",()=>{let n=o.result,s=n.indexOf(";");n.startsWith("; charset=utf-8",s)?t(`${n.slice(0,s)}${n.slice(s+15)}`):t(n)}),o.addEventListener("error",()=>r(o.error)),o.readAsDataURL(e)});var Vx=e=>{let t=new Map,r=async o=>{let n=o.namespace==="npm",s=(n?jx:Bx)(Dp(o));if(B(s)){let a=re(s);return{errors:[{text:a.name,detail:a}]}}let i=await(n?Ux:Dx)(H(s),{resolvedVersions:t,...e});if(B(i)){let a=re(i);return{errors:[{text:`${a.name} ${a.message}`,detail:a}]}}return dx(H(i))};return{name:"remote-loader",setup({onLoad:o,onResolve:n,initialOptions:s}){for(let i of[...Wx,...Gx])n({filter:/.*/,namespace:i.slice(0,-1)},XP);n({filter:/.*/,namespace:"npm"},r),n({filter:/.*/,namespace:"jsr"},r);for(let i of Wx)o({filter:/.*/,namespace:i.slice(0,-1)},a=>YP(Dp(a),{...e,sourcemap:s.sourcemap!==!1&&s.sourcemap!==void 0}));for(let i of Gx)o({filter:/.*/,namespace:i.slice(0,-1)},()=>{throw new Error(`${i} import is not supported yet.`)})}}},XP=e=>({path:e.path,namespace:e.namespace}),Wx=["http:","https:","data:"],Gx=["node:"],YP=async(e,t)=>{let r=t.reload?t.reload===!0?!1:!t.reload.some(l=>l.test(e)):!0,o=t.fetch??oo,n=await o(new Request(e),r);if(B(n))return{errors:[{text:`[${re(n).message}] Failed to fetch ${e}`,detail:re(n)}]};let[s,i]=H(n),a=xx(s);t.onProgress?.({path:e,done:s.clone().blob().then(l=>({size:l.size,loader:a,isCache:i}))});let c=await s.blob();if(t.sourcemap&&yx(a)){let l=await c.text(),u=hx(l,e);if(Ne(u)){let{url:p,start:f,end:m}=H(u);if(p.protocol!=="data:"){let h=await o(new Request(p),r);if(B(h))return{contents:l,loader:a,warnings:[{text:`[${re(h).message}] Failed to fetch the source map URL`,notes:[{text:`Source map URL: ${p}`},{text:`Original URL: ${e}`}],detail:re(h)}]};let g=await H(h)[0].blob().then(Hx);return{contents:l.slice(0,f)+g+l.slice(m),loader:a}}}}return{contents:new Uint8Array(await c.arrayBuffer()),loader:a}};var Rs=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(e,t,r,o,n,s){this.type=e,this.name=t,this.prefix=r,this.value=o,this.suffix=n,this.modifier=s}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},JP=/[$_\p{ID_Start}]/u,QP=/[$_\u200C\u200D\p{ID_Continue}]/u,Xp=".*";function ZP(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function Kx(e,t=!1){let r=[],o=0;for(;o<e.length;){let n=e[o],s=function(i){if(!t)throw new TypeError(i);r.push({type:"INVALID_CHAR",index:o,value:e[o++]})};if(n==="*"){r.push({type:"ASTERISK",index:o,value:e[o++]});continue}if(n==="+"||n==="?"){r.push({type:"OTHER_MODIFIER",index:o,value:e[o++]});continue}if(n==="\\"){r.push({type:"ESCAPED_CHAR",index:o++,value:e[o++]});continue}if(n==="{"){r.push({type:"OPEN",index:o,value:e[o++]});continue}if(n==="}"){r.push({type:"CLOSE",index:o,value:e[o++]});continue}if(n===":"){let i="",a=o+1;for(;a<e.length;){let c=e.substr(a,1);if(a===o+1&&JP.test(c)||a!==o+1&&QP.test(c)){i+=e[a++];continue}break}if(!i){s(`Missing parameter name at ${o}`);continue}r.push({type:"NAME",index:o,value:i}),o=a;continue}if(n==="("){let i=1,a="",c=o+1,l=!1;if(e[c]==="?"){s(`Pattern cannot start with "?" at ${c}`);continue}for(;c<e.length;){if(!ZP(e[c],!1)){s(`Invalid character '${e[c]}' at ${c}.`),l=!0;break}if(e[c]==="\\"){a+=e[c++]+e[c++];continue}if(e[c]===")"){if(i--,i===0){c++;break}}else if(e[c]==="("&&(i++,e[c+1]!=="?")){s(`Capturing groups are not allowed at ${c}`),l=!0;break}a+=e[c++]}if(l)continue;if(i){s(`Unbalanced pattern at ${o}`);continue}if(!a){s(`Missing pattern at ${o}`);continue}r.push({type:"REGEX",index:o,value:a}),o=c;continue}r.push({type:"CHAR",index:o,value:e[o++]})}return r.push({type:"END",index:o,value:""}),r}function Xx(e,t={}){let r=Kx(e);t.delimiter??="/#?",t.prefixes??="./";let o=`[^${Vt(t.delimiter)}]+?`,n=[],s=0,i=0,a="",c=new Set,l=R=>{if(i<r.length&&r[i].type===R)return r[i++].value},u=()=>l("OTHER_MODIFIER")??l("ASTERISK"),p=R=>{let b=l(R);if(b!==void 0)return b;let{type:v,index:k}=r[i];throw new TypeError(`Unexpected ${v} at ${k}, expected ${R}`)},f=()=>{let R="",b;for(;b=l("CHAR")??l("ESCAPED_CHAR");)R+=b;return R},m=R=>R,h=t.encodePart||m,g="",y=R=>{g+=R},x=()=>{g.length&&(n.push(new Rs(3,"","",h(g),"",3)),g="")},E=(R,b,v,k,O)=>{let L=3;switch(O){case"?":L=1;break;case"*":L=0;break;case"+":L=2;break}if(!b&&!v&&L===3){y(R);return}if(x(),!b&&!v){if(!R)return;n.push(new Rs(3,"","",h(R),"",L));return}let N;v?v==="*"?N=Xp:N=v:N=o;let P=2;N===o?(P=1,N=""):N===Xp&&(P=0,N="");let T;if(b?T=b:v&&(T=s++),c.has(T))throw new TypeError(`Duplicate name '${T}'.`);c.add(T),n.push(new Rs(P,T,h(R),N,h(k),L))};for(;i<r.length;){let R=l("CHAR"),b=l("NAME"),v=l("REGEX");if(!b&&!v&&(v=l("ASTERISK")),b||v){let O=R??"";t.prefixes.indexOf(O)===-1&&(y(O),O=""),x();let L=u();E(O,b,v,"",L);continue}let k=R??l("ESCAPED_CHAR");if(k){y(k);continue}if(l("OPEN")){let O=f(),L=l("NAME"),N=l("REGEX");!L&&!N&&(N=l("ASTERISK"));let P=f();p("CLOSE");let T=u();E(O,L,N,P,T);continue}x(),p("END")}return n}function Vt(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function zx(e){return e&&e.ignoreCase?"ui":"u"}function eS(e,t,r){return Yx(Xx(e,r),t,r)}function Sn(e){switch(e){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}function Yx(e,t,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let o=r.start?"^":"";for(let a of e){if(a.type===3){a.modifier===3?o+=Vt(a.value):o+=`(?:${Vt(a.value)})${Sn(a.modifier)}`;continue}t&&t.push(a.name);let c=`[^${Vt(r.delimiter)}]+?`,l=a.value;if(a.type===1?l=c:a.type===0&&(l=Xp),!a.prefix.length&&!a.suffix.length){a.modifier===3||a.modifier===1?o+=`(${l})${Sn(a.modifier)}`:o+=`((?:${l})${Sn(a.modifier)})`;continue}if(a.modifier===3||a.modifier===1){o+=`(?:${Vt(a.prefix)}(${l})${Vt(a.suffix)})`,o+=Sn(a.modifier);continue}o+=`(?:${Vt(a.prefix)}`,o+=`((?:${l})(?:`,o+=Vt(a.suffix),o+=Vt(a.prefix),o+=`(?:${l}))*)${Vt(a.suffix)})`,a.modifier===0&&(o+="?")}let n=`[${Vt(r.endsWith)}]|$`,s=`[${Vt(r.delimiter)}]`;if(r.end)return r.strict||(o+=`${s}?`),r.endsWith.length?o+=`(?=${n})`:o+="$",new RegExp(o,zx(r));r.strict||(o+=`(?:${s}(?=${n}))?`);let i=!1;if(e.length){let a=e[e.length-1];a.type===3&&a.modifier===3&&(i=r.delimiter.indexOf(a)>-1)}return i||(o+=`(?=${s}|${n})`),new RegExp(o,zx(r))}var so={delimiter:"",prefixes:"",sensitive:!0,strict:!0},tS={delimiter:".",prefixes:"",sensitive:!0,strict:!0},rS={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function oS(e,t){return e.length?e[0]==="/"?!0:!t||e.length<2?!1:(e[0]=="\\"||e[0]=="{")&&e[1]=="/":!1}function Jx(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function nS(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function Qx(e){return!e||e.length<2?!1:e[0]==="["||(e[0]==="\\"||e[0]==="{")&&e[1]==="["}var Zx=["ftp","file","http","https","ws","wss"];function eb(e){if(!e)return!0;for(let t of Zx)if(e.test(t))return!0;return!1}function sS(e,t){if(e=Jx(e,"#"),t||e==="")return e;let r=new URL("https://example.com");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):""}function iS(e,t){if(e=Jx(e,"?"),t||e==="")return e;let r=new URL("https://example.com");return r.search=e,r.search?r.search.substring(1,r.search.length):""}function aS(e,t){return t||e===""?e:Qx(e)?ob(e):rb(e)}function cS(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.password=e,r.password}function lS(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.username=e,r.username}function pS(e,t,r){if(r||e==="")return e;if(t&&!Zx.includes(t))return new URL(`${t}:${e}`).pathname;let o=e[0]=="/";return e=new URL(o?e:"/-"+e,"https://example.com").pathname,o||(e=e.substring(2,e.length)),e}function uS(e,t,r){return tb(t)===e&&(e=""),r||e===""?e:nb(e)}function mS(e,t){return e=nS(e,":"),t||e===""?e:Yp(e)}function tb(e){switch(e){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}function Yp(e){if(e==="")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}function fS(e){if(e==="")return e;let t=new URL("https://example.com");return t.username=e,t.username}function dS(e){if(e==="")return e;let t=new URL("https://example.com");return t.password=e,t.password}function rb(e){if(e==="")return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL("https://example.com");return t.hostname=e,t.hostname}function ob(e){if(e==="")return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function nb(e){if(e===""||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}function hS(e){if(e==="")return e;let t=new URL("https://example.com");return t.pathname=e[0]!=="/"?"/-"+e:e,e[0]!=="/"?t.pathname.substring(2,t.pathname.length):t.pathname}function gS(e){return e===""?e:new URL(`data:${e}`).pathname}function yS(e){if(e==="")return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function xS(e){if(e==="")return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var bS=class{#i;#o=[];#t={};#e=0;#s=1;#a=0;#n=0;#m=0;#p=0;#f=!1;constructor(e){this.#i=e}get result(){return this.#t}parse(){for(this.#o=Kx(this.#i,!0);this.#e<this.#o.length;this.#e+=this.#s){if(this.#s=1,this.#o[this.#e].type==="END"){if(this.#n===0){this.#g(),this.#u()?this.#r(9,1):this.#d()?this.#r(8,1):this.#r(7,0);continue}else if(this.#n===2){this.#y(5);continue}this.#r(10,0);break}if(this.#m>0)if(this.#_())this.#m-=1;else continue;if(this.#T()){this.#m+=1;continue}switch(this.#n){case 0:this.#w()&&this.#y(1);break;case 1:if(this.#w()){this.#O();let e=7,t=1;this.#k()?(e=2,t=3):this.#f&&(e=2),this.#r(e,t)}break;case 2:this.#b()?this.#y(3):(this.#E()||this.#d()||this.#u())&&this.#y(5);break;case 3:this.#R()?this.#r(4,1):this.#b()&&this.#r(5,1);break;case 4:this.#b()&&this.#r(5,1);break;case 5:this.#P()?this.#p+=1:this.#S()&&(this.#p-=1),this.#v()&&!this.#p?this.#r(6,1):this.#E()?this.#r(7,0):this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 6:this.#E()?this.#r(7,0):this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 7:this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 8:this.#u()&&this.#r(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port="")}#r(e,t){switch(this.#n){case 0:break;case 1:this.#t.protocol=this.#l();break;case 2:break;case 3:this.#t.username=this.#l();break;case 4:this.#t.password=this.#l();break;case 5:this.#t.hostname=this.#l();break;case 6:this.#t.port=this.#l();break;case 7:this.#t.pathname=this.#l();break;case 8:this.#t.search=this.#l();break;case 9:this.#t.hash=this.#l();break;case 10:break}this.#n!==0&&e!==10&&([1,2,3,4].includes(this.#n)&&[6,7,8,9].includes(e)&&(this.#t.hostname??=""),[1,2,3,4,5,6].includes(this.#n)&&[8,9].includes(e)&&(this.#t.pathname??=this.#f?"/":""),[1,2,3,4,5,6,7].includes(this.#n)&&e===9&&(this.#t.search??="")),this.#h(e,t)}#h(e,t){this.#n=e,this.#a=this.#e+t,this.#e+=t,this.#s=0}#g(){this.#e=this.#a,this.#s=0}#y(e){this.#g(),this.#n=e}#x(e){return e<0&&(e=this.#o.length-e),e<this.#o.length?this.#o[e]:this.#o[this.#o.length-1]}#c(e,t){let r=this.#x(e);return r.value===t&&(r.type==="CHAR"||r.type==="ESCAPED_CHAR"||r.type==="INVALID_CHAR")}#w(){return this.#c(this.#e,":")}#k(){return this.#c(this.#e+1,"/")&&this.#c(this.#e+2,"/")}#b(){return this.#c(this.#e,"@")}#R(){return this.#c(this.#e,":")}#v(){return this.#c(this.#e,":")}#E(){return this.#c(this.#e,"/")}#d(){if(this.#c(this.#e,"?"))return!0;if(this.#o[this.#e].value!=="?")return!1;let e=this.#x(this.#e-1);return e.type!=="NAME"&&e.type!=="REGEX"&&e.type!=="CLOSE"&&e.type!=="ASTERISK"}#u(){return this.#c(this.#e,"#")}#T(){return this.#o[this.#e].type=="OPEN"}#_(){return this.#o[this.#e].type=="CLOSE"}#P(){return this.#c(this.#e,"[")}#S(){return this.#c(this.#e,"]")}#l(){let e=this.#o[this.#e],t=this.#x(this.#a).index;return this.#i.substring(t,e.index)}#O(){let e={};Object.assign(e,so),e.encodePart=Yp;let t=eS(this.#l(),void 0,e);this.#f=eb(t)}},Kp=["protocol","username","password","hostname","port","pathname","search","hash"],no="*";function qx(e,t){if(typeof e!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(e,t);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}function Ar(e,t){return t?ks(e):e}function ws(e,t,r){let o;if(typeof t.baseURL=="string")try{o=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=Ar(o.protocol.substring(0,o.protocol.length-1),r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=Ar(o.username,r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=Ar(o.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=Ar(o.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=Ar(o.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=Ar(o.pathname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=Ar(o.search.substring(1,o.search.length),r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=Ar(o.hash.substring(1,o.hash.length),r))}catch{throw new TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol=="string"&&(e.protocol=mS(t.protocol,r)),typeof t.username=="string"&&(e.username=lS(t.username,r)),typeof t.password=="string"&&(e.password=cS(t.password,r)),typeof t.hostname=="string"&&(e.hostname=aS(t.hostname,r)),typeof t.port=="string"&&(e.port=uS(t.port,e.protocol,r)),typeof t.pathname=="string"){if(e.pathname=t.pathname,o&&!oS(e.pathname,r)){let n=o.pathname.lastIndexOf("/");n>=0&&(e.pathname=Ar(o.pathname.substring(0,n+1),r)+e.pathname)}e.pathname=pS(e.pathname,e.protocol,r)}return typeof t.search=="string"&&(e.search=iS(t.search,r)),typeof t.hash=="string"&&(e.hash=sS(t.hash,r)),e}function ks(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function ES(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function wS(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let r=".*",o=`[^${ES(t.delimiter)}]+?`,n=/[$_\u200C\u200D\p{ID_Continue}]/u,s="";for(let i=0;i<e.length;++i){let a=e[i];if(a.type===3){if(a.modifier===3){s+=ks(a.value);continue}s+=`{${ks(a.value)}}${Sn(a.modifier)}`;continue}let c=a.hasCustomName(),l=!!a.suffix.length||!!a.prefix.length&&(a.prefix.length!==1||!t.prefixes.includes(a.prefix)),u=i>0?e[i-1]:null,p=i<e.length-1?e[i+1]:null;if(!l&&c&&a.type===1&&a.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let f=p.value.length>0?p.value[0]:"";l=n.test(f)}else l=!p.hasCustomName();if(!l&&!a.prefix.length&&u&&u.type===3){let f=u.value[u.value.length-1];l=t.prefixes.includes(f)}l&&(s+="{"),s+=ks(a.prefix),c&&(s+=`:${a.name}`),a.type===2?s+=`(${a.value})`:a.type===1?c||(s+=`(${o})`):a.type===0&&(!c&&(!u||u.type===3||u.modifier!==3||l||a.prefix!=="")?s+="*":s+=`(${r})`),a.type===1&&c&&a.suffix.length&&n.test(a.suffix[0])&&(s+="\\"),s+=ks(a.suffix),l&&(s+="}"),a.modifier!==3&&(s+=Sn(a.modifier))}return s}var sb=class{#i;#o={};#t={};#e={};#s={};#a=!1;constructor(e={},t,r){try{let o;if(typeof t=="string"?o=t:r=t,typeof e=="string"){let a=new bS(e);if(a.parse(),e=a.result,o===void 0&&typeof e.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");e.baseURL=o}else{if(!e||typeof e!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(o)throw new TypeError("parameter 1 is not of type 'string'.")}typeof r>"u"&&(r={ignoreCase:!1});let n={ignoreCase:r.ignoreCase===!0},s={pathname:no,protocol:no,username:no,password:no,hostname:no,port:no,search:no,hash:no};this.#i=ws(s,e,!0),tb(this.#i.protocol)===this.#i.port&&(this.#i.port="");let i;for(i of Kp){if(!(i in this.#i))continue;let a={},c=this.#i[i];switch(this.#t[i]=[],i){case"protocol":Object.assign(a,so),a.encodePart=Yp;break;case"username":Object.assign(a,so),a.encodePart=fS;break;case"password":Object.assign(a,so),a.encodePart=dS;break;case"hostname":Object.assign(a,tS),Qx(c)?a.encodePart=ob:a.encodePart=rb;break;case"port":Object.assign(a,so),a.encodePart=nb;break;case"pathname":eb(this.#o.protocol)?(Object.assign(a,rS,n),a.encodePart=hS):(Object.assign(a,so,n),a.encodePart=gS);break;case"search":Object.assign(a,so,n),a.encodePart=yS;break;case"hash":Object.assign(a,so,n),a.encodePart=xS;break}try{this.#s[i]=Xx(c,a),this.#o[i]=Yx(this.#s[i],this.#t[i],a),this.#e[i]=wS(this.#s[i],a),this.#a=this.#a||this.#s[i].some(l=>l.type===2)}catch{throw new TypeError(`invalid ${i} pattern '${this.#i[i]}'.`)}}}catch(o){throw new TypeError(`Failed to construct 'URLPattern': ${o.message}`)}}test(e={},t){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof e!="string"&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return!1;try{typeof e=="object"?r=ws(r,e,!1):r=ws(r,qx(e,t),!1)}catch{return!1}let o;for(o of Kp)if(!this.#o[o].exec(r[o]))return!1;return!0}exec(e={},t){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof e!="string"&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return;try{typeof e=="object"?r=ws(r,e,!1):r=ws(r,qx(e,t),!1)}catch{return null}let o={};t?o.inputs=[e,t]:o.inputs=[e];let n;for(n of Kp){let s=this.#o[n].exec(r[n]);if(!s)return null;let i={};for(let[a,c]of this.#t[n].entries())if(typeof c=="string"||typeof c=="number"){let l=s[a+1];i[c]=l}o[n]={input:r[n]??"",groups:i}}return o}static compareComponent(e,t,r){let o=(a,c)=>{for(let l of["type","modifier","prefix","value","suffix"]){if(a[l]<c[l])return-1;if(a[l]!==c[l])return 1}return 0},n=new Rs(3,"","","","",3),s=new Rs(0,"","","","",3),i=(a,c)=>{let l=0;for(;l<Math.min(a.length,c.length);++l){let u=o(a[l],c[l]);if(u)return u}return a.length===c.length?0:o(a[l]??n,c[l]??n)};return!t.#e[e]&&!r.#e[e]?0:t.#e[e]&&!r.#e[e]?i(t.#s[e],[s]):!t.#e[e]&&r.#e[e]?i([s],r.#s[e]):i(t.#s[e],r.#s[e])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#a}};globalThis.URLPattern||(globalThis.URLPattern=sb);var ib,ab=async(e,t)=>(ib??=La({wasm:e,worker:t}),await ib,async r=>{let{outputFiles:o}=await Sa({entryPoints:[r],format:"esm",bundle:!0,minify:!0,charset:"utf8",plugins:[Vy(),Vx({fetch:kS,reload:[new URLPattern({hostname:location.hostname}),new URLPattern({hostname:"scrapbox.io"})]})],write:!1});return{contents:o[0].text}}),kS=async(e,t)=>{let r=Qy(new URL(e.url))||!GM_fetch?globalThis.fetch:GM_fetch;if(t){let o=await Jp(e);if(o)return o}try{let o=await r(e);return o.ok?(r===GM_fetch&&!e.url.startsWith("data:")&&await Wi(e,o),ae([o,!1])):await Jp(e)??Q({name:"HTTPError",message:`${o.status} ${o.statusText}`,response:o})}catch(o){let n=await Jp(e);if(n)return n;if(o instanceof TypeError)return Q({name:"NetworkError",message:o.message,request:e});if(o instanceof DOMException)return Q({name:"AbortError",message:o.message,request:e});throw o}},Jp=async e=>{if(e.url.startsWith("data:"))return;let t=await an(e);if(t)return t.url||Object.defineProperty(t,"url",{value:e.url}),ae([t,!0])};var cb=e=>["ts","js","tsx","jsx","mjs","javascript","typescript"].includes(e);var lb=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle-fill"),e.style.color="hsl(133, 46.1%, 47.3%)",e},pb=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-cross-circle"),e.style.color="hsl(1.7, 64.5%, 58%)",e},ub=()=>{let e=document.createElement("i");return e.classList.add("i","fa","fa-spinner"),e},mb=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-play"),e};var fb=()=>{let e;return{show:(o,{x:n,y:s})=>{e=RS(),e.append(vS(o)),e.style.visibility="hidden",document.body.append(e);let{height:i}=e.getBoundingClientRect();e.style.top=`${s-i}px`,e.style.left=`${n}px`,e.style.removeProperty("visibility")},hide:async()=>{e?.classList?.remove?.("in"),await new Promise(o=>setTimeout(o,150)),e?.remove?.()}}},RS=()=>{let e=document.createElement("div");return e.setAttribute("role","tooltip"),e.classList.add("fade","in","tooltip","top"),e},vS=e=>{let t=document.createElement("pre");return t.classList.add("tooltip-inner"),t.style.textAlign="unset",t.style.maxWidth="70vw",t.style.margin="unset",t.innerText=e,t};var db=()=>{let e=document.createElement("a");e.classList.add("tool-btn"),e.type="button",e.setAttribute("aria-haspopup","true");let t=!1,{show:r,hide:o}=fb();return{component:e,setStatus:async(s,i)=>{switch(e.textContent="",await o(),s){case"loading":e.append(ub());break;case"pass":e.append(lb());break;case"fail":e.append(pb());break;case"none":break}i!==void 0&&s!=="none"?(e.style.removeProperty("pointer-events"),e.onclick=async()=>{if(t)await o();else{let{top:a,left:c}=e.getBoundingClientRect();r(i,{y:a+globalThis.scrollY,x:c})}t=!t}):e.style.pointerEvents="none"}}};var hb=e=>{let t=document.createElement("a");return t.classList.add("tool-btn"),t.type="button",t.setAttribute("aria-haspopup","true"),t.append(mb()),t.addEventListener("click",e),t};var gb=e=>{let{component:t,setStatus:r}=db(),o=document.createElement("div");return o.style.position="absolute",o.style.left="-2em",o.style.zIndex="1",o.style.display="flex",o.style.flexFlow="column",o.append(hb(e),t),{menu:o,setStatus:r}};function yb(e){return new Promise(t=>setTimeout(t,e))}function xb(e,t){let{trailing:r=!1,interval:o=0}=t??{},n,s=!1,i=l=>{n?.resolve?.({executed:!1}),n=l},a=()=>{let{...l}=n;return n=void 0,l},c=async()=>{if(s||!n)return;s=!0,o>0&&await yb(o);let{parameters:l,resolve:u,reject:p}=a();try{let f=await e(...l);s=!1,u({result:f,executed:!0})}catch(f){s=!1,p(f)}finally{r?await c():(i(),await Promise.resolve())}};return(...l)=>new Promise((u,p)=>{i({parameters:l,resolve:u,reject:p}),c()})}var bb,Eb=async(e,t)=>{let r=[],n=xb(async()=>{r.forEach(({menu:i,setStatus:a})=>{a("none"),i.remove()});let s=ly(scrapbox.Project.name,scrapbox.Page.title??"",ft());for(let i of s){let a=i.lang.toLowerCase();if(cb(a))for(let c of i.startIds){let l=document.getElementById(`L${c}`),{menu:u,setStatus:p}=gb(async()=>{await p("loading");try{bb??=await ab(e,t);let{contents:f}=await bb(i.path);console.debug("execute:",f),await Function(`return (async()=>{${f}})()`)(),await p("pass")}catch(f){console.error(f),await p("fail",`${f}`)}});r.push({menu:u,setStatus:p}),l?.insertBefore?.(u,l?.firstElementChild)}}await Promise.resolve()},{interval:100,trailing:!0});return await n(),scrapbox.addListener("lines:changed",n),()=>{scrapbox.removeListener("lines:changed",n),r.forEach(({menu:s,setStatus:i})=>{i("none"),s.remove()})}};function _S(e,t){for(var r in t)e[r]=t[r];return e}function wb(e,t){for(var r in e)if(r!=="__source"&&!(r in t))return!0;for(var o in t)if(o!=="__source"&&e[o]!==t[o])return!0;return!1}function On(e,t){var r=t(),o=J({t:{__:r,u:t}}),n=o[0].t,s=o[1];return Li(function(){n.__=r,n.u=t,Qp(n)&&s({t:n})},[e,r,t]),oe(function(){return Qp(n)&&s({t:n}),e(function(){Qp(n)&&s({t:n})})},[e]),r}function Qp(e){var t,r,o=e.u,n=e.__;try{var s=o();return!((t=n)===(r=s)&&(t!==0||1/t==1/r)||t!=t&&r!=r)}catch{return!0}}function kb(e,t){this.props=e,this.context=t}(kb.prototype=new Yt).isPureReactComponent=!0,kb.prototype.shouldComponentUpdate=function(e,t){return wb(this.props,e)||wb(this.state,t)};var Rb=Z.__b;Z.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Rb&&Rb(e)};var nve=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;var PS=Z.__e;Z.__e=function(e,t,r,o){if(e.then){for(var n,s=t;s=s.__;)if((n=s.__c)&&n.__c)return t.__e==null&&(t.__e=r.__e,t.__k=r.__k),n.__c(e,t)}PS(e,t,r,o)};var vb=Z.unmount;function Lb(e,t,r){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(o){typeof o.__c=="function"&&o.__c()}),e.__c.__H=null),(e=_S({},e)).__c!=null&&(e.__c.__P===r&&(e.__c.__P=t),e.__c=null),e.__k=e.__k&&e.__k.map(function(o){return Lb(o,t,r)})),e}function Nb(e,t,r){return e&&r&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(o){return Nb(o,t,r)}),e.__c&&e.__c.__P===t&&(e.__e&&r.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=r)),e}function Zp(){this.__u=0,this.o=null,this.__b=null}function Cb(e){var t=e.__.__c;return t&&t.__a&&t.__a(e)}function ec(){this.i=null,this.l=null}Z.unmount=function(e){var t=e.__c;t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),vb&&vb(e)},(Zp.prototype=new Yt).__c=function(e,t){var r=t.__c,o=this;o.o==null&&(o.o=[]),o.o.push(r);var n=Cb(o.__v),s=!1,i=function(){s||(s=!0,r.__R=null,n?n(a):a())};r.__R=i;var a=function(){if(!--o.__u){if(o.state.__a){var c=o.state.__a;o.__v.__k[0]=Nb(c,c.__c.__P,c.__c.__O)}var l;for(o.setState({__a:o.__b=null});l=o.o.pop();)l.forceUpdate()}};o.__u++||32&t.__u||o.setState({__a:o.__b=o.__v.__k[0]}),e.then(i,i)},Zp.prototype.componentWillUnmount=function(){this.o=[]},Zp.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var r=document.createElement("div"),o=this.__v.__k[0].__c;this.__v.__k[0]=Lb(this.__b,r,o.__O=o.__P)}this.__b=null}var n=t.__a&&xr(Y,null,e.fallback);return n&&(n.__u&=-33),[xr(Y,null,t.__a?null:e.children),n]};var Tb=function(e,t,r){if(++r[1]===r[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(r=e.i;r;){for(;r.length>3;)r.pop()();if(r[1]<r[0])break;e.i=r=r[2]}};(ec.prototype=new Yt).__a=function(e){var t=this,r=Cb(t.__v),o=t.l.get(e);return o[0]++,function(n){var s=function(){t.props.revealOrder?(o.push(n),Tb(t,e,o)):n()};r?r(s):s()}},ec.prototype.render=function(e){this.i=null,this.l=new Map;var t=$r(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var r=t.length;r--;)this.l.set(t[r],this.i=[1,0,this.i]);return e.children},ec.prototype.componentDidUpdate=ec.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,r){Tb(e,r,t)})};var SS=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,OS=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,LS=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,NS=/[A-Z0-9]/g,CS=typeof document<"u",AS=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};Yt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(Yt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var _b=Z.event;function MS(){}function IS(){return this.cancelBubble}function FS(){return this.defaultPrevented}Z.event=function(e){return _b&&(e=_b(e)),e.persist=MS,e.isPropagationStopped=IS,e.isDefaultPrevented=FS,e.nativeEvent=e};var Ab,US={enumerable:!1,configurable:!0,get:function(){return this.class}},Pb=Z.vnode;Z.vnode=function(e){typeof e.type=="string"&&function(t){var r=t.props,o=t.type,n={},s=o.indexOf("-")===-1;for(var i in r){var a=r[i];if(!(i==="value"&&"defaultValue"in r&&a==null||CS&&i==="children"&&o==="noscript"||i==="class"||i==="className")){var c=i.toLowerCase();i==="defaultValue"&&"value"in r&&r.value==null?i="value":i==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?i="ondblclick":c!=="onchange"||o!=="input"&&o!=="textarea"||AS(r.type)?c==="onfocus"?i="onfocusin":c==="onblur"?i="onfocusout":LS.test(i)&&(i=c):c=i="oninput":s&&OS.test(i)?i=i.replace(NS,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&n[i=c]&&(i="oninputCapture"),n[i]=a}}o=="select"&&n.multiple&&Array.isArray(n.value)&&(n.value=$r(r.children).forEach(function(l){l.props.selected=n.value.indexOf(l.props.value)!=-1})),o=="select"&&n.defaultValue!=null&&(n.value=$r(r.children).forEach(function(l){l.props.selected=n.multiple?n.defaultValue.indexOf(l.props.value)!=-1:n.defaultValue==l.props.value})),r.class&&!r.className?(n.class=r.class,Object.defineProperty(n,"className",US)):(r.className&&!r.class||r.class&&r.className)&&(n.class=n.className=r.className),t.props=n}(e),e.$$typeof=SS,Pb&&Pb(e)};var Sb=Z.__r;Z.__r=function(e){Sb&&Sb(e),Ab=e.__c};var Ob=Z.diffed;Z.diffed=function(e){Ob&&Ob(e);var t=e.props,r=e.__e;r!=null&&e.type==="textarea"&&"value"in t&&t.value!==r.value&&(r.value=t.value==null?"":t.value),Ab=null};var vs=e=>e.replaceAll(" ","_").toLowerCase(),Mb=e=>e.replaceAll("_"," "),tc=e=>[...e].map((t,r)=>t===" "?"_":!DS.includes(t)||r===e.length-1&&$S.includes(t)?encodeURIComponent(t):t).join(""),DS='@$&+=:;",',$S=':;",';var Ib=({title:e,projects:t,selected:r,confirm:o})=>d("div",{className:`candidate${r?" selected":""}`,children:[d(jS,{title:e,confirm:o}),t.map(n=>d(BS,{project:n.name,title:e,mark:n.mark,confirm:n.confirm}))]}),jS=({title:e,confirm:t})=>d("a",{className:"button",tabIndex:0,role:"menuitem",href:`./${tc(e)}`,onClick:Fb(t),children:e}),BS=({project:e,title:t,mark:r,confirm:o})=>r===""?d(Y,{}):d("a",{className:"mark",tabIndex:0,href:`../${e}/${tc(t)}`,onClick:Fb(o),title:`/${e}/${tc(t)}`,children:r instanceof URL?d("img",{src:r.href}):`[${r}]`}),Fb=e=>F(t=>{t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),t.stopPropagation(),e())},[e]);var Ub=(e,t)=>{let[r,o]=J(null),n=F(c=>o(l=>{if(e.length===0)return null;if(l===null)return t(e[0]);let u=e.findIndex(p=>t(p)===l);return t(c?.cyclic?e[(u+1)%e.length]:e.at(u+1)??e[0])}),[e,t]),s=F(c=>o(l=>{if(e.length===0)return null;if(l===null)return t(e[e.length-1]);let u=e.findIndex(p=>t(p)===l);return u<0?t(e[e.length-1]):t(c?.cyclic?e[(u-1+e.length)%e.length]:e.at(u-1)??e[e.length-1])}),[e,t]),i=F(()=>o(e.length===0?null:t(e[0])),[e,t]),a=F(()=>o(e.length===0?null:t(e[e.length-1])),[e,t]);return{selectedId:r,next:n,prev:s,selectFirst:i,selectLast:a}};var Db=e=>{let[t,r]=J(null),o=C(()=>{let n=t?.getBoundingClientRect?.(),i=Qn(e.line,e.char)?.getBoundingClientRect?.();return!i||!n?{}:{top:`${i.bottom-n.top}px`,left:`${i?.left??0-n.left}px`,right:`${n.right-(i?.left??0)}px`}},[t,e.line,e.char]);return{updateStandardElement:r,...o}};var tu="enableProjectsOnSuggestion",$b=(e,t)=>{let[r,o]=J(rc([...e],t)),n=F((s,i)=>{HS(s,i,e,t),o(rc([...e],t))},[e,t.enableSelfProjectOnStart]);return oe(()=>{let s=i=>{i.key===tu&&o(rc([...e],t))};return addEventListener("storage",s),()=>removeEventListener("storage",s)},[e,t.enableSelfProjectOnStart]),{projects:r,set:n}},eu=!0,rc=(e,t)=>{try{let r=localStorage.getItem(tu);if(r===null)return oc(e),e;let o=JSON.parse(r);return Array.isArray(o)&&o.every(n=>typeof n=="string")?!t.enableSelfProjectOnStart||!e.includes(scrapbox.Project.name)?o:o.includes(scrapbox.Project.name)?eu?o:o.filter(n=>n!==scrapbox.Project.name):eu?[...o,scrapbox.Project.name]:o:(oc(e),e)}catch(r){if(!(r instanceof TypeError))throw r;return oc(e),e}},HS=(e,t,r,o)=>{let n=rc([...r],o);o.enableSelfProjectOnStart&&e===scrapbox.Project.name&&(eu=t),oc(t?[...n,e]:n.filter(s=>s!==e))},oc=e=>localStorage.setItem(tu,JSON.stringify(e));var jb=()=>C(()=>document.documentElement.dataset.os??"",[]);var Ts=(e,t)=>{if(e instanceof URL)return e;try{return new URL(e)}catch(r){if(!(r instanceof TypeError))throw r;if(!t||!/^\.\/|^\.\.\/|^\//.test(e))return e;try{return new URL(e,t)}catch(o){if(!(o instanceof TypeError))throw o;return e}}};var Bb=({progress:e})=>d("div",{className:"progress",style:`background: linear-gradient(to right, var(--select-suggest-border-color, #eee) ${(e*100).toPrecision(3)}%, transparent ${(e*100).toPrecision(3)}%)`});var Wb=({position:e,start:t,enableSelfProjectOnStart:r,projects:o,...n})=>{let{projects:s,set:i}=$b(o,{enableSelfProjectOnStart:r}),{updateStandardElement:a,top:c,left:l,right:u}=Db({line:e.line,char:t}),p=jb();return d(Y,{children:[d(GS,{itemCount:n.items.length,enableProjects:s,projects:o,top:c,right:u,set:i,os:p,...n}),d(WS,{updateStandardElement:a,start:t,enableProjects:s,projects:o,top:c,left:l,os:p,...n})]})},WS=({start:e,updateStandardElement:t,confirmAfter:r,cancel:o,query:n,enableProjects:s,projects:i,items:a,top:c,left:l,progress:u,callback:p,limit:f,mark:m,os:h})=>{let g=F((P,T,_)=>{let S=`[${T?`/${T}/${P}`:P}${_?.icon?".icon":""}]`;r((A,{line:M})=>[`${[...A].slice(0,e).join("")}${S}${[...A].slice(e+[...n].length).join("")}`,{line:M,char:e+[...S].length}])},[e,n]),y=C(()=>i.size>1||!i.has(scrapbox.Project.name),[i]),x=C(()=>{let P=[];for(let T of a){if(P.length===f)break;T.projects.some(_=>s.includes(_))&&P.push({title:T.title,projects:T.projects.flatMap(_=>s.includes(_)?[{name:_,mark:y?Ts(m[_]??"",import.meta.url)||_[0]:"",confirm:S=>g(T.title,_,S)}]:[]),confirm:_=>g(T.title,void 0,_)})}return P},[s,y,a,f,m,g]),{selectedId:E,next:R,prev:b,selectLast:v,selectFirst:k}=Ub(x,Hb),O=F(P=>E===null?!1:(x.find(T=>Hb(T)===E)?.confirm?.(P),!0),[E,x]);oe(()=>p(x.length===0?void 0:{selectNext:P=>(R(P),!0),selectPrev:P=>(b(P),!0),selectFirst:()=>(k(),!0),selectLast:()=>(v(),!0),confirm:O,cancel:()=>(o(),!0)}),[p,x.length,R,b,k,v,O]);let L=C(()=>x.length>0&&c!=null&&l!=null?{top:c,left:l}:{display:"none"},[x.length,c,l]),N=F(P=>{if(!P){t(P);return}let T=P.parentNode;if(!(T instanceof ShadowRoot))throw Error('The parent of "div.container" must be ShadowRoot');t(T.host.parentElement)},[t]);return d("div",{ref:N,className:"container candidates","data-os":h,style:L,children:[x.map(P=>d(Ib,{...P,selected:E===P.title},P.title)),a.length>f&&d("div",{className:"counter",children:`${a.length-f} more links`}),d(Bb,{progress:u})]})},GS=({enableProjects:e,projects:t,projectScore:r,mark:o,itemCount:n,top:s,right:i,set:a,os:c,freezeUntil:l})=>{let u=C(()=>[...t].sort((f,m)=>(r.get(m)??0)-(r.get(f)??0)).flatMap(f=>r.has(f)?[{name:f,enable:e.includes(f),mark:Ts(o[f]??"",import.meta.url)||f[0],score:r.get(f),onClick:()=>l(()=>{a(f,!e.includes(f)),Xe().focus()})}]:[]),[t,r,e,o]),p=C(()=>n>0&&s!=null&&i!=null&&t.size>1?{top:s,right:i}:{display:"none"},[s,i,n,t.size]);return d("div",{className:"container projects","data-os":c,style:p,children:u.map(f=>d(VS,{...f},f.name))})},VS=e=>d("div",{className:e.enable?"mark":"mark disabled","data-score":e.score.toPrecision(3),onClick:e.onClick,title:e.name,children:e.mark instanceof URL?d("img",{src:e.mark.href}):`[${e.mark}]`}),Hb=e=>e.title;var Gb=function(){};function Ps(e,t={}){Gb.prototype.name=e;let r={};return new Proxy(Gb,{get(o,n){return n==="caller"?null:n==="__createMock__"?Ps:n==="__unenv__"?!0:n in t?t[n]:r[n]=r[n]||Ps(`${e}.${n.toString()}`)},apply(o,n,s){return Ps(`${e}()`)},construct(o,n,s){return Ps(`[${e}]`)},enumerate(){return[]}})}var ru=Ps("mock");function zS(e){return new Error(`[unenv] ${e} is not implemented yet!`)}function pe(e){return Object.assign(()=>{throw zS(e)},{__unenv__:!0})}var qS=Object.freeze(Object.create(null,{__unenv__:{get:()=>!0}})),nc=Object.create(null),KS=globalThis.process?.env,_s=e=>KS||globalThis.__env__||(e?nc:globalThis),XS=new Proxy(nc,{get(e,t){return _s()[t]??nc[t]},has(e,t){let r=_s();return t in r||t in nc},set(e,t,r){let o=_s(!0);return o[t]=r,!0},deleteProperty(e,t){let r=_s(!0);return delete r[t],!0},ownKeys(){let e=_s();return Object.keys(e)}}),YS=Object.assign(function(e){let t=Date.now(),r=Math.trunc(t/1e3),o=t%1e3*1e6;if(e){let n=r-e[0],s=o-e[0];return s<0&&(n=n-1,s=1e9+s),[n,s]}return[r,o]},{bigint:function(){return BigInt(Date.now()*1e6)}}),JS=globalThis.queueMicrotask?(e,...t)=>{globalThis.queueMicrotask(e.bind(void 0,...t))}:QS();function QS(){let e=[],t=!1,r,o=-1;function n(){!t||!r||(t=!1,r.length>0?e=[...r,...e]:o=-1,e.length>0&&s())}function s(){if(t)return;let i=setTimeout(n);t=!0;let a=e.length;for(;a;){for(r=e,e=[];++o<a;)r&&r[o]();o=-1,a=e.length}r=void 0,t=!1,clearTimeout(i)}return(i,...a)=>{e.push(i.bind(void 0,...a)),e.length===1&&!t&&setTimeout(s)}}var ZS="unenv",eO=[],tO="",rO={ares:"",http_parser:"",icu:"",modules:"",node:"",openssl:"",uv:"",v8:"",zlib:""};function tr(){return ou}var oO=tr,nO=tr,sO=tr,iO=tr,aO=tr,cO=tr,lO=function(e){return e==="message"||e==="multipleResolves"?ou:!1},pO=tr,uO=tr,mO=function(e){return[]},fO=()=>0,dO=function(e){throw new Error("[unenv] process.binding is not supported")},Vb="/",hO=function(){return Vb},gO=function(e){Vb=e},yO=function(){return 0},xO=function(){return 1e3},bO=function(){return 1e3},EO=function(){return 1e3},wO=function(){return 1e3},kO=function(){return[]},RO=e=>{},vO=pe("process.abort"),TO=new Set,_O="",PO="",SO=qS,OO=!1,LO=()=>0,NO=()=>0,CO=pe("process.cpuUsage"),AO=0,MO=pe("process.dlopen"),IO=tr,FO=tr,UO=pe("process.eventNames"),DO=[],$O="",jO=pe("process.exit"),BO=Object.create({inspector:void 0,debug:void 0,uv:void 0,ipv6:void 0,tls_alpn:void 0,tls_sni:void 0,tls_ocsp:void 0,tls:void 0,cached_builtins:void 0}),HO=()=>[],WO=pe("process.getMaxListeners"),GO=pe("process.kill"),VO=Object.assign(()=>({arrayBuffers:0,rss:0,external:0,heapTotal:0,heapUsed:0}),{rss:()=>0}),zO=1e3,qO="",KO=1e3,XO=pe("process.rawListeners"),YO=Object.create({name:"",lts:"",sourceUrl:void 0,headersUrl:void 0}),JO=Object.create({compact:void 0,directory:void 0,filename:void 0,getReport:pe("process.report.getReport"),reportOnFatalError:void 0,reportOnSignal:void 0,reportOnUncaughtException:void 0,signal:void 0,writeReport:pe("process.report.writeReport")}),QO=pe("process.resourceUsage"),ZO=pe("process.setegid"),eL=pe("process.seteuid"),tL=pe("process.setgid"),rL=pe("process.setgroups"),oL=pe("process.setuid"),nL=pe("process.setMaxListeners"),sL=pe("process.setSourceMapsEnabled"),iL=ru.__createMock__("process.stdout"),aL=ru.__createMock__("process.stderr"),cL=ru.__createMock__("process.stdin"),lL=!1,pL=()=>0,uL=0,mL=pe("process.setUncaughtExceptionCaptureCallback"),fL=()=>!1,dL=!1,hL=pe("process.loadEnvFile"),gL=void 0,yL={has:()=>!1},xL={ref(){},unref(){}},bL=!1,EL={register(){},unregister(){},registerBeforeExit(){}},wL=pe("process.assert"),kL=pe("process.openStdin"),RL=pe("process._debugEnd"),vL=pe("process._debugProcess"),TL=pe("process._fatalException"),_L=pe("process._getActiveHandles"),PL=pe("process._getActiveRequests"),SL=pe("process._kill"),OL=[],LL=pe("process._rawDebug"),NL=pe("process._startProfilerIdleNotifier"),CL=pe("process.__stopProfilerIdleNotifier"),AL=pe("process._tickCallback"),Qve=pe("process._linkedBinding"),ML=void 0,IL=pe("process.initgroups"),FL=[],UL=tr,DL=!1,$L=[],jL=0,BL=0,ou={_events:$L,_eventsCount:jL,_exiting:DL,_maxListeners:BL,_debugEnd:RL,_debugProcess:vL,_fatalException:TL,_getActiveHandles:_L,_getActiveRequests:PL,_kill:SL,_preload_modules:OL,_rawDebug:LL,_startProfilerIdleNotifier:NL,_stopProfilerIdleNotifier:CL,_tickCallback:AL,domain:ML,initgroups:IL,moduleLoadList:FL,reallyExit:UL,exitCode:uL,abort:vO,addListener:nO,allowedNodeEnvironmentFlags:TO,hasUncaughtExceptionCaptureCallback:fL,setUncaughtExceptionCaptureCallback:mL,loadEnvFile:hL,sourceMapsEnabled:dL,throwDeprecation:bL,mainModule:gL,permission:yL,channel:xL,arch:_O,argv:eO,argv0:PO,assert:wL,binding:dO,chdir:gO,config:SO,connected:OO,constrainedMemory:LO,availableMemory:NO,cpuUsage:CO,cwd:hO,debugPort:AO,dlopen:MO,disconnect:IO,emit:lO,emitWarning:FO,env:XS,eventNames:UO,execArgv:DO,execPath:$O,exit:jO,finalization:EL,features:BO,getBuiltinModule:RO,getegid:xO,geteuid:bO,getgid:EO,getgroups:kO,getuid:wO,getActiveResourcesInfo:HO,getMaxListeners:WO,hrtime:YS,kill:GO,listeners:mO,listenerCount:fO,memoryUsage:VO,nextTick:JS,on:oO,off:iO,once:sO,openStdin:kL,pid:zO,platform:qO,ppid:KO,prependListener:pO,prependOnceListener:uO,rawListeners:XO,release:YO,removeAllListeners:cO,removeListener:aO,report:JO,resourceUsage:QO,setegid:ZO,seteuid:eL,setgid:tL,setgroups:rL,setuid:oL,setMaxListeners:nL,setSourceMapsEnabled:sL,stderr:aL,stdin:cL,stdout:iL,title:ZS,traceDeprecation:lL,umask:yO,uptime:pL,version:tO,versions:rO},Ss=ou;var HL=Object.create,Jb=Object.defineProperty,WL=Object.getOwnPropertyDescriptor,GL=Object.getOwnPropertyNames,VL=Object.getPrototypeOf,zL=Object.prototype.hasOwnProperty,Qb=(e=>typeof co<"u"?co:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof co<"u"?co:t)[r]}):e)(function(e){if(typeof co<"u")return co.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Zb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qL=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of GL(t))!zL.call(e,n)&&n!==r&&Jb(e,n,{get:()=>t[n],enumerable:!(o=WL(t,n))||o.enumerable});return e},eE=(e,t,r)=>(r=e!=null?HL(VL(e)):{},qL(t||!e||!e.__esModule?Jb(r,"default",{value:e,enumerable:!0}):r,e)),KL=Zb((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in Ss&&"node"in Ss.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[Qb][0](`${["node","util"].join(":")}`)}catch{r=null}t.exports=r}),XL=Zb((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in Ss&&"node"in Ss.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[Qb][0](`${["node","fs"].join(":")}`)}catch{r=null}t.exports=r}),YL={},sc=JL(globalThis,YL);function JL(e,t){return new Proxy(e,{get(r,o,n){return o in t?t[o]:e[o]},set(r,o,n){return o in t&&delete t[o],e[o]=n,!0},deleteProperty(r,o){let n=!1;return o in t&&(delete t[o],n=!0),o in e&&(delete e[o],n=!0),n},ownKeys(r){let o=Reflect.ownKeys(e),n=Reflect.ownKeys(t),s=new Set(n);return[...o.filter(i=>!s.has(i)),...n]},defineProperty(r,o,n){return o in t&&delete t[o],Reflect.defineProperty(e,o,n),!0},getOwnPropertyDescriptor(r,o){return o in t?Reflect.getOwnPropertyDescriptor(t,o):Reflect.getOwnPropertyDescriptor(e,o)},has(r,o){return o in t||o in e}})}var zb=["debug","info","warning","error","fatal"];function qb(e,t){let r=zb.indexOf(e);if(r<0)throw new TypeError(`Invalid log level: ${JSON.stringify(e)}.`);let o=zb.indexOf(t);if(o<0)throw new TypeError(`Invalid log level: ${JSON.stringify(t)}.`);return r-o}function Ls(e=[]){return tE.getLogger(e)}var nu=Symbol.for("logtape.rootLogger"),tE=class io{static getLogger(t=[]){let r=nu in sc?sc[nu]??null:null;return r==null&&(r=new io(null,[]),sc[nu]=r),typeof t=="string"?r.getChild(t):t.length===0?r:r.getChild(t)}constructor(t,r){Object.defineProperty(this,"parent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"children",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"category",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sinks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parentSinks",{enumerable:!0,configurable:!0,writable:!0,value:"inherit"}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lowestLevel",{enumerable:!0,configurable:!0,writable:!0,value:"debug"}),Object.defineProperty(this,"contextLocalStorage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.parent=t,this.children={},this.category=r,this.sinks=[],this.filters=[]}getChild(t){let r=typeof t=="string"?t:t[0],o=this.children[r],n=o instanceof io?o:o?.deref();return n==null&&(n=new io(this,[...this.category,r]),this.children[r]="WeakRef"in sc?new WeakRef(n):n),typeof t=="string"||t.length===1?n:n.getChild(t.slice(1))}reset(){for(;this.sinks.length>0;)this.sinks.shift();for(this.parentSinks="inherit";this.filters.length>0;)this.filters.shift();this.lowestLevel="debug"}resetDescendants(){for(let t of Object.values(this.children))(t instanceof io?t:t.deref())?.resetDescendants();this.reset()}with(t){return new QL(this,{...t})}filter(t){for(let r of this.filters)if(!r(t))return!1;return this.filters.length<1?this.parent?.filter(t)??!0:!0}*getSinks(t){if(!(this.lowestLevel===null||qb(t,this.lowestLevel)<0)){if(this.parent!=null&&this.parentSinks==="inherit")for(let r of this.parent.getSinks(t))yield r;for(let r of this.sinks)yield r}}emit(t,r){if(!(this.lowestLevel===null||qb(t.level,this.lowestLevel)<0||!this.filter(t))){for(let o of this.getSinks(t.level))if(!r?.has(o))try{o(t)}catch(n){let s=new Set(r);s.add(o),ZL.log("fatal","Failed to emit a log record to sink {sink}: {error}",{sink:o,error:n,record:t},s)}}}log(t,r,o,n){let s=io.getLogger().contextLocalStorage?.getStore()??{},i,a=typeof o=="function"?{category:this.category,level:t,timestamp:Date.now(),get message(){return Kb(r,this.properties)},rawMessage:r,get properties(){return i==null&&(i={...s,...o()}),i}}:{category:this.category,level:t,timestamp:Date.now(),message:Kb(r,{...s,...o}),rawMessage:r,properties:{...s,...o}};this.emit(a,n)}logLazily(t,r,o={}){let n=io.getLogger().contextLocalStorage?.getStore()??{},s,i;function a(){if((i==null||s==null)&&(i=r((c,...l)=>(s=c,Xb(c,l))),s==null))throw new TypeError("No log record was made.");return[i,s]}this.emit({category:this.category,level:t,get message(){return a()[0]},get rawMessage(){return a()[1]},timestamp:Date.now(),properties:{...n,...o}})}logTemplate(t,r,o,n={}){let s=io.getLogger().contextLocalStorage?.getStore()??{};this.emit({category:this.category,level:t,message:Xb(r,o),rawMessage:r,timestamp:Date.now(),properties:{...s,...n}})}debug(t,...r){typeof t=="string"?this.log("debug",t,r[0]??{}):typeof t=="function"?this.logLazily("debug",t):this.logTemplate("debug",t,r)}info(t,...r){typeof t=="string"?this.log("info",t,r[0]??{}):typeof t=="function"?this.logLazily("info",t):this.logTemplate("info",t,r)}warn(t,...r){typeof t=="string"?this.log("warning",t,r[0]??{}):typeof t=="function"?this.logLazily("warning",t):this.logTemplate("warning",t,r)}error(t,...r){typeof t=="string"?this.log("error",t,r[0]??{}):typeof t=="function"?this.logLazily("error",t):this.logTemplate("error",t,r)}fatal(t,...r){typeof t=="string"?this.log("fatal",t,r[0]??{}):typeof t=="function"?this.logLazily("fatal",t):this.logTemplate("fatal",t,r)}},QL=class rE{constructor(t,r){Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=t,this.properties=r}get category(){return this.logger.category}get parent(){return this.logger.parent}getChild(t){return this.logger.getChild(t).with(this.properties)}with(t){return new rE(this.logger,{...this.properties,...t})}log(t,r,o,n){this.logger.log(t,r,typeof o=="function"?()=>({...this.properties,...o()}):{...this.properties,...o},n)}logLazily(t,r){this.logger.logLazily(t,r,this.properties)}logTemplate(t,r,o){this.logger.logTemplate(t,r,o,this.properties)}debug(t,...r){typeof t=="string"?this.log("debug",t,r[0]??{}):typeof t=="function"?this.logLazily("debug",t):this.logTemplate("debug",t,r)}info(t,...r){typeof t=="string"?this.log("info",t,r[0]??{}):typeof t=="function"?this.logLazily("info",t):this.logTemplate("info",t,r)}warn(t,...r){typeof t=="string"?this.log("warning",t,r[0]??{}):typeof t=="function"?this.logLazily("warning",t):this.logTemplate("warning",t,r)}error(t,...r){typeof t=="string"?this.log("error",t,r[0]??{}):typeof t=="function"?this.logLazily("error",t):this.logTemplate("error",t,r)}fatal(t,...r){typeof t=="string"?this.log("fatal",t,r[0]??{}):typeof t=="function"?this.logLazily("fatal",t):this.logTemplate("fatal",t,r)}},ZL=tE.getLogger(["logtape","meta"]);function Kb(e,t){let r=[],o="";for(let n=0;n<e.length;n++){let s=e.charAt(n),i=e.charAt(n+1);if(s==="{"&&i==="{")o=o+s,n++;else if(s==="}"&&i==="}")o=o+s,n++;else if(s==="{")r.push(o),o="";else if(s==="}"){let a;o.match(/^\s|\s$/)?a=o in t?t[o]:t[o.trim()]:a=t[o],r.push(a),o=""}else o=o+s}return r.push(o),r}function Xb(e,t){let r=[];for(let o=0;o<e.length;o++)r.push(e[o]),o<t.length&&r.push(t[o]);return r}var eN=eE(KL()),Os=eN.default,Yb={debug:"DBG",info:"INF",warning:"WRN",error:"ERR",fatal:"FTL"},oE="Deno"in globalThis&&"inspect"in globalThis.Deno&&typeof globalThis.Deno.inspect=="function"?globalThis.Deno.inspect.bind(globalThis.Deno):Os!=null&&"inspect"in Os&&typeof Os.inspect=="function"?Os.inspect.bind(Os):e=>JSON.stringify(e);function nE(e={}){let t=e.timestamp==null||e.timestamp==="date-time-timezone"?i=>new Date(i).toISOString().replace("T"," ").replace("Z"," +00:00"):e.timestamp==="date-time-tz"?i=>new Date(i).toISOString().replace("T"," ").replace("Z"," +00"):e.timestamp==="date-time"?i=>new Date(i).toISOString().replace("T"," ").replace("Z",""):e.timestamp==="time-timezone"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z"," +00:00"):e.timestamp==="time-tz"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z"," +00"):e.timestamp==="time"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z",""):e.timestamp==="date"?i=>new Date(i).toISOString().replace(/T.*/,""):e.timestamp==="rfc3339"?i=>new Date(i).toISOString():e.timestamp,r=e.category??"·",o=e.value??oE,n=e.level==null||e.level==="ABBR"?i=>Yb[i]:e.level==="abbr"?i=>Yb[i].toLowerCase():e.level==="FULL"?i=>i.toUpperCase():e.level==="full"?i=>i:e.level==="L"?i=>i.charAt(0).toUpperCase():e.level==="l"?i=>i.charAt(0):e.level,s=e.format??(({timestamp:i,level:a,category:c,message:l})=>`${i} [${a}] ${c}: ${l}`);return i=>{let a="";for(let p=0;p<i.message.length;p++)p%2===0?a+=i.message[p]:a+=o(i.message[p]);let c=t(i.timestamp),l=n(i.level),u=typeof r=="function"?r(i.category):i.category.join(r);return`${s({timestamp:c,level:l,category:u,message:a,record:i})}
`}}var tTe=nE(),su="\x1B[0m",iu={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},au={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",strikethrough:"\x1B[9m"},tN={debug:"blue",info:"green",warning:"yellow",error:"red",fatal:"magenta"};function rN(e={}){let t=e.format,r=typeof e.timestampStyle>"u"?"dim":e.timestampStyle,o=e.timestampColor??null,n=`${r==null?"":au[r]}${o==null?"":iu[o]}`,s=r==null&&o==null?"":su,i=typeof e.levelStyle>"u"?"bold":e.levelStyle,a=e.levelColors??tN,c=typeof e.categoryStyle>"u"?"dim":e.categoryStyle,l=e.categoryColor??null,u=`${c==null?"":au[c]}${l==null?"":iu[l]}`,p=c==null&&l==null?"":su;return nE({timestamp:"date-time-tz",value(f){return oE(f,{colors:!0})},...e,format({timestamp:f,level:m,category:h,message:g,record:y}){let x=a[y.level];return f=`${n}${f}${s}`,m=`${i==null?"":au[i]}${x==null?"":iu[x]}${m}${i==null&&x==null?"":su}`,t==null?`${f} ${m} ${u}${h}:${p} ${g}`:t({timestamp:f,level:m,category:`${u}${h}${p}`,message:g,record:y})}})}var rTe=rN();var oN=eE(XL()),nN=oN.default;function Ln(){throw new Error("File sink is not available in the browser.")}var sN={openSync:Ln,writeSync:Ln,flushSync:Ln,closeSync:Ln,statSync:Ln,renameSync:Ln},Vo=nN,oTe=Vo==null?sN:{openSync(e){return Vo.openSync(e,"a")},writeSync:Vo.writeSync,flushSync:Vo.fsyncSync,closeSync:Vo.closeSync,statSync:Vo.statSync,renameSync:Vo.renameSync};var ic="`null`",m_e=wn+ic,cN=Nr+ic,f_e=kn+ic,d_e=Rn+ic;var ac="`undefined`",b_e=wn+ac,lN=Nr+ac,E_e=kn+ac,w_e=Rn+ac;async function*iE(e){let t=[],r=[],o=new Map,n=[];for(let s of e)s.isValid&&(s.id?s.isMember||t.push(s.id):r.push(s.name),n.push(s.name),o.set(s.name,s.checked));for(let s=0;s<t.length;s+=50){let i=t.slice(s,s+50);if(i.length===0)break;i.length===1&&i.push(i[0]);let a=await di(i);if(Rt(a)){r=n;break}for(let c of Bo(a).projects)o.has(c.name)&&(yield Et({...c,checked:o.get(c.name)??0}))}for(let s of r){let i=await yr(s);yield tt(i)?Et({...Bo(i),checked:o.get(s)??0}):At({...Tn(i),project:s})}}var pu=(e,t)=>t.some(r=>e instanceof r),aE,cE;function uN(){return aE||(aE=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function mN(){return cE||(cE=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var uu=new WeakMap,cu=new WeakMap,cc=new WeakMap;function fN(e){let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{r(ao(e.result)),n()},i=()=>{o(e.error),n()};e.addEventListener("success",s),e.addEventListener("error",i)});return cc.set(t,e),t}function dN(e){if(uu.has(e))return;let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{r(),n()},i=()=>{o(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)});uu.set(e,t)}var mu={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return uu.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return ao(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function mE(e){mu=e(mu)}function hN(e){return mN().includes(e)?function(...t){return e.apply(fu(this),t),ao(this.request)}:function(...t){return ao(e.apply(fu(this),t))}}function gN(e){return typeof e=="function"?hN(e):(e instanceof IDBTransaction&&dN(e),pu(e,uN())?new Proxy(e,mu):e)}function ao(e){if(e instanceof IDBRequest)return fN(e);if(cu.has(e))return cu.get(e);let t=gN(e);return t!==e&&(cu.set(e,t),cc.set(t,e)),t}var fu=e=>cc.get(e);function fE(e,t,{blocked:r,upgrade:o,blocking:n,terminated:s}={}){let i=indexedDB.open(e,t),a=ao(i);return o&&i.addEventListener("upgradeneeded",c=>{o(ao(i.result),c.oldVersion,c.newVersion,ao(i.transaction),c)}),r&&i.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),n&&c.addEventListener("versionchange",l=>n(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function dE(e,{blocked:t}={}){let r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",o=>t(o.oldVersion,o)),ao(r).then(()=>{})}var yN=["get","getKey","getAll","getAllKeys","count"],xN=["put","add","delete","clear"],lu=new Map;function lE(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(lu.get(t))return lu.get(t);let r=t.replace(/FromIndex$/,""),o=t!==r,n=xN.includes(r);if(!(r in(o?IDBIndex:IDBObjectStore).prototype)||!(n||yN.includes(r)))return;let s=async function(i,...a){let c=this.transaction(i,n?"readwrite":"readonly"),l=c.store;return o&&(l=l.index(a.shift())),(await Promise.all([l[r](...a),n&&c.done]))[0]};return lu.set(t,s),s}mE(e=>({...e,get:(t,r,o)=>lE(t,r)||e.get(t,r,o),has:(t,r)=>!!lE(t,r)||e.has(t,r)}));var bN=["continue","continuePrimaryKey","advance"],pE={},du=new WeakMap,hE=new WeakMap,EN={get(e,t){if(!bN.includes(t))return e[t];let r=pE[t];return r||(r=pE[t]=function(...o){du.set(this,hE.get(this)[t](...o))}),r}};async function*wN(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,EN);for(hE.set(r,t),cc.set(r,fu(t));t;)yield r,t=await(du.get(r)||t.continue()),du.delete(r)}function uE(e,t){return t===Symbol.asyncIterator&&pu(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&pu(e,[IDBIndex,IDBObjectStore])}mE(e=>({...e,get(t,r,o){return uE(t,r)?wN:e.get(t,r,o)},has(t,r){return uE(t,r)||e.has(t,r)}}));var gE,hu=async()=>{let e=Ls(["@takker/cosense-storage","open"]);return gE??=await fE("scrapbox-storage",4,{upgrade(t,r,o){e.info`start updating DB: ${r} -> ${o}`;let n=Date.now();for(let a of t.objectStoreNames)t.deleteObjectStore(a);t.createObjectStore("titles",{keyPath:"id"}).createIndex("project","project");let i=t.createObjectStore("projects",{keyPath:"id"});i.createIndex("checked","checked"),i.createIndex("name","name"),e.info`finish updating DB: ${Date.now()-n}ms`},blocked(t,r){let o=`The database "@takker/cosense-storage"(v${r}) is blocked because the older one (v${t}) is opened in other tabs.
Please close the other tabs and reload this page.`;e.error(o),alert(o)},blocking(t,r){let o=`The database "@takker/cosense-storage"(v${t}) is blocking the newer one (v${r}) opened.
Please close this page.`;e.error(o),alert(o)}}),gE};var pc=(e,t)=>(gu||(gu=new BroadcastChannel(xE),gu.addEventListener("message",r=>yE(r.data))),lc.set(t,new Set(e).union(lc.get(t)??new Set)),()=>lc.delete(t)),yu=(e,t)=>{if((t.added?.size??0)+(t.updated?.size??0)+(t.deleted?.size??0)===0)return;let r={type:"links:changed",project:e,diff:t};yE(r);let o=new BroadcastChannel(xE);o.postMessage(r),o.close()},yE=e=>{for(let[t,r]of lc)r.has(e.project)&&t(e)},xE="scrapbox-storage-notify",gu,lc=new Map;function xu(e){return Math.trunc(+W(e)/1e3)}var uc=async(e,t)=>{let r=await hu(),o=Ls(["@takker/cosense-storage","check"]),n=new Map;try{{o.debug`check updates of links...`;let i=new Set,a=r.transaction("projects","readwrite"),c=xu(new Date),l=c-600;for await(let f of a.store.index("checked").iterate(IDBKeyRange.lowerBound(l,!0))){let m=f.value;if(m.isValid===!1){i.add(m.id);continue}i.add(m.name);let h=m.checked;if(h+t>c||m?.updating&&h>l)continue;let g=structuredClone(m);g.updating=!0,n.set(m.id,g),f.update(g)}let u=[],p=a.store.index("name");for(let f of e)i.has(f)||u.push(p.get(f).then(m=>{m?.updating&&(m?.checked??0)>l||n.set(f,m??kN(f))}));if(await Promise.all(u),await a.done,n.size===0){o.debug`checked. No project needs upgrade.`;return}o.debug`checked. ${n.size} projects maybe need upgrade.`}let s=xu(new Date);for await(let i of iE(n.values())){if(Rt(i)){let{project:h,name:g}=Tn(i);switch(g){default:continue;case"NotFoundError":o.warn(`"${h}" is not found.`);break;case"NotMemberError":o.warn(`You are not a member of "${h}".`);break;case"NotLoggedInError":o.warn(`You are not a member of "${h}" or You are not logged in yet.`);break}n.set(h,{id:h,name:h,checked:s,updating:!1,isValid:!1,reason:g});continue}let{checked:a,...c}=Bo(i);if(c.updated<a){o.debug`no updates in "${c.name}"`,n.set(c.name,{...c,isValid:!0,checked:s,updating:!1});continue}o.debug`start downloading and storing links of "${c.name}"`;let l=new Set(await r.getAllKeysFromIndex("titles","project",c.name)),u=0,p=0;for await(let h of Nf(c.name)){if(Rt(h)){let{name:E,message:R}=Tn(h);o.error`Failed to get links of "${c.name}" with ${E}: ${R}`;break}let g=Bo(h),y={},x=r.transaction("titles","readwrite");await Promise.all(g.map(async E=>{let R={...E,project:c.name},b=await x.store.get(E.id);if(!b)return y.added?.set?.(E.id,R)??(y.added=new Map([[E.id,R]])),x.store.add(R);if(l.delete(E.id),!!RN(R,b))return y.updated?.set?.(E.id,[b,R])??(y.updated=new Map([[E.id,[b,R]]])),x.store.put(R)})),await x.done,u+=y.added?.size??0,p+=y.updated?.size??0,o.debug`Updating "/${c.name}": +${u} pages, ~${p} pages`,yu(c.name,y)}let f=r.transaction("titles","readwrite"),m=new Map((await Promise.all([...l].map(async h=>{let g=await f.store.get(h);if(!g)return[];let y=[[h,g]];return await f.store.delete(h),y}))).flat());await f.done,o.debug`Finish downloading and storing links of "${c.name}"`,o.debug`Update "/${c.name}": +${u} pages, ~${p} pages, -${m.size} pages`,n.set(c.name,{...c,isValid:!0,checked:s,updating:!1}),yu(c.name,{deleted:m})}}finally{let s=r.transaction("projects","readwrite");await Promise.all([...n].map(([,i])=>(i.updating=!1,s.store.put({...i})))),await s.done}},Nn=async e=>{let t=[...new Set(e)];if(t.length===0)return[];let r=Date.now(),n=(await hu()).transaction("titles","readonly"),s=n.store.index("project"),i=(await Promise.all(t.map(c=>s.getAll(c)))).flat();return await n.done,Ls(["@takker/cosense-storage","load"]).debug`Read ${i.length} links from ${t.length} projects in ${Date.now()-r}ms`,i},kN=e=>({name:e,displayName:e,id:"",isValid:!0,publicVisible:!0,isMember:!0,loginStrategies:[],theme:"default",gyazoTeamsName:null,translation:!0,infobox:!0,checked:0,updated:0,created:0,updating:!0}),RN=(e,t)=>e.updated>t.updated||e.links.sort().join()!==t.links.sort().join();dE("userscript-links").catch(e=>console.error(e));var vN=Ur("scrapbox-select-suggestion:useSource.ts"),EE=e=>On(...C(()=>{let t=[];return[n=>{let s=Nn(e).then(i=>{let a=TN(i);return t=[...a.values()],n(),a});return uc(e,600),pc(e,({diff:i})=>s=s.then(a=>(vN.debug(`Update: +${i.added?.size??0} pages, ~${i.updated?.size??0} pages, -${i.deleted?.size??0} pages`),a=_N(a,i),t=[...a.values()],n(),a)))},()=>t]},[e])),TN=e=>{let t=new Map;for(let r of e)bu(t,r);return t},_N=(e,t)=>{let r=new Map(e);if(t.added)for(let[,o]of t.added)bu(r,o);if(t.updated)for(let[,[o,n]]of t.updated)bE(r,o),bu(r,n);if(t.deleted)for(let[,o]of t.deleted)bE(r,o);return r},bu=(e,t)=>{let r=vs(t.title),o=e.get(r);if((o?.updated??0)>t.updated)return;let n=o?.metadata??new Map;n.set(t.project,{image:t.image}),e.set(r,{title:t.title,titleLc:r,updated:t.updated,linked:o?.linked??0,metadata:n});for(let s of t.links){let i=vs(s),a=e.get(i),c=a?.metadata??new Map;c.set(t.project,c.get(t.project)??{image:t.image}),e.set(i,{title:a?.title??s,titleLc:i,updated:a?.updated??0,linked:(a?.linked??0)+1,metadata:c})}},bE=(e,t)=>{let r=vs(t.title),o=e.get(r);if(!o||(o.updated??0)>t.updated)return;let n=o.metadata;n.delete(t.project),n.size<=0?e.delete(r):e.set(r,{title:o.title,titleLc:r,updated:t.updated,linked:o.linked,metadata:n});for(let s of t.links){let i=vs(s),a=e.get(i);if(!a)continue;let c=a.metadata;c.delete(t.project),c.size<=0?e.delete(i):e.set(i,{title:a.title,titleLc:i,updated:t.updated,linked:a.linked-1,metadata:c})}};var wE=e=>{let t=C(()=>Ts(e.style,import.meta.url),[e.style]);return d(Y,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var kE=()=>d("style",{children:`.container {
position: absolute;
margin-top: 14px;
max-height: 80vh;
z-index: 301;
background-color: var(--select-suggest-bg, #111);
font-family: var(--select-suggest-font-family, "Open Sans", Helvetica, Arial, "Hiragino Sans", sans-serif);
font-size: 14px;
color: var(--select-suggest-text-color, #eee);
border-radius: 4px;
}
.candidates {
max-width: 80vw;
}
.candidates:not([data-os*="android"]):not([data-os*="ios"]) {
font-size:11px;
}
.projects {
margin-right: 4px;
display: grid;
grid-template-rows: repeat(4, min-content);
grid-auto-flow: column;
direction: rtl;
}
.projects:is([data-os*="android"], [data-os*="ios"]) > * {
padding: 6px;
}
.candidates > :not(:first-child) {
border-top: 1px solid var(--select-suggest-border-color, #eee);
}
.candidates > *{
line-height: 1.2em;
padding: 0.5em 10px;
}
.candidate {
display: flex;
}
a {
display: block;
text-decoration: none;
color: inherit;
}
a:not(.mark) {
width: 100%;
}
.selected a {
background-color: var(--select-suggest-selected-bg, #222);
text-decoration: underline
}
img {
height: 1.3em;
width: 1.3em;
position: relative;
object-fit: cover;
object-position: 0% 0%;
}
.disabled {
filter: grayscale(1.0) opacity(0.5);
}
.counter {
color: var(--select-suggest-information-text-color, #aaa);
font-size: 80%;
font-style: italic;
}
.progress[style] {
padding: unset;
border: unset;
height: 0.5px;
transition: background 0.1s;
}`});function*RE(e){if(!("nodes"in e))return;let t=0;function*r(o){for(let n of Array.isArray(o)?o:[o]){if(typeof n=="string"){t+=[...n].length;continue}switch(n.type){case"link":yield{whole:n.unit.whole,start:t},t+=[...n.unit.whole].length;break;case"indent":case"quote":t+=[...n.unit.tag].length,yield*r(n.children);break;case"deco":t+=[...n.unit.deco].length+2,yield*r(n.children),t++;break;case"strong":t+=2,yield*r(n.children),t+=2;break;default:t+=[...n.unit.whole].length;break}}}yield*r(e.nodes)}var vE=(e,t)=>{if(t.type==="unlock"){if(!e.lock)return e;let{lock:i,...a}=e;return{...a}}if(e.lock)return e;switch(t.type){case"lock":{let{lock:i,...a}=e;return{lock:!0,...a}}case"enable":return e.type==="disabled"&&e.isManuallyDisabled?{type:"ready"}:e;case"disable":return e.type==="disabled"&&e.isManuallyDisabled?e:{type:"disabled",isManuallyDisabled:!0}}if(e.type==="disabled")return e.isManuallyDisabled||!t.lines?e:{type:"ready"};if(t.type==="cancel")return e.type==="completion"?{type:"cancelled",context:e.context}:e;if(!t.lines)return{type:"disabled"};let r=Math.min(t.range.start.char,t.range.end.char),o=Math.max(t.range.start.char,t.range.end.char),n=t.lines?t.range.start.line!==t.range.end.line?`
`:[...t.lines[t.range.start.line].text].slice(r,o).join(""):"";if(SN(t.lines[t.position.line],n)&&e.type!=="cancelled")return{type:"completion",context:"selection",query:n,start:r,position:t.position};if(n!=="")return e.type==="completion"?{type:"ready"}:e;let s=PN(t.lines[t.position.line],t.position.char);return s?e.type==="cancelled"&&e.context==="input"?e:e.type==="completion"||t.type==="lines:changed"?{type:"completion",context:"input",query:s.whole,start:s.start,position:t.position}:e.type==="ready"?e:{type:"ready"}:e.type==="ready"?e:{type:"ready"}},PN=(e,t)=>{for(let{whole:r,start:o}of RE(e))if(!(t<=o||o+[...r].length<=t))return{whole:r,start:o}},SN=(e,t)=>!(t.trim()===""||t.includes(`
`)||"codeBlock"in e||"title"in e||"tableBlock"in e&&e.tableBlock.start);var TE=()=>{let e=qe(scrapbox.Page.lines),t=qe(!1);return oe(()=>{let r=()=>{t.current=!0};return scrapbox.addListener("lines:changed",r),scrapbox.addListener("layout:changed",r),()=>{scrapbox.removeListener("lines:changed",r),scrapbox.removeListener("layout:changed",r)}},[]),F(()=>(t.current&&(e.current=scrapbox.Page.lines,t.current=!1),e.current??void 0),[])};var ON=Ur("scrapbox-select-suggestion:useLifecycle.ts"),_E=()=>{let[e,t]=jr(vE,{type:"ready"}),r=TE(),o=C(()=>{let i;return a=>{i!==void 0&&clearTimeout(i),i=setTimeout(()=>{let{cursor:c,selection:l}=Lt();t({type:a,lines:r(),range:l.getRange({normalizeOrder:!0}),position:c.getPosition()})},a==="cursor:changed"?100:void 0)}},[]);oe(()=>{let i=()=>{o("lines:changed")};scrapbox.addListener("lines:changed",i),scrapbox.addListener("layout:changed",i);let a=()=>{o("selection:changed")},c=Gi();return c.addChangeListener(a),()=>{scrapbox.removeListener("lines:changed",i),scrapbox.removeListener("layout:changed",i),c.removeChangeListener(a)}},[]),oe(()=>{if(e.context!=="input")return;let i=()=>{o("cursor:changed")},a=Br();return a.addChangeListener(i),()=>a.removeChangeListener(i)},[e.context]);let[n,s]=J(e);return n!==e&&(s(e),ON.debug("Detect changes",e)),{state:e,setEnable:F(i=>t({type:i?"enable":"disable"}),[]),cancel:F(()=>t({type:"cancel"}),[]),freezeUntil:F(i=>{t({type:"lock"});let a=i();if(a instanceof Promise)return a.then(()=>{t({type:"unlock"})});t({type:"unlock"})},[]),confirmAfter:F(async i=>{let a=r();if(!a)return;t({type:"lock"});let{cursor:c,selection:l}=Lt(),u=c.getPosition().line,p=a[u].text,[f,m]=i(p,c.getPosition());l.setRange({start:{line:u,char:0},end:{line:u,char:[...p].length}}),await Je(f),c.setPosition(m),c.focus(),t({type:"unlock"}),t({type:"cancel"})},[])}};var PE=(e,t)=>{let r=e.dist-t.dist;if(r!==0)return r;let o=e.matches.map(([i])=>i).sort(),n=t.matches.map(([i])=>i).sort();for(let i=0;i<o.length;i++){let a=o[i]-(n[i]??n.length);if(a!==0)return a}let s=e.title.length-t.title.length;return s!==0?s:t.updated-e.updated};var SE=e=>{let t=new Map,r=[...e].reverse();{let i=1;for(let a of r){t.set(a,(t.get(a)??0)|i);let c=a.toLowerCase();t.set(c,(t.get(c)??0)|i);let l=a.toUpperCase();t.set(l,(t.get(l)??0)|i),i<<=1}}let o=r.length,n=~(-1<<o),s=1<<o-1;return i=>{let a=0,c=n,l=[...i].reverse(),u=[],p=l.length;u[p]=o;for(let f of l){let m=t.get(f)??0,h=m|a,g=(m&c)+c^c|m,y=a|~(g|c),x=c&g;u[p-1]=u[p]+(y&s?1:x&s?-1:0),c=x<<1|~(h|y<<1),a=y<<1&h,p--}return u}};var LN=[0,0,0,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6],OE=e=>{let t=Mb(e.trim()).split(/\s+/).sort((r,o)=>o.length-r.length);if(!(t.length===0||t.every(r=>r==="")))return r=>{let o=[...r];for(let n of t)o=NN(n,o);return o}},NN=(e,t)=>{let r=[...e].length,o=LN[r],n=SE(e);return t.flatMap(({title:s,dist:i,matches:a,...c})=>{a??=[],i??=0;let l=n(s).flatMap((p,f)=>p<=o&&a.every(([m,h])=>f+r<=m||h<f)?[[f,p]]:[]);if(l.length===0)return[];let u=l.reduce((p,[f,m])=>(p.dist<=m||(p.dist=m,p.start=f),p),{dist:r,start:0});return a.push([u.start,u.start+r-1]),[{title:s,dist:u.dist+i,matches:a,...c}]})};var CN=Ur("scrapbox-select-suggestion:cancelableSearch.ts");async function*LE(e,t,r){let o=OE(e);if(!o)return;let n=r?.chunk??1e3,s=Math.floor(t.length/n)+1,i=0,a=new Date;try{for(;i<s;i++)await new Promise(c=>requestAnimationFrame(c)),yield[o(t.slice(i*n,(i+1)*n)),(i+1)/s]}finally{let l=new Date().getTime()-a.getTime();CN.debug(`search ${(i/s*100).toPrecision(3)}% of the source for "${e}" in ${l}ms`)}}var NE=(e,t)=>{let r=t?.interval??0,o=t?.maxQueued??1/0,n,s,i=[],a=(...c)=>{if(!n)return n=(async()=>{do{await new Promise(m=>{let h=setTimeout(m,r);s=()=>{for(clearTimeout(h);i.length>0;)i.shift()("discarded");m()}});let f=i.pop();if(!f)break;f("delayed")}while(i.length>0);n=void 0})(),new Promise(f=>f(e.call(a,...c,"immediate")));for(;i.length>Math.max(o,0);)i.shift()("discarded");let{promise:l,resolve:u,reject:p}=Promise.withResolvers();return i.push(f=>{try{u(e.call(a,...c,f))}catch(m){p(m)}}),l};return a.clear=()=>{s?.()},Object.defineProperty(a,"ready",{get:()=>n}),a};var zo=e=>"query"in e,CE=e=>(t,r)=>{if("query"in r){let i=zo(t)?t.query:"";if(r.query===i)return t;let a=zo(t)?t.job:void 0;if(!r.query)return a?.abort?.(),{source:t.source};let{run:c,abort:l}=e(r.query,t.source,!1),u=a?.abort?.()?.then?.(c)??c();return{query:r.query,source:t.source,job:{done:u,abort:()=>(l(),u)},progress:0,candidates:!i||!zo(t)?[]:t.candidates}}if("source"in r){if(!zo(t))return r.source===t.source?t:r;let{source:i,job:a,...c}=t;if(r.source===i)return t;let{run:l,abort:u}=e(c.query,r.source,!0),p=a.done.then(l);return{source:r.source,job:{done:p,abort:()=>a.abort().then(()=>(u(),p))},...c}}if(!zo(t))return t;if(!r.candidates){let{progress:i,...a}=t;return i===r.progress?t:{progress:r.progress,...a}}let{candidates:o,progress:n,...s}=t;return o===r.candidates&&n===r.progress?t:{candidates:r.candidates??o,progress:r.progress,...s}};var AN=Ur("scrapbox-select-suggestion:useSearch.ts"),AE=e=>{let t=F((n,s,i)=>{let a=!1,c=LE(n,s,{chunk:5e3});return{run:async()=>{if(i){let p=[];for await(let[f]of c){if(a)return;p.push(...f)}o({progress:1,candidates:p});return}let l=NE((p,f)=>{f!=="discarded"&&(a||o(p))},{interval:500,maxQueued:0}),u=[];for await(let[p,f]of c){if(a)return;u=[...u,...p],o({progress:f}),p.length!==0&&l({progress:f,candidates:u})}l({progress:1,candidates:u})},abort:()=>a=!0}},[]),[r,o]=jr(C(()=>CE(t),[t]),{source:e});return[C(()=>{if(!zo(r))return;let[n,s]=MN(r.candidates);return AN.debug("Detect changes",{progress:r.progress,items:s}),{progress:r.progress,projectScore:n,items:s}},[r]),{search:F(n=>o({query:n}),[]),update:F(n=>o({source:n}),[])}]},MN=e=>{let t=new Map,r=[];for(let o of e.sort(PE)){let n=[...o.metadata.keys()];for(let s of n)t.set(s,(t.get(s)??0)+.5**o.dist);r.push({title:o.title,dist:o.dist,projects:n})}return[t,r]};var ME=(e,t)=>{let r=qe({...t});oe(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),oe(()=>{e(r.current)},[e])};var IN={selectNext:()=>!1,selectPrev:()=>!1,selectFirst:()=>!1,selectLast:()=>!1,confirm:()=>!1,cancel:()=>!1},IE=e=>{let t=EE(e.projects),[r,{update:o,search:n}]=AE(t),{state:s,setEnable:i,...a}=_E();o(t),n(s.type==="completion"?s.context==="input"?s.query.slice(1,-1):s.query:"");let[c,l]=J(),{callback:u,style:p,...f}=e;return ME(u,{enable:F(()=>i(!0),[]),disable:F(()=>i(!1),[]),...s.type!=="completion"||!c?IN:c}),d(Y,{children:[d(kE,{}),d(wE,{style:p}),s.type==="completion"&&r&&d(Wb,{callback:l,...r,...s,...a,...f})]})};var FE=e=>{let t=document.createElement("div");t.dataset.userscriptName="scrapbox-select-suggestion";let r=t.attachShadow({mode:"open"});document.body.append(t);let{limit:o=5,debug:n=!1,mark:s={},style:i="",enableSelfProjectOnStart:a=!0}=e??{},c=new Set([...a?[scrapbox.Project.name]:[],...e?.projects??[scrapbox.Project.name]]);return Ri(n),new Promise(l=>mt(d(IE,{limit:o,projects:c,mark:s,style:i,callback:l,enableSelfProjectOnStart:a}),r))};var It=e=>e.flatMap(t=>{let r=t.slice(1),o=Math.min(...r.map(n=>n.text.length-n.text.trimStart().length));return r.map(n=>n.text.slice(o))}).join(`
`).trim();function*UE(e,t){for(let[r,o]of t.entries()){let n=e.get(r);if(n&&It(n.blocks)===It(o)){yield{changed:!1,filename:r};continue}yield{changed:!0,filename:r}}for(let r of e.keys())t.has(r)||(yield{changed:!0,filename:r})}var Cn={};zs(Cn,{getTitle:()=>Ef,parse:()=>He});var DE=e=>{let t=new Map;if(e.length===0)return t;let r=He(e.map(n=>n.text).join(`
`),{hasTitle:!0}),o=0;for(let n of r)switch(n.type){case"title":case"line":o++;break;case"table":o+=n.cells.length+1;break;case"codeBlock":{let s=t.get(n.fileName)??[],i=n.content.split(`
`).length+1;s.push(e.slice(o,o+i)),t.set(n.fileName,s),o+=i;break}}return t};var $E=e=>{let t,r,o=async()=>{for(;t;){let[n,s]=t;t=void 0;try{let i=await e(...n);s({type:"resolve",value:i})}catch(i){s({type:"reject",value:i})}}r=void 0};return(...n)=>{let{resolve:s,promise:i}=Promise.withResolvers();return t?.[1]?.({type:"cancel"}),t=[n,s],r??=o(),i}};var mc=class{constructor(t,r){this._filename=t;this._preview=$E(async(o,n,s)=>(this._dispose=await r(s?{filename:this.filename,before:o,after:n,render:(...i)=>{s.textContent="",s.append(...i)}}:{filename:this.filename,before:o}),!1))}get filename(){return this._filename}get blocks(){return this._blocks??[]}async update(t){if(await this._dispose?.(),!t||It(t)===""){let a=await this._preview(this.blocks);if(a.type==="cancel")return a;if(a.type==="reject")throw a.value;return this._area?.remove?.(),this._style?.remove?.(),this._area=void 0,this._style=void 0,this._blocks=void 0,{type:"resolve",value:!0}}let r=this.blocks;this._blocks=t,this.makeStyle();let o=this.makeArea(),n=t.at(0)?.at?.(-1)?.id,s=wr(n);if(!s)throw new Error(`"div.lines#L${n}" could not be found.`);s.insertAdjacentElement("afterend",o);let i=()=>{let a=s.getElementsByClassName("indent")[0];a instanceof HTMLElement&&(o.style.marginLeft=a.style.marginLeft)};return this._observer?.disconnect?.(),i(),this._observer=new MutationObserver(i),this._observer.observe(s,{childList:!0,subtree:!0}),this._preview(r,t,o)}makeArea(){if(this._area)return this._area;let t=document.createElement("div");return t.classList.add("scrap-run"),t.dataset.filename=this.filename,this._area=t,t}makeStyle(){let t=this.blocks.flatMap(o=>o.slice(1).map(({id:n})=>`#L${n}`)),r=this.blocks.flatMap(o=>o.map(({id:n})=>`#L${n}`));this._style||(this._style=document.createElement("style"),document.head.append(this._style)),this._style.textContent=`.lines:not(:has(:is(${[...r].join(",")}).cursor-line)) :is(${[...t].join(",")}){display:none}`}_blocks;_dispose;_preview;_area;_observer;_style};var jE=({previewers:e})=>{let t=new Map,r=()=>{let s=DE(ft());for(let{changed:i,filename:a}of UE(t,s)){if(!i)continue;let c=s.get(a),l=t.get(a);if(!l){if(!c)continue;let u=e.find(({when:p})=>p.test(a))?.preview;if(!u)continue;l=new mc(a,u),t.set(a,l)}l.update(c).then(u=>{switch(u.type){case"resolve":u.value&&t.delete(a);return;case"reject":throw u.value;case"cancel":return}})}},o=()=>{if(scrapbox.Layout!=="page"){scrapbox.off("lines:changed",r);return}r(),scrapbox.on("lines:changed",r)};o(),scrapbox.on("page:changed",o);let n=document.createElement("style");return n.textContent=".scrap-run{display:block;width:95%}",document.head.append(n),()=>{scrapbox.off("page:changed",o),n.remove()}};var Ns=e=>{let t=new FileReader,r=new Promise(o=>t.onload=()=>o(t.result));return t.readAsDataURL(e),r};var BE=async e=>{if(!("after"in e))return;let t=It(e.after),o=new DOMParser().parseFromString(t,"image/svg+xml").querySelector("parsererror");if(o){let i=document.createElement("pre"),a=document.createElement("code");a.innerText=o.innerHTML,i.append(a),e.render(i);return}let n=await Ns(new Blob([t],{type:"image/svg+xml"})),s=document.createElement("img");s.src=n,e.render(s)};var Eu={};zs(Eu,{default:()=>GE});var uC=Object.create,WE=Object.defineProperty,mC=Object.getOwnPropertyDescriptor,fC=Object.getOwnPropertyNames,dC=Object.getPrototypeOf,hC=Object.prototype.hasOwnProperty,gC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),yC=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of fC(t))!hC.call(e,n)&&n!==r&&WE(e,n,{get:()=>t[n],enumerable:!(o=mC(t,n))||o.enumerable});return e},xC=(e,t,r)=>(r=e!=null?uC(dC(e)):{},yC(t||!e||!e.__esModule?WE(r,"default",{value:e,enumerable:!0}):r,e)),bC=gC((e,t)=>{t.exports=o;var r=Object.prototype.toString;function o(n){if(!n)return!1;var s=r.call(n);return s==="[object Function]"||typeof n=="function"&&s!=="[object RegExp]"||typeof window<"u"&&(n===window.setTimeout||n===window.alert||n===window.confirm||n===window.prompt)}}),HE=xC(bC()),GE=HE.default??HE;var wu={};zs(wu,{default:()=>qE});var EC=Object.create,zE=Object.defineProperty,wC=Object.getOwnPropertyDescriptor,kC=Object.getOwnPropertyNames,RC=Object.getPrototypeOf,vC=Object.prototype.hasOwnProperty,TC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_C=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of kC(t))!vC.call(e,n)&&n!==r&&zE(e,n,{get:()=>t[n],enumerable:!(o=wC(t,n))||o.enumerable});return e},PC=(e,t,r)=>(r=e!=null?EC(RC(e)):{},_C(t||!e||!e.__esModule?zE(r,"default",{value:e,enumerable:!0}):r,e)),SC=TC((e,t)=>{var r=function(n){return n.replace(/^\s+|\s+$/g,"")},o=function(n){return Object.prototype.toString.call(n)==="[object Array]"};t.exports=function(n){if(!n)return{};for(var s={},i=r(n).split(`
`),a=0;a<i.length;a++){var c=i[a],l=c.indexOf(":"),u=r(c.slice(0,l)).toLowerCase(),p=r(c.slice(l+1));typeof s[u]>"u"?s[u]=p:o(s[u])?s[u].push(p):s[u]=[s[u],p]}return s}}),VE=PC(SC()),qE=VE.default??VE;var OC=(()=>{var e=globalThis;return{default:e}})(),LC=(()=>{var e=(...t)=>Object.assign({},...t);return{default:e}})(),An=e=>{let t=o=>typeof o.default<"u"?o.default:o,r=o=>Object.assign({__esModule:!0},o);switch(e){case"npm:global/window":return t(OC);case"is-function":return t(Eu);case"parse-headers":return t(wu);case"npm:xtend":return t(LC);default:return console.error('module "'+e+'" not found'),null}},NC=Object.create,XE=Object.defineProperty,CC=Object.getOwnPropertyDescriptor,AC=Object.getOwnPropertyNames,MC=Object.getPrototypeOf,IC=Object.prototype.hasOwnProperty,fc=(e=>typeof An<"u"?An:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof An<"u"?An:t)[r]}):e)(function(e){if(typeof An<"u")return An.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),FC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),UC=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of AC(t))!IC.call(e,n)&&n!==r&&XE(e,n,{get:()=>t[n],enumerable:!(o=CC(t,n))||o.enumerable});return e},DC=(e,t,r)=>(r=e!=null?NC(MC(e)):{},UC(t||!e||!e.__esModule?XE(r,"default",{value:e,enumerable:!0}):r,e)),$C=FC((e,t)=>{"use strict";var r=fc("npm:global/window"),o=fc("is-function"),n=fc("parse-headers"),s=fc("npm:xtend");t.exports=l,t.exports.default=l,l.XMLHttpRequest=r.XMLHttpRequest||f,l.XDomainRequest="withCredentials"in new l.XMLHttpRequest?l.XMLHttpRequest:r.XDomainRequest,i(["get","put","post","patch","head","delete"],function(m){l[m==="delete"?"del":m]=function(h,g,y){return g=c(h,g,y),g.method=m.toUpperCase(),u(g)}});function i(m,h){for(var g=0;g<m.length;g++)h(m[g])}function a(m){for(var h in m)if(m.hasOwnProperty(h))return!1;return!0}function c(m,h,g){var y=m;return o(h)?(g=h,typeof m=="string"&&(y={uri:m})):y=s(h,{uri:m}),y.callback=g,y}function l(m,h,g){return h=c(m,h,g),u(h)}function u(m){if(typeof m.callback>"u")throw new Error("callback argument missing");var h=!1,g=function(M,D,I){h||(h=!0,m.callback(M,D,I))};function y(){b.readyState===4&&setTimeout(R,0)}function x(){var M=void 0;if(b.response?M=b.response:M=b.responseText||p(b),_)try{M=JSON.parse(M)}catch{}return M}function E(M){return clearTimeout(S),M instanceof Error||(M=new Error(""+(M||"Unknown XMLHttpRequest Error"))),M.statusCode=0,g(M,A)}function R(){if(!k){var M;clearTimeout(S),m.useXDR&&b.status===void 0?M=200:M=b.status===1223?204:b.status;var D=A,I=null;return M!==0?(D={body:x(),statusCode:M,method:L,headers:{},url:O,rawRequest:b},b.getAllResponseHeaders&&(D.headers=n(b.getAllResponseHeaders()))):I=new Error("Internal XMLHttpRequest Error"),g(I,D,D.body)}}var b=m.xhr||null;b||(m.cors||m.useXDR?b=new l.XDomainRequest:b=new l.XMLHttpRequest);var v,k,O=b.url=m.uri||m.url,L=b.method=m.method||"GET",N=m.body||m.data,P=b.headers=m.headers||{},T=!!m.sync,_=!1,S,A={body:void 0,headers:{},statusCode:0,method:L,url:O,rawRequest:b};if("json"in m&&m.json!==!1&&(_=!0,P.accept||P.Accept||(P.Accept="application/json"),L!=="GET"&&L!=="HEAD"&&(P["content-type"]||P["Content-Type"]||(P["Content-Type"]="application/json"),N=JSON.stringify(m.json===!0?N:m.json))),b.onreadystatechange=y,b.onload=R,b.onerror=E,b.onprogress=function(){},b.onabort=function(){k=!0},b.ontimeout=E,b.open(L,O,!T,m.username,m.password),T||(b.withCredentials=!!m.withCredentials),!T&&m.timeout>0&&(S=setTimeout(function(){if(!k){k=!0,b.abort("timeout");var M=new Error("XMLHttpRequest timeout");M.code="ETIMEDOUT",E(M)}},m.timeout)),b.setRequestHeader)for(v in P)P.hasOwnProperty(v)&&b.setRequestHeader(v,P[v]);else if(m.headers&&!a(m.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in m&&(b.responseType=m.responseType),"beforeSend"in m&&typeof m.beforeSend=="function"&&m.beforeSend(b),b.send(N||null),b}function p(m){try{if(m.responseType==="document")return m.responseXML;var h=m.responseXML&&m.responseXML.documentElement.nodeName==="parsererror";if(m.responseType===""&&!h)return m.responseXML}catch{}return null}function f(){}}),KE=DC($C()),dc=KE.default??KE;var hc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},INe=function(){function e(r){this.value=r}function t(r){var o,n;function s(c,l){return new Promise(function(u,p){var f={key:c,arg:l,resolve:u,reject:p,next:null};n?n=n.next=f:(o=n=f,i(c,l))})}function i(c,l){try{var u=r[c](l),p=u.value;p instanceof e?Promise.resolve(p.value).then(function(f){i("next",f)},function(f){i("throw",f)}):a(u.done?"return":"normal",u.value)}catch(f){a("throw",f)}}function a(c,l){switch(c){case"return":o.resolve({value:l,done:!0});break;case"throw":o.reject(l);break;default:o.resolve({value:l,done:!1});break}o=o.next,o?i(o.key,o.arg):n=null}this._invoke=s,typeof r.return!="function"&&(this.return=void 0)}return typeof Symbol=="function"&&Symbol.asyncIterator&&(t.prototype[Symbol.asyncIterator]=function(){return this}),t.prototype.next=function(r){return this._invoke("next",r)},t.prototype.throw=function(r){return this._invoke("throw",r)},t.prototype.return=function(r){return this._invoke("return",r)},{wrap:function(r){return function(){return new t(r.apply(this,arguments))}},await:function(r){return new e(r)}}}(),QE=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},ZE=function(){function e(t,r){for(var o=0;o<r.length;o++){var n=r[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),ku=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}else return Array.from(e)},Cs="";function jC(e){return`
<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>
<td align="center">
<div style="display: table-cell; vertical-align: middle;">
<div style="">`+e+`</div>
</div>
</td></tr></table>
`}var BC=`
This page requires a browser that supports WebGL.<br/>
<a href="http://get.webgl.org">Click here to upgrade your browser.</a>
`,HC=`
It does not appear your computer can support WebGL.<br/>
<a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>
`,WC=1,GC=2;function VC(e,t,r){function o(i){var a=e.parentNode;a&&(a.innerHTML=jC(i))}function n(i,a){typeof r=="function"?r(i):o(a)}if(!window.WebGLRenderingContext)return n(WC,BC),null;var s=zC(e,t);return s?s.getExtension("OES_standard_derivatives"):n(GC,HC),s}function zC(e,t){for(var r=["webgl","experimental-webgl"],o=null,n=0;n<r.length;++n)try{o=e.getContext(r[n],t)}catch{if(o)break}return o}function Mn(e,t,r,o){var n=e.gl,s=n.createShader(r);n.shaderSource(s,t),n.compileShader(s);var i=n.getShaderParameter(s,n.COMPILE_STATUS);return i?s:(Cs=n.getShaderInfoLog(s),console.error("*** Error compiling shader "+s+":"+Cs),e.trigger("error",{shader:s,source:t,type:r,error:Cs,offset:o||0}),n.deleteShader(s),null)}function YE(e,t,r,o){for(var n=e.gl,s=n.createProgram(),i=0;i<t.length;++i)n.attachShader(s,t[i]);if(r)for(var a=0;a<r.length;++a)n.bindAttribLocation(s,o?o[a]:a,r[a]);n.linkProgram(s);var c=n.getProgramParameter(s,n.LINK_STATUS);return c?s:(Cs=n.getProgramInfoLog(s),console.log("Error in program linking:"+Cs),n.deleteProgram(s),null)}function Ru(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r=[];for(var o in e){var n=e[o],s=void 0;if(t&&(o=t+"."+o),typeof n=="number")r.push({type:"float",method:"1f",name:o,value:n});else if(Array.isArray(n)){if(typeof n[0]=="number")n.length===1?r.push({type:"float",method:"1f",name:o,value:n}):n.length>=2&&n.length<=4?r.push({type:"vec"+n.length,method:n.length+"fv",name:o,value:n}):n.length>4&&r.push({type:"float[]",method:"1fv",name:o+"[0]",value:n});else if(typeof n[0]=="string")r.push({type:"sampler2D",method:"1i",name:o,value:n});else if(Array.isArray(n[0])&&typeof n[0][0]=="number"){if(n[0].length>=2&&n[0].length<=4)for(s=0;s<n.length;s++)r.push({type:"vec"+n[0].length,method:n[s].length+"fv",name:o+"["+s+"]",value:n[s]})}else if(hc(n[0])==="object")for(s=0;s<n.length;s++)r.push.apply(r,ku(Ru(n[s],o+"["+s+"]")))}else typeof n=="boolean"?r.push({type:"bool",method:"1i",name:o,value:n}):typeof n=="string"?r.push({type:"sampler2D",method:"1i",name:o,value:n}):(typeof n>"u"?"undefined":hc(n))==="object"&&r.push.apply(r,ku(Ru(n,o)))}return r}function qC(e){var t=e.getBoundingClientRect();return t.top+t.height>0&&t.top<(window.innerHeight||document.documentElement.clientHeight)}function JE(e){return(e&e-1)===0}function KC(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function XC(e,t){return e&&t?e.toString()!==t.toString():!1}function YC(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(),t.status==200?t.responseText:""}function ew(e){var t=new Set;return Object.assign(e,{on:function(r,o){var n={};n[r]=o,t.add(n)},off:function(r,o){if(o){var n={};n[r]=o,t.delete(n)}else{var s=!0,i=!1,a=void 0;try{for(var c=t[Symbol.iterator](),l;!(s=(l=c.next()).done);s=!0){var u=l.value,p=!0,f=!1,m=void 0;try{for(var h=Object.keys(u)[Symbol.iterator](),g;!(p=(g=h.next()).done);p=!0){var y=g.value;if(y===r){t.delete(u);return}}}catch(x){f=!0,m=x}finally{try{!p&&h.return&&h.return()}finally{if(f)throw m}}}}catch(x){i=!0,a=x}finally{try{!s&&c.return&&c.return()}finally{if(i)throw a}}}},listSubscriptions:function(){var r=!0,o=!1,n=void 0;try{for(var s=t[Symbol.iterator](),i;!(r=(i=s.next()).done);r=!0){var a=i.value;console.log(a)}}catch(c){o=!0,n=c}finally{try{!r&&s.return&&s.return()}finally{if(o)throw n}}},subscribe:function(r){t.add(r)},unsubscribe:function(r){t.delete(r)},unsubscribeAll:function(){t.clear()},trigger:function(r){for(var o=arguments.length,n=Array(o>1?o-1:0),s=1;s<o;s++)n[s-1]=arguments[s];var i=!0,a=!1,c=void 0;try{for(var l=t[Symbol.iterator](),u;!(i=(u=l.next()).done);i=!0){var p=u.value;typeof p[r]=="function"&&p[r].apply(p,ku(n))}}catch(f){a=!0,c=f}finally{try{!i&&l.return&&l.return()}finally{if(a)throw c}}}})}var vu=function(){function e(t,r){var o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};QE(this,e),ew(this),this.gl=t,this.texture=t.createTexture(),this.texture&&(this.valid=!0),this.bind(),this.name=r,this.source=null,this.sourceType=null,this.loading=null,this.setData(1,1,new Uint8Array([0,0,0,255]),{filtering:"linear"}),this.setFiltering(o.filtering),this.load(o)}return ZE(e,[{key:"destroy",value:function(){this.valid&&(this.gl.deleteTexture(this.texture),this.texture=null,delete this.data,this.data=null,this.valid=!1)}},{key:"bind",value:function(t){this.valid&&(typeof t=="number"&&e.activeUnit!==t&&(this.gl.activeTexture(this.gl.TEXTURE0+t),e.activeUnit=t),e.activeTexture!==this.texture&&(this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),e.activeTexture=this.texture))}},{key:"load",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.loading=null,typeof t.url=="string"?(this.url===void 0||t.url!==this.url)&&this.setUrl(t.url,t):t.element?this.setElement(t.element,t):t.data&&t.width&&t.height&&this.setData(t.width,t.height,t.data,t)}},{key:"setUrl",value:function(t){var r=this,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.valid)return this.url=t,this.source=this.url,this.sourceType="url",this.loading=new Promise(function(n,s){var i=t.split(".").pop().toLowerCase(),a=i==="ogv"||i==="webm"||i==="mp4",c=void 0;a?(c=document.createElement("video"),c.autoplay=!0,c.muted=!0,setTimeout(function(){c.play()},1),o.filtering="nearest"):c=new Image,c.onload=function(){try{r.setElement(c,o)}catch(l){console.log("Texture '"+r.name+"': failed to load url: '"+r.source+"'",l,o)}n(r)},c.onerror=function(l){console.log("Texture '"+r.name+"': failed to load url: '"+r.source+"'",l,o),n(r)},KC()&&r.source.slice(0,5)==="data:"||(c.crossOrigin="anonymous"),c.src=r.source,a&&r.setElement(c,o)}),this.loading}},{key:"setData",value:function(t,r,o){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.width=t,this.height=r,this.source=o,this.sourceType="data",this.update(n),this.setFiltering(n),this.loading=Promise.resolve(this),this.loading}},{key:"setElement",value:function(t,r){var o=this,n=t;if(typeof t=="string"&&(t=document.querySelector(t)),t instanceof HTMLCanvasElement||t instanceof HTMLImageElement||t instanceof HTMLVideoElement)this.source=t,this.sourceType="element",t instanceof HTMLVideoElement?(this.width=this.source.videoWidth,this.height=this.source.videoHeight,t.addEventListener("canplaythrough",function(){o.intervalID=setInterval(function(){o.update(r)},15)},!0),t.addEventListener("ended",function(){t.currentTime=0,t.play()},!0)):this.update(r),this.setFiltering(r);else{var s="the 'element' parameter (`element: "+JSON.stringify(n)+"`) must be a CSS ";s+="selector string, or a <canvas>, <image> or <video> object",console.log("Texture '"+this.name+"': "+s,r)}return this.loading=Promise.resolve(this),this.loading}},{key:"update",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.valid&&(this.bind(),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,t.UNPACK_FLIP_Y_WEBGL!==!1),this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.UNPACK_PREMULTIPLY_ALPHA_WEBGL||!1),this.sourceType==="element"&&(this.source instanceof HTMLCanvasElement||this.source instanceof HTMLVideoElement||this.source instanceof HTMLImageElement&&this.source.complete)?(this.source instanceof HTMLVideoElement?(this.width=this.source.videoWidth,this.height=this.source.videoHeight):(this.width=this.source.width,this.height=this.source.height),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.source)):this.sourceType==="data"&&this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.width,this.height,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.source),this.trigger("loaded",this))}},{key:"setFiltering",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.valid){this.powerOf2=JE(this.width)&&JE(this.height),this.filtering=t.filtering||"linear";var r=this.gl;this.bind(),this.powerOf2?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,t.TEXTURE_WRAP_S||r.REPEAT),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,t.TEXTURE_WRAP_T||r.REPEAT),this.filtering==="mipmap"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR_MIPMAP_LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.generateMipmap(r.TEXTURE_2D)):this.filtering==="linear"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR)):this.filtering==="nearest"&&(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST))):(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),this.filtering==="mipmap"&&(this.filtering="linear"),this.filtering==="nearest"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST)):(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR)))}}}]),e}();vu.getMaxTextureSize=function(e){return e.getParameter(e.MAX_TEXTURE_SIZE)};vu.activeUnit=-1;var tw=function(){function e(t,r,o){var n=this;QE(this,e),ew(this),r=r||{},o=o||{},t.hasAttribute("data-fullscreen")&&(t.getAttribute("data-fullscreen")=="1"||t.getAttribute("data-fullscreen")=="true")?(this.width=window.innerWidth,this.height=window.innerHeight,t.width=window.innerWidth,t.height=window.innerHeight):(this.width=t.clientWidth,this.height=t.clientHeight),this.canvas=t,this.gl=void 0,this.deps={},this.program=void 0,this.textures={},this.buffers={},this.uniforms={},this.vbo={},this.isValid=!1,this.animationFrameRequest=void 0,this.BUFFER_COUNT=0,this.vertexString=r.vertexString||`
#ifdef GL_ES
precision mediump float;
#endif
attribute vec2 a_position;
attribute vec2 a_texcoord;
varying vec2 v_texcoord;
void main() {
gl_Position = vec4(a_position, 0.0, 1.0);
v_texcoord = a_texcoord;
}
`,this.fragmentString=r.fragmentString||`
#ifdef GL_ES
precision mediump float;
#endif
varying vec2 v_texcoord;
void main(){
gl_FragColor = vec4(0.0);
}
`;var s=VC(t,r,o.onError);if(!s)return;if(this.gl=s,this.timeLoad=this.timePrev=performance.now(),this.timeDelta=0,this.forceRender=!0,this.paused=!1,this.realToCSSPixels=window.devicePixelRatio||1,t.style.backgroundColor=r.backgroundColor||"rgba(1,1,1,0)",t.hasAttribute("data-fragment"))this.fragmentString=t.getAttribute("data-fragment");else if(t.hasAttribute("data-fragment-url")){var i=t.getAttribute("data-fragment-url");dc.get(i,function(g,y,x){n.load(x,n.vertexString)})}if(t.hasAttribute("data-vertex"))this.vertexString=t.getAttribute("data-vertex");else if(t.hasAttribute("data-vertex-url")){var a=t.getAttribute("data-vertex-url");dc.get(a,function(g,y,x){n.load(n.fragmentString,x)})}if(this.load(),!this.program)return;var c=s.getAttribLocation(this.program,"a_texcoord");this.vbo.texCoords=s.createBuffer(),this.gl.bindBuffer(s.ARRAY_BUFFER,this.vbo.texCoords),this.gl.bufferData(s.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),s.STATIC_DRAW),this.gl.enableVertexAttribArray(c),this.gl.vertexAttribPointer(c,2,s.FLOAT,!1,0,0);var l=s.getAttribLocation(this.program,"a_position");if(this.vbo.vertices=s.createBuffer(),this.gl.bindBuffer(s.ARRAY_BUFFER,this.vbo.vertices),this.gl.bufferData(s.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),s.STATIC_DRAW),this.gl.enableVertexAttribArray(l),this.gl.vertexAttribPointer(l,2,s.FLOAT,!1,0,0),t.hasAttribute("data-textures")){var u=t.getAttribute("data-textures").split(",");for(var p in u)this.setUniform("u_tex"+p,u[p])}var f={x:0,y:0};document.addEventListener("mousemove",function(g){f.x=g.clientX||g.pageX,f.y=g.clientY||g.pageY},!1);var m=this;function h(){m.nMouse>1&&m.setMouse(f),m.resize()&&(m.forceRender=!0),m.render(),m.animationFrameRequest=window.requestAnimationFrame(h)}return this.setMouse({x:0,y:0}),h(),this}return ZE(e,[{key:"destroy",value:function(){cancelAnimationFrame(this.animationFrameRequest),this.animated=!1,this.isValid=!1;for(var t in this.textures)t.destroy&&t.destroy();this.textures={};for(var r in this.attribs)this.gl.deleteBuffer(this.attribs[r]);this.gl.useProgram(null),this.gl.deleteProgram(this.program);for(var o in this.buffers){var n=this.buffers[o];this.gl.deleteProgram(n.program)}this.program=null,this.gl=null}},{key:"load",value:function(t,r){var o=this;r&&(this.vertexString=r),t&&(this.fragmentString=t);var n=this.fragmentString.split(/\r?\n/);this.fragmentString=`#define PLATFORM_WEBGL
#line 0
`,n.forEach(function(g,y){var x=g.trim();if(x.startsWith('#include "lygia')){var E=x.substring(15).replace(/\'|\"|\;|\s/g,"");if(E.endsWith("glsl")){if(o.deps[E]===void 0){var R="https://lygia.xyz"+E;o.deps[E]=YC(R)}o.fragmentString+=o.deps[E]+`
#line `+(y+1)+`
`}}else o.fragmentString+=g+`
`}),this.animated=!1,this.nDelta=(this.fragmentString.match(/u_delta/g)||[]).length,this.nTime=(this.fragmentString.match(/u_time/g)||[]).length,this.nDate=(this.fragmentString.match(/u_date/g)||[]).length,this.nMouse=(this.fragmentString.match(/u_mouse/g)||[]).length,this.animated=this.nDate>1||this.nTime>1||this.nMouse>1;var s=this.fragmentString.search(/sampler2D/g);if(s)for(var i=this.fragmentString.split(`
`),a=0;a<i.length;a++){var c=i[a].match(/uniform\s*sampler2D\s*([\w]*);\s*\/\/\s*([\w|\:\/\/|\.|\-|\_]*)/i);if(c){var l=c[2].split(".").pop().toLowerCase();c[1]&&c[2]&&(l==="jpg"||l==="jpeg"||l==="png"||l==="ogv"||l==="webm"||l==="mp4")&&this.setUniform(c[1],c[2])}var u=i[a].match(/\s*void\s*main\s*/g);if(u)break}var p=Mn(this,this.vertexString,this.gl.VERTEX_SHADER),f=Mn(this,this.fragmentString,this.gl.FRAGMENT_SHADER);f?this.isValid=!0:(f=Mn(this,`void main(){
gl_FragColor = vec4(1.0);
}`,this.gl.FRAGMENT_SHADER),this.isValid=!1);var m=YE(this,[p,f]);this.gl.useProgram(m),this.gl.deleteShader(p),this.gl.deleteShader(f),this.program=m,this.change=!0,this.BUFFER_COUNT=0;var h=this.getBuffers(this.fragmentString);Object.keys(h).length&&this.loadPrograms(h),this.buffers=h,this.texureIndex=this.BUFFER_COUNT,this.trigger("load",{}),this.forceRender=!0,this.render()}},{key:"test",value:function(t,r,o){var n=this.vertexString,s=this.fragmentString,i=this.paused,a=this.gl.getExtension("EXT_disjoint_timer_query"),c=a.createQueryEXT(),l=this.isValid;(r||o)&&(this.load(r,o),l=this.isValid,this.forceRender=!0,this.render()),this.paused=!0,a.beginQueryEXT(a.TIME_ELAPSED_EXT,c),this.forceRender=!0,this.render(),a.endQueryEXT(a.TIME_ELAPSED_EXT);var u=this;function p(){u.paused=i,(r||o)&&u.load(s,n)}function f(){u.forceRender=!0,u.render();var m=a.getQueryObjectEXT(c,a.QUERY_RESULT_AVAILABLE_EXT),h=u.gl.getParameter(a.GPU_DISJOINT_EXT);if(m&&!h){var g={wasValid:l,frag:r||u.fragmentString,vert:o||u.vertexString,timeElapsedMs:a.getQueryObjectEXT(c,a.QUERY_RESULT_EXT)/1e6};p(),t(g)}else window.requestAnimationFrame(f)}f()}},{key:"loadTexture",value:function(t,r,o){var n=this;o||(o={}),typeof r=="string"?o.url=r:(typeof r>"u"?"undefined":hc(r))==="object"&&r.data&&r.width&&r.height?(o.data=r.data,o.width=r.width,o.height=r.height):(typeof r>"u"?"undefined":hc(r))==="object"&&(o.element=r),this.textures[t]?this.textures[t]&&(this.textures[t].load(o),this.textures[t].on("loaded",function(s){n.forceRender=!0})):(this.textures[t]=new vu(this.gl,t,o),this.textures[t].on("loaded",function(s){n.forceRender=!0}))}},{key:"refreshUniforms",value:function(){this.uniforms={}}},{key:"setUniform",value:function(t){for(var r={},o=arguments.length,n=Array(o>1?o-1:0),s=1;s<o;s++)n[s-1]=arguments[s];r[t]=n,this.setUniforms(r)}},{key:"setUniforms",value:function(t){var r=Ru(t);for(var o in r)r[o].type==="sampler2D"?this.loadTexture(r[o].name,r[o].value[0]):this.uniform(r[o].method,r[o].type,r[o].name,r[o].value);this.forceRender=!0}},{key:"setMouse",value:function(t){var r=this.canvas.getBoundingClientRect();if(t&&t.x&&t.x>=r.left&&t.x<=r.right&&t.y&&t.y>=r.top&&t.y<=r.bottom){var o=(t.x-r.left)*this.realToCSSPixels,n=this.canvas.height-(t.y-r.top)*this.realToCSSPixels;this.uniform("2f","vec2","u_mouse",o,n)}}},{key:"uniform",value:function(t,r,o){this.uniforms[o]=this.uniforms[o]||{};for(var n=this.uniforms[o],s=arguments.length,i=Array(s>3?s-3:0),a=3;a<s;a++)i[a-3]=arguments[a];var c=XC(n.value,i);if(c||this.change||!n.location||!n.value){n.name=o,n.type=r,n.value=i,n.method="uniform"+t,this.gl.useProgram(this.program),n.location=this.gl.getUniformLocation(this.program,o),this.gl[n.method].apply(this.gl,[n.location].concat(n.value));for(var l in this.buffers){var u=this.buffers[l];this.gl.useProgram(u.program);var p=this.gl.getUniformLocation(u.program,o);this.gl[n.method].apply(this.gl,[p].concat(n.value))}}}},{key:"uniformTexture",value:function(t,r,o){if(this.textures[t]===void 0)this.loadTexture(t,r,o);else{this.uniform("1i","sampler2D",t,this.texureIndex);for(var n in this.buffers){var s=this.buffers[n];this.gl.useProgram(s.program),this.gl.activeTexture(this.gl.TEXTURE0+this.texureIndex),this.gl.bindTexture(this.gl.TEXTURE_2D,this.textures[t].texture)}this.gl.useProgram(this.program),this.gl.activeTexture(this.gl.TEXTURE0+this.texureIndex),this.gl.bindTexture(this.gl.TEXTURE_2D,this.textures[t].texture),this.uniform("2f","vec2",t+"Resolution",this.textures[t].width,this.textures[t].height)}}},{key:"resize",value:function(){if(this.width!==this.canvas.clientWidth||this.height!==this.canvas.clientHeight){this.realToCSSPixels=window.devicePixelRatio||1;var t=Math.floor(this.gl.canvas.clientWidth*this.realToCSSPixels),r=Math.floor(this.gl.canvas.clientHeight*this.realToCSSPixels);return(this.gl.canvas.width!==t||this.gl.canvas.height!==r)&&(this.gl.canvas.width=t,this.gl.canvas.height=r,this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height)),this.width=this.canvas.clientWidth,this.height=this.canvas.clientHeight,this.resizeSwappableBuffers(),!0}else return!1}},{key:"render",value:function(){if(this.visible=qC(this.canvas),this.forceRender||this.change||this.animated&&this.visible&&!this.paused){var t=new Date,r=performance.now();this.timeDelta=(r-this.timePrev)/1e3,this.timePrev=r,this.nDelta>1&&this.uniform("1f","float","u_delta",this.timeDelta),this.nTime>1&&this.uniform("1f","float","u_time",(r-this.timeLoad)/1e3),this.nDate&&this.uniform("4f","float","u_date",t.getFullYear(),t.getMonth(),t.getDate(),t.getHours()*3600+t.getMinutes()*60+t.getSeconds()+t.getMilliseconds()*.001),this.uniform("2f","vec2","u_resolution",this.canvas.width,this.canvas.height);for(var o in this.buffers){var n=this.buffers[o];this.uniform("1i","sampler2D",n.name,n.bundle.input.index)}this.texureIndex=this.BUFFER_COUNT;for(var s in this.textures)this.uniformTexture(s),this.texureIndex++;this.renderPrograms(),this.trigger("render",{}),this.change=!1,this.forceRender=!1}}},{key:"pause",value:function(){this.paused=!0}},{key:"play",value:function(){this.paused=!1}},{key:"renderPrograms",value:function(){var t=this.gl,r=t.canvas.width,o=t.canvas.height;t.viewport(0,0,r,o);for(var n in this.buffers){var s=this.buffers[n];s.bundle.render(r,o,s.program,s.name),t.bindFramebuffer(t.FRAMEBUFFER,null)}t.useProgram(this.program),t.drawArrays(t.TRIANGLES,0,6)}},{key:"getBuffers",value:function(t){var r={};return t&&t.replace(/(?:^\s*)((?:#if|#elif)(?:\s*)(defined\s*\(\s*BUFFER_)(\d+)(?:\s*\))|(?:#ifdef)(?:\s*BUFFER_)(\d+)(?:\s*))/gm,function(){var o=arguments[3]||arguments[4];r["u_buffer"+o]={fragment:"#define BUFFER_"+o+`
`+t}}),r}},{key:"loadPrograms",value:function(t){var r=this,o=this.gl,n=Mn(r,r.vertexString,o.VERTEX_SHADER);for(var s in t){var i=t[s],a=Mn(r,i.fragment,o.FRAGMENT_SHADER,1);a?r.isValid=!0:(a=Mn(r,`void main(){
gl_FragColor = vec4(1.0);
}`,o.FRAGMENT_SHADER),r.isValid=!1);var c=YE(r,[n,a]);i.name=s,i.program=c,i.bundle=r.createSwappableBuffer(r.canvas.width,r.canvas.height,c),o.deleteShader(a)}o.deleteShader(n)}},{key:"createSwappableBuffer",value:function(t,r,o){var n=this.createBuffer(t,r,o),s=this.createBuffer(t,r,o),i=this.gl;return{input:n,output:s,swap:function(){var a=n;n=s,s=a,this.input=n,this.output=s},render:function(a,c,l,u){i.useProgram(l),i.viewport(0,0,a,c),i.bindFramebuffer(i.FRAMEBUFFER,this.input.buffer),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.output.texture,0),i.drawArrays(i.TRIANGLES,0,6),this.swap()},resize:function(a,c,l,u){i.useProgram(l),i.viewport(0,0,a,c),this.input.resize(a,c),this.output.resize(a,c)}}}},{key:"createBuffer",value:function(t,r,o){var n=this.gl,s=this.BUFFER_COUNT;this.BUFFER_COUNT+=2,n.getExtension("OES_texture_float");var i=n.createTexture();n.activeTexture(n.TEXTURE0+s),n.bindTexture(n.TEXTURE_2D,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,t,r,0,n.RGBA,n.FLOAT,null),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);var a=n.createFramebuffer();return{index:s,texture:i,buffer:a,W:t,H:r,resize:function(c,l){n.bindFramebuffer(n.FRAMEBUFFER,a);var u=Math.min(c,this.W),p=Math.min(l,this.H),f=new Float32Array(u*p*4);n.readPixels(0,0,u,p,n.RGBA,n.FLOAT,f),n.bindFramebuffer(n.FRAMEBUFFER,null);var m=s+1,h=n.createTexture();n.activeTexture(n.TEXTURE0+m),n.bindTexture(n.TEXTURE_2D,h),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,c,l,0,n.RGBA,n.FLOAT,null),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texSubImage2D(n.TEXTURE_2D,0,0,0,u,p,n.RGBA,n.FLOAT,f);var g=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(i),n.activeTexture(n.TEXTURE0+s),n.bindTexture(n.TEXTURE_2D,h),s=this.index=s,i=this.texture=h,a=this.buffer=g,this.W=c,this.H=l}}}},{key:"resizeSwappableBuffers",value:function(){var t=this.gl,r=t.canvas.width,o=t.canvas.height;t.viewport(0,0,r,o);for(var n in this.buffers){var s=this.buffers[n];s.bundle.resize(r,o,s.program,s.name)}t.useProgram(this.program)}},{key:"version",value:function(){return"0.1.7"}}]),e}();function JC(){var e=document.getElementsByClassName("glslCanvas");if(e.length>0){window.glslCanvases=[];for(var t=0;t<e.length;t++){var r=new tw(e[t]);r.isValid&&window.glslCanvases.push(r)}}}window.addEventListener("load",function(){JC()});var gc=tw;var rw=e=>{if(!("after"in e))return Promise.resolve(void 0);let t=document.createElement("canvas");return new gc(t).load(It(e.after)),e.render(t),Promise.resolve(void 0)};var ow=e=>{let t="";for(let r=0;r<e.length;r+=3)r+2===e.length?t+=Tu(e[r],e[r+1],0):r+1===e.length?t+=Tu(e[r],0,0):t+=Tu(e[r],e[r+1],e[r+2]);return t},yc=e=>e<10?String.fromCharCode(48+e):(e-=10,e<26?String.fromCharCode(65+e):(e-=26,e<26?String.fromCharCode(97+e):(e-=26,e===0?"-":e===1?"_":"?"))),Tu=(e,t,r)=>{let o=e>>2,n=(e&3)<<4|t>>4,s=(t&15)<<2|r>>6,i=r&63;return yc(o&63)+yc(n&63)+yc(s&63)+yc(i&63)};var nw=async(e,t="svg")=>{let r=new Blob([new TextEncoder().encode(e)]).stream().pipeThrough(new CompressionStream("deflate")),o=new Uint8Array(await new Response(r).arrayBuffer());return`https://www.plantuml.com/plantuml/${t}/~1${ow(o)}`};var sw=async e=>{if(!("after"in e))return;let t=document.createElement("img"),r=await nw(It(e.after));t.src=r,e.render(t)};var _u=Promise.resolve({log:new Uint8Array(0)}),xc,iw=(e,t,r,o)=>(_u=(async()=>{await _u,xc??=await QC(t,r);let n=new Promise(i=>{let a=c=>{if(c.data.type==="stdout"){o(c.data.message);return}c.data.type==="compile"&&(i(c.data),xc.removeEventListener("message",a))};xc.addEventListener("message",a)}),s={type:"compile",input:e};return xc.postMessage(s),n})(),_u),QC=async(e,t)=>{let r=new Worker(e,{type:"module"}),o=new Promise(s=>{let i=a=>{a.data.type==="asset-url"&&(s(),r.removeEventListener("message",i))};r.addEventListener("message",i)}),n={type:"asset-url",url:`${t}`};return r.postMessage(n),await o,r};var aw=(e,t)=>async r=>{if(!("after"in r))return;let o=ZC(),n="Compile is not started yet. Please wait...",s=l=>{n=[...n.split(`
`),l].join(`
`),o.log(n)},i=document.createElement("img"),a=setTimeout(()=>{r.render(o.div),o.log(n)},2e3),{svg:c}=await iw(It(r.after),e,t,s);if(clearTimeout(a),!c){r.render(o.div),o.log(n);return}i.src=await Ns(new Blob([c],{type:"image/svg+xml"})),r.render(i)},ZC=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"}),r=document.createElement("style");r.textContent='*{box-sizing:border-box;}pre{display:block;padding:9.5px;margin:0 0 10px;border:1px solid #ccc;border-radius:4px;height:20em;overflow:auto;font-size:13px;line-height:1.428571429;}pre code{padding:0;font-family:Menlo,Monaco,Consolas,"Courier New",monospace;font-size:inherit;word-break:break-all;word-wrap:break-word;white-space:pre-wrap;color:var(--code-color,#342d9c);background-color: rgba(0,0,0,0);border-radius:0;}',t.append(r);let o=document.createElement("pre"),n=document.createElement("code");return o.append(n),t.append(o),{div:e,log:s=>{n.textContent=s,o.scroll(0,o.scrollHeight)}}};var Mr=()=>/mobile/i.test(navigator.userAgent);var cw="Cannot complete the mapping as an error was thrown from an item";function Pu(e,t,r){let o=new TransformStream({async transform(n,s){try{let i=await n;s.enqueue(i)}catch(i){i instanceof AggregateError&&i.message===cw&&s.error(i)}}});return(async()=>{let n=o.writable.getWriter(),s=[];try{for await(let i of t){let a=Promise.resolve().then(()=>r(i));n.write(a);let c=a.then(()=>s.splice(s.indexOf(c),1));s.push(c),s.length>=e&&await Promise.race(s)}await Promise.all(s),n.close()}catch{let i=[];for(let a of await Promise.allSettled(s))a.status==="rejected"&&i.push(a.reason);n.write(Promise.reject(new AggregateError(i,cw))).catch(()=>{})}})(),Symbol.asyncIterator in o.readable&&typeof o.readable[Symbol.asyncIterator]=="function"?o.readable[Symbol.asyncIterator]():async function*(){let n=o.readable.getReader();for(;;){let{done:s,value:i}=await n.read();if(s)break;yield i}n.releaseLock()}()}async function*lw(e,t){if(e.length===0||e.every(({before:o,after:n})=>o===n))return;let r=X(await Ve());try{let{readable:o,writable:n}=new TransformStream(void 0),s=n.getWriter(),i=Pu(5,e,async l=>{let u=0,p=0;l.before===l.after&&(await s.ready,await s.write({link:l,projectCount:0,replaced:0,done:!0}));let f=Pu(2,new Set(t),async m=>{let h=await eA(l,m,r);if(G(h))throw tA(rn(h));u++,p+=X(h),await s.ready,await s.write({link:l,projectCount:u,replaced:p,done:!1})});await Array.fromAsync(f),await s.ready,await s.write({link:l,projectCount:u,replaced:p,done:!0})}),a=Array.fromAsync(i).then(async()=>{await s.ready,await s.close()}),c=o.getReader();for(;;){let{done:l,value:u}=await c.read();if(l)return;yield u}await a}finally{await ot(r)}}var eA=async(e,t,r)=>{let[o]=await Promise.all([gi(t,e.before,e.after),xe(t,e.before,(n,{persistent:s})=>{if(s)return[e.after,...n.map(i=>i.text).slice(1)]},{socket:r})]);return o},Ir=e=>e.split(`
`).flatMap(t=>[...t.matchAll(/\[((?:[^\[!"#%&'()\*\+,\-\.\/\{\|\}<>_~] |.[^ ]*)[^\[\]]*)\]/g)]).map(([,t])=>t),tA=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var pw=e=>He(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return rA(r);case"table":return oA(r);case"line":return nA(r)}}).map(r=>r).join(`
`),rA=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[`${o}code:${e}`,...t.split(`
`).map(n=>`${o} ${n}`)]},oA=({fileName:e,cells:t,indent:r})=>{let o=" ".repeat(r);return[`${o}table:${e}`,...t.map(n=>`${o} ${n.map(s=>s.map(i=>As(i)).join("")).join(" ")}`)]},nA=({nodes:e,indent:t})=>[`${" ".repeat(t)}${e.map(r=>`${As(r)}`).join("")}`],As=e=>{switch(e.type){case"quote":return`> ${e.nodes.map(t=>As(t)).join("")}`;case"strong":return`[[${e.nodes.map(t=>As(t)).join("")}]]`;case"decoration":{let t=e.decos.map(r=>{let o=parseInt(r.match(/\*-(\d)/)?.[1]??"0");return o>0?"*".repeat(o):r}).join("");return`[${t?`${t} `:""}${e.nodes.map(r=>As(r)).join("")}]`}case"hashTag":return e.href;case"link":return e.pathType==="absolute"?e.raw:e.href;default:return e.raw}};scrapbox.PopupMenu.addButton({title:e=>Ir(e).length>0?"":"",onClick:e=>{let t=pw(e);if(e!=t)return t}});var uw=e=>!e.includes(`
`)&&/\[[^\]]+\]/.test(e);scrapbox.PopupMenu.addButton({title:e=>uw(e)?"[][]":"",onClick:e=>{if(!uw(e))return;let t=e.replaceAll("[","").replaceAll("]","");return(async()=>{let{render:r,dispose:o}=Le();try{let n=scrapbox.Project.name;r({type:"spinner"},{type:"text",text:`create /${n}/${t}`}),await xe(n,t,([{text:s}],{persistent:i})=>{if(!i)return[s,e]}),r({type:"check-circle"},{type:"text",text:`create /${n}/${t}`})}catch(n){if(console.error(n),!(n instanceof Error))throw n;r({type:"exclamation-triangle"},{type:"text",text:`${n.name} ${n.message}`})}finally{await Pe(2e3),o()}})(),`[${t}]`}});var fw=(e,t)=>{switch(e.type){case"title":return"";case"codeBlock":return[e.fileName,`
\`\`\`${uA(e.fileName)}`,e.content,"```\n"].join(`
`);case"table":return sA(e);case"line":return aA(e,t)}},sA=e=>{let t=[e.fileName],r=Math.max(...e.cells.map(o=>o.length));return e.cells.forEach((o,n)=>{t.push(`| ${o.map(s=>s.map(i=>In(i)).join("")).join(" | ")} |`),n===0&&t.push(`|${" -- |".repeat(r)}`)}),t.join(`
`)},iA=" ",aA=(e,t)=>{let r=e.nodes.map(n=>In(n,{section:e.indent===t})).join("").trim();if(r==="")return"";if(e.indent===t)return r;let o=iA.repeat(e.indent-t-1);return/^\d+\. /.test(r)||(o+="- "),o+r},In=(e,t)=>{let{section:r=!1}=t??{};switch(e.type){case"quote":return`> ${e.nodes.map(o=>In(o)).join("")}`;case"helpfeel":return`\`? ${e.text}\``;case"image":case"strongImage":return``;case"icon":case"strongIcon":return["/icons/hr","/scrapboxlab/hr"].includes(e.path)?"---":"";case"strong":return`**${e.nodes.map(o=>In(o)).join("")}**`;case"formula":return`$${e.formula}$`;case"decoration":{let o=e.nodes.map(n=>In(n)).join("");return e.decos.includes("/")&&(o=`*${o}*`),r?(e.decos.includes("*-3")&&(o=`# ${o}
`),e.decos.includes("*-2")&&(o=`## ${o}
`),e.decos.includes("*-1")&&(o=`### ${o}
`)):e.decos.some(n=>/\*-/.test(n[0]))&&(o=`**${o}**`),e.decos.includes("~")&&(o=`~~${o}~~`),o}case"code":return`\`${e.text}\``;case"commandLine":return`\`${e.symbol} ${e.text}\``;case"link":switch(e.pathType){case"root":{let[,o,...n]=e.href.split("/");return`[${e.href}](https://scrapbox.io/${o}/${mw(n.join("/"))})`}case"relative":return`[${e.href}](https://scrapbox.io/${scrapbox.Project.name}/${mw(e.href)})`;default:return e.content===""?` ${e.href} `:`[${e.content}](${e.href})`}case"googleMap":return`[${e.place}](${e.url})`;case"hashTag":return`[#${e.href}](https://scrapbox.io/${scrapbox.Project.name}/${e.href})`;case"numberList":return`${e.number}. ${e.nodes.map(o=>In(o)).join("")}`;case"blank":case"plain":return e.text}},mw=e=>[...e].map((t,r)=>t===" "?"_":!cA.includes(t)||r===e.length-1&&lA.includes(t)?encodeURIComponent(t):t).join(""),cA='@$&+=:;",',lA=':;",',pA=[{extensions:["javascript","js"],fileType:"javascript"},{extensions:["typescript","ts"],fileType:"typescript"},{extensions:["cpp","hpp"],fileType:"cpp"},{extensions:["c","cc","h"],fileType:"c"},{extensions:["cs","csharp"],fileType:"cs"},{extensions:["markdown","md"],fileType:"markdown"},{extensions:["htm","html"],fileType:"html"},{extensions:["json"],fileType:"json"},{extensions:["xml"],fileType:"xml"},{extensions:["yaml","yml"],fileType:"yaml"},{extensions:["toml"],fileType:"toml"},{extensions:["ini"],fileType:"ini"},{extensions:["tex","sty"],fileType:"tex"},{extensions:["svg"],fileType:"svg"}],uA=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return pA.find(r=>r.extensions.includes(t))?.fileType??""};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{(async()=>{try{let t=Cn.parse(e,{hasTitle:!1}),r=Math.min(...t.map(o=>o.indent));await navigator.clipboard.writeText(t.map(o=>fw(o,r)).join(`
`))}catch(t){alert(`Failed to copy:
${JSON.stringify(t)}`)}})()}});var Su=(e,...t)=>{let r=t.reduce((o,n)=>$e(o)?o:o instanceof Promise?o.then(s=>$e(s)?s:n(s)):n(o),e);return r instanceof Promise?r.then(o=>`${o}`):`${e}`};var Fn=e=>e.ok?ae(e):Q({name:"HTTPError",message:`${e.status} ${e.statusText}`,response:e});var dw=e=>window.GM_fetch?.(`https://cdn.syndication.twimg.com/tweet-result?id=${e}&token=x`)?.then?.(t=>_t(Fn(t),r=>r.json()));var bc=e=>{let{fetch:t=globalThis.fetch,...r}=e;return{fetch:t,...r}},hw=e=>typeof e=="object"&&e!==null;var Ms=class e extends Error{name="UnexpectedResponseError";status;statusText;body;path;constructor(t){super(`${t.status} ${t.statusText} when fetching ${t.path.toString()}`),this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.path=t.path,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};var Ec=async e=>{let t=await e.text();if(e.ok)return ae(t);if(e.status===400)return Q({name:"BadRequestError",message:t});try{let r=JSON.parse(t);if(!hw(r)||typeof r.message!="string")throw new Ms({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)});switch(e.status){case 401:return Q({name:"UnauthorizedError",message:r.message});case 403:return Q({name:"NotPrivilegeError",message:r.message});case 404:return Q({name:"NotFoundError",message:r.message});case 422:return Q({name:"InvalidParameterError",message:r.message});case 429:return Q({name:"RateLimitError",message:r.message});default:throw new Ms({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)})}}catch(r){throw r instanceof SyntaxError?new Ms({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)}):r}};var gw=async(e,t)=>{let{title:r,description:o,metadataIsPublic:n,collectionId:s,refererURL:i,accessToken:a,created:c,app:l,fetch:u}=bc(t),p=new FormData;p.append("imagedata",e),p.append("access_token",a),i&&p.append("referer_url",i.toString()),l!==void 0&&p.append("app",l),r!==void 0&&p.append("title",r),o!=null&&p.append("desc",o),s&&p.append("collection_id",s),n&&p.append("metadata_is_public","true"),c!==void 0&&p.append("created_at",`${c}`);let f=await u("https://upload.gyazo.com/api/upload",{method:"POST",mode:"cors",credentials:"omit",body:p}),m=await Ec(f);return B(m)?m:ae(JSON.parse(H(m)))};var yw=(e,t)=>{let r=new FormData;return r.append("data",e),r.append("metadata",JSON.stringify({app:"Gyazo",title:e.name})),GM_fetch(`https://gif.gyazo.com/${t?.teams?"teams":"gif"}/upload`,{method:"POST",body:r,credentials:"include",headers:{Origin:"https://gyazo.com","sec-fetch-site":"same-site"},referrer:"https://gyazo.com/"})};var wc="",xw=!1,kc=new Map,bw=async(e,t,r,o)=>{let n=kc.get(e.href);if(n)return n;if(e.hostname==="video.twimg.com"||`${e}`.endsWith(".svg")){let c=await GM_fetch(e);if(!c.ok)return;let l=c.headers.get("content-type")?.split?.(";")?.[0]??`${e}`.endsWith(".mp4")?"video/mp4":"video/webm",u=new File([await c.blob()],o||`${t}`,{type:l});if(l==="video/mp4"){let m=await yw(u);if(m.ok){let h=new URL(await m.text());return kc.set(e.href,h),h}}let p=await Gf(u,r);if(B(p))throw Error(re(p).name);let f=new URL(H(p).embedUrl);return kc.set(e.href,f),f}if(e.hostname!=="pbs.twimg.com"||!e.pathname.startsWith("/media"))return;if(xw){if(!wc)return}else{let c=await If();if(xw=!0,B(c)){alert("You haven't logged in Gyazo yet, so you can only upload images to scrapbox.io.");return}if(wc=H(c)||"",!wc){alert("You haven't connect Gyazo to scrapbox.io yet.");return}}let s=await GM_fetch(e);if(!s.ok)return;let i=await gw(await s.blob(),{accessToken:wc,refererURL:t,description:o});if(B(i))throw Error(re(i).name);let a=new URL(H(i).permalink_url);return kc.set(e.href,a),a};var kw=[["&","&"],["<","<"],[">",">"],['"',"""],["'","'"]],mA=Object.fromEntries([...kw.map(([e,t])=>[t,e]),["'","'"],[" "," "]]),fA=new Map(kw),HAe=new RegExp(`[${[...fA.keys()].join("")}]`,"g");var dA={entityList:mA},hA=1114111,gA=/&#([0-9]+);/g,yA=/&#x(\p{AHex}+);/gu,Ew=new WeakMap;function Ou(e,t={}){let{entityList:r}={...dA,...t},o=Ew.get(r);return o||(o=new RegExp(`(${Object.keys(r).sort((n,s)=>s.length-n.length).join("|")})`,"g"),Ew.set(r,o)),e.replaceAll(o,n=>r[n]).replaceAll(gA,(n,s)=>ww(s,10)).replaceAll(yA,(n,s)=>ww(s,16))}function ww(e,t){let r=parseInt(e,t);return r>hA?"�":String.fromCodePoint(r)}var Rc=e=>{let t={name:e.user.name,screenName:e.user.screen_name},r=new Date(e.created_at),o=[...e.entities.hashtags.map(i=>({type:"hashtag",...i})),...e.entities.symbols.map(i=>({type:"symbol",...i})),...e.entities.user_mentions.map(i=>({type:"mention",name:i.name,screenName:i.screen_name,indices:i.indices})),...e.entities.urls.map(i=>{let a={type:"url",indices:i.indices,url:new URL(i.expanded_url)};if(e.card&&e.card?.url===i.url){let{description:c,title:l}=e.card.binding_values,u="STRING";c?.type===u&&(a.description=c.string_value),l?.type===u&&(a.title=l.string_value)}return a}),...e.entities.media?.map?.(i=>({type:"media",indices:i.indices,media:e.mediaDetails?.flatMap?.(a=>a.url===i.url?[{type:a.type,url:new URL(a.video_info?.variants?.sort?.((c,l)=>(l.bitrate??0)-(c.bitrate??0))?.[0].url??a.media_url_https)}]:[])??[]}))??[]].sort((i,a)=>i.indices[0]-a.indices[0]),n=[];{let i=0,a=e.text;for(let{indices:c,...l}of o){let u=[...a].slice(0,c[0]-i).join("");n.push({type:"plain",text:Ou(u)}),n.push(l),a=[...a].slice(c[1]-i).join(""),i=c[1]}a&&n.push({type:"plain",text:Ou(a)})}let s={id:e.id_str,content:n,author:t,posted:r,replyCount:"reply_count"in e?e.reply_count:e.conversation_count};return e.self_thread&&(s.rootId=e.self_thread.id_str),e.in_reply_to_status_id_str&&(s.replyId=e.in_reply_to_status_id_str),e.parent&&(s.replyTo=Rc(e.parent)),e.quoted_tweet&&(s.quote=Rc(e.quoted_tweet)),s};var xA=["landing","product","enterprise","pricing","try-enterprise","contact","terms","privacy","jp-commercial-act","support","case","features","business","auth","login","logout","oauth2","_","api","app.html","assets","file","files","billing","billings","config","feed","index","io","new","opensearch","project","projects","search","setting","settings","setup-profile","slide","socket.io","stream","user","users"],vc=(e=scrapbox.Project.name,t=location.host)=>r=>{if(r.host!==t)return r;let[,o,n]=r.pathname.match(/^\/([\w\d][\w\d-]{0,22}[\w\d])(?:\/?|\/(.+))$/)??[];return!o||xA.includes(o)?r:n?o===e?`[${decodeURIComponent(n)}]`:`[/${o}/${decodeURIComponent(n)}]`:`[/${o}]`};var Rw=(e=bA)=>t=>{let[,r]=t.href.match(/^https:\/\/(?:(?:www\.|mobile\.|m\.)?twitter|x)\.com\/[\w\d_]+\/(?:status|statuses)\/(\d+)/)??[];return r?(async()=>{let o=await(dw(r)??Mf(t.href));if(B(o))throw re(o);let n=H(o);return e("images"in n?{...n,id:r}:n,t)})():t},bA=async e=>{if("images"in e)return Is(e);let{quote:t,replyTo:r,...o}=Rc(e);return[...r?[...(await Is(r)).split(`
`).map(n=>` > ${n}`),...r.quote?(await Is(r.quote)).split(`
`).map(n=>` > ${n}`):[]]:[],...(await Is(o)).split(`
`).map(n=>`> ${n}`),...t?(await Is(t)).split(`
`).map(n=>`> > ${n}`):[]].join(`
`)},Is=async e=>{let t=new URL(`https://twitter.com/${"author"in e?e.author.screenName:e.screenName}/status/${e.id}`);if("images"in e)return[`> [@${Nu(e.screenName)} ${t.origin}${t.pathname}]`,...e.description?.split?.(`
`)?.map?.(n=>`> ${Nu(n)}`)??["> [/ no description provided]"],...e.images.length>0?[`> ${e.images.map(n=>`[${n}]`)}`]:[]].join(`
`);let r=e.content,o=e.author.screenName;return[`[@${Nu(o)} ${t}]`,...(await Promise.all(r.map(async n=>{switch(n.type){case"plain":return n.text;case"hashtag":return` #${n.text} `;case"symbol":return` #$${n.text} `;case"mention":return`[@${n.screenName} https://twitter.com/${n.screenName}]`;case"media":{let s=[],i=1;for(;i<n.media.length;i+=2)s.push(`[${await Lu(n.media[i-1],t)}] [${await Lu(n.media[i],t)}]`);return i===n.media.length&&s.push(`[${await Lu(n.media[i-1],t)}]`),`
${s.join(`
`)}
`}case"url":return`${vc()(n.url)} `}}))).join("").split(`
`)].join(`
`)},Tc="",EA=async()=>{if(Tc)return Tc;let e=await yr(scrapbox.Project.name);if(B(e))throw new Error(re(e).name);return Tc=H(e).id,Tc},Lu=async(e,t)=>await bw(e.url,t,await EA(),"")??e.url,Nu=e=>e.replace(/\b/gm,"").replace(/[\s\r\n\u2028\u2029]+/gm," ").replace(/\s*[[\]`]\s*/g," ").trim();var vw=e=>window.GM_fetch?.(`https://t.co/${e}`)?.then?.(t=>_t(Fn(t),async r=>{let o=new DOMParser().parseFromString(await r.text(),"text/html");try{return new URL(o.title)}catch(n){if(n instanceof TypeError)return;throw n}}));var Tw=e=>{let t=window.GM_fetch;if(["bit.ly","amzn.to","amzn.asia","goo.gl","s.nikkei.com","apple.co","nico.ms","w.wiki"].includes(e.hostname)&&t)return t(e).then(o=>o.ok?new URL(o.url):e);if(e.hostname!=="t.co")return e;let r=vw(e.pathname.slice(1));return r?r.then(o=>fl(o,()=>e,n=>n??e)):e};var _w=e=>{if(!e.pathname.startsWith("/wiki/"))return e;if(!/^\w+\.wikipedia\.org$/.test(e.hostname)){let[,n]=e.hostname.match(/^(\w+)\.m\.wikipedia\.org$/)??[];if(!n)return e;e.hostname=`${n}.wikipedia.org`}let t=decodeURIComponent(e.pathname.slice(6)),r=e.hash?decodeURIComponent(e.hash.slice(1)):"",o=`${e.origin}/wiki/${t}`;return r?`[${r} | ${t} - Wikipedia ${o}#${r}]`:`[${t} - Wikipedia ${o}]`};var Pw=e=>{if(e.hostname!=="www.wikiwand.com")return e;let[,t,r]=e.pathname.match(/^\/([^\/]+)\/([^\/]+)/)??[];return!t||!r||(e.hostname=`${t}.wikipedia.org`,e.pathname=`/wiki/${r}`,e.hash=e.hash.startsWith("#/")?`#${e.hash.slice(2)}`:e.hash),e};var Cu=e=>{if(!e.hostname.startsWith("www.google."))return e;let t=e.searchParams.get("url");return t?new URL(decodeURIComponent(t)):e};var Sw=/charset=([^;]+)/,Ow=e=>window.GM_fetch?.(`${e}`)?.then?.(t=>_t(Fn(t),async r=>{let o=r.headers.get("content-type")?.match?.(Sw)?.[1]??await wA(r.clone());return new TextDecoder(o).decode(await r.arrayBuffer())})),wA=async e=>{let t=new DOMParser().parseFromString(await e.text(),"text/html");return t.querySelector("meta[charset]")?.getAttribute?.("charset")??t.querySelector('meta[http-equiv="content-type"]')?.getAttribute?.("content")?.match?.(Sw)?.[1]??"utf-8"};var Lw=(e=kA)=>async t=>e(await RA(t),t),kA=(e,t)=>{let r=($e(e)?e:e.title).replace(/\s/g," ").replaceAll("[","[").replaceAll("]","]");return r?`[${t.hash?`${decodeURIComponent(t.hash.slice(1))} | `:""}${r} ${t}]`:`${t}`},RA=async e=>{let t=Ow(e);if(!t){let o=await Af(e);if(B(o))throw re(o);return H(o)}let r=await t;if(B(r))throw re(r);return new DOMParser().parseFromString(H(r),"text/html")};var Nw=e=>{if(!/^(?:www\.)?amazon(?:\.co|com)?\.(?:au|br|ca|fr|de|in|it|jp|mx|nl|sg|es|tr|ae|uk|cn)$/.test(e.hostname))return e;let[,t]=e.pathname.match(/\/dp\/([\w\d]+)/)??e.pathname.match(/\/gp\/product\/([\w\d]+)/)??e.pathname.match(/\/exec\/obidos\/asin\/([\w\d]+)/)??e.pathname.match(/\/o\/ASIN\/([\w\d]+)/)??[];return t&&(e.hash="",e.search="",e.pathname=`/dp/${t}`),e};var Cw=e=>{if(!/(?:[0-9a-z-]\.)?gyazo\.com/.test(e.hostname))return e;let[,t]=e.pathname.match(/^\/([0-9a-f]{32})(?:\/raw)?$/)??[];return t?`[https://gyazo.com/${t}]`:e};var Aw=(e,...t)=>{if(e instanceof URL)return Su(new URL(e),...t);let r=0,o=0,n=0,s=!1,i=e.split(/(https?:\/\/\S+)/g).map(u=>{if(!/^https?:\/\/\S+$/.test(u))return u;r++;try{let p=Su(new URL(u),...t);return $e(p)?(o++,p):(s=!0,[p,u])}catch(p){return console.error(p),n++,u}});if(!s)return i.join("");let{render:a,dispose:c}=Le(),l=()=>a({type:"spinner"},{type:"text",text:`URL: ${o}/${r} converted, ${n} failed`});return l(),Promise.all(i.map(async u=>{if($e(u))return u;try{let p=await u[0];return o++,p}catch(p){return console.error(p),n++,u[1]}finally{l()}})).then(u=>(a({type:"check-circle"},{type:"text",text:`URL: ${o}/${r} converted, ${n} failed`}),u.join(""))).finally(()=>{setTimeout(c,1e3)})};var Mw=e=>{if(!/^(?:\w+\.nicovideo\.jp|nico\.ms)$/.test(e.hostname))return e;let t=e.pathname.match(/(?:sm|nm|so|ca|ax|yo|nl|ig|na|cw|z[a-e]|om|sk|yk|lv)\d{1,14}$/)?.[0];return t?`[https://nicothumb2img.vercel.app/image/${t}#.png https://nico.ms/${t}]`:e};var Iw=e=>He(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return vA(r);case"table":return TA(r);case"line":return _A(r)}}).map(r=>r).join(`
`),vA=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[`${o}code:${e}`,...t.split(`
`).map(n=>`${o} ${n}`)]},TA=({fileName:e,cells:t,indent:r})=>{let o=" ".repeat(r);return[`${o}table:${e}`,...t.map(n=>`${o} ${n.map(s=>s.map(i=>i.raw).join("")).join(" ")}`)]},_A=({nodes:e,indent:t})=>[`${" ".repeat(t)}${e.map(r=>`${Fs(r)}`).join("")}`],Fs=e=>{switch(e.type){case"quote":return`> ${e.nodes.map(t=>Fs(t)).join("")}`;case"helpfeel":return`[-? ${e.text}]`;case"commandLine":return`[-${e.symbol} ${e.text}]`;case"icon":case"strongIcon":case"image":case"strongImage":case"formula":case"code":case"googleMap":return e.raw;case"strong":return`[[${e.nodes.map(t=>Fs(t)).join("")}]]`;case"decoration":{e.decos.includes("-")||e.decos.push("-");let t=e.decos.map(r=>{let o=parseInt(r.match(/\*-(\d)/)?.[1]??"0");return o>0?"*".repeat(o):r}).join("");return`[${t?`${t} `:""}${e.nodes.map(r=>Fs(r)).join("")}]`}case"link":switch(e.pathType){case"root":case"relative":return`[- [${e.href}]]`;case"absolute":return`[- ${e.content?`${e.content} `:""}${e.href}]]`}case"hashTag":return`[- #${e.href}]`;case"numberList":return`${e.number}. ${e.nodes.map(t=>Fs(t)).join("")}`;case"blank":case"plain":return`[- ${e.text}]`}};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=Iw(e);if(e!==t)return t}});var Au=e=>{let t=e.indexOf(`
`);if(t<0)return;let r=e.slice(0,t).split(`
`).map(s=>{let[i="",a=""]=s.split(" => ",2);return[i,a]});if(r.length===0)return;let o=e.slice(t+2).split(`
`);if(o.length===0)return;for(let[s,i]of r){let a=s.match(/^\/(.*?)\/([gimy]*)$/);if(a){let c=new RegExp(a[1],a[2]);o=o.map(l=>l.replace(c,i.replaceAll("\\n",`
`)))}else o=o.map(c=>c.replaceAll(s,i.replaceAll("\\n",`
`)))}let n=`${e.slice(0,t+2)}${o.join(`
`)}`;if(e!==n)return n};scrapbox.PopupMenu.addButton({title:e=>Au(e)?"replace":"",onClick:e=>{let t=Au(e);if(t!==void 0)return t}});var Fw=e=>{let t=document.createElement("div"),r=t.attachShadow({mode:"open"}),o=document.createElement("style");o.textContent="dialog::backdrop{background-color:#000c}dialog{flex-direction:column;align-items:center;row-gap:10px;padding:10px;background:unset;margin-top:unset;margin-bottom:unset;border:unset;height:unset}dialog[open]{display:flex}dialog>*{color:var(--page-text-color, #4a4a4a);background-color:var(--dropdown-menu-bg, #fff);border:1px solid rgba(0,0,0,.2);border-radius:6px}@media (min-width: 768px){dialog{padding:30px 0}}.container{display:flex;padding:5px;gap:0.2em;flex-direction:column;width:100%;}.button-container{flex-direction:unset;}.button-container>*{flex:1;}",r.append(o);let n=document.createElement("dialog");n.insertAdjacentHTML("beforeend",`
<div class="container">
Replace Links:
<textarea class="editor"></textarea>
<div class="container button-container">
<button class="cancel">cancel</button>
<button class="replace">replace</button>
</div>
</div>
`),r.append(n);let s=n.querySelector(".editor");s.rows=e.length,s.value=e.join(`
`);let i=()=>{n.style.minWidth=`${Math.max(...s.value.split(`
`).map(u=>[...u].length))+6}em`};i(),s.addEventListener("input",i);let a=n.querySelector(".cancel"),c=n.querySelector(".replace"),l=new Promise(u=>{let p=()=>{u({convert:!1}),t.remove()};n.addEventListener("close",p),n.addEventListener("click",p),a.addEventListener("click",p),c.addEventListener("click",()=>{let f=s.value.split(`
`);u({convert:!0,links:e.flatMap((m,h)=>m===f[h]||m===""||!f[h]?[]:[{before:m,after:f[h]??m}])}),t.remove()}),n.querySelector(".container").addEventListener("click",f=>{f.stopPropagation()})});return document.body.append(t),n.showModal(),l};var Uw=async(e,t)=>{let r=Ir(e),o=await Fw([...new Set(r)]);if(!o.convert||o.links.length===0)return;let n=new Map(o.links.map(s=>[s.before,Le()]));for await(let{link:s,projectCount:i,replaced:a,done:c}of lw(o.links,t)){let l=n.get(s.before);if(!l)return;if(c){l.render({type:"check-circle"},{type:"text",text:`"${s.after}", ${a}l. ${i}p.`}),setTimeout(()=>l.dispose(),1e3);return}l.render({type:"spinner"},{type:"text",text:`"${s.after}", ${a}l. ${i}p.`})}};var Dw=async(e,t)=>{let r=Ir(e)[0];if(!r)return;let o=window.prompt(`Replace "${r}" to this in ${t.map(a=>`"/${a}"`).join(", ")}`,r)?.replace?.(/[\[\]\n]/g," ")??"";if(o==="")return;let{render:n,dispose:s}=Le(),i=H(await Ve());try{n({type:"spinner"},{type:"text",text:`Replacing links in ${t.length} projects...`});let a=0,l=(await Promise.all(t.map(async u=>{let[p]=await Promise.all([gi(u,r,o),xe(u,r,(f,{persistent:m})=>{if(m)return[o,...f.map(h=>h.text).slice(1)]},{socket:i})]);if(B(p))throw n({type:"exclamation-triangle"},{type:"text",text:`${re(p).name} ${re(p).message}`}),PA(re(p));return a++,n({type:"spinner"},{type:"text",text:`Replacing links in ${t.length-a} projects...`}),H(p)}))).reduce((u,p)=>u+p,0);n({type:"check-circle"},{type:"text",text:`Successfully replaced ${l} links.`})}finally{await ot(i),setTimeout(s,1e3)}},PA=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var $w=e=>{let t=[scrapbox.Project.name,...e];scrapbox.PopupMenu.addButton({title:r=>{let o=Ir(r).length;return o>1?"update links":o===1?"update a link":""},onClick:r=>{let o=Ir(r).length;o>1?Uw(r,t):o===1&&Dw(r,t)}})};scrapbox.PopupMenu.addButton({title:e=>/[\n..。]/.test(e)?"\\n":"",onClick:e=>e.replace(/(\w)\n(\w)/g,"$1 $2").replaceAll(`
`,"").replaceAll(".",`.
`).replaceAll(".",`.
`).replaceAll("。",`。
`)});scrapbox.PopupMenu.addButton({title:e=>/https:\/\/(?:thumb\.|i\.)?gyazo\.com\/[a-z0-9]+/.test(e)?globalThis.GM_fetch?"copy Gyazo OCR":"open Gyazo":"",onClick:async e=>{let t=e.match(/https:\/\/(?:thumb\.|i\.)?gyazo\.com\/([a-z0-9]+)/)?.[1];if(!t)return;if(!globalThis.GM_fetch){window.open(`https://gyazo.com/${t}`);return}let o=(await(await GM_fetch(`https://gyazo.com/${t}.json`)).json()).metadata?.ocr?.description;if(o)try{await navigator.clipboard.writeText(o)}catch(n){console.error(n),alert(`${n.name} ${n.message}`)}}});scrapbox.PopupMenu.addButton({title:e=>/https:\/\/gyazo\.com\/[a-z0-9]+/.test(e)?"":"",onClick:e=>{let t=e.match(/https:\/\/gyazo\.com\/([a-z0-9]+)/)?.[1];t&&window.open(`https://gyazo.com/${t}/transform`)}});var jw=e=>{let t="",r=0;for(let o of e)if(o.type!=="title"){if(o.indent>r)for(let n=r;n<o.indent;n++)t+=Us(`${n!==r?"\\item":""}\\begin{itemize}`,n*2)+`
`;if(o.indent<r)for(let n=r;n>o.indent;n--)t+=Us("\\end{itemize}",(n-1)*2)+`
`;r=o.indent,t+=Us(`${r>0?"\\item ":""}${SA(o)}`,r*2)+`
`}for(let o=r;o>0;o--)t+=Us("\\end{itemize}",(o-1)*2)+`
`;return t},SA=e=>{switch(e.type){case"codeBlock":return OA(e);case"table":return LA(e);case"line":return NA(e)}},OA=e=>`\\begin{lstlisting}[language=${Tt(AA(e.fileName))},caption=${Tt(e.fileName)},label=lang:${e.fileName},numbers=left]
${e.content}
\\end{lstlisting}`,LA=e=>{let t=`\\caption{${Tt(e.fileName)}}\\label{table:${Tt(e.fileName)}}`,r=Math.max(...e.cells.map(n=>n.length)),o=e.cells.map(n=>` ${n.map(s=>s.map(i=>Un(i)).join("")).join(" & ")}\\\\`);return`\\begin{table}[htbp]
${t}
\\centering
\\begin{tabular}{${"c".repeat(r)}}
${o.length===0?"":o.length===1?` \\toprule
${o.join(`
`)}
\\bottomrule`:` \\toprule
${o[0]}
\\midrule
${o.slice(1).join(`
`)}
\\bottomrule`}
\\end{tabular}
\\end{table}`},NA=e=>e.nodes.map(t=>Un(t)).join(""),Un=e=>{switch(e.type){case"quote":return`\\begin{quote}
${Us(e.nodes.map(t=>Un(t)).join(""),2)}
\\end{quote}`;case"image":case"strongImage":return`\\begin{figure}[hbtp]
iamge:\\url{${e.src}}
\\end{figure}`;case"icon":case"strongIcon":return`\\textit{${Tt(e.path)}}`;case"strong":return`\\textbf{${e.nodes.map(t=>Un(t)).join("")}}`;case"formula":return`$${e.formula}$`;case"decoration":{let t=e.nodes.map(r=>Un(r)).join("");return e.decos.includes("/")&&(t=`\\textit{${t}}`),e.decos.some(r=>/\*-/.test(r[0]))&&(t=`\\textbf{${t}}`),e.decos.includes("_")&&(t=`\\uline{${t}}`),e.decos.includes("-")&&(t=`\\sout{${t}}`),t}case"numberList":return`${e.number}. ${e.nodes.map(t=>Un(t)).join("")}`;case"helpfeel":return`\\lstinline!? ${Tt(e.text)}!`;case"code":return`\\lstinline!${Tt(e.text)}!`;case"commandLine":return`\\lstinline!${Tt(e.symbol)} ${Tt(e.text)}!`;case"link":return e.pathType==="absolute"?e.content===""?`\\url{${e.href}}`:`\\href{${e.href}}{${Tt(e.content)}}`:Tt(e.href);case"googleMap":return`\\href{${e.url}}{${Tt(e.place)}}`;case"hashTag":return Tt(`#${e.href}`);case"blank":case"plain":return Tt(e.text)}},CA=[{extensions:["javascript","js"],fileType:"javascript"},{extensions:["typescript","ts"],fileType:"typescript"},{extensions:["cpp","hpp"],fileType:"C++"},{extensions:["c","cc","h"],fileType:"C"},{extensions:["cs","csharp"],fileType:"cs"},{extensions:["markdown","md"],fileType:"markdown"},{extensions:["htm","html"],fileType:"html"},{extensions:["json"],fileType:"json"},{extensions:["xml"],fileType:"xml"},{extensions:["yaml","yml"],fileType:"yaml"},{extensions:["toml"],fileType:"toml"},{extensions:["ini"],fileType:"ini"},{extensions:["tex","sty"],fileType:"tex"},{extensions:["svg"],fileType:"svg"}],AA=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return CA.find(r=>r.extensions.includes(t))?.fileType??""},Tt=e=>e.replaceAll("\\","\\textbackslash ").replaceAll("#","\\#").replaceAll("%","\\%").replaceAll("$","\\$").replaceAll("&","\\&").replaceAll("~","\\textasciitilde ").replaceAll("^","\\textasciicircum ").replaceAll("_","\\_").replaceAll("{","\\{").replaceAll("}","\\}").replaceAll("|","\\textbar ").replaceAll("<","\\textless ").replaceAll(">","\\textgreater "),Us=(e,t)=>e.split(`
`).map(r=>`${" ".repeat(t)}${r}`).join(`
`);scrapbox.PopupMenu.addButton({title:"TeX",onClick:e=>{navigator.clipboard.writeText(jw(He(e))).catch(t=>{console.error(t),alert(`${t.name} ${t.message}
${t.stack}`)})}});var _c="https://keicho.herokuapp.com/api/";var Bw=async(e,t)=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let r=await window.GM_fetch(`${_c}web/`,{mode:"cors",method:"POST",body:JSON.stringify({user:"nobody",talk:t,text:e}),headers:{"Content-Type":"application/json"}});if(!r.ok)return{ok:!1,value:{name:"ResponseError",res:r}};let o=await r.json();return{ok:!0,value:{text:o.text,buttons:o.buttons,canInput:o.can_input}}};var Hw=()=>{let{popupMenu:e,render:t}=MA();Od()?.append?.(e);let r=Br(),o=()=>{requestAnimationFrame(()=>{let n=document.getElementsByClassName("cursor")[0];e.style.top=`${parseInt(n.style.top)+parseInt(n.style.height)+4}px`})};return r.addChangeListener(o),{render:t,visible:()=>!e.hidden,open:()=>e.hidden=!1,close:()=>e.hidden=!0,toggle:()=>e.hidden=!e.hidden,dispose:()=>{e.remove(),r.removeChangeListener(o)}}},MA=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"});t.innerHTML=`
<style>
:host {
position: absolute;
left: 0px;
width:100%;
z-index:300;
user-select:none;
font-family:"Open Sans",Helvetica,Arial,"Hiragino Sans",sans-serif;
pointer-events:none
}
.button-container {
position: relative;
display:inline-block;
max-width:70vw;
min-width:80px;
text-align:center;
background-color:#111;
padding:0 1px;
border-radius:4px;
pointer-events:auto
}
html[data-os*='android'] .button-container {
max-width:90vw
}
html[data-os*='ios'] .button-container {
max-width:90vw
}
.button {
font-size:11px;
color:#eee;
cursor:pointer;
display:inline-block;
padding:0 5px
}
.button:not(:first-of-type) {
border:0;
border-left:1px solid #eee
}
.button.selected {
background-color:#222;
text-decoration:underline
}
html[data-os*='android'] .button {
font-size:13px;
padding:6px;
min-width:12vw
}
html[data-os*='ios'] .button{
font-size:13px;
padding:6px;
min-width:12vw
}
.button div.icon {
height:2em;
max-width:10em;
display:inline-block;
overflow:hidden;
margin-left:1px;
vertical-align:top
}
.button div.icon img {
max-height:100%;
vertical-align:unset
}
</style>
<div class="button-container"></div>
`;let r=t.lastElementChild;return{popupMenu:e,render:(...o)=>{r.textContent="",r.append(...o.map(({text:n,onClick:s})=>{let i=document.createElement("div");return i.classList.add("button"),i.textContent=n,s&&i.addEventListener("click",()=>s()),i}))}}};var Ww=async(e="normal")=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let t=await window.GM_fetch(`${_c}web/create/?mode=${e}`,{mode:"cors"});return t.ok?{ok:!0,value:await t.text()}:{ok:!1,value:{name:"ResponseError",res:t}}};var Gw=e=>`https://keicho.netlify.app/#talk=${e}`;var Vw=e=>{let t=e.split(`
`),r=t[1]??t[0],o=e===t[0]?"":t[0];return o?[o.trim(),r].join(`
`):r};var Pc=async(e,t,r)=>{let o=Br(),n=o.lines.findIndex(i=>i.id===t.id);n<0&&(n=o.lines.findIndex(i=>i.text===t.text)),n<0&&(n=Math.min(r,Math.max(0,o.lines.length-1)));let s=o.lines[n].text;return Gi().clear(),o.setPosition({line:n,char:[...s].length}),await Je(`
${e}`),o.getPosition().line};var zw=e=>He(e,{hasTitle:!1}).map(t=>{if(t.type==="title")return t.text.trimEnd();let r=" ".repeat(t.indent);switch(t.type){case"codeBlock":return[`${r}${t.fileName}`,...t.content.split(`
`).map(o=>`${r} ${o}`)].join(`
`).trimEnd();case"table":return[`${r}${t.fileName}`,...t.cells.map(o=>`${r} ${o.flatMap(n=>n.map(s=>Sc(s))).join(" ")}`)].join(`
`).trimEnd();case"line":return`${r}${t.nodes.map(o=>Sc(o)).join("")}`.trimEnd()}}).join(`
`),Sc=e=>{switch(e.type){case"quote":return`> ${e.nodes.map(t=>Sc(t)).join("")}`;case"helpfeel":case"commandLine":return e.raw;case"strongImage":case"image":case"strongIcon":case"icon":case"googleMap":return"";case"strong":case"decoration":case"numberList":return e.nodes.map(t=>Sc(t)).join("");case"formula":return`\\(${e.formula}\\)`;case"code":return` ${e.text} `;case"blank":case"plain":return e.raw;case"hashTag":return e.href;case"link":switch(e.pathType){case"absolute":return e.content?` ${e.content} `:"";case"root":return e.href.split("/").pop()??"";case"relative":return e.href}}};var Dn=e=>/^[((]/.test(e);var Kw=async e=>{let t=scrapbox.Page.lines;if(!t)return;let{cursor:r,selection:o}=Lt(),n=e?.entire||o.hasSelectionAll(),s=n?t.map(_=>_.text).join(`
`):o.getSelectedText(),i=e?.botIcon??"[/nishio/nisbot.icon]",{render:a,visible:c,open:l,close:u,dispose:p}=Hw();u();let f=new Set,m=()=>{p();for(let _ of f)_()},h=_=>f.add(_),g={text:"Exit",onClick:m},y=e?.talkId||qw(s)||(n?"":qw(t.slice(0,1+r.getPosition().line).map(_=>_.text).join(`
`))),x=!y;if(!y){let _=Ww(e?.mode),S=setTimeout(()=>{a({text:"Start talking..."}),l();let M=0;S=setInterval(()=>{a({text:`Start talking${".".repeat(M%3)}`}),M++},1e3)},1e3),A=await _;if(clearTimeout(S),!A.ok){if(A.value.name==="GMFetchNotAvailableError"){alert("`GM_fetch` is not available. Please use Tampermonkey and install `GM_fethc`.");return}if(A.value.name==="ResponseError"){a({text:`Error: ${A.value.res.status} ${A.value.res.statusText}`},g),l(),console.error(`Error: ${A.value.res.status} ${A.value.res.statusText}`,await A.value.res.text());return}return}y=A.value}let E=y,R=o.normalizeOrder(o.getRange()),b=n?t.length-1:R.end.line,v=t[b],k=n?"":" ".repeat(Math.min(...t.slice(R.start.line,R.end.line+1).map(_=>Er(_.text)))),O=async _=>{let S=await Bw(_,E);if(!S.ok)switch(S.value.name){case"ResponseError":return a({text:`Error: ${S.value.res.status} ${S.value.res.statusText}`},g),l(),console.error(`Error: ${S.value.res.status} ${S.value.res.statusText}`,await S.value.res.text()),S;case"GMFetchNotAvailableError":return alert("`GM_fetch` is not available. Please use Tampermonkey and install `GM_fethc`."),S}return S},L="",N=async _=>{let S=zw(_).split(`
`).map(I=>I.trim()).join(`
`).trim();S.startsWith(L)&&(S=S.slice(L.length));let A=S.split(`
`);if(A.length===0)return;if(A.every(I=>Dn(I))&&(L=S),A.filter(I=>!Dn(I)).length<2){let I,z;for(let $ of A){if(z=await O($),!z.ok)return z;Dn($)||(I=z)}return I??z}let D=0;{let I;for(;D<A.length&&Dn(A[D]);D++)if(I=await O(A[D]),!I.ok)return I}{let I=await O("まず聞いて");if(!I.ok)return I}for(;D<A.length&&!Dn(A[D]);D++){let I=await O(A[D]);if(!I.ok)return I}return await O("おしまい")},P=async _=>{if(scrapbox.Layout!=="page"||_==="")return;let S=N(_),A=setTimeout(()=>{a({text:"Asking..."}),l();let $=0;A=setInterval(()=>{a({text:`Asking${".".repeat($%3)}`}),$++},1e3)},1e3),M=await S;if(clearTimeout(A),!M||!M.ok)return;let{text:D,buttons:I}=M.value,z=Vw(D);if(z.trim()){let $=`${k}${i}${z.includes(`
`)?`
${z.split(`
`).map(q=>` ${k}${q}`).join(`
`)}`:z}
${k}`;b=await Pc($,v,b),v=t[b]}a({text:"Send",onClick:T},{text:"🙂",onClick:()=>Je("🙂")},{text:"🙁",onClick:()=>Je("🙁")},...I.map($=>({text:$,onClick:async()=>{b=await Pc($,v,b),v=t[b],await P($)}})),g),l()},T=async()=>{if(scrapbox.Layout!=="page")return;let _=scrapbox.Page.lines,S=r.getPosition().line,[A,M,D]=IA(_,S,i);A!==""&&(b=D,v=_[b],k=" ".repeat(Math.min(..._.slice(M,D+1).map(I=>Er(I.text)))),await P(A))};return x&&(b=await Pc(Gw(E),v,b),v=t[b]),await P(s),{ask:T,open:l,close:u,visible:c,exit:m,onExit:h}},qw=e=>{for(let t of e.split(`
`).reverse()){let r=t.match(/https?:\/\/keicho\.netlify\.app\/#talk=(\w+)/)?.[1];if(r)return r}},IA=(e,t,r)=>{let o=Math.max(e.findLastIndex((s,i)=>i<t&&s.text.trim().startsWith(r)),1),n=o+ho(o,e)+1;return[e.slice(n,t+1).map(s=>s.text.trim()).join(`
`).trim(),n,t]};scrapbox.PopupMenu.addButton({title:"",onClick:e=>`[_ ${e}]`});scrapbox.PopupMenu.addButton({title:"",onClick:e=>`[$ ${e}]`});var Xw=[Oo,Lo,No];scrapbox.PopupMenu.addButton({title:e=>{let t=kr({project:scrapbox.Project.name,mode:"noopen",hooks:Xw});return!t||t.hookName.includes("default")?"":t.hookName.includes("task")?"":t.hookName.includes("split")?"":""},onClick:()=>{let e=window.prompt("Create a new page at",scrapbox.Project.name);e&&kr({project:e,mode:"noopen",hooks:Xw})?.()}});scrapbox.PopupMenu.addButton({title:e=>/(https?:\/\/[^\s]+)/g.test(e)?"":"",onClick:e=>{let t=e.replace(/(https?:\/\/[^\s]+)/g,"[$1#.jpg]");if(e!==t)return t}});scrapbox.PopupMenu.addButton({title:"S",onClick:e=>{window.open(`https://scrapbox.io/${scrapbox.Project.name}/search/page?q=${e}`)}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\[(.*)\]/g,"$1")).join(`
`);window.open(`https://www.google.com/search?q=${encodeURIComponent(t)}`)}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=o=>[...o].some(n=>n.charCodeAt(0)>255),r=e.split(/\n/).map(o=>o.replace(/\[(.*)\]/g,"$1")).join(`
`).trim().replace(/\s+/g,"+");t(r)?window.open(`https://www.ldoceonline.com/search/japanese-english/direct/?q=${encodeURIComponent(r)}`):window.open(`https://www.oxfordlearnersdictionaries.com/search/english/?q=${encodeURIComponent(r)}`)}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\[(.*)\]/g,"$1")).join(`
`);window.open(`https://www.google.com/search?q=${encodeURIComponent(t)}+site:scrapbox.io`)}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>`[" ${e}]`});scrapbox.PopupMenu.addButton({title:"🖍",onClick:e=>`[[${e}]]`});scrapbox.PopupMenu.addButton({title:e=>/\$([^$]+)\$/.test(e)?"L":"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\$([^$]+)\$/g,"[$ $1]")).join(`
`);if(e!=t)return t}});var FA=[Cu,Tw,Cu,Pw,Nw,vc(),Cw,Rw(),_w,e=>{if(e.hostname!=="ekitan.com"||!/^\/transit\/(?:route|first|last)\//.test(e.pathname))return e;let t=e.searchParams.get("dt"),r=e.searchParams.get("tm"),o=e.searchParams.get("sr"),n=new URL(e);return n.search="",t&&n.searchParams.append("dt",t),n.pathname.startsWith("/transit/route/")&&(r&&n.searchParams.append("tm",r),o&&n.searchParams.append("sr",o)),n},e=>{if(e.host!==location.host||!e.pathname.startsWith("/api/code/"))return e;let t=encodeURIComponent(`${e.origin}${e.pathname}`);return`${e}`.endsWith(".svg")?`[https://svg-hosting.vercel.app/api/svg?url=${t} ${e}]`:`${e}`.endsWith(".mlt")?`[https://aa2svg.vercel.app/svg/${t}?width=1000 ${e}]`:e},e=>{if(e.hostname==="raw.githubusercontent.com")return`[https://code2svg.vercel.app/svg/${e.origin}${e.pathname}#.svg ${e}]`;if(e.hostname!=="github.com")return e;let[t,r,o]=e.pathname.match(/^\/([^\\]+)\/([^\\]+)\/blob\/(.+)$/)?.slice?.(1)??[];if(!t||!r||!o)return e;let[,n,s]=e.hash.match(/L(\d+)-L(\d+)/)??e.hash.match(/L(\d+)/)??[];return`[https://code2svg.vercel.app/svg/${n&&s?`L${n}-${s}/`:n?`L${n}/`:""}https://raw.githubusercontent.com/${t}/${r}/${o}#.svg ${e}]`},e=>e.hostname==="github.com"?`${e}`:e,Mw,Lw()];scrapbox.PopupMenu.addButton({title:e=>/https?:\/\/\S+/.test(e)?"URL":"",onClick:e=>{let t=Aw(e,...FA);if(typeof t=="string")return e===t?void 0:t;t.then(r=>{if(e!==r)return Je(r)})}});$w(["takker","takker-memex","takker-private","takker-books"]);if(!/mobile/i.test(navigator.userAgent)){let e=(t,r)=>{t.trim()!==""&&Kw({mode:r}).then(o=>{if(!o)return;let{ask:n,visible:s,onExit:i}=o,a=c=>{!s()||c.key!=="Enter"||!c.ctrlKey||c.altKey||c.shiftKey||(c.preventDefault(),c.stopPropagation(),n())};Xe().addEventListener("keydown",a),i(()=>Xe().removeEventListener("keydown",a))})};scrapbox.PopupMenu.addButton({title:()=>"🤖",onClick:t=>e(t)})}var Ds=(e,t)=>t.map(r=>r.replace(/@yyyy-MM-dd HH:mm:ss@/g,be(e,"yyyy-MM-dd HH:mm:ss")).replace(/@yyyy-MM-dd@/g,be(e,"yyyy-MM-dd")).replace(/@yyyy-MM-dd(?:([+-])(\d+)(w?))?(?:\((Sun|Mon|Tue|Wed|Thu|Fri|Sat)\))?@/g,(o,n,s,i,a)=>{let c=n?n==="+"?Ue(e,parseInt(s)*(i==="w"?7:1)):vr(e,parseInt(s)*(i==="w"?7:1)):e;return be(a?Ue(dt(c),UA(a)):c,"yyyy-MM-dd")}).replace(/@yyyy-ww@/g,`${bo(e)}-w${`${xo(e)}`.padStart(2,"0")}`).replace(/@yyyy-ww([+-])(\d+)(w?)@/g,(o,n,s,i)=>{let a=n==="+"?Ue(e,parseInt(s)*(i==="w"?7:1)):vr(e,parseInt(s)*(i==="w"?7:1));return`${bo(a)}-w${`${xo(a)}`.padStart(2,"0")}`}).replace(/@yyyy@/g,`${bo(e)}`).replace(/@yyyy([+-])(\d+)y@/g,(o,n,s)=>{let i=parseInt(s);return`${bo(e)+(n==="+"?i:-i)}`})),UA=e=>{switch(e){case"Sun":return 0;case"Mon":return 1;case"Tue":return 2;case"Wed":return 3;case"Thu":return 4;case"Fri":return 5;default:return 6}};var Jw=async(e,t,r,o=new Date(2023,1,3))=>{if(scrapbox.Project.name!==e)return()=>{};let n=scrapbox.Project.pages;await new Promise(l=>{let u=setInterval(()=>{if(n.length===0){n=scrapbox.Project.pages;return}clearInterval(u),l()},2e3)});let s=async()=>{let l=new Date,u={start:o,end:Ue(l,1)},{render:p,dispose:f}=Le(),m;try{let h=await Yw(t),g=await Yw(r),y=Yi(u).filter(b=>{let v=Ds(b,h)[0],k=n.find(O=>O.title===v);return!k||!k.exists}),x=Mh(u).filter(b=>{let v=Ds(b,g)[0],k=n.find(O=>O.title===v);return!k||!k.exists});if(y.length===0&&x.length===0)return;let E=y.length+x.length;p({type:"spinner"},{type:"text",text:`create ${E} review pages...`});let R=await Ve();if(B(R))throw re(R);m=H(R);for(let b of[...y.map(v=>Ds(v,h)),...x.map(v=>Ds(v,g))])await xe(e,b[0],(v,k)=>k.persistent?void 0:b,m?{socket:m}:{}),E--,p({type:"spinner"},{type:"text",text:`create ${E} review pages...`});p({type:"check-circle"},{type:"text",text:`created ${y.length+x.length} review pages.`}),o=l}catch(h){p({type:"exclamation-triangle"},{type:"text",text:h instanceof Error?`${h.name} ${h.message}`:"Unknown error! (see developper console)"}),console.error(h)}finally{m&&await ot(m),await Pe(1e3),f()}},i=s(),a=new Date,c=setInterval(()=>{let l=new Date;ht(a,l)||(a=l,i.then(()=>i=s()))},1e4);return()=>(clearTimeout(c),i)},Yw=async e=>{let t=await yi(e[0],e[1],e[2]);if(B(t)){let o=new Error;throw o.name=re(t).name,o.message=`${re(t).message} at fetching /${e[0]}/${e[1]}/${e[2]}`,o}let r=H(t).split(`
`);if(r.length===0)throw new Error(`template "/${e[0]}/${e[1]}/${e[2]}" is empty!`);return r};var wt=e=>`${e.getFullYear()}-${Qt(e.getMonth()+1)}-${Qt(e.getDate())}`,$s=e=>{let[t,r,o]=e.split("-").map(n=>parseInt(n,10));return{year:t,month:r,date:o}},js=e=>`${ea(e)}-w${Qt(xo(e))}`,Oc=e=>{let[t,r]=e.split("-w").map(o=>parseInt(o,10));return dt(Ah(new Date(t,0,1),r))};var Qw="takker-memex",Zw=async(e=new Date(2023,0,24))=>{if(scrapbox.Project.name!==Qw)return()=>{};let t=scrapbox.Project.pages;await new Promise(i=>{let a=setInterval(()=>{if(t.length===0){t=scrapbox.Project.pages;return}clearInterval(a),i()},2e3)});let r=async()=>{let i=new Date,c=Yi({start:e,end:i}).filter(f=>{let m=qr(f),h=t.find(g=>g.title===m);return!h||!h.exists});if(c.length===0)return;let{render:l,dispose:u}=Le(),p;try{l({type:"spinner"},{type:"text",text:`load tasks for ${c.length} diary pages`});let f=new Map,m=new Set,h=c.map(x=>wt(x));for(let{title:x,links:E,project:R}of await Nn(["takker","takker-memex"]))for(let b of[x,...E]){let v=Bt(b);if(!v)continue;if(B(v)){let{name:L,message:N}=re(v);console.error(`[/${R}/${b}]: ${L} ${N}`);continue}let k=ne(b);if(m.has(k))continue;m.add(k);let O=H(v);if(O.freshness?.status!=="done")for(let L of c){let N=So(O,L);if(!N)continue;let P=wt(N.base);h.includes(P)&&(f.set(P,[...f.get(P)??[],N]),Xr(O))}}let g=await Ve();if(B(g))throw re(g);p=H(g);let y=0;l({type:"spinner"},{type:"text",text:`create 0/${c.length} diary pages...`});for(let x of c){let E=qr(x),R=f.get(wt(x))?.map?.(k=>Ee(k))??[],b=`#${be(x,"yyyy-MM-dd")}`,v=`#${be(x,"yyyy-MM-dd HH:mm:ss")}`;await xe(Qw,E,(k,{persistent:O})=>{if(O)return;let L=[...k.map(N=>N.text),...R];return L.some(N=>N.includes(b))?To(L):To([...L,v])},{socket:p}),y++,l({type:"spinner"},{type:"text",text:`create ${y}/${c.length} diary pages...`})}l({type:"check-circle"},{type:"text",text:`created ${c.length} diary pages.`}),e=i}catch(f){l({type:"exclamation-triangle"},{type:"text",text:f instanceof Error?`${f.name} ${f.message}`:"Unknown error! (see developper console)"}),console.error(f)}finally{p&&await ot(p),await Pe(1e3),u()}},o=r(),n=new Date,s=setInterval(()=>{let i=new Date;ht(n,i)||(n=i,o.then(()=>o=r()))},1e4);return()=>(clearTimeout(s),o)};Zw(new Date(2024,11,24));var Iu=(...e)=>{let t=e.flatMap(o=>{if(typeof o=="string")return[Lc(o)];if(Array.isArray(o.type))return[ek(o.type)];switch(o.type){case"text":return[Lc(o.text)];case"group":{let n=Iu(...o.items);return n?[n]:[]}default:return[ek(o.type)]}});if(t.length===0)return;if(t.length===1)return t[0];let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r},Lc=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},ek=e=>{if(Array.isArray(e)){let t=document.createElement("span");t.classList.add("fa-stack");let r=Mu(e[0]);r.classList.add("fa-stack-1x");let o=Mu(e[1]);return o.classList.add("fa-stack-1x"),t.append(r,o),Lc(t)}return Lc(Mu(e))},Mu=e=>{let t=document.createElement("i");switch(e){case"spinner":t.classList.add("fa","fa-spinner");break;case"check-circle":case"gyazo":case"ocr":case"calendar":case"trim":t.classList.add("kamon",`kamon-${e}`);break;case"markdown":case"google":t.classList.add("fab",`fa-${e}`);break;case"copy":case"clipboard":t.classList.add("far",`fa-${e}`);break;default:t.classList.add("fas",`fa-${e}`);break}return t};var{cursor:Fu,selection:Uu}=Lt(),rk=e=>{let{className:t,display:r,onClick:o,context:n="page"}=e,s=document.createElement("div");t&&s.classList.add(t),tk(n)||(s.style.display="none");let i=(...l)=>{if(l.length===1&&l[0]===""){s.style.display="none";return}s.textContent="";let u=Iu(...l);u&&s.append(u)},a=typeof r=="function"?r({cursor:Fu,selection:Uu}):r;return i(...Array.isArray(a)?a:[a]),s.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),o({cursor:Fu,selection:Uu,setDisplay:i})}),{status:s,context:n,update:()=>{if(tk(n)?s.removeAttribute("style"):s.style.display="none",typeof r=="function"){let l=r({cursor:Fu,selection:Uu});i(...Array.isArray(l)?l:[l])}}}},tk=e=>e!=="stream"?scrapbox.Layout===e:scrapbox.Layout==="list"&&location.pathname.startsWith("/stream");var ok=()=>{let e=document.createElement("style");e.textContent=`.status-bar.left {
position: absolute;
top: 0;
left: 0;
max-width: 80vw;
overflow-x: auto;
overflow-y: hidden;
}
.status-bar.left:empty {
display: none;
}
.status-bar.left > div {
border-left: unset;
}
.status-bar.left > div {
border-right: 1px solid var(--tool-light-color, #a9aaaf);
}
.status-bar.left > div:first-of-type {
border-top-left-radius: unset;
}
.status-bar.left > div:last-of-type {
border-top-right-radius: 3px;
}`,document.head.append(e);let t=document.createElement("div");return t.classList.add("status-bar","left"),document.getElementsByClassName("footer")[0].append(t),t};var Du=new Set,{cursor:DA,selection:$A}=Lt(),jA=ok();var qt=e=>{let t=rk(e);return Du.add(t),jA.append(t.status),()=>{t.status.remove(),Du.delete(t)}},$u=()=>{for(let{update:e}of Du)e()};DA.addChangeListener(()=>$u());$A.addChangeListener(()=>$u());scrapbox.addListener("layout:changed",$u);var nk=async(e,t)=>{try{let r=t.getSelectedText()||Ye(e.getPosition().line);if(!r)return;await navigator.clipboard.writeText(r)}catch(r){console.error(r),alert(`Faild to copy:
${JSON.stringify(r)}`)}},sk=async(e,t)=>{try{let r=t.hasSelection(),o=r?t.getRange().start.line:e.getPosition().line,n=r?t.getSelectedText():Ye(o);if(!n)return;await navigator.clipboard.writeText(n),r||t.setRange({start:{line:o,char:0},end:{line:o,char:n.length}}),e.focus(),We("Delete")}catch(r){console.error(r),alert(`Faild to cut:
${JSON.stringify(r)}`)}},ik=async e=>{try{let t=await navigator.clipboard.readText();if(!t)return;e.focus(),await Je(t)}catch(t){console.error(t),alert(`Faild to paste:
${JSON.stringify(t)}`)}},ak=e=>{e.getVisible()&&e.hasFocus&&e.visiblePopupMenu?e.hide():(e.focus(),e.showEditPopupMenu())};globalThis.addEventListener("keydown",e=>{if(e.key!=="i"||e.shiftKey||e.altKey||e.metaKey||!e.ctrlKey||e.isComposing)return;let t=Br();t.hasFocus||(e.preventDefault(),t.focus())});var ju=class{get editor(){return document.getElementById("editor")}get lines(){return document.getElementsByClassName("lines")?.[0]}get computeLine(){return document.getElementById("compute-line")}get grid(){return document.getElementsByClassName("related-page-list clearfix")?.[0]?.getElementsByClassName("grid")?.[0]}get cursorLine(){return document.getElementsByClassName("cursor-line")?.[0]}get textInput(){return document.getElementById("text-input")}get cursor(){return document.getElementsByClassName("cursor")?.[0]}get selections(){return document.getElementsByClassName("selections")?.[0]}get popupMenu(){return document.getElementsByClassName("popup-menu")?.[0]}get pageMenus(){return document.getElementsByClassName("page-menu")?.[0]}get pageInfoMenu(){return document.getElementById("page-info-menu")}get pageEditMenu(){return document.getElementById("page-edit-menu")}get pageEditButtons(){return this.pageEditMenu.nextElementSibling.getElementsByTagName("a")}get randomJumpButton(){return document.getElementsByClassName("random-jump-button")?.[0]}get pageCustomButtons(){return document.getElementsByClassName("page-menu-extension")}},ck=new ju;var lk=e=>new Promise(t=>setTimeout(t,e));async function rr(e,{wait:t=1}={}){let r=ck.textInput;r.focus(),r.value=e;let o=document.createEvent("UIEvent");o.initEvent("input",!0,!1),r.dispatchEvent(o),await lk(t)}if(Mr()){let e="Timestamp";scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/add-time.png"}),scrapbox.PageMenu(e).addItem({title:"#YYYY-MM-DD HH:mm:ss ",onClick:()=>rr(be(new Date,"#yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD HH:mm:ss ",onClick:()=>rr(be(new Date,"yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD",onClick:()=>rr(be(new Date,"yyyy-MM-dd"))}),scrapbox.PageMenu(e).addItem({title:"HH:mm:ss ",onClick:()=>rr(be(new Date,"HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"⬜",onClick:()=>rr("⬜")}),scrapbox.PageMenu(e).addItem({title:"🚧",onClick:()=>rr("🚧")}),scrapbox.PageMenu(e).addItem({title:"⌛",onClick:()=>rr("⌛")}),scrapbox.PageMenu(e).addItem({title:"📝",onClick:()=>rr("📝")}),scrapbox.PageMenu(e).addItem({title:"✅",onClick:()=>rr("✅")}),scrapbox.PageMenu(e).addItem({title:"❌",onClick:()=>rr("❌")})}scrapbox.PageMenu.addItem({title:"Open kakeru",image:"https://i.kakeru.app/15c3b1a40b6b3c2ebd68f33f4c86b3f6-opaque.png",onClick:()=>window.open("https://kakeru.app")});var BA=()=>{let e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.right="0",e.style.textAlign="right",e},$n=new Map,Nc,Bu=()=>{for(let e of $n.values())e.remove();if($n.clear(),scrapbox.Layout!=="page"||scrapbox.Project.name!=="takker-memex"){if(scrapbox.removeListener("lines:changed",Cc),!Nc)return;clearInterval(Nc),Nc=void 0;return}Cc(),scrapbox.addListener("lines:changed",Cc),Nc=setInterval(Cc,60*1e3)},Cc=()=>{let e=ft();for(let t of e){let r=nt(t.text);if(!r?.record?.start){$n.get(t.id)?.remove?.(),$n.delete(t.id);continue}let o=ts(r.record.end??new Date,r.record.start),n=Math.round(o/30),s=n>20?`🍅x${(o/30).toFixed(1)}`:"🍅".repeat(n),i=$n.get(t.id)??BA();wr(t.id)?.append?.(i),$n.set(t.id,i),i.textContent=s}};Bu();scrapbox.addListener("page:changed",Bu);scrapbox.addListener("lines:changed",Bu);async function pk(e,{from:t,to:r,merge:o}){if(t===r)return{success:!0,dup:!1};let n=await Dt(t,e);if(B(n))return{success:!1,at:"from",name:re(n).name,message:re(n).message};let s=H(n);if(!s.persistent)return{success:!1,at:"from",name:"EmptyPageError",message:"The request page is empty."};let i=await Dt(r,e);if(B(i))return{success:!1,at:"to",name:re(i).name,message:re(i).message};let a=H(n);return a.persistent&&!o?{success:!1,at:"to",name:"NoEmptyPageError",message:`The same page already exists in "/${r}"`}:(await xe(r,e,c=>[...c,...s.lines.slice(1)].map(l=>l.text)),await Sf(t,e),{success:!0,dup:a.persistent})}var Hu=async()=>{let e=scrapbox.Page.title,t=scrapbox.Project.name,r=globalThis.prompt(`Take "/${t}/${e}" from "${t}" to:`,"takker");if(!r)return;let{render:o,dispose:n}=Le();o({type:"spinner"},{type:"text",text:`/${t}/${e} → /${r}/${e}`});try{let s=await pk(e,{from:t,to:r,merge:!0});if(!s.success){o({type:"exclamation-triangle"},{type:"text",text:`${s.name} ${s.message}`});return}return o({type:"check-circle"},{type:"text",text:`Moved ${s.dup?"and merged ":""}to "/${r}/${e}".`}),`https://scrapbox.io/${r}/${me(e)}`}catch(s){o({type:"exclamation-triangle"},{type:"text",text:s instanceof Error?`${s.name} ${s.message}`:"Unknown error! (see developper console)"}),console.error(s)}finally{setTimeout(()=>n(),1e3)}};scrapbox.PageMenu.addItem({title:"Transport",onClick:async()=>{await Hu()}});scrapbox.PageMenu.addItem({title:"Transport and Open",onClick:async()=>{let e=await Hu();e&&window.open(e)}});var Wu=e=>e.replace(/[\[\]]/g,"").replace(/\s/g," "),qo=e=>`${e}`.padStart(2,"0"),uk=e=>`${e.getFullYear()}-${qo(e.getMonth()+1)}-${qo(e.getDate())} ${qo(e.getHours())}:${qo(e.getMinutes())}:${qo(e.getSeconds())}`,Gu=e=>`${e.getFullYear()}-${qo(e.getMonth()+1)}-${qo(e.getDate())}`;var mk=async(e,t,r,o)=>{let{render:n,dispose:s}=Le(),i=[],a=[];for(let l of HA(r)){if(l.type==="line"){i.push(`[${Wu(l.text)}~@${Gu(new Date)}]`);continue}let u=`${Wu(l.lines[0])}~@${Gu(new Date)}`;a.push([u,...l.lines.slice(1),"",`#${uk(new Date)}`]),i.push(`[${u}]`)}let c=H(await Ve(o?.socket));try{n({type:"spinner"},{type:"text",text:`Adding ${i.length} items...`}),await xe(e,t,l=>{let u=l.map(f=>f.text),p=u.flatMap((f,m)=>f.trim()==="[/icons/hr.icon]"?[m]:[]).pop()??-1;return p<0?[...u,...i]:[...u.slice(0,p),...i,...u.slice(p)]},{socket:c}),n({type:"spinner"},{type:"text",text:`Create ${a.length} pages...`}),await Promise.all(a.map(l=>xe(e,l[0],u=>[u[0].text,...u.slice(1).map(p=>p.text),...l.slice(1)],{socket:c}))),n({type:"check-circle"},{type:"text",text:"Added to the inbox."})}catch(l){n({type:"exclamation-triangle"},{type:"text",text:"Failed to add (see console). Write directory instead."}),console.error(l),Zn(e,t,[...i,...a].join(`
`))}finally{let l=Pe(1e3);o?.socket&&await ot(c),await l,s()}};function*HA(e){let t=0;for(;t<e.length;){let r=Wh(t,e);if(r===0){yield{type:"line",text:e[t].trim()},t++;continue}let o=Kr(e[t]);yield{type:"block",lines:e.slice(t,t+r+1).map(n=>n.slice(o))},t+=r+1}}var fk=async(e,t)=>{let r=window.prompt("Type all you think of","");if(!r||r.trim()==="")return;let o=r.trim().split(/\s+/);await mk(e,t,o)};var WA="button.";document.getElementById("editor").addEventListener("click",async e=>{let t=e.target;if(t.tagName==="IMG"&&t.classList.contains("icon")&&t.title.endsWith("-button")){e.preventDefault(),e.stopImmediatePropagation();try{let r=`../${encodeURIComponent(t.title)}/${WA}`,{execute:o}=await import(r);o()}catch(r){console.log(r)}}});scrapbox.PageMenu.addItem({title:"Copy link for Markdown",onClick:()=>{let e=scrapbox.Page.title.replaceAll(" ","_").replace(/[/?#\{}^|<>]/g,t=>encodeURIComponent(t));navigator.clipboard.writeText(`[${scrapbox.Page.title}](https://${location.hostname}/${scrapbox.Project.name}/${e}${location.hash})`).catch(t=>alert(`${t.name}: ${t.message}`))}});var Bs=e=>On(...C(()=>{let t={tasks:[],errors:[],load:async()=>{},loading:!1},r=Promise.resolve();return[o=>{t.load=()=>(r=(async()=>{await r,t={...t,loading:!0},o(),await uc(e,60),t={...t,loading:!1},o()})(),r);let n=()=>{r=(async()=>{await r,t={...t,loading:!0},o();let[s,i]=GA(await Nn(e));t={...t,tasks:s,errors:i,loading:!1},o()})()};return n(),pc(e,n)},()=>t]},e)),GA=e=>{let t=new Set,r=[],o=[];for(let{title:n,links:s,project:i}of e)for(let a of[n,...s]){let c=ne(a);if(t.has(c))continue;t.add(c);let l=Bt(a);if(l){if(B(l)){o.push({project:i,title:a,...re(l)});continue}r.push({project:i,title:a,...H(l)})}}return[r,o]};var Ac=()=>{let[e,t]=jr(VA,{isOpen:!1,prevOverflowY:""}),r=qe(null),o=F(()=>{t(i=>{r?.current?.showModal?.();let a=r?.current?.open??!1,c=i.isOpen?i.prevOverflowY:document.documentElement.style.overflowY;return document.documentElement.style.overflowY="hidden",{isOpen:a,prevOverflowY:c}})},[]),n=F(()=>{t(i=>{r?.current?.close?.();let a=r?.current?.open??!1;return a?{isOpen:a,prevOverflowY:i.prevOverflowY}:(i.prevOverflowY?document.documentElement.style.overflowY=i.prevOverflowY:document.documentElement.style.removeProperty("overflow-y"),{isOpen:a})})},[]),s=C(()=>{let i;return a=>{if(!a){i?.(),r.current=null;return}let c=new AbortController;a.addEventListener("cancel",n,{signal:c.signal}),a.addEventListener("click",l=>{if(l.target!==l.currentTarget){l.stopPropagation();return}n()},{signal:c.signal}),i=()=>{c.abort()},r.current=a}},[n]);return{isOpen:e.isOpen,open:o,close:n,ref:s}},VA=(e,t)=>{let r=t(e);return e.isOpen===r.isOpen&&e.prevOverflowY===r.prevOverflowY?e:r.isOpen?r:{isOpen:!1}};var Hs=String.raw`.fa,.far{font-weight:900;font-family:"Font Awesome 5 Free";-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:inline-block;font-style:normal;font-variant:normal;text-rendering:auto;line-height:1}.far{font-weight:400}.fa-spinner{animation:spin 2s infinite linear}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(359deg)}}.fa-spinner:before{content:"\f110"}.fa-sync:before{content:"\f021"}.fa-bookmark:before{content:"\f02e"}.fa-fw{text-align:center;width:1.25em}.kamon:before{font-family:AppIcons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-style:normal;font-variant:normal;font-weight:400;text-decoration:none;text-transform:none}.kamon-check-circle:before{content:"\e018"}.timeline-wrap{display:flex;flex-direction:column;height:100%;overflow-y:hidden;--timeline-bg: var(--dropdown-menu-bg, #fff);--timeline-text-color: var(--page-text-color, #4a4a4a);--timeline-link-color: var(--page-link-color, #5e8af7);--row-header-width: 40px;--timeline-border-color: #888;--timeline-border: solid 1px var(--timeline-border-color);--timeline-hour-height: 40px;background-color:var(--timeline-bg);color:var(--timeline-text-color);.column-header{flex:none;display:flex;flex-direction:row;.cell{flex:1 1 1px;h2{font-weight:400;margin:0;text-align:center;width:100%}}}.week-container{position:relative;height:100%;overflow-y:auto;scrollbar-width:none;.week{flex:auto;display:flex;width:100%;.borders{.border{height:var(--timeline-hour-height)}.border:after{content:attr(data-time);font-size:10px;text-align:right;border-top:var(--timeline-border);position:absolute;width:100%;margin-top:-1px;pointer-events:none}}.timeline{flex:auto;border-left:var(--timeline-border);position:relative;.indicator{position:absolute;top:calc(var(--start) * 40px - .5px);width:100%;height:1px;background-color:red}.copy{position:absolute;top:1.5em}.event{position:absolute;top:calc(var(--start) * 40px - 1px);height:calc(40px * var(--duration) / 60);outline:none;--event-bg2: var(--timeline-text-color);--event-bg: var(--timeline-bg);--event-bg-ratio: 50%;--event-color-ratio: 0%;--event-border-color-ratio: 0%;background-color:color-mix(in srgb,var(--event-bg) var(--event-bg-ratio),var(--event-bg2));color:color-mix(in srgb,var(--event-bg) var(--event-color-ratio),var(--timeline-text-color));border:var(--timeline-border);border-color:color-mix(in srgb,var(--event-bg) var(--event-border-color-ratio),var(--timeline-border-color));border-radius:4px;overflow:hidden;text-wrap:nowrap;max-width:100%;text-overflow:ellipsis}.event[data-status=done]{--event-bg-ratio: 90%;--event-color-ratio: 50%;--event-border-color-ratio: 50%}.event[data-status=expired]{font-weight:700}a.event{--event-bg2: var(--timeline-link-color);text-decoration:none}}.timeline:first-child{border-right:var(--timeline-border)}}}}.wedget{position:fixed;top:60px;left:10px;max-height:calc(90vh - 60px);max-width:100px;width:calc(100vw / 767 * 100 - 10px);min-width:60px;border:solid 1px #888;border-radius:4px;display:flex;flex-direction:column;background-color:var(--dropdown-menu-bg, #fff);color:var(--page-text-color, #4a4a4a);&:not(.open){display:none}}dialog{flex-direction:column;align-items:center;row-gap:10px;&::backdrop{background-color:#000c}padding:10px;background:unset;margin-top:unset;margin-bottom:unset;border:unset;height:unset;overflow-y:hidden;&[open]{display:flex}>*{color:var(--page-text-color, #4a4a4a);background-color:var(--dropdown-menu-bg, #fff);border:1px solid rgba(0,0,0,.2);border-radius:6px}}@media (min-width: 768px){dialog{padding:30px 0;--item-width: 600px}}.result{padding:15px;width:calc(var(--item-width, 100%) - 30px);overflow-y:scroll}.controller{padding:5px;width:calc(var(--item-width, 100%) - 10px);display:flex;flex-wrap:wrap;flex:none;gap:.2em}.progress{flex-grow:1;>*{padding:0 2px}}a{text-decoration:none;color:var(--page-link-color, #5e8af7);&:hover{color:var(--page-link-hover-color, #2d67f5)}}button{cursor:pointer;background:unset;color:unset;border:unset}.copy,.close,.today{font-family:"Font Awesome 5 Free"}.navi{font-family:AppIcons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-style:normal;font-variant:normal;font-weight:400;text-decoration:none;text-transform:none}.close,.today{font-weight:900}ul{list-style-type:none;word-break:break-all}.task-list li:not([data-freshness^="-"]):not([data-freshness="0"]){font-weight:700}.scheduler details li{&[data-status=done]{opacity:.4}&[data-status=expired]{font-weight:700}}.task-list li{&[data-type=deadline] .label.type{color:var(--takker-scheduler-label-deadline-color, rgb(255, 75, 0))}&[data-type=todo] .label.type{color:var(--takker-scheduler-label-todo-color, rgb(246, 170, 0))}&[data-type=note] .label.type{color:var(--takker-scheduler-label-note-color, rgb(200, 200, 203))}&[data-type=up-down] .label.type{color:var(--takker-scheduler-label-up-down-color, rgb(77, 196, 255))}}:is([data-page-no=expired],[data-page-no=errors]) li{opacity:1!important}.scheduler{--takker-scheduler-summary-meter-width: 10em;overflow-y:hidden}.label{display:inline-block;font-size:90%;padding:0 3px}.type{text-align:center;width:2.5em;border:1px solid;border-radius:3px}.freshness{text-align:right;width:2.5em}.start,.duration{text-align:right;width:3em}
`;var jn=({text:e,title:t})=>{let[r,o]=J(""),n=F(async s=>{s.preventDefault(),s.stopPropagation();try{await navigator.clipboard.writeText(e),o("Copied"),await Pe(1e3),o("")}catch(i){alert(`Failed to copy the code block
Error:${i instanceof Error?i.message:i}`),console.error(i)}},[e]);return d("button",{className:"copy",title:t??"Copy",onClick:n,children:r})};var zA=60*60*24*1e3,dk=(e,t)=>{let r=ge(e.refDate),o=(t.getTime()-r.getTime())/zA;switch(r.setHours(0),r.setMinutes(0),e.status){case"done":return-1/0;case"deadline":return o/(e.speed??1);case"todo":return Math.min(o/(e.speed??1),0);case"note":return t.getTime()<r.getTime()?-1/0:-o/(e.speed??1);case"up-down":{let n=e.speed??30;return n*(-1+Math.cos(Math.PI*2*o/n))}}};var gk=(e,t)=>{if(t.score!==e.score)return t.score-e.score;let r=hk(e.freshness),o=hk(t.freshness);return r!==o?o-r:jt(lr(e),lr(t))?-1:1},hk=e=>{switch(e.status){case"todo":return 3;case"note":return 2;case"deadline":return 5;case"up-down":return 1;case"done":return 0}};var Ws=({loading:e,onClick:t})=>e?d("div",{children:d("i",{className:"fa fa-spinner"})}):d("button",{className:"navi reload",onClick:t,children:""});var Bn=()=>{let[e,t]=J(new Date);return oe(()=>{let r=setInterval(()=>t(new Date),6e4);return()=>{clearInterval(r)}},[]),e};var yk=e=>{switch(e){case"todo":return"ToDo";case"note":return"覚書";case"deadline":return"締切";case"up-down":return"浮遊";case"done":return"完了"}};var xk=(e,t)=>new URL(`/${e.project}/${me(e.title)}`,t??location.href);var Mc=({children:e,project:t,title:r,className:o,...n})=>d("a",{...n,className:[o??"","page-link"].join(" "),type:"link",href:xk({project:t,title:r}).pathname,...t===scrapbox.Project.name?{rel:"route"}:{rel:"noopener noreferrer",target:"_blank"},children:e});var bk=({action:e,pActions:t})=>{let r=C(()=>yk(e.freshness.status),[e.freshness.status]),o=C(()=>ar(lr(e)).slice(11)||" ",[lr(e)]),n=C(()=>ls(e),[e]),s=Math.floor(Math.round(e.score)/7),i=Bn(),a=C(()=>e.executed!==void 0&&Eo(Vr(ge(e.executed.start),e.executed.duration),i),[e.executed?.start,e.executed?.duration,i]),c=C(()=>[...t,e].map(l=>`[${l.raw}]`).join(`
`),[t,e]);return d("li",{"data-type":e.freshness.status,"data-freshness":e.score.toFixed(0),"data-level":s,...s<0?{style:{opacity:qA(e).toFixed(2)}}:{},children:[d(jn,{text:c,title:"ここまでコピー"}),d("span",{className:"label type",children:r}),d("i",{className:`label far fa-fw${a?" fa-bookmark":""}`}),d("span",{className:"label freshness",children:e.score.toFixed(0)}),d("time",{className:"label start",children:o}),d("span",{className:"label duration",children:[n,"m"]}),d(Mc,{project:e.project,title:e.raw,children:e.name})]})},qA=e=>Math.max(.8*Math.exp(Math.log(8/7)/7*e.score),.05);var Ek=(e=wt(new Date))=>{let[t,r]=J(e),o=F(()=>{r(s=>{switch(s){case"errors":return"expired";case"expired":return wt(new Date);default:{let i=ge($s(s));return i.setDate(i.getDate()+1),wt(i)}}})},[]),n=F(()=>{r(s=>{let i=wt(new Date);switch(s){case"errors":return"errors";case"expired":return"errors";case i:return"expired";default:{let a=ge($s(s));return a.setDate(a.getDate()-1),wt(a)}}})},[]);return{pageNo:t,next:o,prev:n}};var Ic=(e,t)=>oe(()=>(scrapbox.on(e,t),()=>scrapbox.off(e,t)),[]);var Gs=(e,t)=>{let r=qe({...t});oe(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),oe(()=>{e(r.current)},[e])};var wk=e=>{let t=document.createElement("div");t.dataset.userscriptName="takker-workflow@0.0.1/next-action-viewer";let r=t.attachShadow({mode:"open"});return document.body.append(t),new Promise(o=>mt(d(KA,{getController:o,projects:e}),r))},KA=({getController:e,projects:t})=>{let{tasks:r,errors:o,load:n,loading:s}=Bs(t),{pageNo:i,next:a,prev:c}=Ek(),l=C(()=>{if(i==="errors")return o.map(g=>({name:`${g.title}
name:${g.name}
message:${g.message}`,raw:g.title,freshness:{refDate:{year:9999,month:1,date:1},status:"todo"},project:g.project,generated:!0,score:0}));if(i==="expired"){let g=new Date;return r.flatMap(y=>!cr(y)&&jt(Jh(y),bt(g))&&y.freshness===void 0&&y.recurrence===void 0?[{...y,score:0,freshness:{refDate:y.executed.start,status:"todo"}}]:[]).sort((y,x)=>jt(lr(y),lr(x))?-1:0)}let h=ge($s(i));return r.flatMap(g=>{if(!g.freshness)return[];if(Xr(g))return[];let y=dk(g.freshness,h);return y>-999?[{...g,score:y}]:[]}).sort(gk)},[r,o,i]),{ref:u,open:p,close:f}=Ac();Gs(e,{open:p,close:f});let m=C(()=>[i,...l.map(h=>` [${h.raw}]`)].join(`
`),[l,i]);return Ic("page:changed",f),d(Y,{children:[d("style",{children:Hs}),d("dialog",{ref:u,children:[d("div",{className:"controller",children:[d(jn,{text:m,title:"Copy All Tasks"}),d("span",{children:i}),d("button",{className:"navi left",onClick:c,children:""}),d("button",{className:"navi right",onClick:a,children:""}),d(Ws,{loading:s,onClick:n}),d("button",{className:"close",onClick:f,children:""})]}),d("ul",{className:"result task-list","data-page-no":i,children:l.map((h,g)=>d(bk,{action:h,pActions:l.slice(0,g)},h.raw))})]})]})};var Uc=(e,t)=>`/${e}/${ne(t)}`,Vs=new Map,Vu=new Map,kk=(e,t)=>{Vs.set(e,t);for(let r of Vu.get(e)??[])r(t)},Fc=()=>{Ko!==void 0&&(clearInterval(Ko),Ko=void 0);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=Uc(e,t);if(!Vs.has(r))return;let o=ft().map(n=>n.text);Ko=setInterval(()=>{ne(t)===ne(o[0])&&(kk(r,o),Ko!==void 0&&(clearInterval(Ko),Ko=void 0))},1e3)},Ko;scrapbox.on("page:changed",()=>{scrapbox.off("lines:changed",Fc);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=Uc(e,t);Vs.has(r)&&scrapbox.on("lines:changed",Fc)});var XA=(e,t)=>{let r=Uc(e,t),o=Vs.get(r);return o||(Vs.set(r,[]),Dt(e,t).then(n=>{if(B(n))return[];let s=H(n).lines.map(i=>i.text);kk(r,s),t===scrapbox.Page.title&&!scrapbox.listeners("lines:changed").includes(Fc)&&scrapbox.on("lines:changed",Fc)})),o??[]},Rk=(e,t)=>{let[r,o]=J(XA(e,t));return oe(()=>{let n=Uc(e,t),s=Vu.get(n)??new Set;return s.add(o),Vu.set(n,s),()=>{s.delete(o)}},[e,t]),r};var zu=e=>e.duration===void 0?void 0:bt(Vr(ge(e.start),e.duration)),qu=(e,t)=>{let r=ge(e.start),o=t.getTime(),n=Math.round((o-r.getTime())/(60*1e3));if(n<=0)return[void 0,e];if(e.duration<=n)return[e,void 0];let s={start:e.start,duration:n};return[s,{start:zu(s),duration:e.duration-n}]};var Xo=e=>"title"in e,YA=e=>e.record?.duration!==void 0,vk=(e,t)=>Xo(e)&&e.status==="done"?e.status:YA(e)?Xo(e)&&e.executed?jt(bt(t),e.executed.start)?"moved":"expired":"done":jt(zu(e.plan),bt(t))?Xo(e)?"expired":"done":"undone";var Tk=(e,t)=>{let r=Bt(e.title.slice(1,-1));if(!e.plan.start)return;let o={name:r&&Ne(r)?H(r).name:e.title,plan:{start:bt(e.plan.start),duration:(e.plan.duration??0)/60}};if(e.record.start&&(o.record={start:bt(e.record.start)},e.record.end&&(o.record.duration=ts(e.record.end,e.record.start))),!r||B(r))return o;let n=H(r),s={...o,title:n.raw,project:t};return n.freshness&&(s.status=n.freshness.status),cr(n)||(s.executed=n.executed),s},Ku=(e,t)=>{let r=oa(e);return r!==void 0?{name:e.name,project:t,title:r,executed:e.executed,plan:e.executed,status:e.freshness?.status}:{name:e.name,plan:e.executed}};var _k=(e,t,r)=>{let o=[Xu(e,vr(t,1),r),Xu(e,t,r),Xu(e,Ue(t,1),r)],n=C(()=>o.flat(),o);return C(()=>{let s=Hr(t),i=Lh(t);return n.flatMap(a=>{let[,c]=qu(a.plan,s);if(!c)return[];let[l]=qu(c,i);if(!l)return[];let{plan:u,...p}=a;return[{plan:l,...p}]}).sort((a,c)=>jt(a.plan.start,c.plan.start)?-1:0)},[n,t])},Xu=(e,t,r)=>{let o=Rk(e,qr(t)),n=C(()=>QA(o,e),[o,e]);return C(()=>n.length!==0?n:JA(t,r),[n,t,r])},JA=(e,t)=>t.flatMap(r=>{if(r.freshness?.status==="done")return[];if(cr(r))return[];if(Xr(r)){let n=ra(r,e);return n?[Ku(n,r.project)]:[]}let o=ge(r.executed.start);return ht(o,e)?[Ku(r,r.project)]:[]}),QA=(e,t)=>{let r=[];for(let o of wo(e)){if(zr(o))continue;let n=Tk(o,t);n&&r.push(n)}return r};var Pk=({event:e})=>{let t=C(()=>e.plan.start.hours+e.plan.start.minutes/60,[e.plan.start]),r=C(()=>`--start: ${t}; --duration: ${e.plan.duration};`,[t,e.plan.duration]),o=Bn(),n=C(()=>vk(e,o),[e,o]);return Xo(e)?d(Mc,{className:"event","data-status":n,style:r,title:e.title,project:e.project,children:e.name}):d("div",{className:"event","data-status":n,title:e.name,style:r,children:e.name})};var Sk=({project:e,date:t,tasks:r})=>{let o=_k(e,t,r),n=C(()=>o.flatMap(a=>Xo(a)?[`[${a.title}]`]:[]).join(`
`),[o]),s=Bn(),i=C(()=>ht(s,t)?d("div",{className:"indicator",style:`--start: ${Sh(s)+Th(s)/60}`}):d(Y,{}),[s,t]);return d("div",{className:"timeline",role:"gridcell",children:[o.map(a=>d(Pk,{event:a},a.name)),i,d(jn,{text:n})]})};var Yu=({dateList:e,tasks:t,project:r,hasColumn:o})=>d("div",{className:"timeline-wrap",role:"grid",children:[(o??!0)&&d("div",{className:"column-header",role:"row",children:e.map(n=>d("div",{className:"cell",role:"columnheader",children:d("h2",{children:Zi(n)})},wt(n)))}),d("div",{className:"week-container",role:"presentation",children:d("div",{className:"week",role:"presentation",children:[d("div",{className:"borders",children:[...Array(24).keys()].map(n=>d("div",{className:"border","data-time":`${Qt(n)}:00`},n))}),e.map(n=>d(Sk,{project:r,date:n,tasks:t},wt(n)))]})})]});var Ju=(e,t,r)=>{let[o,n]=J(e),s=F(()=>n(t),[t]),i=F(()=>n(r),[t]),a=F(c=>n(c),[]);return{pageNo:o,next:s,prev:i,jump:a}};var Ok=e=>{let t=qe(new Set),[r,o]=J(e),n=F(()=>{for(let l of t.current)l()},[]),s=F(()=>{o(!0),n()},[]),i=F(()=>o(!1),[]),a=F(()=>o(l=>(l||n(),!l)),[]),c=F(l=>(t.current.add(l),()=>t.current.delete(l)),[]);return{isOpen:r,open:s,close:i,toggle:a,onOpen:c}};var Ck=e=>{let t=document.createElement("div");t.dataset.userscriptName="takker-scheduler/weekly-scheduler";let r=t.attachShadow({mode:"open"});return document.body.append(t),new Promise(o=>mt(d(ZA,{getController:o,projects:e,mainProject:e[0]}),r))},Ak=(e,t)=>{let r=document.createElement("div");r.dataset.userscriptName="takker-scheduler/timeline-wedget";let o=r.attachShadow({mode:"open"});return document.body.append(r),new Promise(n=>mt(d(e1,{getController:n,projects:e,mainProject:e[0],open:t}),o))},Lk=!1,ZA=({getController:e,projects:t,mainProject:r})=>{let{tasks:o,load:n,loading:s}=Bs(t),{pageNo:i,next:a,prev:c,jump:l}=Ju(js(new Date),t1,r1),u=C(()=>{let y=Oc(i);return[0,1,2,3,4,5,6].map(x=>Ue(y,x))},[i]),{ref:p,open:f,close:m,isOpen:h}=Ac();Lk||=h,Gs(e,{open:f,close:m,isOpen:h}),Ic("page:changed",m);let g=F(()=>l(js(new Date)),[l]);return d(Y,{children:[d("style",{children:Hs}),d("dialog",{ref:p,children:[d("div",{className:"controller",children:[d("span",{children:i}),d("button",{className:"navi left",onClick:c,children:""}),d("button",{className:"navi right",onClick:a,children:""}),d("button",{className:"today",onClick:g,children:""}),d(Ws,{loading:s,onClick:n}),d("button",{className:"close",onClick:m,children:""})]}),Lk&&d("div",{ref:Mk,className:"result scheduler","data-page-no":i,children:d(Yu,{dateList:u,tasks:o,project:r})})]})]})},Nk=!1,e1=({projects:e,mainProject:t,getController:r,open:o})=>{let{tasks:n,load:s,loading:i}=Bs(e),{pageNo:a,next:c,prev:l,jump:u}=Ju(new Date,o1,n1),p=C(()=>[a],[a]),f=F(()=>u(new Date),[u]),{isOpen:m,open:h,close:g}=Ok(o);return Nk||=m,Gs(r,{open:h,close:g,isOpen:m}),d(Y,{children:[d("style",{children:Hs}),Nk&&d("div",{className:`wedget${m?" open":""}`,ref:Mk,children:[d("div",{className:"controller",children:[d("span",{children:wt(a)}),d("button",{className:"navi left",onClick:l,children:""}),d("button",{className:"navi right",onClick:c,children:""}),d("button",{className:"today",onClick:f,children:""}),d(Ws,{loading:i,onClick:s})]}),d(Yu,{dateList:p,tasks:n,project:t,hasColumn:!1})]})]})},t1=e=>js(cn(Oc(e),1)),r1=e=>js(Ch(Oc(e),1)),o1=e=>Ue(e,1),n1=e=>vr(e,1),Mk=e=>{let t=e?.getElementsByClassName?.("indicator")?.[0];if(!t)return;let r=globalThis.scrollY;t.scrollIntoView({block:"center"}),globalThis.scroll(0,r)};Qf({project:"takker-dist"});Ri(!0);eh().then(e=>{scrapbox.PageMenu.addItem({title:"Fulltext Search",onClick:()=>{e.toggle()}})});var s1="https://scrapbox.io/files/67344295032adf96d1e4c276.wasm",i1="/api/code/takker-dist/for-any-project-min/esbuild-worker.js";(async()=>{let e=new Request(s1),t=await an(e);t||(t=await fetch(e),await Wi(e,t)),await Eb(await WebAssembly.compileStreaming(t),i1)})();(async()=>{let e=[scrapbox.Project.name,"takker","takker-memex","takker-books","takker-private","villagepump","hub","arpla","work4ai","unnamedcamp","unnamed-project","nishio","enchi","rashitamemo","motoso","shokai","masui","rakusai","yuiseki","akiroom","c4j","miyamonz","mrsekut-p","masuilab","kidaaam-92022284","nwtgck","juneboku","marshmallow-rm","sushitecture","sno2wman","inteltank","issac-37765679","blu3mo","yosider","Mijinko","Mijinko-other","scrapbox-drinkup","nota-techconf","customize","scrapboxlab","scrasobox","programming-notes","tus-alpine","tus-alpine-private","guiland"],t=await FE({projects:e,mark:{...Object.fromEntries([["takker","takker"],["takker-memex","takker"],["takker-books","takker-books"],["takker-private","takker-private"],["nishio","nishio"],["rashitamemo","rashita"],["enchi","雑談_2022-04-12~"],["rakusai","rakusai"],["masui","概要"],["shokai","shokai"],["yuiseki","yuiseki"],["akiroom","はじめに"],["inteltank","sawachin"],["motoso","もとそのもと"],["villagepump","井戸端"],["hub","scrapbox.io%2Fhub_について"],["masuilab","増井研に入ったらまずやること"],["marshmallow-rm","読書猿マシュマロ全質問回答"],["miyamonz","miyamonz"],["mrsekut-p","mrsekut"],["kidaaam-92022284","kidooom"],["c4j","Code_for_Japan"],["suto3","suto3"],["blu3mo","blu3mo"],["nwtgck","nwtgck"],["juneboku","juneboku"],["jigsaw","jgs"],["sno2wman","SnO2WMaN"],["sushitecture","hashrock"],["unnamedcamp","知を営む"],["unnamed-project","unnamed-project"],["issac-37765679","cFQ2f7LRuLYP"],["blu3mo","blu3mo"],["yosider","yosider"],["Mijinko","Mijinko_SD"],["Mijinko-other","Mijinko_SD"],["customize","みんなのカスタマイズ"],["scrapboxlab","入会手続き"],["scrasobox","Scrapboxとあそぶ"],["programming-notes","参加する"],["guiland","概要と参加方法"],["work4ai","work4ai"]].map(([n,s])=>[n,`https://scrapbox.io/api/pages/${n}/${s}/icon`])),"NDLSH-SB":"📚","scrapbox-drinkup":"https://scrapbox.io/assets/img/page-icon/scrapbox_beaver.png","nota-techconf":"https://i.gyazo.com/727f42bbd9e2534d99d70e6ea90705b3.jpg","plurality-japanese":"⿻"},enableSelfProjectOnStart:!0}),r=n=>{n.preventDefault(),n.stopPropagation()},o=()=>document.querySelector(".line .popup-menu")!==null;Xl.bind({"<Tab>":n=>{o()||t.selectNext?.({cyclic:!0})&&r(n)},"<S-Tab>":n=>{o()||t.selectPrev?.({cyclic:!0})&&r(n)},"<Enter>":n=>{o()||t.confirm?.()&&r(n)},"<Esc>":n=>{o()||t.cancel?.()&&r(n)}})})();jE({previewers:[{when:/(?:^|\.)svg$/,preview:BE},{when:/(?:^|\.)glsl$/,preview:rw},{when:/(?:^|\.)(?:plantuml|puml|pu)$/,preview:sw},{when:/(?:^|\.)tikz\(tex\)$/,preview:aw("/api/code/takker-dist/for-any-project-min/tex-worker.js","https://scrapbox.io/files/65d1645c19cd8e002433c3df")}]});Jw("takker",["takker","振り返り(takker-workflow@0.0.1)のtemplate","txt"],["takker","1週間の振り返り(takker-workflow@0.0.1)のtemplate","txt"],new Date(2024,11,24));Mr()&&(qt({display:{type:"caret-left"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?$i():Ii()}}),qt({display:{type:"caret-right"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Di():Mi()}}),qt({display:{type:"caret-up"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?ji():Fi()}}),qt({display:{type:"caret-down"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Bi():Ui()}}),qt({display:{type:"copy"},onClick:async({cursor:e,selection:t})=>await nk(e,t)}),qt({display:{type:"cut"},onClick:async({cursor:e,selection:t})=>await sk(e,t)}),qt({display:{type:"clipboard"},onClick:async({cursor:e})=>await ik(e)}),qt({display:{type:"undo"},onClick:()=>Bd()}),qt({display:{type:"redo"},onClick:()=>Hd()}),qt({display:({cursor:e})=>e.getVisible()&&e.hasFocus&&e.visiblePopupMenu?{type:["i-cursor","slash"]}:{type:"i-cursor"},onClick:({cursor:e})=>ak(e)}));if(Mr()&&scrapbox.Project.name!=="takker-memex"){let e="task";scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/todo-list--v2.png"}),scrapbox.PageMenu(e).addItem({title:"Book starting",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:vo}),scrapbox.PageMenu(e).addItem({title:"Transport",onClick:()=>_o({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"})})}if(Mr()){let e="New Page",t=[Oo,Lo,No];scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/cut-paper.png"}),scrapbox.PageMenu(e).addItem({title:"New Page",onClick:()=>{let r=window.prompt("Create a new page at",scrapbox.Project.name);r&&kr({project:r,mode:"noopen",hooks:t})?.()}}),scrapbox.PageMenu(e).addItem({title:"New Page and Open",onClick:()=>{let r=window.prompt("Create a new page at",scrapbox.Project.name);r&&kr({project:r,mode:"self",hooks:t})?.()}})}scrapbox.PageMenu.addMenu({title:"Add to inbox",image:"https://img.icons8.com/ios/180/FFFFFF/inbox.png",onClick:()=>fk("takker-memex","メモ帳")});(async()=>{let e="next-action",t=`head style[data-userscript-name="${e}"]`;document.querySelector(t)?.remove?.();let r=document.createElement("style");r.dataset.userscriptName=e,r.textContent=`
button:is(#${e}, #scheduler).tool-btn::before {
position: absolute;
font: 900 20px/46px "Font Awesome 5 Free";
}
button#${e}.tool-btn::before {
content: "\\f0ae";
}
button#scheduler.tool-btn::before {
content: "\\f073";
font-weight: 400;
}
button:is(#${e}, #scheduler).tool-btn img {
opacity: 0;
}`,document.head.append(r);let o=["takker-memex","takker"],{open:n}=await wk(o);scrapbox.PageMenu.addMenu({title:e,image:"/assets/img/favicon/apple-touch-icon.png",onClick:n});let s=await Ck(o);scrapbox.PageMenu.addMenu({title:"scheduler",image:"/assets/img/favicon/apple-touch-icon.png",onClick:s.open});{let i="takker-scheduler/wedget",a=JSON.parse(localStorage.getItem(i)??"{}"),c=scrapbox.Project.name;a[c]??=!1;let l=await Ak(o,a[c]),u=()=>{a[c]=!l.isOpen,l.isOpen?l.close():l.open?.(),localStorage.setItem(i,JSON.stringify(a))};Mr()?qt({display:{type:"calendar"},onClick:u}):scrapbox.PageMenu.addItem({title:"toggle wedget",onClick:u})}})();var Ik=e=>String(e).padStart(2,"0"),Fk=e=>`${e.getFullYear()}-${Ik(e.getMonth()+1)}-${Ik(e.getDate())}`;for(let e of document.getElementsByClassName("new-button")){let t=`#${Fk(new Date)}`;e.href=`/${scrapbox.Project.name}/new?body=${encodeURIComponent(`
`+t)}`}console.log('The hrefs of "New Button" have been changed.');scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=Cn.parse(e,{hasTitle:!1});if(console.log("Parserd text:"),console.log(t),navigator.clipboard){let r=a1(t).join(`
`);console.log(r),navigator.clipboard.writeText(r).catch(o=>console.log(o)),console.log("Copied.")}}});function a1(e){let t=Math.min(...e.map(n=>n.indent)),r=t,o=["<p>"];for(let n of e.filter(s=>s.type==="line")){let s=n.indent-r;s<0&&o.push(...[...Array(-s)].map(a=>"</ul>")),s>0&&o.push(...[...Array(s)].map(a=>'<ul style="margin-top: 5px;margin-bottom: 5px;">'));let i=n.nodes.map(a=>Dc(a)).join("");n.indent>t?o.push(`<li>${i}</li>`):o.push(`${i}<br/>`),r=n.indent}return o.push(...[...Array(r-t)].map(n=>"</ul>")),o.push("</p>"),o}function Dc(e){switch(e.type){case"quote":return`<span style="
font-style: italic;
background-color: rgba(128,128,128,0.1);
display: block;
border-left: solid 4px #a0a0a0;
padding-left: 4px;">${e.nodes.map(s=>Dc(s)).join("")}</span>`;case"image":case"strongImage":return`<img src="${e.src}" style="max-width: 50vw;"/>`;case"icon":let t="",r="",o="";switch(e.pathType){case"root":r=`https://scrapbox.io${e.path}`,t=`https://scrapbox.io/api/pages/${e.path}/icon`,o=e.path.replace(/^\/[^\/]+\/(.*)/,"$1");break;case"relative":r=`https://scrapbox.io/${scrapbox.Project.name}/${e.path}`,t=`https://scrapbox.io/api/pages/${scrapbox.Project.name}/${e.path}/icon`,o=e.path;break}return`<a target="_blank" href="${r}"><img style="
height: 1.3em;
vertical-align: top;" src="${t}" alt="${o}" /></a>`;case"strongIcon":return"";case"formula":return`\\( ${e.formula} \\)`;case"helpfeel":return"";case"decoration":let n=e.nodes.map(s=>Dc(s)).join("");return e.decos.includes("*-4")&&(n=`<h4>${n}</h4>`),e.decos.includes("*-3")&&(n=`<h5>${n}</h5>`),e.decos.includes("*-2")&&(n=`<h6>${n}</h6>`),e.decos.includes("*-1")&&(n=`<strong>${n}</strong>`),e.decos.includes("/")&&(n=`<i>${n}</i>`),e.decos.includes("-")&&(n=`<strike>${n}</strike>`),e.decos.includes("!")&&(n=`<pre>${n}</pre>`),n;case"strong":return`<strong>${e.nodes.map(s=>Dc(s)).join("")}</strong>`;case"code":return`<code>${e.text}</code>`;case"commandLine":case"googleMap":return"";case"blank":return`<span>${e.text}</span>`;case"link":switch(e.pathType){case"root":return`<a target="_blank" href="https://scrapbox.io${e.href}">${e.href}</a>`;case"relative":return`<a target="_blank" href="https://scrapbox.io/${scrapbox.Project.name}/${e.href}">${e.href}</a>`;case"absolute":return`<a target="_blank" href="${e.href}">${e.content||e.href}</a>`}case"hashTag":return`<a href="https://scrapbox.io/${scrapbox.Project.name}/${e.href}">#${e.href}</a>`;case"plain":return`<span>${e.text}</span>`}}scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=window.open();t.document.write(`<html>
<body>
<textarea spellcheck="true">${e}</textarea>
</body>
</html>`),t.document.close()}});scrapbox.PopupMenu.addButton({title:e=>{let t=e.replace(/[\r\n]/g,"").length,r=e.trim().split(/[\r\n\s]+/).length;return`${t}c ${r}w`},onClick:()=>null});if(Mr()){let e="task";scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/todo-list--v2.png"}),scrapbox.PageMenu.addMenu({title:"Toggle task",image:"https://img.icons8.com/ios/180/FFFFFF/repeat.png",onClick:Bl}),scrapbox.PageMenu(e).addItem({title:"Add task",image:"https://img.icons8.com/ios/180/FFFFFF/plus-math.png",onClick:rs}),scrapbox.PageMenu(e).addItem({title:"Start task",image:"https://img.icons8.com/ios/180/FFFFFF/start--v1.png",onClick:ko}),scrapbox.PageMenu(e).addItem({title:"End task",image:"https://img.icons8.com/ios/180/FFFFFF/stop-squared.png",onClick:Tr}),scrapbox.PageMenu(e).addItem({title:"Posteriori end task",image:"https://img.icons8.com/ios/180/FFFFFF/end--v1.png",onClick:os}),scrapbox.PageMenu(e).addItem({title:"Book starting",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:async()=>{let[t,r]=c1(),o=Jt().slice(t,r+1).map(n=>{let s=n.text,i=n.text.match(/\[([^\]]+)\]/)?.[1];if(!i)return s;let a=Bt(i);if(!a||!a.ok)return s;let c=a.value;if(c.freshness?.status==="done")return s;let l=So(c);return l.title=`[${i}]`,l?Ee(l):s}).join(`
`);await ct(t,r,o),await vo()}}),scrapbox.PageMenu(e).addItem({title:"Walk a day",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:()=>ns()}),scrapbox.PageMenu(e).addItem({title:"Move today",image:"https://img.icons8.com/ios/180/FFFFFF/date-to.png",onClick:()=>ss()}),scrapbox.PageMenu(e).addItem({title:"Format",image:"https://img.icons8.com/ios/180/FFFFFF/sort-by-start-date.png",onClick:()=>as(scrapbox.Project.name,scrapbox.Page.title)}),scrapbox.PageMenu(e).addItem({title:"Transport",onClick:()=>_o({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"})}),scrapbox.PageMenu(e).addItem({title:"Sync",onClick:()=>window.open("https://script.google.com/macros/s/AKfycbyAgN8nmUXjVXL_tahDzVyyrMzFaI4CJVmIapk8G0GuxxVN-7oUbuDJOf31fP7SFjx9/exec")})}var c1=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=Me();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var Uk="scrapbox-episopass",$c=!1;scrapbox.PopupMenu.addButton({title:e=>$c?"remove EP":/https:\/\/scrapbox\.io\/files\/\w+\.html/.test(e)?"run EP":"",onClick:async e=>{if(document.getElementById(Uk)?.remove(),$c){$c=!1;return}if(!/https:\/\/scrapbox\.io\/files\/\w+\.html/.test(e))return;let t=e.match(/https:\/\/scrapbox\.io(\/files\/\w+\.html)/)[1];try{let o=await(await fetch(t)).text();if(!o.includes("<title>EpisoPass</title>"))return;let n=new Blob([o],{type:"text/html"}),s=URL.createObjectURL(n);document.getElementsByClassName("cursor-line")[0].insertAdjacentHTML("beforeend",`<iframe id="${Uk}" src="${s}" width="800" height="400"></iframe>`),$c=!0;return}catch(r){console.error("Failed to load an EpisoPass html: ",r)}}});export{qt as addButton,Je as insertText,Xl as scrapBindings};
/** @license
* esbuild-wasm@v0.24.0
*
* MIT License
*
* Copyright (c) 2020 Evan Wallace
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
tex-worker.jsvar ht=Object.defineProperty;var Ge=(t,e)=>{for(var r in e)ht(t,r,{get:e[r],enumerable:!0})};var be={};Ge(be,{close:()=>Et,deleteEverything:()=>ue,eof:()=>Rt,eoln:()=>$t,erstat:()=>Lt,executeAsync:()=>xe,get:()=>At,inputln:()=>Mt,pages:()=>C,printBoolean:()=>Pt,printChar:()=>Ut,printFloat:()=>St,printInteger:()=>vt,printNewline:()=>kt,printString:()=>Tt,put:()=>Nt,readFileSync:()=>se,reset:()=>Ft,rewrite:()=>Ct,setConsole:()=>de,setFileLoader:()=>ge,setInput:()=>he,setMemory:()=>me,tex_final_end:()=>ye,writeFileSync:()=>fe});var X={},m=[],re,O="",P=null,G=null,N=null,F=null,W=null,He=null,H=null,C=1100,z=(C-100)*1024*64,gt=C*1024*64,oe=0,I=!1,xt=()=>{W&&(W[z>>2]=z+8,W[z+4>>2]=gt),F.asyncify_start_unwind(z),oe=oe+1},yt=()=>{F.asyncify_start_rewind(z),F.main()},bt=()=>{oe=oe-1,F.asyncify_stop_rewind()},ue=()=>{m=[],X={},P=null,G=null,N=null,re=void 0,H=null,F=null,W=null,I=!1},fe=(t,e)=>{X[t]=e},se=t=>{for(let e of m)if(e.filename==t)return e.content.slice(0,e.position);throw Error(`Could not find file ${t}`)},Be=(t,e)=>{let r=I;I&&(bt(),I=!1);let n=new Uint8Array;if(X[t])n=X[t];else if(e=="r"&&m.findIndex(s=>s.filename==t&&!s.erstat)==-1)return r||t.match(/\.(aux|log|dvi)$/)?(m.push({filename:t,erstat:1}),m.length-1):(xt(),I=!0,setTimeout(async()=>{try{let s=await He(t);X[t]=s}catch{}yt()},0),-1);return m.push({filename:t,position:0,position2:0,erstat:0,eoln:!1,content:n,descriptor:m.length}),m.length-1},wt=()=>{},$=(t,e,r,n)=>{for(r===void 0&&(r=0),n===void 0&&(n=e.length-r);n>t.content.length-t.position;){let o=new Uint8Array(1+t.content.length*2);o.set(t.content),t.content=o}t.content.subarray(t.position).set(e.subarray(r,r+n)),t.position+=n},_t=(t,e,r,n,o)=>(r===void 0&&(r=0),n===void 0&&(n=e.length-r),n>t.content.length-o&&(n=t.content.length-o),e.subarray(r).set(t.content.subarray(o,o+n)),n),M=t=>{if(re&&(O+=t,O.indexOf(`
`)>=0)){let e=O.split(`
`);O=e.pop();for(let r of e)r.length&&re(r)}},de=t=>{re=t},me=t=>{P=t,W=new Int32Array(t)},he=(t,e)=>{G=t,e&&(N=e)},ge=t=>{He=t},xe=t=>(F=t,H=Promise.withResolvers(),F.main(),F.asyncify_stop_unwind(),H.promise),Tt=(t,e)=>{let r=t<0?{stdout:!0}:m[t],n=new Uint8Array(P,e,1)[0],o=new Uint8Array(P,e+1,n),s=String.fromCharCode.apply(null,o);if(r.stdout){M(s);return}$(r,new TextEncoder().encode(s))},Pt=(t,e)=>{let r=t<0?{stdout:!0}:m[t],n=e?"TRUE":"FALSE";if(r.stdout){M(n);return}$(r,new TextEncoder().encode(n))},Ut=(t,e)=>{let r=t<0?{stdout:!0}:m[t];if(r.stdout){M(String.fromCharCode(e));return}let n=new Uint8Array(1);n[0]=e,$(r,n)},vt=(t,e)=>{let r=t<0?{stdout:!0}:m[t];if(r.stdout){M(e.toString());return}$(r,new TextEncoder().encode(`${e}`))},St=(t,e)=>{let r=t<0?{stdout:!0}:m[t];if(r.stdout){M(e.toString());return}$(r,new TextEncoder().encode(`${e}`))},kt=(t,e)=>{let r=t<0?{stdout:!0}:m[t];if(r.stdout){M(`
`);return}$(r,new TextEncoder().encode(`
`))},Ft=(t,e)=>{let r=new Uint8Array(P,e,t),n=String.fromCharCode.apply(null,r);return n=n.replace(/\000+$/g,""),n.startsWith("{")&&(n=n.replace(/^{/g,""),n=n.replace(/}.*/g,"")),n.startsWith('"')&&(n=n.replace(/^"/g,""),n=n.replace(/".*/g,"")),n=n.replace(/ +$/g,""),n=n.replace(/^\*/,""),n=n.replace(/^TeXfonts:/,""),n=="TeXformats:TEX.POOL"&&(n="tex.pool"),n=="TTY:"?(m.push({filename:"stdin",stdin:!0,position:0,position2:0,erstat:0,eoln:!1,content:new TextEncoder().encode(G)}),m.length-1):Be(n,"r")},Ct=(t,e)=>{let r=new Uint8Array(P,e,t),n=String.fromCharCode.apply(null,r);return n=n.replace(/ +$/g,""),n.startsWith('"')&&(n=n.replace(/^"/g,""),n=n.replace(/".*/g,"")),n=="TTY:"?(m.push({filename:"stdout",stdout:!0,erstat:0}),m.length-1):Be(n,"w")},Et=t=>{let e=m[t];e.descriptor&&wt(e.descriptor)},Rt=t=>m[t].eof?1:0,Lt=t=>m[t].erstat,$t=t=>m[t].eoln?1:0,Mt=(t,e,r,n,o,s,a)=>{let i=m[t],c=new Uint8Array(P,r,a),d=new Uint32Array(P,n,4),l=new Uint32Array(P,o,4);l[0]=d[0],e&&!i.eof&&i.eoln&&(i.position2=i.position2+1);let h=i.content.indexOf(10,i.position2);if(h<0&&(h=i.content.length),i.position2>=i.content.length)return i.stdin&&(N&&N(),ye()),i.eof=!0,!1;for(c.subarray(d[0]).set(i.content.subarray(i.position2,h)),l[0]=d[0]+h-i.position2;c[l[0]-1]==32;)l[0]=l[0]-1;return i.position2=h,i.eoln=!0,!0},At=(t,e,r)=>{let n=m[t],o=new Uint8Array(P);if(n.stdin)n.position>=G.length?(o[e]=13,n.eof=!0,N&&N(),ye()):o[e]=G[n.position].charCodeAt(0);else if(n.descriptor){if(_t(n,o,e,r,n.position)==0){o[e]=0,n.eof=!0,n.eoln=!0;return}}else{n.eof=!0,n.eoln=!0;return}n.eoln=!1,o[e]==10&&(n.eoln=!0),o[e]==13&&(n.eoln=!0),n.position=n.position+r},Nt=(t,e,r)=>{let n=m[t],o=new Uint8Array(P);$(n,o,e,r)},ye=()=>{O.length&&M(`
`),H&&H.resolve()};var we={};Ge(we,{getCurrentDay:()=>Ot,getCurrentMinutes:()=>Dt,getCurrentMonth:()=>zt,getCurrentYear:()=>It});var Dt=()=>{let t=new Date;return 60*t.getHours()+t.getMinutes()},Ot=()=>new Date().getDate(),zt=()=>new Date().getMonth()+1,It=()=>new Date().getFullYear();var Ve,Ye,Ze=async(t,e)=>{Ye??=await e.fileLoader("tex.wasm"),Ve??=new Uint8Array(await e.fileLoader("core.dump"),0,C*65536),fe("input.tex",new TextEncoder().encode(t));let r=new WebAssembly.Memory({initial:C,maximum:C});new Uint8Array(r.buffer,0,C*65536).set(Ve.slice(0)),me(r.buffer),he(` input.tex
\\end
`),ge(e.fileLoader),e.console&&de(e.console);let o=await WebAssembly.instantiate(Ye,{library:{...be,...we},env:{memory:r}});await xe(o.instance.exports);let s=se("input.log");try{return{dvi:se("input.dvi"),log:s}}catch{return{log:s}}finally{ue()}};async function*qe(t){let e=await new Response(t).arrayBuffer(),r=new DataView(e),n=e.byteLength-4;for(;r.getUint32(n,!0)!==101010256;)n--;let o=n;o+=4,o+=4;let s=r.getUint16(o,!0);o+=2,o+=2,o+=4;let a=r.getUint32(o,!0);o+=4,o=a;for(let i=0;i<s;i++){o+=4,o+=4,o+=4,o+=4,o+=4;let c=r.getUint32(o,!0);o+=4;let d=r.getUint32(o,!0);o+=4;let l=r.getUint16(o,!0);o+=2;let h=r.getUint16(o,!0);o+=2;let w=r.getUint16(o,!0);o+=2,o+=8;let _=r.getUint32(o,!0);o+=4,o+=l+h+w,yield Xt(r,_,c,d)}}var Xt=(t,e,r,n)=>{e+=4,e+=2,e+=2;let o=t.getUint16(e,!0);e+=2,e+=4,e+=4,e+=8;let s=t.getUint16(e,!0);e+=2;let a=t.getUint16(e,!0);e+=2;let i=new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset+e,s));e+=s,e+=a;let c=new Uint8Array(t.buffer,t.byteOffset+e,r);if(o==0)return Ke(i,r,n,c,!0);if(o==8)return Ke(i,r,n,c,!1);throw"unknown compression method: "+o},Ke=(t,e,r,n,o)=>{if(o)return{name:t,csize:e,usize:r,arrayBuffer:()=>Promise.resolve(n),file:()=>Promise.resolve(new File([n],t)),text:()=>Promise.resolve(new TextDecoder().decode(n))};let s,a=async()=>(s??=await Wt(n),s);return{name:t,csize:e,usize:r,arrayBuffer:a,file:async()=>new File([await a()],t),text:async()=>new TextDecoder().decode(await a())}};var zn=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r&1?r=3988292384^r>>>1:r=r>>>1;t[e]=r}return t})();var Wt=t=>new Response(new Response(t).body.pipeThrough(new DecompressionStream("deflate-raw"))).arrayBuffer();var je=async(t,e)=>{let r=await globalThis.caches.keys();for(let n of r.sort().reverse()){let s=await(await caches.open(n)).match(t,e);if(s)return s}},Qe=async(t,e)=>{let n=(await globalThis.caches.keys()).filter(s=>s.startsWith("api")).sort().reverse().at(0);if(!n)return;await(await caches.open(n)).put(t,e.clone())};var Je=[1,0,0,1,0,0],Gt=t=>Math.abs(t[0]-1)<Number.EPSILON&&Math.abs(t[1])<Number.EPSILON&&Math.abs(t[2])<Number.EPSILON&&Math.abs(t[3]-1)<Number.EPSILON&&Math.abs(t[4])<Number.EPSILON&&Math.abs(t[5])<Number.EPSILON;var _e=(t,e,r)=>[t[0]*e,t[1]*e,t[2]*r,t[3]*r,t[4],t[5]],Te=(t,e,r)=>[t[0],t[1],t[2],t[3],t[0]*e+t[2]*r+t[4],t[1]*e+t[3]*r+t[5]],Pe=(t,e)=>{let r=e*Math.PI/180,n=Math.cos(r),o=Math.sin(r);return[t[0]*n+t[2]*o,t[1]*n+t[3]*o,-t[0]*o+t[2]*n,-t[1]*o+t[3]*n,t[4],t[5]]},Ue=t=>Gt(t)?"":`transform="matrix(${t.join(" ")})"`;var et=t=>{let e=new FileReader,r=new Promise(n=>e.onload=()=>n(e.result));return e.readAsDataURL(t),r};var tt=async(t,e)=>(await Promise.all([...t].sort().map(async r=>[r.slice(0,-4),await et(new Blob([await e(r)],{type:"font/truetype"}))]))).map(([r,n])=>`@font-face{font-family:${r};src:local(${r}),url(${n})format("truetype");}.${r}{font-family:${r};}`).join("");var nt=async(t,e)=>{let r=0,n="black",o=e.svg?1:0,s=[...Je],a="",i=0,c="",d=0,l=0,h=0,w=0,_=new Set;for(let u of t)switch(u.type){case"text":{let p=0,b=0,f="";for(let L of u.text){let y=L.codePointAt(0)??0,pe=u.font.metrics.characters.at(y);if(pe===void 0)throw Error(`Could not find font metric for ${y}`);p+=pe.width,b=Math.max(b,pe.height),f+=String.fromCodePoint(y>=0&&y<=9?161+y:y>=10&&y<=19?173+y-10:y===20?8729:y>=21&&y<=32?184+y-21:y===127?196:y)}let T=u.font.metrics.design_size/1048576*65536/1048576,g=u.left*r,x=p*r*T,v=b*r*T,le=u.top*r;a=u.font.name,i=u.font.metrics.design_size/1048576*u.font.scaleFactor/u.font.designSize;let ne=["#000","black"].includes(n)?"CanvasText":n;if(_.add(`${a}.ttf`),o<=0){let L=d==u.top&&g>l+2;c+=`<span class="text ${a}" style="top:${le-v}pt;left:${g}pt;color:${ne};font-size:${i}pt;"><span ${L?'class="has-space" ':""} style="vertical-align:${-v}pt;">${f}</span></span>
`,d=u.top,l=g+x}else{let L=u.top*r;c+=`<text alignment-baseline="baseline" y="${L}" x="${g}" fill="${ne}" font-size="${i}" font-family="${a}">${f}</text>
`}break}case"rect":{let p=u.height*r,b=u.width*r,f=u.left*r,g=u.top*r-p,x=["#000","black"].includes(n)?"CanvasText":n;c+=o>0?`<rect x="${f}" y="${g}" width="${b}" height="${p}" fill="${x}" ${Ue(s)}></rect>
`:`<span class="rect" style="background: ${x}; top: ${g}pt; left: ${f}pt; width: ${b}pt; height: ${p}pt;"></span>
`;break}case"special":break;case"info":{r=u.magnification*u.numerator/1e3/u.denominator*72.27/1e5/2.54;break}case"svg":{let p=u.svg;for(let T of u.svg.matchAll(/<svg\s[^>]+>/g)){let g=T[0];g==="<svg beginpicture>"&&(p=p.replace(g,o>0?"":ve(h,w))),o++}for(let T of u.svg.matchAll(/<\/svg\s[^>]+>/g)){let g=T[0];g==="</svg endpicture>"&&(p=p.replace(g,o===1?"</svg>":"")),o=Math.max(0,o-1)}let b=u.top*r,f=u.left*r;c+=p.replaceAll("{?x}",`${f}`).replaceAll("{?y}",`${b}`);break}case"papersize":w=u.height,h=u.width;break;case"color":n=u.color;break;case"ps":s=u.interpret(s);break;case"psfile":c+=o>0?u.toSVG(s):`${ve(h,w)}${u.toSVG(s)}</svg>}`;break}for(let u=o;u>0;u--)c+="</svg>";let k=`<title>${e.title??"input.tex"}</title>`,U=`<style>${await tt(_,e.fileLoader)}:root{color-scheme:light dark;background-color:Canvas;color:CanvasText;}.page{position:relative;width:100%;}.text{line-height:0;position:absolute;overflow:visible;}.rect{position:absolute;min-width:1px;min-height:1px;}</style>`;return c=c.replace(/("#000"|"black")/g,'"CanvasText"').replace(/("#fff"|"white")/g,'"var(--background-primary, Canvas)"'),e.svg?`${ve(h,w)}${k}${U}${c}`:`<!DOCTYPE html><html><head><meta charset="UTF-8">${k}${U}</head><body>${c}</body></html>`},ve=(t,e)=>`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${t}pt" height="${e}pt" viewBox="-72 -72 ${t} ${e}">`;var rt=t=>{let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=e.getUint16(0),n=e.getUint16(2),o=e.getUint16(4),s=e.getUint16(6),a={header:Math.max(18,n),character_info:s-o+1,width:e.getUint16(8),height:e.getUint16(10),depth:e.getUint16(12),italic_correction:e.getUint16(14),lig_kern:e.getUint16(16),kern:e.getUint16(18),extensible_character:e.getUint16(20),font_parameter:e.getUint16(22)};if(!(o<=s+1&&s<256))throw new Error(`Smallest character code (${o}) must be larger than largest character code (${s}) and largest character code must be less than 256 (actual: ${s})`);if(a.extensible_character>256)throw new Error(`Extensible character must be less than 256 (actual: ${a.extensible_character})`);{let x=6+n+a.character_info+a.width+a.height+a.depth+a.italic_correction+a.lig_kern+a.kern+a.extensible_character+a.font_parameter;if(r!==x)throw new Error(`entire_file_length must be ${x} (actual: ${r})`)}let i=24,c=x=>[...Array(x).keys()].map(v=>e.getUint32(i+v*4)),d=e.buffer.slice(i,i+a.header*4);i+=a.header*4;let l=c(a.character_info);i+=a.character_info*4;let h=c(a.width);i+=a.width*4;let w=c(a.height);i+=a.height*4;let _=c(a.depth);i+=a.depth*4;let k=c(a.italic_correction);i+=a.italic_correction*4;let U=c(a.lig_kern);i+=a.lig_kern*4;let u=c(a.kern);i+=a.kern*4;let p=c(a.extensible_character);i+=a.extensible_character*4;let b=c(a.font_parameter);i+=a.font_parameter*4;let f=Ht(d),T=Bt(l),g=Yt(b,f.coding_scheme);return{checksum:f.checksum,design_size:f.design_size,family:f.family,face:f.face,ligKernPrograms:Vt(U),characters:T.map(x=>{let{width_index:v,height_index:le,depth_index:ne,italic_index:L}=x,y={width:h[v],height:w.at(le)??0,depth:_.at(ne)??0,italic_correction:k.at(L)??0};switch(x.type){case"lig":y.lig_kern_program=U[x.lig_kern_index];break;case"link":y.next_larger_char=x.next_larger_char;break;case"ext":y.extensible_recipe=p[x.extensible_index];break;default:break}return y}),...g}},Ht=t=>{let e=new DataView(t),r=e.getUint32(0),n=e.getUint32(4),o=e.getUint8(8);if(o>39)throw new Error("Invalid TFM file");let s=new TextDecoder().decode(t.slice(9,9+o)),a=e.getUint8(48);if(a>20)throw new Error("Invalid TFM file");let i=new TextDecoder().decode(t.slice(49,49+a)),c=new Uint8Array(t,68,4),d=c[0],l=c[3];return{checksum:r,design_size:n,coding_scheme:s,family:i,seven_bit_safe_flag:d,face:l}},Bt=t=>t.map(e=>{let r=e>>24,n=e>>20&15,o=e>>16&15,s=e>>10&1118481,a=e>>8&3,i=e&255;switch(a){case 1:return{type:"lig",width_index:r,height_index:n,depth_index:o,italic_index:s,lig_kern_index:i};case 2:return{type:"link",width_index:r,height_index:n,depth_index:o,italic_index:s,next_larger_char:i};case 3:return{type:"ext",width_index:r,height_index:n,depth_index:o,italic_index:s,extensible_index:i};default:return{width_index:r,height_index:n,depth_index:o,italic_index:s}}}),Vt=t=>t.map((e,r)=>{let n=e>>24;if((r===0||r===t.length)&&n===255)throw Error(`Font has ${r===0?"right":"left"} boundary char. This is not supported yet.`);let o=e>>16&255,s=e>>8&255,a=e&255;if(s>=128){let h=256*(s-128)+a;return{skip_byte:n,next_char:o,op_byte:s,kern:a}}let i=s>>2,c=(s&2)==0,d=(s&1)==0,l=a;return n>=128?{skip_byte:n,next_char:o,op_byte:s,remainder:a}:{skip_byte:n,next_char:o,op_byte:s,kern:a}}),Yt=(t,e)=>{let r=t[0],n=t[1],o=t[2],s=t[3],a=t[4],i=t[5];if(e==="TeX math italic")return{coding_scheme:e,slant:r,spacing:n,space_stretch:o,space_shrink:s,x_height:a,quad:i};let c=t[6];if(e==="TeX math symbols"){let d=t[7],l=t[8],h=t[9],w=t[10],_=t[11],k=t[12],U=t[13],u=t[14],p=t[15],b=t[16],f=t[17],T=t[18],g=t[19],x=t[20],v=t[21];return{coding_scheme:e,slant:r,spacing:n,space_stretch:o,space_shrink:s,x_height:a,quad:i,extra_space:c,num1:d,num2:l,num3:h,denom1:w,denom2:_,sup1:k,sup2:U,sup3:u,sub1:p,sub2:b,supdrop:f,subdrop:T,delim1:g,delim2:x,axis_height:v}}if(e==="TeX math extension"||e==="euler substitutions only"){let d=t[7],l=t.slice(8,13);return{coding_scheme:e,slant:r,spacing:n,space_stretch:o,space_shrink:s,x_height:a,quad:i,extra_space:c,default_rule_thickness:d,big_op_spacing:l}}return{coding_scheme:e,slant:r,spacing:n,space_stretch:o,space_shrink:s,x_height:a,quad:i,extra_space:c}};var Cn=t=>{let e=t[0];if(0<=e&&e<128)return[{opcode:0,c:e},1];if(171<=e&&e<235)return[{opcode:171,k:e-171},1];if(249<e&&e<=255)return[{opcode:138},1];let r=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(e){case 128:case 129:case 130:case 131:{let n=e-128+1;return t.byteLength<n+1?void 0:[{opcode:0,c:Se(t,1,n)},n+1]}case 132:case 137:return t.byteLength<9?void 0:[{opcode:e,a:r.getInt32(1),b:r.getInt32(5)},9];case 133:case 134:case 135:case 136:{let n=e-128+1;return t.byteLength<n+1?void 0:[{opcode:133,c:Se(t,1,n)},n+1]}case 138:case 140:case 141:case 142:return[{opcode:e},1];case 139:return t.byteLength<45?void 0:[{opcode:e,c_0:r.getUint32(1),c_1:r.getUint32(5),c_2:r.getUint32(9),c_3:r.getUint32(13),c_4:r.getUint32(17),c_5:r.getUint32(21),c_6:r.getUint32(25),c_7:r.getUint32(29),c_8:r.getUint32(33),c_9:r.getUint32(37),p:r.getInt32(41)},45];case 143:case 144:case 145:case 146:{let n=e-143+1;return t.byteLength<n+1?void 0:[{opcode:143,b:E(t,1,n)},n+1]}case 147:case 152:return[{opcode:e,b:0},1];case 148:case 149:case 150:case 151:{let n=e-147;return t.byteLength<n+1?void 0:[{opcode:147,b:E(t,1,n)},n+1]}case 153:case 154:case 155:case 156:{let n=e-152;return t.byteLength<n+1?void 0:[{opcode:152,b:E(t,1,n)},n+1]}case 157:case 158:case 159:case 160:{let n=e-157+1;return t.byteLength<n+1?void 0:[{opcode:157,a:E(t,1,n)},n+1]}case 161:case 166:return[{opcode:e,a:0},1];case 162:case 163:case 164:case 165:{let n=e-161;return t.byteLength<n+1?void 0:[{opcode:161,a:E(t,1,n)},n+1]}case 167:case 168:case 169:case 170:{let n=e-166;return t.byteLength<n+1?void 0:[{opcode:166,a:E(t,1,n)},n+1]}case 235:case 236:case 237:case 238:{let n=e-235+1;return t.byteLength<n+1?void 0:[{opcode:171,k:E(t,1,n)},n+1]}case 239:case 240:case 241:case 242:{let n=e-239+1;if(t.byteLength<n+1)return;let o=Se(t,1,n);return t.byteLength<n+1+o?void 0:[{opcode:239,x:t.subarray(n+1,n+1+o),k:o},n+1+o]}case 243:case 244:case 245:case 246:{let n=e-243+1;if(t.byteLength<n+1)return;let o=E(t,1,n);if(t.byteLength<n+15)return;let s=t[n+13],a=t[n+14];return t.byteLength<n+15+s+a?void 0:[{opcode:243,k:o,c:r.getUint32(n+1),s:r.getUint32(n+5),d:r.getUint32(n+9),a:s,l:a,n:new TextDecoder().decode(t.subarray(n+15,n+15+s+a))},n+15+s+a]}case 247:{if(t.byteLength<15)return;let n=t[1],o=t[14];return t.byteLength<15+o?void 0:[{opcode:e,i:n,num:r.getUint32(2),den:r.getUint32(6),mag:r.getUint32(10),x:new TextDecoder().decode(t.subarray(15,15+o)),k:o},15+o]}case 248:return t.byteLength<29?void 0:[{opcode:e,p:r.getUint32(1),num:r.getUint32(5),den:r.getUint32(9),mag:r.getUint32(13),l:r.getUint32(17),u:r.getUint32(21),s:r.getUint16(25),t:r.getUint16(27)},29];case 249:return t.byteLength<6?void 0:[{opcode:e,q:r.getUint32(1),i:r.getUint8(5)},6]}};function*ot(t){let e=t,r=0;for(;r<t.byteLength;){let[n,o]=Cn(e)??[,0];if(r+=o,e=e.subarray(o),!n)break;if(n.opcode===249){if(e.every(s=>s===223))break;throw Error("Only 223 bytes are permitted after the post-postamble.")}yield n}}var Se=(t,e,r)=>[...t.subarray(e,e+r)].reduce((n,o,s)=>n+o*256**(r-s-1),0),E=(t,e,r)=>{switch(r){case 1:return t[e];case 2:{let n=t[e]*256+t[e+1];return n|(n&2**15)*131070}case 3:{let n=t[e]*65536+t[e+1]*256+t[e+2];return n|(n&2**23)*510}case 4:return(t[e]<<24)+t[e+1]*2**16+t[e+2]*2**8+t[e+3]}};var st=()=>{let t=[],e="black";return r=>{let n=new TextDecoder().decode(r.data);if(n.startsWith("color push "))return t.push(e),e=it(n.slice(11)),{type:"color",color:e};if(n.startsWith("color pop")){let o=t.pop();if(!o)throw new Error("Popped from empty color stack");return e=o,{type:"color",color:e}}}},En=t=>`${Math.round(t).toString(16)}`.padStart(2,"0"),it=t=>{if(t==="gray 0")return"black";if(t==="gray 1")return"white";if(t.startsWith("rgb "))return`#${t.split(" ").slice(1).map(e=>En(parseFloat(e)*255)).join("")}`;if(t.startsWith("gray ")){let e=t.split(" ")[1];return it(`rgb ${e} ${e} ${e}`)}return"black"};var at=()=>{let t="";return(e,r)=>{let n=new TextDecoder().decode(e.data);if(!n.startsWith("dvisvgm:raw "))return;if(t+=n.slice(12),r?.type==="special"){let s=new TextDecoder().decode(r.data);if(e.horizontal===r.horizontal&&e.vertical===r.vertical&&s.startsWith("dvisvgm:raw "))return null}let o=t.replaceAll("{?nl}",`
`);return t="",{type:"svg",svg:o,left:e.horizontal,top:e.vertical}}};var ct=t=>{let e=new TextDecoder().decode(t.data);if(!e.startsWith("papersize="))return;let[r,n]=e.slice(10).split(",");if(r===void 0||n===void 0)throw Error("Papersize special requires two arguments.");if(!r.endsWith("pt"))throw Error("Papersize special width must be in points.");if(!n.endsWith("pt"))throw Error("Papersize special height must be in points.");return{type:"papersize",width:parseFloat(r.slice(0,-2)),height:parseFloat(n.slice(0,-2))}};var lt=[],pt=(t,e,r,n)=>{let o=[],s={matrix:e,horizontal:r,vertical:n},a={pop:()=>o.pop(),exch:()=>{let i=o.pop(),c=o.pop();i&&o.push(i),c&&o.push(c)},dup:()=>{o.push(o[o.length-1])},mark:()=>o.push(new ze),neg:()=>{let i=o.pop();i&&o.push(new S(-i.value))},add:()=>{let i=o.pop(),c=o.pop();i&&c&&o.push(new S(i.value+c.value))},sub:()=>{let i=o.pop(),c=o.pop();i&&c&&o.push(new S(c.value-i.value))},mul:()=>{let i=o.pop(),c=o.pop();i&&c&&o.push(new S(i.value*c.value))},div:()=>{let i=o.pop(),c=o.pop();i&&c&&o.push(new S(c.value/i.value))},gsave:()=>lt.push([...e]),grestore:()=>{let i=lt.pop();i&&(s.matrix=i)},currentpoint:()=>o.push(new S(s.horizontal),new S(s.vertical)),moveto:()=>{let i=o.pop(),c=o.pop();s.horizontal=c?.value,s.vertical=i?.value},scale:()=>{let i=o.pop(),c=o.pop();c&&i&&(s.matrix=_e(s.matrix,c.value,i.value))},translate:()=>{let i=o.pop(),c=o.pop();c&&i&&(s.matrix=Te(s.matrix,c.value,i.value))},rotate:()=>{let i=o.pop();i&&(s.matrix=Pe(s.matrix,i.value))}};for(let i of Rn(t)){if(/^[+-]?\d+(\.\d*)?$/.test(i)){o.push(new S(i));continue}if(i[0]==="("){o.push(new De(i));continue}if(i==="["){a.mark();continue}if(i==="]"){let c=new Oe,d=o.pop();if(!d)continue;for(;d.name!=="mark";)c.push(d);o.push(c)}if(i[0]==="/"&&o.push(new Ie(i)),i[0]==="{"&&o.push(new Xe(i)),i in a){a[i](void 0);continue}throw Error("Invalid or unimplemented postscript expression")}return s};function*Rn(t){let e="",r=0,n=0,o=t[Symbol.iterator]();for(let s of o){let a;switch(s){case" ":case" ":case`
`:if(n){e[e.length-1]!==" "&&(e+=" ");continue}if(r){switch(s){case" ":e+=" ";break;case`
`:e+="\\n";break;case" ":e+="\\t";break}continue}e&&(yield e,e="");continue;case"[":case"]":if(!n&&!r){e&&(yield e),e="",yield s;continue}e+=s;continue;case"{":r||(n==0&&e&&(yield e),++n),e+=s;continue;case"}":if(e+=s,r||(--n,n))continue;yield e,e="";continue;case"(":++r,e&&!n&&r==1&&(yield e),r>1&&(e+="\\"),e+=s;continue;case")":if(--r,r&&(e+="\\"),e+=s,n||r)continue;yield e,e="";continue;case"\\":if(e+=s,a=o.next(),a.done)throw Error("Invalid escape character.");a.done||(e+=a.value);continue;case"/":!n&&!r&&e&&(yield e),e+=s;continue;case"%":do a=o.next();while(!a.done&&a.value!==`
`);continue;default:e+=s}}e&&(yield e)}var R=class{name;value;constructor(e){this.name=e}},S=class extends R{constructor(e){super("number"),this.value=typeof e=="number"?e:parseFloat(e)}},De=class extends R{constructor(e){super("string"),this.value=e.replace(/^\(|\)$/g,"")}},Oe=class extends R{constructor(e){super("array"),this.value=e||[]}push(e){this.value.push(e)}pop(){return this.value.pop()}},ze=class extends R{constructor(){super("mark"),this.value="-mark-"}},Ie=class extends R{constructor(e){super("identifier"),this.value=e.replace(/^\//,"")}},Xe=class extends R{constructor(e){super("procedure"),this.value=e}};var ut=()=>{let t="";return(e,r)=>{let n=new TextDecoder().decode(e.data);if(!n.startsWith("ps: "))return;if(t+=n.slice(4),r?.type==="special"&&new TextDecoder().decode(r.data).startsWith("ps: "))return null;let o=s=>{let a=pt(t,s,e.horizontal,e.vertical);return e.emitChange({horizontal:a.horizontal,vertical:a.vertical,w:e.w,x:e.x,y:e.y,z:e.z}),a.matrix};return t="",{type:"ps",ps:t,interpret:o}}};async function*ft(t,e){let r=Ln(t,e.tfmLoader),n=await r.next(),o=n.done?void 0:n.value;for(;o;){let s=o,a=await r.next();if(o=a.done?void 0:a.value,s.type==="special"&&e.plugins){let i=!1;for(let c of e.plugins){let d=c(s,o);if(d!==void 0){d!==null&&(yield d),i=!0;break}}i||(yield s);continue}yield s}}async function*Ln(t,e){let r=2,n=254e5,o=473628672,s=1e3,a="",i=0,c=0,d=0,l={horizontal:0,vertical:0,w:0,x:0,y:0,z:0,fontNum:0},h=[],w=new Map,_="",k=ot(t),U=k.next(),u=U.done?void 0:U.value;for(;u;){let p=u,b=k.next();switch(u=b.done?void 0:b.value,p.opcode){case 0:case 133:if(_+=String.fromCharCode(p.c),u?.opcode!==0&&u?.opcode!==133||!u){let f=w.get(l.fontNum);if(!f)throw Error(`Font "${l.fontNum}" is not loaded`);yield{type:"text",text:_,font:f,top:l.vertical,left:l.horizontal},p.opcode===0&&(l.horizontal+=$n(_,f)),_=""}break;case 132:case 137:p.a>0&&p.b>0&&(yield{type:"rect",left:l.horizontal,top:l.vertical,height:p.a,width:p.b}),p.opcode===132&&(l.horizontal+=p.b);break;case 138:case 140:break;case 139:l.horizontal=0,l.vertical=0,l.w=0,l.x=0,l.y=0,l.z=0,l.fontNum=0,h.splice(0,h.length);break;case 141:h.push({...l});break;case 142:{let f=h.pop();f&&(l.horizontal=f.horizontal,l.vertical=f.vertical,l.w=f.w,l.x=f.x,l.y=f.y,l.z=f.z);break}case 143:l.horizontal+=p.b;break;case 147:p.b!==0&&(l.w=p.b),l.horizontal+=l.w;break;case 152:p.b!==0&&(l.x=p.b),l.horizontal+=l.x;break;case 157:l.vertical+=p.a;break;case 161:p.a!==0&&(l.y=p.a),l.vertical+=l.y;break;case 166:p.a!==0&&(l.z=p.a),l.vertical+=l.z;break;case 171:case 235:case 236:case 237:case 238:l.fontNum=p.k;break;case 239:yield{type:"special",data:p.x,...l,emitChange:f=>{l.horizontal=f.horizontal,l.vertical=f.vertical,l.w=f.w,l.x=f.x,l.y=f.y,l.z=f.z}};break;case 243:{if(w.has(p.k))break;let f=p.n,T=p.s,g=p.d,x=p.c,v=rt(new Uint32Array((await e(`${p.n}.tfm`)).buffer));w.set(p.k,{name:f,checksum:x,scaleFactor:T,designSize:g,metrics:v});break}case 247:r=p.i,n=p.num,o=p.den,s=p.mag,a=p.x,yield{type:"info",version:r,numerator:n,denominator:o,magnification:s,comment:a};break;case 248:i=p.l,c=p.u,d=p.t;break;case 249:yield{type:"info",version:r,numerator:n,denominator:o,magnification:s,comment:a,maxHeight:i,maxWidth:c,pages:d,dviVersion:p.i};break}}}var $n=(t,e)=>{let r=0;for(let o of t){let s=o.codePointAt(0)??0,a=e.metrics.characters.at(s);if(a===void 0)throw Error(`Could not find font metric for ${s}`);r+=a.width}let n=e.metrics.design_size/1048576*65536/1048576;return r*n*e.scaleFactor/e.designSize};globalThis.onmessage=async t=>{let e=t.data;switch(e.type){case"asset-url":{mt=e.url;let r={type:e.type};globalThis.postMessage(r)}break;case"compile":{let{dvi:r,log:n}=await Ze(e.input,{fileLoader:We,console:c=>{let d={type:"stdout",message:c};globalThis.postMessage(d)}});if(!r){let c={type:e.type,log:n};globalThis.postMessage(c,[n.buffer]);return}let o=[],s=new Set;for await(let c of ft(r,{plugins:[ct,ut(),at(),st()],tfmLoader:We}))o.push(c),c.type==="text"&&s.add(c.font.name);let a=await nt(o,{fileLoader:We,svg:!0}),i={type:e.type,svg:a,log:n};globalThis.postMessage(i,[n.buffer])}break}};var dt,We=async t=>{dt??=await Mn();let e=dt.get(t);if(!e){let r=new Error(`File ${t} not found in assets`);throw console.log(r),r}return new Uint8Array(await e())},mt="",Mn=async()=>{let t=new Request(mt),e=await je(t,{ignoreSearch:!0}),r=e??await fetch(t);e||await Qe(t,r);let n=new Map;for await(let{name:o,arrayBuffer:s}of qe(await r.arrayBuffer()))n.set(o,s);return n};
esbuild-worker.jsvar b="0.24.0";(()=>{let r=()=>{let c=new Error("not implemented");return c.code="ENOSYS",c};if(!globalThis.fs){let c="";globalThis.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1},writeSync(i,s){c+=f.decode(s);let n=c.lastIndexOf(`
`);return n!=-1&&(console.log(c.substring(0,n)),c=c.substring(n+1)),s.length},write(i,s,n,o,h,u){if(n!==0||o!==s.length||h!==null){u(r());return}let m=this.writeSync(i,s);u(null,m)},chmod(i,s,n){n(r())},chown(i,s,n,o){o(r())},close(i,s){s(r())},fchmod(i,s,n){n(r())},fchown(i,s,n,o){o(r())},fstat(i,s){s(r())},fsync(i,s){s(null)},ftruncate(i,s,n){n(r())},lchown(i,s,n,o){o(r())},link(i,s,n){n(r())},lstat(i,s){s(r())},mkdir(i,s,n){n(r())},open(i,s,n,o){o(r())},read(i,s,n,o,h,u){u(r())},readdir(i,s){s(r())},readlink(i,s){s(r())},rename(i,s,n){n(r())},rmdir(i,s){s(r())},stat(i,s){s(r())},symlink(i,s,n){n(r())},truncate(i,s,n){n(r())},unlink(i,s){s(r())},utimes(i,s,n,o){o(r())}}}if(globalThis.process||(globalThis.process={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw r()},pid:-1,ppid:-1,umask(){throw r()},cwd(){throw r()},chdir(){throw r()}}),!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");let y=new TextEncoder("utf-8"),f=new TextDecoder("utf-8");globalThis.Go=class{constructor(){this.argv=["js"],this.env={},this.exit=e=>{e!==0&&console.warn("exit code:",e)},this._exitPromise=new Promise(e=>{this._resolveExitPromise=e}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;let c=(e,t)=>{this.mem.setUint32(e+0,t,!0),this.mem.setUint32(e+4,Math.floor(t/4294967296),!0)},i=(e,t)=>{this.mem.setUint32(e+0,t,!0)},s=e=>{let t=this.mem.getUint32(e+0,!0),l=this.mem.getInt32(e+4,!0);return t+l*4294967296},n=e=>{let t=this.mem.getFloat64(e,!0);if(t===0)return;if(!isNaN(t))return t;let l=this.mem.getUint32(e,!0);return this._values[l]},o=(e,t)=>{if(typeof t=="number"&&t!==0){if(isNaN(t)){this.mem.setUint32(e+4,2146959360,!0),this.mem.setUint32(e,0,!0);return}this.mem.setFloat64(e,t,!0);return}if(t===void 0){this.mem.setFloat64(e,0,!0);return}let a=this._ids.get(t);a===void 0&&(a=this._idPool.pop(),a===void 0&&(a=this._values.length),this._values[a]=t,this._goRefCounts[a]=0,this._ids.set(t,a)),this._goRefCounts[a]++;let g=0;switch(typeof t){case"object":t!==null&&(g=1);break;case"string":g=2;break;case"symbol":g=3;break;case"function":g=4;break}this.mem.setUint32(e+4,2146959360|g,!0),this.mem.setUint32(e,a,!0)},h=e=>{let t=s(e+0),l=s(e+8);return new Uint8Array(this._inst.exports.mem.buffer,t,l)},u=e=>{let t=s(e+0),l=s(e+8),a=new Array(l);for(let g=0;g<l;g++)a[g]=n(t+g*8);return a},m=e=>{let t=s(e+0),l=s(e+8);return f.decode(new DataView(this._inst.exports.mem.buffer,t,l))},d=Date.now()-performance.now();this.importObject={_gotest:{add:(e,t)=>e+t},gojs:{"runtime.wasmExit":e=>{e>>>=0;let t=this.mem.getInt32(e+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(t)},"runtime.wasmWrite":e=>{e>>>=0;let t=s(e+8),l=s(e+16),a=this.mem.getInt32(e+24,!0);fs.writeSync(t,new Uint8Array(this._inst.exports.mem.buffer,l,a))},"runtime.resetMemoryDataView":e=>{e>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":e=>{e>>>=0,c(e+8,(d+performance.now())*1e6)},"runtime.walltime":e=>{e>>>=0;let t=new Date().getTime();c(e+8,t/1e3),this.mem.setInt32(e+16,t%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":e=>{e>>>=0;let t=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(t,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(t);)console.warn("scheduleTimeoutEvent: missed timeout event"),this._resume()},s(e+8))),this.mem.setInt32(e+16,t,!0)},"runtime.clearTimeoutEvent":e=>{e>>>=0;let t=this.mem.getInt32(e+8,!0);clearTimeout(this._scheduledTimeouts.get(t)),this._scheduledTimeouts.delete(t)},"runtime.getRandomData":e=>{e>>>=0,crypto.getRandomValues(h(e+8))},"syscall/js.finalizeRef":e=>{e>>>=0;let t=this.mem.getUint32(e+8,!0);if(this._goRefCounts[t]--,this._goRefCounts[t]===0){let l=this._values[t];this._values[t]=null,this._ids.delete(l),this._idPool.push(t)}},"syscall/js.stringVal":e=>{e>>>=0,o(e+24,m(e+8))},"syscall/js.valueGet":e=>{e>>>=0;let t=Reflect.get(n(e+8),m(e+16));e=this._inst.exports.getsp()>>>0,o(e+32,t)},"syscall/js.valueSet":e=>{e>>>=0,Reflect.set(n(e+8),m(e+16),n(e+32))},"syscall/js.valueDelete":e=>{e>>>=0,Reflect.deleteProperty(n(e+8),m(e+16))},"syscall/js.valueIndex":e=>{e>>>=0,o(e+24,Reflect.get(n(e+8),s(e+16)))},"syscall/js.valueSetIndex":e=>{e>>>=0,Reflect.set(n(e+8),s(e+16),n(e+24))},"syscall/js.valueCall":e=>{e>>>=0;try{let t=n(e+8),l=Reflect.get(t,m(e+16)),a=u(e+32),g=Reflect.apply(l,t,a);e=this._inst.exports.getsp()>>>0,o(e+56,g),this.mem.setUint8(e+64,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+56,t),this.mem.setUint8(e+64,0)}},"syscall/js.valueInvoke":e=>{e>>>=0;try{let t=n(e+8),l=u(e+16),a=Reflect.apply(t,void 0,l);e=this._inst.exports.getsp()>>>0,o(e+40,a),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueNew":e=>{e>>>=0;try{let t=n(e+8),l=u(e+16),a=Reflect.construct(t,l);e=this._inst.exports.getsp()>>>0,o(e+40,a),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueLength":e=>{e>>>=0,c(e+16,parseInt(n(e+8).length))},"syscall/js.valuePrepareString":e=>{e>>>=0;let t=y.encode(String(n(e+8)));o(e+16,t),c(e+24,t.length)},"syscall/js.valueLoadString":e=>{e>>>=0;let t=n(e+8);h(e+16).set(t)},"syscall/js.valueInstanceOf":e=>{e>>>=0,this.mem.setUint8(e+24,n(e+8)instanceof n(e+16)?1:0)},"syscall/js.copyBytesToGo":e=>{e>>>=0;let t=h(e+8),l=n(e+32);if(!(l instanceof Uint8Array||l instanceof Uint8ClampedArray)){this.mem.setUint8(e+48,0);return}let a=l.subarray(0,t.length);t.set(a),c(e+40,a.length),this.mem.setUint8(e+48,1)},"syscall/js.copyBytesToJS":e=>{e>>>=0;let t=n(e+8),l=h(e+16);if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray)){this.mem.setUint8(e+48,0);return}let a=l.subarray(0,t.length);t.set(a),c(e+40,a.length),this.mem.setUint8(e+48,1)},debug:e=>{console.log(e)}}}}async run(c){if(!(c instanceof WebAssembly.Instance))throw new Error("Go.run: WebAssembly.Instance expected");this._inst=c,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,globalThis,this],this._goRefCounts=new Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[globalThis,5],[this,6]]),this._idPool=[],this.exited=!1;let i=4096,s=d=>{let e=i,t=y.encode(d+"\0");return new Uint8Array(this.mem.buffer,i,t.length).set(t),i+=t.length,i%8!==0&&(i+=8-i%8),e},n=this.argv.length,o=[];this.argv.forEach(d=>{o.push(s(d))}),o.push(0),Object.keys(this.env).sort().forEach(d=>{o.push(s(`${d}=${this.env[d]}`))}),o.push(0);let u=i;if(o.forEach(d=>{this.mem.setUint32(i,d,!0),this.mem.setUint32(i+4,0,!0),i+=8}),i>=12288)throw new Error("total length of command line and environment variables exceeds limit");this._inst.exports.run(n,u),this.exited&&this._resolveExitPromise(),await this._exitPromise}_resume(){if(this.exited)throw new Error("Go program has already exited");this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(c){let i=this;return function(){let s={id:c,this:this,args:arguments};return i._pendingEvent=s,i._resume(),s.result}}}})();onmessage=({data:r})=>{let y=new TextDecoder,f=globalThis.fs,c="";f.writeSync=(h,u)=>{if(h===1)postMessage(u);else if(h===2){c+=y.decode(u);let m=c.split(`
`);m.length>1&&console.log(m.slice(0,-1).join(`
`)),c=m[m.length-1]}else throw new Error("Bad write");return u.length};let i=[],s,n=0;onmessage=({data:h})=>(h.length>0&&(i.push(h),s&&s()),o),f.read=(h,u,m,d,e,t)=>{if(h!==0||m!==0||d!==u.length||e!==null)throw new Error("Bad read");if(i.length===0){s=()=>f.read(h,u,m,d,e,t);return}let l=i[0],a=Math.max(0,Math.min(d,l.length-n));u.set(l.subarray(n,n+a),m),n+=a,n===l.length&&(i.shift(),n=0),t(null,a)};let o=new globalThis.Go;return o.argv=["",`--service=${b}`],w(r,o).then(h=>{postMessage(null),o.run(h)},h=>{postMessage(h)}),o};async function w(r,y){if(r instanceof WebAssembly.Module)return WebAssembly.instantiate(r,y.importObject);let f=r instanceof Response?r:await fetch(r);if(!f.ok)throw new Error(`Failed to download ${JSON.stringify(r)}`);if("instantiateStreaming"in WebAssembly&&/^application\/wasm($|;)/i.test(f.headers.get("Content-Type")||""))return(await WebAssembly.instantiateStreaming(f,y.importObject)).instance;let c=await f.arrayBuffer();return(await WebAssembly.instantiate(c,y.importObject)).instance}
/** @license esbuild-wasm@0.24.0
*
* MIT License
*
* Copyright (c) 2020 Evan Wallace
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
takker-project.css@import"https://fonts.googleapis.com/css?family=M+PLUS+Rounded+1c";html,body,#editor,.grid li{font-family:helvetica,arial,"M PLUS Rounded 1c",Sawarabi Gothic,Noto Sans JP,sans-serif}body *:before{--code-number-color: var(--code-color, #342d9c)}.section-title{counter-reset:codeline}.code-block span.indent code.code-body{counter-increment:codeline;margin-left:-1.5em;padding-left:2.3em}.code-block span.indent code.code-body:before{content:counter(codeline);position:absolute;display:inline-block;z-index:10;margin-left:-2.4em;width:2em;padding-right:.2em;text-align:right;vertical-align:bottom;border-right:solid 1px #fff;color:var(--code-number-color)}.code-block span.indent code.code-body:before{opacity:.5}.cursor-line .code-block span.indent code.code-body:before{opacity:1;font-weight:bolder;background-color:var(--accent-color)}.navbar-form .dropdown.open .dropdown-menu{min-width:100%;max-height:calc(100vh - 130px)!important;overflow-y:auto}.page-list-item.pin+.page-list-item:not(.pin){grid-column-start:1}.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):not([href^="https://scrapbox.io"]):after{font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";font-weight:900;font-size:.8rem;content:" ";display:inline-block}.line .deco-\.{font-size:.8em;position:relative;top:-.5em}.line:not(.cursor-line) .deco-\. a:is(.page-link:not(.icon),.link) span:not(.empty-char-index)+span+span~span{display:inline-block;width:0;text-indent:-9999px}.line:not(.cursor-line) .deco-\. .page-link:not(.icon) span.empty-char-index~span.char-index{display:inherit;width:inherit;text-indent:inherit}.line:not(.cursor-line) .deco-\. a.page-link:not(.icon) span.empty-char-index+span:before{content:"#"}.line .deco-\. :is(.page-link:not(.icon),.link):before{display:inline-block;min-width:1.15em;padding-left:1px;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";text-align:center;vertical-align:middle;font-weight:900;content:""}.line .deco-\..deco-\/{font-style:initial}.line .deco-\..deco-\/ :is(.page-link:not(.icon),.link):before{font-weight:400;content:""}div.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):is([href$=".pdf"],[href^="https://twitter.com"],[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):after{display:none}.line span:not(.deco-\.)>span>a.link:is([href$=".pdf"],[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{display:inline-block;width:1em;height:1em;vertical-align:-1px;text-align:center;background-size:contain;background-repeat:no-repeat;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands"}.line a.link:not(.icon)[href$=".pdf"]:before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"]):before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{content:"";font-weight:400;margin-right:3px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index{display:inline-block;width:0;text-indent:-9999px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index:nth-of-type(30)~span.char-index{display:inherit;width:inherit;text-indent:inherit}.deco-\"{border-radius:.2em;padding:0 .4em;background-color:#8080801a;font-size:95%;font-style:italic}.deco-\":before{color:#a0a0a0;font-size:85%;font-family:"Font Awesome 5 Free";content:"";font-weight:900;vertical-align:super}.line .indent-mark .dot{opacity:0}.line .indent-mark .c-0+.dot{opacity:1}.line .indent-mark .c-1+.dot{opacity:.8}.line .indent-mark .c-2+.dot{opacity:.6}.line .indent-mark .c-3+.dot{opacity:.4}.line .indent-mark .c-4+.dot{opacity:.2}.line strong:not([class]){background:linear-gradient(transparent 60%,#abff4f99 60% 100%)}.time-range .lines{user-select:unset;-webkit-user-select:unset}.line:not(.cursor-line) .deco-\|{display:inline-flex}.line .deco-\| img.image{object-fit:contain;margin:0}.line [class^=level] .deco-\|{flex-wrap:wrap}.line .level-1 .deco-\|>span{width:100%}.line .level-2 .deco-\|>span{width:50%}.line .level-3 .deco-\|>span{width:calc(100%/3)}.line .level-4 .deco-\|>span{width:25%}.line .level-5 .deco-\|>span{width:20%}.line [class^=level] .deco-\| img.image{object-fit:cover;width:100%;height:100%}.line .deco-\|>span,.line [class^=level] .deco-\|>span{overflow:hidden}.line .deco-\| img.image,.line [class^=level] .deco-\| img.image{margin:.2em}.selections .popup-menu .button-container .button:empty{display:none}.strong-button>strong,.italic-button>i,.strike-button>strike{display:inline-block;width:0;text-indent:-9999px}.selections .popup-menu .button-container .button:is(.link-button,.new-page-button,.copy-plain-button){font-size:0}.selections .popup-menu .button-container .button{font-family:Open Sans,Helvetica,Arial,Hiragino Sans,sans-serif,"Font Awesome 5 Free","Font Awesome 5 Brands";font-size:11px;line-height:20px;font-weight:600;display:inline-block;text-align:center}.link-button:after{font-size:11px;content:""}.strong-button:after{content:""}.italic-button:after{content:""}.strike-button:after{content:""}.copy-plain-button:after{font-size:11px;content:""}.new-page-button:after{font-size:11px;content:""}.line a.icon[href$="/hr"]{pointer-events:none}.page-column{grid-template-columns:var(--page-column-columns, 46px minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas, "spacer page menu")}@media (991px < width){.page-column:has(.page-sidebar){grid-template-columns:var(--page-column-columns-sidebar, minmax(200px, 3fr) minmax(170px, 1fr) min-content);grid-template-areas:var(--page-column-areas-sidebar, "page sidebar menu")}}@media (min-width: 768px) and (max-width: 991px){.page-column{grid-template-columns:var(--page-column-columns-768, minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas-768, "page menu")}}@media (max-width: 767px){.page-column{display:grid;grid-template-columns:var(--page-column-columns-767, 1fr);grid-template-areas:var(--page-column-areas-767, "page")}}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: minmax(200px, 960px) min-content;--page-column-areas-sidebar: "page menu"}.page-sidebar:not(:has(.definition-term)){display:none}.deco-\#{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace}.grid li.page-list-item a .pin{background-color:transparent;background-image:none}.grid li.page-list-item a .pin:after{content:"";font-family:"Font Awesome 5 Free";font-weight:900;font-size:20px;color:#1f915e;bottom:0}.deco-\>{position:absolute;width:100%;text-align:right}li.page-list-item.grid-style-item div.title{-webkit-line-clamp:2}.line.number-list .dot{background-color:transparent!important;display:list-item}.line.number-list .dot:before{display:block;position:absolute;font-family:"Font Awesome 5 Free";top:-11px;content:"";font-weight:900;font-size:11px;color:#c9c9c9;opacity:0}.line.number-list .c-0+.dot:before{opacity:1}.line.number-list .c-1+.dot:before{opacity:.8}.line.number-list .c-2+.dot:before{opacity:.6}.line.number-list .c-3+.dot:before{opacity:.4}.line.number-list .c-4+.dot:before{opacity:.2}img[src^="https://i.kakeru.app"]{background-color:#fff}.brand-icon{display:none!important}.navbar-brand:before{content:"";font-family:"Font Awesome 5 Free";font-size:28px;font-weight:900;color:#bbb}body{--empty-page-link-color: #309b98;--empty-page-link-hover-color: #28807d}.project-home .title{font-size:2rem}.expandable-menu{max-width:calc(100% - 232px)}@media screen and (min-width: 768px) and (max-width: 991px){.expandable-menu{max-width:calc(100% - 247px)}}@media screen and (min-width: 992px) and (max-width: 1260px){.expandable-menu{max-width:calc(100% - 262px)}}.line .indent-mark .dot{top:11px;width:6px;height:3px;background-color:#c9c9c9}.dropdown-menu,.drawer .drawer-menu{background-color:var(--dropdown-menu-bg, #fff);border:var(--dropdown-menu-border, unset)}.dropdown-menu>li>a,.drawer .drawer-menu ul li a,.page-menu ul>li>div{color:var(--dropdown-menu-text-color, #333)}.dropdown-menu>li>a:active,.drawer-menu ul li a:active,[data-hover-visible] :is(.dropdown-menu,.drawer-menu)>li>:is(a:hover,a:focus){color:var(--dropdown-menu-text-hover-color, #262626);background-color:var(--dropdown-menu-text-hover-bg, #f5f5f5)}:is(.dropdown-menu,.drawer-menu) .divider{color:var(--dropdown-menu-divider-color, #e5e5e5)}@media (prefers-color-scheme: dark){body{--body-bg: #202228;--navbar-bg: rgba(55, 59, 68, .3);--navbar-icon-color: #fff;--navbar-icon-active-color: #338c46;--navbar-icon-hovered-color: #338c46;--search-form-bg: rgba(255, 255, 255, .13);--search-form-icon-color: #fff;--search-form-icon-focus-color: #4a4a4a;--card-title-color: #f0f0f0;--card-title-bg: #2b2e38;--card-bg: #373b44;--card-hover-bg: rgba(0, 0, 0, .1);--card-active-bg: rgba(229, 229, 229, .1);--card-backside: #545860;--card-description-color: #c4c4c4;--card-description-link-color: #80c9fe;--card-description-code-color: #ccc;--card-box-shadow-color: #000;--card-box-shadow: 0 2px 0 var(--card-box-shadow-color);--card-box-hover-shadow: 0 2px 0 rgba(0, 0, 0, .23);--card-title-bg-pinned: #2b2e38;--relation-label-bg: #2b2e38;--relation-label-text: #dddede;--relation-label-links-bg: #80c9fe;--relation-label-links-text: #202228;--relation-label-empty-bg: #fb7476;--relation-label-empty-text: #fff;--tool-color: #535863;--tool-light-color: #353b48;--tool-badge-bg: #2b2e38;--tool-bg: #2b2e38;--tool-text-color: #dddede;--new-button-vertical-color: #fff;--new-button-horizontal-color: #fff;--new-button-bg: #46af5d;--new-button-hover-bg: #338c46;--new-button-active-bg: #346447;--telomere-border: #545863;--telomere-unread: #56a066;--page-text-color: rgba(255, 255, 255, .87);--page-link-color: #80c9fe;--page-link-hover-color: #6a9ec6;--page-link-color-cursor-line: #a985e4;--page-bg: #373b44;--empty-page-link-color: #fb7476;--empty-page-link-hover-color: #b47576;--line-title-color: rgba(255, 255, 255, .87);--line-permalink-color: rgba(234, 218, 74, .35);--code-color: #ccc;--code-bg: rgba(0, 0, 0, .18);--quote-bg-color: rgba(0, 0, 0, .2);--cursor-color: #fff}body{--dark-theme-bg: #24292f;--dark-theme-border: solid 1px #888}body{--navbar-bg: rgba(2, 167, 137, .5)}body{--new-button-horizontal-color: #b44a29;--new-button-vertical-color: var(--new-button-horizontal-color);--new-button-bg: #f4835f;--new-button-hover-bg: #f2693e;--new-button-active-bg: #ef4c17}body{--tool-color: #535863;--tool-light-color: #353b48;--tool-badge-bg: #2b2e38;--tool-bg: #2b2e38;--tool-text-color: #dddede;--body-headings-color: var(--tool-color)}body{--code-line-number-color: #D181FF;--cursor-code-line-number-color: #FF00F0}body{--dropdown-menu-bg: #373b44;--dropdown-menu-border: 1px solid #8888882d;--dropdown-menu-text-color: var(--page-text-color);--dropdown-menu-divider-color: #e5e5e5;--dropdown-menu-text-hover-color: var(--page-text-color);--dropdown-menu-text-hover-bg: #373b44}body{--card-title-bg: var(--navbar-bg);--card-title-bg-pinned: var(--navbar-bg)}.page{box-shadow:none;border:solid 1px #888}.table-block .cell{border-bottom:solid 1px #888}.line code.helpfeel{background-color:var(--code-bg)}.line span.code-block .code-block-start{border:solid 1px #66667F;background-color:#272822;padding:2px 5px;color:#7c9ff7}.line span.code-block .code-block-start a{color:#7c9ff7}.code-block{--code-bg: #2d2b57;--code-color: #e3dfff;font-weight:400}code.highlight .hljs-subst{color:#e3dfff}code.highlight .hljs-title{color:#fad000;font-weight:400}code.highlight .hljs-name{color:#a1feff}code.highlight .hljs-tag{color:#fff}code.highlight .hljs-attr{color:#f8d000;font-style:italic}code.highlight :is(.hljs-built_in,.hljs-selector-tag,.hljs-section){color:#fb9e00}code.highlight .hljs-keyword{color:#fb9e00}code.highlight :is(.hljs-string,.hljs-attribute,.hljs-symbol,.hljs-bullet,.hljs-addition,.hljs-code,.hljs-regexp,.hljs-selector-class,.hljs-selector-attr,.hljs-selector-pseudo,.hljs-template-tag,.hljs-quote,.hljs-deletion){color:#4cd213}code.highlight :is(.hljs-meta,.hljs-meta .hljs-string){color:#fb9e00}code.highlight .hljs-comment{color:#ac65ff}code.highlight :is(.hljs-keyword,.hljs-selector-tag,.hljs-literal,.hljs-name){font-weight:400}code.highlight :is(.hljs-literal,.hljs-number){color:#fa658d}code.highlight .hljs-emphasis{font-style:italic}code.highlight .hljs-strong{font-weight:700}code.highlight :is(.hljs-selector-pseudo,.hljs-deletion){color:#e06c75}::selection{color:unset;background:#0073e680}.selection{background-color:#fff7}.line .indent-mark .dot{background-color:gray}.line.number-list .dot:before{color:gray}}.page-link[href*=".@"]:before{content:"✅"}.page-link[href*="@20"]:not([href*=".@"]):before{content:"⬜"}body{background-image:url(https://i.gyazo.com/8d65198f72652e8887d2c941f39805b4.png)}.grid li.page-list-item a .description .formula{display:inline}.page-link:is([href^="/tosuke-notes"],[href^="/blu3mo/"],[href^="/masuilab/"],[href^="/takker-memex"],[href^="/takker-books"],[href^="/takker-CEPM"],[href^="/takker-MBRC"],[href^="/takker-CVBH"],[href^="/takker-CVST"],[href^="/takker-PS"],[href^="/takker-SM"],[href^="/takker-SoM"],[href^="/takker-private"]):before{content:"🔒"}
takker-user.css@media screen and (min-width: 400px){html:is([data-os*=android],[data-os*=ios]) .popup-menu .button-container .button,.popup-menu .button-container .button:is([data-os*=android],[data-os*=ios]){min-width:3em}}.page-column{--page-column-columns: 100px minmax(200px, 960px) min-content 1fr;--page-column-areas: "spacer page menu spacer2";--page-column-columns-sidebar: 100px minmax(200px, 3fr) minmax(170px, 1fr) min-content;--page-column-areas-sidebar: "spacer page sidebar menu";--page-column-columns-768: var(--page-column-columns);--page-column-areas-768: var(--page-column-areas);--page-column-columns-767: minmax(60px, calc(100% / 767 * 100)) 1fr;--page-column-areas-767: "spacer page"}@container (width > 1236px){.page-column{--page-column-columns: minmax(200px, 960px) min-content;--page-column-areas: "page menu"}}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: var(--page-column-columns);--page-column-areas-sidebar: var(--page-column-areas)}.page-sidebar:not(:has(.definition-term)){display:none}.search-form .form-group input:focus{color:var(--page-text-color);background-color:var(--search-form-bg, rgba(255,255,255,.15))}.line span.code-block .code-block-start [title=css] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=html] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=javascript] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=typescript] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=cpp] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=c] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=cs] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=python] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=toml] a:before,.line span.code-block .code-block-start [title=json] a:before,.line span.code-block .code-block-start [title=yaml] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=xml] a:before{content:"謹";display:inline-block}.line span.code-block .code-block-start [title=gitignore] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=markdown] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=txt] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=csv] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=fish] a:before,.line span.code-block .code-block-start [title=bash] a:before,.line span.code-block .code-block-start [title=zsh] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=dos] a:before{content:"";display:inline-block}.line code,.line span.code-block{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace;font-size:105%}[data-os=android]{.page-column{div.page-menu{position:fixed;display:flex;flex-direction:row-reverse;right:0;.dropdown-menu-top,.dropdown-menu-right{top:46px}}}}
takker-memex.cssbody *:before{--code-number-color: var(--code-color, #342d9c)}.section-title{counter-reset:codeline}.code-block span.indent code.code-body{counter-increment:codeline;margin-left:-1.5em;padding-left:2.3em}.code-block span.indent code.code-body:before{content:counter(codeline);position:absolute;display:inline-block;z-index:10;margin-left:-2.4em;width:2em;padding-right:.2em;text-align:right;vertical-align:bottom;border-right:solid 1px #fff;color:var(--code-number-color)}.code-block span.indent code.code-body:before{opacity:.5}.cursor-line .code-block span.indent code.code-body:before{opacity:1;font-weight:bolder;background-color:var(--accent-color)}.navbar-form .dropdown.open .dropdown-menu{min-width:100%;max-height:calc(100vh - 130px)!important;overflow-y:auto}.page-list-item.pin+.page-list-item:not(.pin){grid-column-start:1}.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):not([href^="https://scrapbox.io"]):after{font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";font-weight:900;font-size:.8rem;content:" ";display:inline-block}.line .deco-\.{font-size:.8em;position:relative;top:-.5em}.line:not(.cursor-line) .deco-\. a:is(.page-link:not(.icon),.link) span:not(.empty-char-index)+span+span~span{display:inline-block;width:0;text-indent:-9999px}.line:not(.cursor-line) .deco-\. .page-link:not(.icon) span.empty-char-index~span.char-index{display:inherit;width:inherit;text-indent:inherit}.line:not(.cursor-line) .deco-\. a.page-link:not(.icon) span.empty-char-index+span:before{content:"#"}.line .deco-\. :is(.page-link:not(.icon),.link):before{display:inline-block;min-width:1.15em;padding-left:1px;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";text-align:center;vertical-align:middle;font-weight:900;content:""}.line .deco-\..deco-\/{font-style:initial}.line .deco-\..deco-\/ :is(.page-link:not(.icon),.link):before{font-weight:400;content:""}div.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):is([href$=".pdf"],[href^="https://twitter.com"],[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):after{display:none}.line span:not(.deco-\.)>span>a.link:is([href$=".pdf"],[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{display:inline-block;width:1em;height:1em;vertical-align:-1px;text-align:center;background-size:contain;background-repeat:no-repeat;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands"}.line a.link:not(.icon)[href$=".pdf"]:before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"]):before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{content:"";font-weight:400;margin-right:3px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index{display:inline-block;width:0;text-indent:-9999px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index:nth-of-type(30)~span.char-index{display:inherit;width:inherit;text-indent:inherit}.deco-\"{border-radius:.2em;padding:0 .4em;background-color:#8080801a;font-size:95%;font-style:italic}.deco-\":before{color:#a0a0a0;font-size:85%;font-family:"Font Awesome 5 Free";content:"";font-weight:900;vertical-align:super}.line .indent-mark .dot{opacity:0}.line .indent-mark .c-0+.dot{opacity:1}.line .indent-mark .c-1+.dot{opacity:.8}.line .indent-mark .c-2+.dot{opacity:.6}.line .indent-mark .c-3+.dot{opacity:.4}.line .indent-mark .c-4+.dot{opacity:.2}.line strong:not([class]){background:linear-gradient(transparent 60%,#abff4f99 60% 100%)}.time-range .lines{user-select:unset;-webkit-user-select:unset}.line:not(.cursor-line) .deco-\|{display:inline-flex}.line .deco-\| img.image{object-fit:contain;margin:0}.line [class^=level] .deco-\|{flex-wrap:wrap}.line .level-1 .deco-\|>span{width:100%}.line .level-2 .deco-\|>span{width:50%}.line .level-3 .deco-\|>span{width:calc(100%/3)}.line .level-4 .deco-\|>span{width:25%}.line .level-5 .deco-\|>span{width:20%}.line [class^=level] .deco-\| img.image{object-fit:cover;width:100%;height:100%}.line .deco-\|>span,.line [class^=level] .deco-\|>span{overflow:hidden}.line .deco-\| img.image,.line [class^=level] .deco-\| img.image{margin:.2em}.selections .popup-menu .button-container .button:empty{display:none}.strong-button>strong,.italic-button>i,.strike-button>strike{display:inline-block;width:0;text-indent:-9999px}.selections .popup-menu .button-container .button:is(.link-button,.new-page-button,.copy-plain-button){font-size:0}.selections .popup-menu .button-container .button{font-family:Open Sans,Helvetica,Arial,Hiragino Sans,sans-serif,"Font Awesome 5 Free","Font Awesome 5 Brands";font-size:11px;line-height:20px;font-weight:600;display:inline-block;text-align:center}.link-button:after{font-size:11px;content:""}.strong-button:after{content:""}.italic-button:after{content:""}.strike-button:after{content:""}.copy-plain-button:after{font-size:11px;content:""}.new-page-button:after{font-size:11px;content:""}.line a.icon[href$="/hr"]{pointer-events:none}.page-column{grid-template-columns:var(--page-column-columns, 46px minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas, "spacer page menu")}@media (991px < width){.page-column:has(.page-sidebar){grid-template-columns:var(--page-column-columns-sidebar, minmax(200px, 3fr) minmax(170px, 1fr) min-content);grid-template-areas:var(--page-column-areas-sidebar, "page sidebar menu")}}@media (min-width: 768px) and (max-width: 991px){.page-column{grid-template-columns:var(--page-column-columns-768, minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas-768, "page menu")}}@media (max-width: 767px){.page-column{display:grid;grid-template-columns:var(--page-column-columns-767, 1fr);grid-template-areas:var(--page-column-areas-767, "page")}}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: minmax(200px, 960px) min-content;--page-column-areas-sidebar: "page menu"}.deco-\#{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace}.grid li.page-list-item a .pin{background-color:transparent;background-image:none}.grid li.page-list-item a .pin:after{content:"";font-family:"Font Awesome 5 Free";font-weight:900;font-size:20px;color:#1f915e;bottom:0}@media screen and (min-width: 400px){html:is([data-os*=android],[data-os*=ios]) .popup-menu .button-container .button,.popup-menu .button-container .button:is([data-os*=android],[data-os*=ios]){min-width:3em}}.page-column{--page-column-columns: 100px minmax(200px, 960px) min-content 1fr;--page-column-areas: "spacer page menu spacer2";--page-column-columns-sidebar: 100px minmax(200px, 3fr) minmax(170px, 1fr) min-content;--page-column-areas-sidebar: "spacer page sidebar menu";--page-column-columns-768: var(--page-column-columns);--page-column-areas-768: var(--page-column-areas);--page-column-columns-767: minmax(60px, calc(100% / 767 * 100)) 1fr;--page-column-areas-767: "spacer page"}@container (width > 1236px){.page-column{--page-column-columns: minmax(200px, 960px) min-content;--page-column-areas: "page menu"}}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: var(--page-column-columns);--page-column-areas-sidebar: var(--page-column-areas)}.page-sidebar:not(:has(.definition-term)){display:none}.deco-\>{position:absolute;width:100%;text-align:right}.search-form .form-group input:focus{color:var(--page-text-color);background-color:var(--search-form-bg, rgba(255,255,255,.15))}.line span.code-block .code-block-start [title=css] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=html] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=javascript] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=typescript] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=cpp] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=c] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=cs] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=python] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=toml] a:before,.line span.code-block .code-block-start [title=json] a:before,.line span.code-block .code-block-start [title=yaml] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=xml] a:before{content:"謹";display:inline-block}.line span.code-block .code-block-start [title=gitignore] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=markdown] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=txt] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=csv] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=fish] a:before,.line span.code-block .code-block-start [title=bash] a:before,.line span.code-block .code-block-start [title=zsh] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=dos] a:before{content:"";display:inline-block}.line code,.line span.code-block{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace;font-size:105%}.table-block .cell{border:solid 1px var(--telomere-border, #808b8c)}li.page-list-item.grid-style-item div.title{-webkit-line-clamp:2}.line.number-list .dot{background-color:transparent!important;display:list-item}.line.number-list .dot:before{display:block;position:absolute;font-family:"Font Awesome 5 Free";top:-11px;content:"";font-weight:900;font-size:11px;color:#c9c9c9;opacity:0}.line.number-list .c-0+.dot:before{opacity:1}.line.number-list .c-1+.dot:before{opacity:.8}.line.number-list .c-2+.dot:before{opacity:.6}.line.number-list .c-3+.dot:before{opacity:.4}.line.number-list .c-4+.dot:before{opacity:.2}img[src^="https://i.kakeru.app"]{background-color:#fff}@media screen{.quick-launch .left-box{position:fixed;top:-2px;left:40px;z-index:1000}}@media screen and (min-width: 768px) and (max-width: 991px){.quick-launch .left-box{left:55px}}@media screen and (min-width: 992px) and (max-width: 1260px){.quick-launch .left-box{left:70px}}@media screen and (min-width: 1261px){.quick-launch .left-box{left:calc((100% - 1280px)/2 + 80px)}}.expandable-menu{max-width:calc(100% - 291px)}@media screen and (min-width: 768px) and (max-width: 991px){.expandable-menu{max-width:calc(100% - 306px)}}@media screen and (min-width: 992px) and (max-width: 1260px){.expandable-menu{max-width:calc(100% - 321px)}}.deco-\* img.image{max-height:600px}.page-link[href*=".@"]:before{content:"✅"}.page-link[href*="@20"]:not([href*=".@"]):before{content:"⬜"}[data-os=android]{.page-column{div.page-menu{position:fixed;display:flex;flex-direction:row-reverse;right:0;.dropdown-menu-top,.dropdown-menu-right{top:46px}}}}.dropdown-menu,.drawer .drawer-menu{background-color:var(--dropdown-menu-bg, #fff);border:var(--dropdown-menu-border, unset)}.dropdown-menu>li>a,.drawer .drawer-menu ul li a,.page-menu ul>li>div{color:var(--dropdown-menu-text-color, #333)}.dropdown-menu>li>a:active,.drawer-menu ul li a:active,[data-hover-visible] :is(.dropdown-menu,.drawer-menu)>li>:is(a:hover,a:focus){color:var(--dropdown-menu-text-hover-color, #262626);background-color:var(--dropdown-menu-text-hover-bg, #f5f5f5)}:is(.dropdown-menu,.drawer-menu) .divider{color:var(--dropdown-menu-divider-color, #e5e5e5)}body{--dropdown-menu-bg: #373b44;--dropdown-menu-border: 1px solid #8888882d;--dropdown-menu-text-color: var(--page-text-color);--dropdown-menu-text-hover-color: var(--page-text-color);--dropdown-menu-text-hover-bg: #373b44}.line:not(.cursor-line) .deco-\'{position:absolute;width:100%;text-align:center}.navbar-brand:before{content:"";width:44px;height:44px;position:absolute;background-color:#252a30;background-image:url(https://daiiz-apps.appspot.com/today/jp.svg);background-size:cover;background-position:center;border-radius:6px}.line:not(.cursor-line) [class="deco-( deco-)"]:not(:has(img.icon)){border-radius:50%;border:.05em solid var(--page-text-color, #4a4a4a);line-height:1;color:var(--page-text-color, #4a4a4a);font-weight:600;padding:5px;a{color:var(--page-text-color, #4a4a4a)}}
takker-private.cssbody *:before{--code-number-color: var(--code-color, #342d9c)}.section-title{counter-reset:codeline}.code-block span.indent code.code-body{counter-increment:codeline;margin-left:-1.5em;padding-left:2.3em}.code-block span.indent code.code-body:before{content:counter(codeline);position:absolute;display:inline-block;z-index:10;margin-left:-2.4em;width:2em;padding-right:.2em;text-align:right;vertical-align:bottom;border-right:solid 1px #fff;color:var(--code-number-color)}.code-block span.indent code.code-body:before{opacity:.5}.cursor-line .code-block span.indent code.code-body:before{opacity:1;font-weight:bolder;background-color:var(--accent-color)}.navbar-form .dropdown.open .dropdown-menu{min-width:100%;max-height:calc(100vh - 130px)!important;overflow-y:auto}.page-list-item.pin+.page-list-item:not(.pin){grid-column-start:1}.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):not([href^="https://scrapbox.io"]):after{font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";font-weight:900;font-size:.8rem;content:" ";display:inline-block}.line .deco-\.{font-size:.8em;position:relative;top:-.5em}.line:not(.cursor-line) .deco-\. a:is(.page-link:not(.icon),.link) span:not(.empty-char-index)+span+span~span{display:inline-block;width:0;text-indent:-9999px}.line:not(.cursor-line) .deco-\. .page-link:not(.icon) span.empty-char-index~span.char-index{display:inherit;width:inherit;text-indent:inherit}.line:not(.cursor-line) .deco-\. a.page-link:not(.icon) span.empty-char-index+span:before{content:"#"}.line .deco-\. :is(.page-link:not(.icon),.link):before{display:inline-block;min-width:1.15em;padding-left:1px;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";text-align:center;vertical-align:middle;font-weight:900;content:""}.line .deco-\..deco-\/{font-style:initial}.line .deco-\..deco-\/ :is(.page-link:not(.icon),.link):before{font-weight:400;content:""}div.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):is([href$=".pdf"],[href^="https://twitter.com"],[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):after{display:none}.line span:not(.deco-\.)>span>a.link:is([href$=".pdf"],[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{display:inline-block;width:1em;height:1em;vertical-align:-1px;text-align:center;background-size:contain;background-repeat:no-repeat;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands"}.line a.link:not(.icon)[href$=".pdf"]:before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"]):before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{content:"";font-weight:400;margin-right:3px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index{display:inline-block;width:0;text-indent:-9999px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index:nth-of-type(30)~span.char-index{display:inherit;width:inherit;text-indent:inherit}.deco-\"{border-radius:.2em;padding:0 .4em;background-color:#8080801a;font-size:95%;font-style:italic}.deco-\":before{color:#a0a0a0;font-size:85%;font-family:"Font Awesome 5 Free";content:"";font-weight:900;vertical-align:super}.line .indent-mark .dot{opacity:0}.line .indent-mark .c-0+.dot{opacity:1}.line .indent-mark .c-1+.dot{opacity:.8}.line .indent-mark .c-2+.dot{opacity:.6}.line .indent-mark .c-3+.dot{opacity:.4}.line .indent-mark .c-4+.dot{opacity:.2}.line strong:not([class]){background:linear-gradient(transparent 60%,#abff4f99 60% 100%)}.time-range .lines{user-select:unset;-webkit-user-select:unset}.line:not(.cursor-line) .deco-\|{display:inline-flex}.line .deco-\| img.image{object-fit:contain;margin:0}.line [class^=level] .deco-\|{flex-wrap:wrap}.line .level-1 .deco-\|>span{width:100%}.line .level-2 .deco-\|>span{width:50%}.line .level-3 .deco-\|>span{width:calc(100%/3)}.line .level-4 .deco-\|>span{width:25%}.line .level-5 .deco-\|>span{width:20%}.line [class^=level] .deco-\| img.image{object-fit:cover;width:100%;height:100%}.line .deco-\|>span,.line [class^=level] .deco-\|>span{overflow:hidden}.line .deco-\| img.image,.line [class^=level] .deco-\| img.image{margin:.2em}.selections .popup-menu .button-container .button:empty{display:none}.strong-button>strong,.italic-button>i,.strike-button>strike{display:inline-block;width:0;text-indent:-9999px}.selections .popup-menu .button-container .button:is(.link-button,.new-page-button,.copy-plain-button){font-size:0}.selections .popup-menu .button-container .button{font-family:Open Sans,Helvetica,Arial,Hiragino Sans,sans-serif,"Font Awesome 5 Free","Font Awesome 5 Brands";font-size:11px;line-height:20px;font-weight:600;display:inline-block;text-align:center}.link-button:after{font-size:11px;content:""}.strong-button:after{content:""}.italic-button:after{content:""}.strike-button:after{content:""}.copy-plain-button:after{font-size:11px;content:""}.new-page-button:after{font-size:11px;content:""}.line a.icon[href$="/hr"]{pointer-events:none}.page-column{grid-template-columns:var(--page-column-columns, 46px minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas, "spacer page menu")}@media (991px < width){.page-column:has(.page-sidebar){grid-template-columns:var(--page-column-columns-sidebar, minmax(200px, 3fr) minmax(170px, 1fr) min-content);grid-template-areas:var(--page-column-areas-sidebar, "page sidebar menu")}}@media (min-width: 768px) and (max-width: 991px){.page-column{grid-template-columns:var(--page-column-columns-768, minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas-768, "page menu")}}@media (max-width: 767px){.page-column{display:grid;grid-template-columns:var(--page-column-columns-767, 1fr);grid-template-areas:var(--page-column-areas-767, "page")}}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: minmax(200px, 960px) min-content;--page-column-areas-sidebar: "page menu"}.deco-\#{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace}.grid li.page-list-item a .pin{background-color:transparent;background-image:none}.grid li.page-list-item a .pin:after{content:"";font-family:"Font Awesome 5 Free";font-weight:900;font-size:20px;color:#1f915e;bottom:0}@media screen and (min-width: 400px){html:is([data-os*=android],[data-os*=ios]) .popup-menu .button-container .button,.popup-menu .button-container .button:is([data-os*=android],[data-os*=ios]){min-width:3em}}.page-column{--page-column-columns: 100px minmax(200px, 960px) min-content 1fr;--page-column-areas: "spacer page menu spacer2";--page-column-columns-sidebar: 100px minmax(200px, 3fr) minmax(170px, 1fr) min-content;--page-column-areas-sidebar: "spacer page sidebar menu";--page-column-columns-768: var(--page-column-columns);--page-column-areas-768: var(--page-column-areas);--page-column-columns-767: minmax(60px, calc(100% / 767 * 100)) 1fr;--page-column-areas-767: "spacer page"}@container (width > 1236px){.page-column{--page-column-columns: minmax(200px, 960px) min-content;--page-column-areas: "page menu"}}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: var(--page-column-columns);--page-column-areas-sidebar: var(--page-column-areas)}.page-sidebar:not(:has(.definition-term)){display:none}.deco-\>{position:absolute;width:100%;text-align:right}.search-form .form-group input:focus{color:var(--page-text-color);background-color:var(--search-form-bg, rgba(255,255,255,.15))}.line span.code-block .code-block-start [title=css] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=html] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=javascript] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=typescript] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=cpp] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=c] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=cs] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=python] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=toml] a:before,.line span.code-block .code-block-start [title=json] a:before,.line span.code-block .code-block-start [title=yaml] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=xml] a:before{content:"謹";display:inline-block}.line span.code-block .code-block-start [title=gitignore] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=markdown] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=txt] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=csv] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=fish] a:before,.line span.code-block .code-block-start [title=bash] a:before,.line span.code-block .code-block-start [title=zsh] a:before{content:"";display:inline-block}.line span.code-block .code-block-start [title=dos] a:before{content:"";display:inline-block}.line code,.line span.code-block{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace;font-size:105%}.table-block .cell{border:solid 1px var(--telomere-border, #808b8c)}.line.number-list .dot{background-color:transparent!important;display:list-item}.line.number-list .dot:before{display:block;position:absolute;font-family:"Font Awesome 5 Free";top:-11px;content:"";font-weight:900;font-size:11px;color:#c9c9c9;opacity:0}.line.number-list .c-0+.dot:before{opacity:1}.line.number-list .c-1+.dot:before{opacity:.8}.line.number-list .c-2+.dot:before{opacity:.6}.line.number-list .c-3+.dot:before{opacity:.4}.line.number-list .c-4+.dot:before{opacity:.2}img[src^="https://i.kakeru.app"]{background-color:#fff}[data-os=android]{.page-column{div.page-menu{position:fixed;display:flex;flex-direction:row-reverse;right:0;.dropdown-menu-top,.dropdown-menu-right{top:46px}}}}.dropdown-menu,.drawer .drawer-menu{background-color:var(--dropdown-menu-bg, #fff);border:var(--dropdown-menu-border, unset)}.dropdown-menu>li>a,.drawer .drawer-menu ul li a,.page-menu ul>li>div{color:var(--dropdown-menu-text-color, #333)}.dropdown-menu>li>a:active,.drawer-menu ul li a:active,[data-hover-visible] :is(.dropdown-menu,.drawer-menu)>li>:is(a:hover,a:focus){color:var(--dropdown-menu-text-hover-color, #262626);background-color:var(--dropdown-menu-text-hover-bg, #f5f5f5)}:is(.dropdown-menu,.drawer-menu) .divider{color:var(--dropdown-menu-divider-color, #e5e5e5)}body{--dropdown-menu-bg: #373b44;--dropdown-menu-border: 1px solid #8888882d;--dropdown-menu-text-color: var(--page-text-color);--dropdown-menu-text-hover-color: var(--page-text-color);--dropdown-menu-text-hover-bg: #373b44}html,body,#editor,.grid li{font-family:ヒラギノ角ゴ Pro W3,Hiragino Kaku Gothic Pro,メイリオ,Meiryo,MS Pゴシック,-apple-system,BlinkMacSystemFont,sans-serif}