import-dev
code:script.js
await import("../../takker-dist/import-devにbackgroundでテストコードを貼り付けるUserScript/script.js");
const { setup } = await import("./mod.js");
code:mod.js
var Qs=Object.defineProperty;var Js=(e,t)=>{for(var r in t)Qs(e,r,{get:tr,enumerable:!0})};var tr=" must not return ",Xs="transformer",Zs="recoverer",ei="defaultValue",xc=Xs+tr,rr="called with ",_c=ei+" must not be ",bc=Zs+tr,ti="Ok",or="Err",ri=rr+or,oi=rr+ti,Tc="Carrying E in "+or+" instead of throwing it directly. See .cause",Rt="an instance of Error of the current realm.",Oc="The thrown value is not "+Rt,wc="The contained E should be "+Rt,kc="This .cause is not "+Rt;function P(e){return e.ok}function N(e){return{ok:!0,val:e,err:null}}function g(e){return!e.ok}function O(e){return{ok:!1,val:null,err:e}}function k(e){return nr(e,ri)}function Ie(e){return sr(e,oi)}function nr(e,t){if(g(e))throw new TypeError(t);return e.val}function sr(e,t){if(P(e))throw new TypeError(t);return e.err}function ni(e){return e.val}async function Nt(e,t){if(g(e))return e;let r=ni(e);return await t(r)}function ii(e){return e.val}function Ee(e,t){if(g(e))return e;let r=ii(e),o=t(r);return N(o)}function ai(e){return e.val}async function G(e,t){if(g(e))return e;let r=ai(e),o=await t(r);return N(o)}function pi(e){return e.err}async function W(e,t){if(P(e))return e;let r=pi(e),o=await t(r);return O(o)}var ar=" must not return ",ci="transformer",ui="recoverer",li="defaultValue",mi=ci+ar,fi="called with ",di=li+" must not be ",hi=ui+ar,Be="null",yu=mi+Be,gu=fi+Be,Ru=di+Be,Nu=hi+Be;var pr=" must not return ",Ei="transformer",yi="recoverer",gi="defaultValue",Ri=Ei+pr,Ni="called with ",xi=gi+" must not be ",_i=yi+pr,De="undefined",_u=Ri+De,bu=Ni+De,Tu=xi+De,Ou=_i+De;var cr=" must not return ",bi="transformer",Ti="recoverer",Oi="defaultValue",Mu=bi+cr,ur="called with ",Su=Oi+" must not be ",Uu=Ti+cr;var wi="Ok",lr="Err",Cu=ur+lr,Iu=ur+wi,Bu="Carrying E in "+lr+" instead of throwing it directly. See .cause",xt="an instance of Error of the current realm.",Du="The thrown value is not "+xt,ju="The contained E should be "+xt,Hu="This .cause is not "+xt;var mr=" must not return ",ki="transformer",Li="recoverer",Fi="defaultValue",Gu=ki+mr,fr="called with ",$u=Fi+" must not be ",Wu=Li+mr;var Ai="Ok",dr="Err",Ku=fr+dr,Yu=fr+Ai,zu="Carrying E in "+dr+" instead of throwing it directly. See .cause",_t="an instance of Error of the current realm.",Qu="The thrown value is not "+_t,Ju="The contained E should be "+_t,Xu="This .cause is not "+_t;var hr=" must not return ",Pi="transformer",vi="recoverer",Mi="defaultValue",sl=Pi+hr,Er="called with ",il=Mi+" must not be ",al=vi+hr,Si="Ok",yr="Err",pl=Er+yr,cl=Er+Si,ul="Carrying E in "+yr+" instead of throwing it directly. See .cause",bt="an instance of Error of the current realm.",ll="The thrown value is not "+bt,ml="The contained E should be "+bt,fl="This .cause is not "+bt;var $=e=>e.ok?N(e):O({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var gr=async(e,t)=>{let r=new Request(e,t);try{return N(await globalThis.fetch(r))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return O({name:"AbortError",message:o.message,request:r});if(o instanceof TypeError)return O({name:"NetworkError",message:o.message,request:r});throw o}};var S=e=>{let{fetch:t=gr,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var Rr=e=>{let{sid:t,hostName:r}=S(e??{});return new Request(https://${r}/api/users/me,t?{headers:{Cookie:U(t)}}:void 0)},Nr=e=>G($(e),async t=>await t.json()),je=(()=>{let e=async t=>{let{fetch:r,...o}=S(t??{}),n=await r(Rr(o));return g(n)?n:Nr(k(n))};return e.toRequest=Rr,e.fromResponse=Nr,e})();var U=e=>connect.sid=${e},ye=async e=>{let t=e?.csrf??globalThis._csrf;return t?N(t):Ee(await je(e),r=>r.csrfToken)};function He(e,t={}){if(e===null)return"null";if(Array.isArray(e))return Ci(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:Ii(e,t);case"function":return e.name||"(anonymous)"}return e?.toString()??"undefined"}function Ci(e,t){let{threshold:r=20}=t,o=e.map(i=>He(i,t)),n=o.join(", ");if(n.length<=r)return[${n}];let s=o.join(`,
);return[
${xr(2,s)}
]}function Ii(e,t){let{threshold:r=20}=t,o=[...Object.keys(e),...Object.getOwnPropertySymbols(e)].map(i=>${i.toString()}: ${He(ei,t)}),n=o.join(", ");if(n.length<=r)return{${n}};let s=o.join(,
);return{
${xr(2,s)}
}}function xr(e,t){let r=" ".repeat(e);return t.split(
).map(o=>${r}${o}).join(
)}function qe(e,t,...r){let o;return Object.defineProperties(e,{name:{get:()=>o||(o=${t}(${r.map(n=>He(n)).join(", ")}),o)}})}function Ve(e){return Array.isArray(e)}function _r(e){return qe(t=>Ve(t)&&t.every(r=>e(r)),"isArrayOf",e)}function Tt(e){let t=new Set(e);return qe(r=>t.has(r),"isLiteralOneOf",e)}function Ot(e){return e!=null&&!Array.isArray(e)&&typeof e=="object"}function ie(e){return typeof e=="string"}var Y=async(e,t)=>{let r=e.response.clone(),o=Tt(t);try{let n=await r.json();if(!Ot(n))return;if(r.status===422){if(!ie(n.message))return;for(let s of["NoQueryError","InvalidURLError"])if(t.includes(s))return{name:s,message:n.message}}return!o(n.name)||!ie(n.message)?void 0:n.name==="NotLoggedInError"?!Ot(n.detals)||!ie(n.detals.project)||!_r(Bi)(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}},Bi=Tt(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var ne=e=>e.replaceAll(" ","_").toLowerCase();var ve=e=>[...e].map((t,r)=>t===" "?"_":!Di.includes(t)||r===e.length-1&&ji.includes(t)?encodeURIComponent(t):t).join(""),Di='@$&+=:;",',ji=':;",';var br=" must not return ",Hi="transformer",qi="recoverer",Vi="defaultValue",Tr=Hi+br,Or="called with ",wr=Vi+" must not be ",kr=qi+br;var Ge="null or undefined",ge=Tr+Ge,Gi=Or+Ge,$e=wr+Ge,We=kr+Ge;function Q(e){return e!=null}function re(e,t){if(Q(e))return e;throw new TypeError(t)}function wt(e,t){return Q(e)?e:re(t,$e)}var Lr=(e,t,r)=>{let{sid:o,hostName:n,followRename:s,projects:i}=S(r??{}),a=new URLSearchParams([["followRename",${s??!0}],...i?.map?.(p=>["projects",p])??[]]);return new Request(https://${n}/api/pages/${e}/${ve(t)}?${a},o?{headers:{Cookie:U(o)}}:void 0)},Fr=async e=>W(await G($(e),t=>t.json()),async t=>t.response.status===414?{name:"TooLongURIError",message:"project ids may be too much."}:wt(await Y(t,["NotFoundError","NotLoggedInError","NotMemberError"]),t)),Ar=(()=>{let e=async(t,r,o)=>Nt(await S(o??{}).fetch(Lr(t,r,o)),n=>Fr(n));return e.toRequest=Lr,e.fromResponse=Fr,e})();var Pr=(e,t)=>{let{sid:r,hostName:o}=S(t??{});return new Request(https://${o}/api/projects/${e},r?{headers:{Cookie:U(r)}}:void 0)},vr=async e=>G(await W($(e),async t=>await Y(t,["NotFoundError","NotLoggedInError","NotMemberError"])??t),t=>t.json()),Mr=(()=>{let e=async(t,r)=>{let{fetch:o}=S(r??{}),n=Pr(t,r),s=await o(n);return g(s)?s:vr(k(s))};return e.toRequest=Pr,e.fromResponse=vr,e})();var Ke=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i}=S(o??{}),a=await ye(o);if(g(a))return a;let p=new Request(https://${s}/api/pages/${e}/replace/links,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":k(a),...n?{Cookie:U(n)}:{}},body:JSON.stringify({from:t,to:r})}),u=await i(p);return g(u)?u:G(await W($(k(u)),async c=>await Y(c,["NotFoundError","NotLoggedInError","NotMemberError"])??c),async c=>{let{message:l}=await c.json();return parseInt(l.match(/\d+/)?.[0]??"0")})};var Ki=new TextEncoder().encode("0123456789abcdef"),Sr=new Uint8Array(128).fill(16);Ki.forEach((e,t)=>Sr[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>Sr[e]=t+10);var Yi=new TextEncoder().encode("0123456789abcdef"),Ur=new Uint8Array(128).fill(16);Yi.forEach((e,t)=>Ur[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>Ur[e]=t+10);var Cr=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var Ir=()=>zi(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),zi=(e,t)=>{if(e)return Cr(e,t),e};function ze(e,t={}){let{signal:r,persistent:o=!0}=t;return r?.aborted?Promise.reject(r.reason):new Promise((n,s)=>{let i=()=>{clearTimeout(+p),s(r?.reason)},p=Zi(()=>{r?.removeEventListener("abort",i),n()},e);if(r?.addEventListener("abort",i,{once:!0}),o===!1)try{Deno.unrefTimer(+p)}catch(u){if(!(u instanceof ReferenceError))throw clearTimeout(+p),u;console.error("persistent option is only available in Deno")}})}var Br=2**31-1;function Zi(e,t){let r=t=Math.trunc(Math.max(t,0)||0),o=Date.now(),n,s=()=>{r=t-(Date.now()-o),n=r>Br?Number(setTimeout(s,Br)):Number(setTimeout(e,r))};return s(),{valueOf:()=>n}}var Qe=()=>{let e=Ir();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=Dr(...r);o&&t.append(o)},dispose:()=>t.remove(),[Symbol.dispose]:()=>t.remove()}},Dr=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":return[oa()];case"check-circle":return[na()];case"exclamation-triangle":return[sa()];case"text":return[Je(o.text)];case"group":{let n=Dr(...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},Je=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},oa=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),Je(e)},na=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),Je(e)},sa=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),Je(e)};function L(e){if(e)return aa(e)}function aa(e){for(var t in L.prototype)e[t]=L.prototype[t];return e}L.prototype.on=L.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};L.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};L.prototype.off=L.prototype.removeListener=L.prototype.removeAllListeners=L.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};L.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};L.prototype.emitReserved=L.prototype.emit;L.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};L.prototype.hasListeners=function(e){return!!this.listeners(e).length};var se=Object.create(null);se.open="0";se.close="1";se.ping="2";se.pong="3";se.message="4";se.upgrade="5";se.noop="6";var et=Object.create(null);Object.keys(se).forEach(e=>{et[se[e]]=e});var Ft={type:"error",data:"parser error"},Vr=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Gr=typeof ArrayBuffer=="function",$r=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,tt=({type:e,data:t},r,o)=>Vr&&t instanceof Blob?r?o(t):jr(t,o):Gr&&(t instanceof ArrayBuffer||$r(t))?r?o(t):jr(new Blob([t]),o):o(se[e]+(t||"")),jr=(e,t)=>{let r=new FileReader;return r.onload=function(){let o=r.result.split(",")[1];t("b"+(o||""))},r.readAsDataURL(e)};function Hr(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var kt;function pa(e,t){if(Vr&&e.data instanceof Blob)return e.data.arrayBuffer().then(Hr).then(t);if(Gr&&(e.data instanceof ArrayBuffer||$r(e.data)))return t(Hr(e.data));tt(e,!1,r=>{kt||(kt=new TextEncoder),t(kt.encode(r))})}var qr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Me=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<qr.length;e++)Me[qr.charCodeAt(e)]=e;var ca=e=>{let t=e.length*.75,r=e.length,o,n=0,s,i,a,p;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);let u=new ArrayBuffer(t),c=new Uint8Array(u);for(o=0;o<r;o+=4)s=Me[e.charCodeAt(o)],i=Me[e.charCodeAt(o+1)],a=Me[e.charCodeAt(o+2)],p=Me[e.charCodeAt(o+3)],c[n++]=s<<2|i>>4,c[n++]=(i&15)<<4|a>>2,c[n++]=(a&3)<<6|p&63;return u},ua=typeof ArrayBuffer=="function",rt=(e,t)=>{if(typeof e!="string")return{type:"message",data:Wr(e,t)};let r=e.charAt(0);return r==="b"?{type:"message",data:la(e.substring(1),t)}:et[r]?e.length>1?{type:et[r],data:e.substring(1)}:{type:et[r]}:Ft},la=(e,t)=>{if(ua){let r=ca(e);return Wr(r,t)}else return{base64:!0,data:e}},Wr=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},Kr="",Yr=(e,t)=>{let r=e.length,o=new Array(r),n=0;e.forEach((s,i)=>{tt(s,!1,a=>{o[i]=a,++n===r&&t(o.join(Kr))})})},zr=(e,t)=>{let r=e.split(Kr),o=[];for(let n=0;n<r.length;n++){let s=rt(r[n],t);if(o.push(s),s.type==="error")break}return o};function Qr(){return new TransformStream({transform(e,t){pa(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 Lt;function Xe(e){return e.reduce((t,r)=>t+r.length,0)}function Ze(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 Jr(e,t){Lt||(Lt=new TextDecoder);let r=[],o=0,n=-1,s=!1;return new TransformStream({transform(i,a){for(r.push(i);;){if(o===0){if(Xe(r)<1)break;let p=Ze(r,1);s=(p[0]&128)===128,n=p[0]&127,n<126?o=3:n===126?o=1:o=2}else if(o===1){if(Xe(r)<2)break;let p=Ze(r,2);n=new DataView(p.buffer,p.byteOffset,p.length).getUint16(0),o=3}else if(o===2){if(Xe(r)<8)break;let p=Ze(r,8),u=new DataView(p.buffer,p.byteOffset,p.length),c=u.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Ft);break}n=c*Math.pow(2,32)+u.getUint32(4),o=3}else{if(Xe(r)<n)break;let p=Ze(r,n);a.enqueue(rt(s?p:Lt.decode(p),t)),o=0}if(n===0||n>e){a.enqueue(Ft);break}}}})}var At=4;var Se=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),J=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),ma="arraybuffer";function Zr(e,...t){return t.reduce((r,o)=>(e.hasOwnProperty(o)&&(r[o]=e[o]),r),{})}var fa=J.setTimeout,da=J.clearTimeout;function Ue(e,t){t.useNativeTimers?(e.setTimeoutFn=fa.bind(J),e.clearTimeoutFn=da.bind(J)):(e.setTimeoutFn=J.setTimeout.bind(J),e.clearTimeoutFn=J.clearTimeout.bind(J))}var ha=1.33;function Ea(e){return typeof e=="string"?ya(e):Math.ceil((e.byteLength||e.size)*ha)}function ya(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 eo(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function ga(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}function Ra(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 Na=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},Mt=class extends L{constructor(e){super(),this.writable=!1,Ue(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 Na(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=rt(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=ga(e);return t.length?"?"+t:""}},xa=class extends Mt{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)};zr(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,Yr(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]=eo()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},to=!1;try{to=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var _a=to;function ba(){}var Ta=class extends xa{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}},Re=class ot extends L{constructor(t,r,o){super(),this.createRequest=t,Ue(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=Zr(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=ot.requestsCount++,ot.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=ba,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ot.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()}};Re.requestsCount=0;Re.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Xr);else if(typeof addEventListener=="function"){let e="onpagehide"in J?"pagehide":"unload";addEventListener(e,Xr,!1)}}function Xr(){for(let e in Re.requests)Re.requests.hasOwnProperty(e)&&Re.requests[e].abort()}var Oa=function(){let e=ro({xdomain:!1});return e&&e.responseType!==null}(),St=class extends Ta{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Oa&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Re(ro,this.uri(),e)}};function ro(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||_a))return new XMLHttpRequest}catch{}if(!t)try{return new J[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var oo=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",wa=class extends Mt{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=oo?{}:Zr(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;tt(r,this.supportsBinary,n=>{try{this.doWrite(r,n)}catch{}o&&Se(()=>{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]=eo()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Pt=J.WebSocket||J.MozWebSocket,Ut=class extends wa{createSocket(e,t,r){return oo?new Pt(e,t,r):t?new Pt(e,t):new Pt(e)}doWrite(e,t){this.ws.send(t)}},no=class extends Mt{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=Jr(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),o=Qr();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&&Se(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}},ka={websocket:Ut,webtransport:no,polling:St},La=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Fa=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function at(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=La.exec(e||""),s={},i=14;for(;i--;)s[Fa[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=Aa(s,s.path),s.queryKey=Pa(s,s.query),s}function Aa(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 Pa(e,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(o,n,s){n&&(r[n]=s)}),r}var vt=typeof addEventListener=="function"&&typeof removeEventListener=="function",nt=[];vt&&addEventListener("offline",()=>{nt.forEach(e=>e())},!1);var st=class it extends L{constructor(t,r){if(super(),this.binaryType=ma,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=at(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=at(r.host).host);Ue(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=Ra(this.opts.query)),vt&&(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"})},nt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){let r=Object.assign({},this.opts.query);r.EIO=At,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&&it.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",it.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+=Ea(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,Se(()=>{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(it.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(),vt&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let o=nt.indexOf(this._offlineEventListener);o!==-1&&nt.splice(o,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};st.protocol=At;var va=class extends st{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;st.priorWebsocketSuccess=!1;let o=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",c=>{if(!r)if(c.type==="pong"&&c.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;st.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let l=new Error("probe error");l.transport=t.name,this.emitReserved("upgradeError",l)}}))};function n(){r||(r=!0,u(),t.close(),t=null)}let s=c=>{let l=new Error("probe error: "+c);l.transport=t.name,n(),this.emitReserved("upgradeError",l)};function i(){s("transport closed")}function a(){s("socket closed")}function p(c){t&&c.name!==t.name&&n()}let u=()=>{t.removeListener("open",o),t.removeListener("error",s),t.removeListener("close",i),this.off("close",a),this.off("upgrading",p)};t.once("open",o),t.once("error",s),t.once("close",i),this.once("close",a),this.once("upgrading",p),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}},Ct=class extends va{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=>ka[o]).filter(o=>!!o)),super(e,r)}};var cN=Ct.protocol;var jt={};Js(jt,{Decoder:()=>Ha,Encoder:()=>ja,PacketType:()=>x,protocol:()=>ao});var Ma=typeof ArrayBuffer=="function",Sa=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,io=Object.prototype.toString,Ua=typeof Blob=="function"||typeof Blob<"u"&&io.call(Blob)==="[object BlobConstructor]",Ca=typeof File=="function"||typeof File<"u"&&io.call(File)==="[object FileConstructor]";function Dt(e){return Ma&&(e instanceof ArrayBuffer||Sa(e))||Ua&&e instanceof Blob||Ca&&e instanceof File}function pt(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,o=e.length;r<o;r++)if(pt(e[r]))return!0;return!1}if(Dt(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return pt(e.toJSON(),!0);for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&pt(e[r]))return!0;return!1}function Ia(e){let t=[],r=e.data,o=e;return o.data=It(r,t),o.attachments=t.length,{packet:o,buffers:t}}function It(e,t){if(!e)return e;if(Dt(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]=It(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]=It(e[o],t));return r}return e}function Ba(e,t){return e.data=Bt(e.data,t),delete e.attachments,e}function Bt(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]=Bt(e[r],t);else if(typeof e=="object")for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Bt(e[r],t));return e}var Da=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],ao=5,x;(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"})(x||(x={}));var ja=class{constructor(e){this.replacer=e}encode(e){return(e.type===x.EVENT||e.type===x.ACK)&&pt(e)?this.encodeAsBinary({type:e.type===x.EVENT?x.BINARY_EVENT:x.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===x.BINARY_EVENT||e.type===x.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=Ia(e),r=this.encodeAsString(t.packet),o=t.buffers;return o.unshift(r),o}};function so(e){return Object.prototype.toString.call(e)==="[object Object]"}var Ha=class po extends L{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===x.BINARY_EVENT;o||r.type===x.BINARY_ACK?(r.type=o?x.EVENT:x.ACK,this.reconstructor=new qa(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(Dt(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(x[o.type]===void 0)throw new Error("unknown packet type "+o.type);if(o.type===x.BINARY_EVENT||o.type===x.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(po.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 x.CONNECT:return so(r);case x.DISCONNECT:return r===void 0;case x.CONNECT_ERROR:return typeof r=="string"||so(r);case x.EVENT:case x.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&Da.indexOf(r[0])===-1);case x.ACK:case x.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},qa=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=Ba(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Va(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=at(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 oe(e,t,r){return e.on(t,r),function(){e.off(t,r)}}var Ga=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),co=class extends L{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=[oe(e,"open",this.onopen.bind(this)),oe(e,"packet",this.onpacket.bind(this)),oe(e,"error",this.onerror.bind(this)),oe(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(Ga.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:x.EVENT,data:t};if(s.options={},s.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let p=this.ids++,u=t.pop();this._registerAckCallback(p,u),s.id=p}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:x.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 x.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 x.EVENT:case x.BINARY_EVENT:this.onevent(e);break;case x.ACK:case x.BINARY_ACK:this.onack(e);break;case x.DISCONNECT:this.ondisconnect();break;case x.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:x.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:x.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 xe(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}xe.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};xe.prototype.reset=function(){this.attempts=0};xe.prototype.setMin=function(e){this.ms=e};xe.prototype.setMax=function(e){this.max=e};xe.prototype.setJitter=function(e){this.jitter=e};var Ht=class extends L{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,Ue(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 xe({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||jt;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 Ct(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let o=oe(t,"open",function(){r.onopen(),e&&e()}),n=i=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",i),e?e(i):this.maybeReconnectOnOpen()},s=oe(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(oe(e,"ping",this.onping.bind(this)),oe(e,"data",this.ondata.bind(this)),oe(e,"error",this.onerror.bind(this)),oe(e,"close",this.onclose.bind(this)),oe(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){Se(()=>{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 co(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)}},Ce={};function Ne(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};let r=Va(e,t.path||"/socket.io"),o=r.source,n=r.id,s=r.path,i=Ce[n]&&s in Ce[n].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||i,p;return a?p=new Ht(o,t):(Ce[n]||(Ce[n]=new Ht(o,t)),p=Ce[n]),r.query&&!t.query&&(t.query=r.queryKey),p.socket(r.path,t)}Object.assign(Ne,{Manager:Ht,Socket:co,io:Ne,connect:Ne});var _e=(e,t)=>{if(e?.connected)return Promise.resolve(N(e));e??=Ne("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"],...t?{rejectUnauthorized:!1,extraHeaders:{Cookie:U(t),Host:"scrapbox.io",Referer:"https://scrapbox.io/"}}:{}});let r=new Promise(o=>{let n=s=>o(O(s));e.once("connect",()=>{e.off("disconnect",n),o(N(e))}),e.once("disconnect",n)});return e.connect(),r},be=e=>{if(e.disconnected)return Promise.resolve(N(void 0));let t=new Promise(r=>{let o=n=>{if(n!=="io client disconnect"){r(O(n));return}r(N(void 0)),e.off("disconnect",o)};e.on("disconnect",o)});return e.disconnect(),t};var uo=e=>$a.includes(e.name),$a=["SocketIOError","DuplicateTitleError","NotFastForwardError"];var lo=(e,t,r,o)=>{if(t==="cursor")return e.emit(t,r),Promise.resolve(N(void 0));let{resolve:n,promise:s,reject:i}=Promise.withResolvers(),a=()=>{e.off("disconnect",p),clearTimeout(c)},p=R=>{if(R==="io client disconnect"){a(),i(new Error("io client disconnect"));return}if(R==="io server disconnect"){a(),n(O({name:"SocketIOError"}));return}};e.on("disconnect",p);let u=o?.timeout??9e4,c=setTimeout(()=>{a(),n(O({name:"TimeoutError",message:exceeded ${u} (ms)}))},u),l=t==="commit"?{method:"commit",data:r}:{method:"room:join",data:r};return e.emit("socket.io-request",l,R=>{if(a(),"error"in R){n(O(uo(R.error)?R.error:{name:"UnexpectedRequestError",...R}));return}n(N(R.data))}),s};var Vt=async(e,t,r)=>{let[o,n,s]=await Promise.all([Ar(e,t,r),Wa(r),Ka(e,r)]);return g(o)?o:g(n)?n:g(s)?s:N({...k(o),projectId:k(s),userId:k(n)})},qt,Wa=async e=>{if(qt)return N(qt);let t=await je(e);if(g(t))return t;let r=k(t);return"id"in r?(qt=r.id,N(r.id)):O({name:"NotLoggedInError",message:"This script cannot be used without login"})},mo=new Map,Ka=async(e,t)=>{let r=mo.get(e);return r?N(r):Ee(await Mr(e,t),({id:o})=>(mo.set(e,o),o))};var Te=async(e,t,r,o)=>{let n=await _e(o?.socket,o?.sid);if(g(n))return O({name:"UnexpectedRequestError",error:Ie(n)});let s=k(n),i=await Vt(e,t,o);if(g(i))return i;let a=k(i);try{let p=0,u=[],c;for(;o?.maxAttempts===void 0||p<o.maxAttempts;){let l=r(a,p,u,c);if(u=l instanceof Promise?await l:l,p++,u.length===0)return N(a.commitId);let R={kind:"page",projectId:a.projectId,pageId:a.id,parentId:a.commitId,userId:a.userId,changes:u,cursor:null,freeze:!0};for(;;){let M=await lo(s,"commit",R);if(P(M))return a.commitId=k(M).commitId,N(a.commitId);let F=Ie(M),d=F.name;if(d==="SocketIOServerDisconnectError"||d==="UnexpectedRequestError")return O(F);if(d==="TimeoutError"||d==="SocketIOError"){await ze(3e3);continue}if(d==="NotFastForwardError"){await ze(1e3);let K=await Vt(e,t,o);if(g(K))return K;a=k(K)}c=d;break}}return O({name:"RetryError",attempts:p,message:Retrying exceeded the maxAttempts (${p}).})}finally{o?.socket||await be(s)}};var Gt=(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 p=[];function u(d,K,f){let h=Math.max(K,f),te=h-d;for(;te<o.length&&h<n.length&&o[te]===n[h];)++te,++h;return a[d+s]=p.length,p.push([{x:te,y:h},a[d+(K>f?-1:1)+s]]),h}let c=new Array(i);c.fill(-1);let l=-1,R=n.length-o.length;do{++l;for(let d=-l;d<=R-1;++d)c[d+s]=u(d,c[d-1+s]+1,c[d+1+s]);for(let d=R+l;d>=R+1;--d)c[d+s]=u(d,c[d-1+s]+1,c[d+1+s]);c[R+s]=u(R,c[R-1+s]+1,c[R+1+s])}while(c[R+s]!==n.length);let M=[],F=a[R+s];for(;F!==-1;)M.push(p[F][0]),F=p[F][1];return{from:e,to:t,editDistance:R+l*2,buildSES:function*(){let d=0,K=0;for(let{x:f,y:h}of Ya(M))for(;d<f||K<h;)h-f>K-d?(yield{value:n[K],type:r?"deleted":"added"},++K):h-f<K-d?(yield{value:o[d],type:r?"added":"deleted"},++d):(yield{value:o[d],type:"common"},++d,++K)}}};function*$t(e){let t=[],r=[];function*o(){if(t.length>r.length){for(let n=0;n<r.length;n++)yield fo(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 fo(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 fo=(e,t)=>({value:e.value,oldValue:t.value,type:"replaced"});function*Ya(e){for(let t=e.length-1;t>=0;t--)yield e[t]}var ho=e=>e.padStart(8,"0"),Wt=e=>{let t=Math.floor(new Date().getTime()/1e3).toString(16),r=Math.floor(16777214*Math.random()).toString(16);return${ho(t).slice(-8)}${e.slice(-6)}0000${ho(r)}};function*Kt(e,t,{userId:r}){let{buildSES:o}=Gt(e.map(({text:i})=>i),t),n=0,s=e[0].id;for(let i of $t(o())){switch(i.type){case"added":yield{_insert:s,lines:{id:Wt(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 Eo=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 _=(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 p=a.exec(n);if(p===null)continue;let u=n.substring(0,p.index),c=n.substring(p.index+(p[0]?.length??0)),l=e(p[0]??"",s);return[...z(u,s),...l,...z(c,s)]}return i?.()??[]};var b=e=>[{type:"plain",raw:e,text:e}],yo=_(b,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]});var za=/\[\s+\]/,Qa=(e,t)=>t.context==="table"?b(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],go=_(Qa,{parseOnNested:!1,parseOnQuoted:!0,patterns:[za]});var Ja=/.*?/,Xa=(e,t)=>t.context==="table"?b(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],Ro=_(Xa,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Ja]});var Za=/^[$%] .+$/,ep=(e,t)=>{if(t.context==="table")return b(e,t);let r=e[0]??"",o=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:o}]},No=_(ep,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Za]});var tp=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,rp=(e,t)=>{if(t.context==="table")return b(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:z(n,{...t,nested:!0})}]},xo=_(rp,{parseOnNested:!1,parseOnQuoted:!0,patterns:[tp]});var op=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,np=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,sp=/\[https?:\/\/[^\s\]]+\]/,ip=/https?:\/\/[^\s]+/,ap=(e,t)=>{if(t.context==="table")return b(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()}]},_o=_(ap,{parseOnNested:!0,parseOnQuoted:!0,patterns:[op,np,sp,ip]});var pp=/\[\$ .+? \]/,cp=/\[\$ [^\]]+\]/,up=(e,t)=>t.context==="table"?b(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],bo=_(up,{parseOnNested:!1,parseOnQuoted:!0,patterns:[pp,cp]});var To=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,Oo=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,lp=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}},mp=(e,t)=>{if(t.context==="table")return b(e,t);let r=e.match(To)??e.match(Oo);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:p}=lp(n),u=s!==""?https://www.google.com/maps/place/${encodeURIComponent(s)}/@${i},${a},${p}z:https://www.google.com/maps/@${i},${a},${p}z;return[{type:"googleMap",raw:e,latitude:i,longitude:a,zoom:p,place:s,url:u}]},wo=_(mp,{parseOnNested:!1,parseOnQuoted:!0,patterns:[To,Oo]});var fp=/(?:^|\s)#\S+/,dp=(e,t)=>{if(t.context==="table")return b(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[...b(r,t),{type:"hashTag",raw:o,href:o.substring(1)}]},ko=_(dp,{parseOnNested:!0,parseOnQuoted:!0,patterns:[fp]});var hp=/^\? .+$/,Ep=(e,t)=>t.context==="table"?b(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],Lo=_(Ep,{parseOnNested:!1,parseOnQuoted:!1,patterns:[hp]});var yp=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/,gp=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}))},Fo=_(gp,{parseOnNested:!0,parseOnQuoted:!0,patterns:[yp]});var Rp=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,Np=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?\]/i,xp=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,_p=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,bp=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg|webp)(\?[^\]\s]+)?$/i.test(e)||Tp(e),Tp=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),Op=(e,t)=>{if(t.context==="table")return b(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]=bp(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}]},Ao=_(Op,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Rp,Np,xp,_p]});var wp=/\[\/?[^[\]]+\]/,kp=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},Po=_(kp,{parseOnNested:!0,parseOnQuoted:!0,patterns:[wp]});var Lp=/^[0-9]+\. .*$/,Fp=(e,t)=>{if(t.context==="table")return b(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:z(s,{...t,nested:!1})}]},vo=_(Fp,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Lp]});var Ap=/^>.*$/,Pp=(e,t)=>t.context==="table"?b(e,t):[{type:"quote",raw:e,nodes:z(e.substring(1),{...t,quoted:!0})}],Mo=_(Pp,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Ap]});var vp=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,Mp=(e,t)=>{if(t.context==="table")return b(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}))},So=_(Mp,{parseOnNested:!1,parseOnQuoted:!0,patterns:[vp]});var Sp=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)\]\]/i,Up=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,Cp=(e,t)=>{if(t.context==="table")return b(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}]},Uo=_(Cp,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Sp,Up]});var Ip=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,Bp=(e,t)=>t.context==="table"?b(e,t):[{type:"strong",raw:e,nodes:z(e.substring(2,e.length-2),{...t,nested:!0})}],Co=_(Bp,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Ip]});var Dp=(e,t,r)=>e===""?[]:r?.()??[],jp=(...e)=>(t,r)=>e.reduceRight((o,n)=>()=>n(t,r,o),()=>yo(t,r))(),z=jp(Dp,Mo,Lo,vo,Ro,No,go,xo,bo,Uo,So,Co,Ao,_o,Fo,wo,Po,ko);var Io=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:z(r.substring(t),{nested:!1,quoted:!1,context:"line"})}};var Bo=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=>z(a,{nested:!1,quoted:!1,context:"table"})))}};var Do=e=>({type:"title",text:e.rows[0].text});var jo=e=>{switch(e.type){case"title":return Do(e);case"codeBlock":return Eo(e);case"table":return Bo(e);case"line":return Io(e)}};var Hp=(e,t)=>(e.type==="codeBlock"||e.type==="table")&&t.indent>(e.rows[0]?.indent??0),Ho=(e,t)=>{let r=e[e.length-1];return r!==void 0&&Hp(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)},qo=(e,t)=>{if(t.hasTitle??!0){let[r,...o]=e;return r===void 0?[]:[{type:"title",rows:[r]},...o.reduce(Ho,[])]}return e.reduce(Ho,[])};var Vo=e=>e.split(
).map(t=>({indent:/^\s+/.exec(t)?.[0]?.length??0,text:t}));var Yt=(e,t)=>{let r=Vo(e);return qo(r,{hasTitle:t?.hasTitle??!0}).map(jo)};var qp=/https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/,Vp=/https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/,Gp=/https?:\/\/(?:www\.|)youtube\.com\/shorts\/([a-zA-Z\d_-]+)(?:\?([^\s]+)|)/,$p=/https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/,zt=e=>{if(qp.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(Vp);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"dotbe"}}}{let t=e.match(Gp);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"short"}}}{let t=e.match($p);if(t){let[,r,o]=t;return{listId:o,params:new URLSearchParams(r),pathType:"list"}}}};var Wo=e=>{let t=Yt(e,{hasTitle:!0}),r="",o=new Map,n=[],s=new Set,i=[],a=new Set,p=[],u=null,c=[],l=new Set,R=new Set,M=new RegExp(${globalThis.location?.origin??"https://scrapbox.io"}/files/([a-z0-9]{24})(?:|\\.[a-zA-Z0-9]+)(?:|\\?[^\\s]*)$),F=f=>{switch(f.type){case"hashTag":if(o.has(ne(f.href)))return;o.set(ne(f.href),!1),n.push(f.href);return;case"link":switch(f.pathType){case"relative":{let h=$o(f.href);if(o.get(ne(h)))return;o.set(ne(h),!0),n.push(h);return}case"root":{let h=$o(f.href);if(/^\/[\w\d-]+\/?$/.test(h)||s.has(ne(h)))return;s.add(ne(h)),i.push(h);return}case"absolute":{if(f.content)return;let h=zt(f.href);if(h&&h.pathType!=="list"){u??=https://i.ytimg.com/vi/${h.videoId}/mqdefault.jpg;return}let te=f.href.match(M)?.[1];te&&l.add(te);return}default:return}case"icon":case"strongIcon":{if(f.pathType==="root"||a.has(ne(f.path)))return;a.add(ne(f.path)),p.push(f.path);return}case"image":case"strongImage":{u??=f.src.endsWith("/thumb/1000")?f.src.replace(/\/thumb\/1000$/,"/raw"):f.src;{let h=f.src.match(M)?.[1];h&&l.add(h)}if(f.type==="image"){let h=f.link.match(M)?.[1];h&&l.add(h)}return}case"helpfeel":R.add(f.text);return;case"numberList":case"strong":case"quote":case"decoration":{for(let h of f.nodes)F(h);return}default:return}},d=[];for(let f of t)switch(f.type){case"title":{r=f.text;continue}case"line":c.length<5&&f.nodes.length>0&&c.push(f.nodes[0].type==="helpfeel"||f.nodes[0].type==="commandLine"?Go(f.nodes[0].raw):f.nodes.map(h=>h.raw).join("").trim().slice(0,200));for(let h of f.nodes)F(h);continue;case"codeBlock":c.length<5&&c.push(Go(f.content));continue;case"table":{for(let h of f.cells)for(let te of h)for(let gt of te)F(gt);if(!["infobox","cosense"].includes(f.fileName))continue;d.push(...f.cells.map(h=>h.map(te=>te.map(gt=>gt.raw).join("")).join(" ").trim()));continue}}let K=e.split(
);return[r,n,i,p,u,c,[...l],[...R],d,K.length,K.reduce((f,h)=>f+[...h].length,0)]},Go=e=>\${e.trim().replaceAll("","\\").slice(0,198)}\`,$o=e=>e.replace(/#a-f\d{24,32}$/,"");var ce=(e,t)=>e.length===t.length&&e.every(r=>t.includes(r));var Ko=e=>e.flatMap(({text:t})=>/^\s*\? .*$/.test(t)?t.trimStart().slice(2):[]);function*Yo(e,t,r){let o=t.flatMap(d=>(ie(d)?d:d.text).split(`
));for(let d of Kt(e.lines,o,{userId:r}))yield d;let[n,s,i,a,p,u,c,l,R,M,F]=Wo(o.join(
));(e.title!==n||!e.persistent)&&(yield{title:n}),ce(e.links,s)||(yield{links:s}),ce(e.projectLinks,i)||(yield{projectLinks:i}),ce(e.icons,a)||(yield{icons:a}),e.image!==p&&(yield{image:p}),ce(e.descriptions,u)||(yield{descriptions:u}),ce(e.files,c)||(yield{files:c}),ce(Ko(e.lines),l)||(yield{helpfeels:l}),ce(e.infoboxDefinition,R)||(yield{infoboxDefinition:R}),yield{linesCount:M},yield{charsCount:F}}var zo=e=>{let t=e.match(/(.+?)(?:_(\d+))?$/),r=t?.[1]??e,o=t?.[2]?parseInt(t[2])+1:2;return${r}_${o}};var Qo=()=>Number.MAX_SAFE_INTEGER-Math.floor(Date.now()/1e3);var ct=(e,t,r,o)=>Te(e,t,async(n,s,i,a)=>{if(a==="DuplicateTitleError"){let M=zo(t);return i.map(F=>("title"in F&&(F.title=M),F))}let p=r(n.lines,{...n,attempts:s}),u=p instanceof Promise?await p:p;if(u===void 0)return[];let[c,l]=Array.isArray(u)?[u,void 0]:[u.lines,u.pin];if(c.length===0)return[{deleted:!0}];let R=n.lines===c?[]:[...Yo(n,c,n.userId)];return l!==void 0&&(l&&n.pin===0||!l&&n.pin>0)&&R.push({pin:l?Qo():0}),R},o);var Jo=" must not return ",Kp="transformer",Yp="recoverer",zp="defaultValue",Oe=Kp+Jo,ae="called with ",we=zp+" must not be ",ke=Yp+Jo;var ut="null or undefined",X=Oe+ut,Qp=ae+ut,Le=we+ut,ue=ke+ut;function C(e){return e!=null}function I(e){return e==null}function B(e,t){if(C(e))return e;throw new TypeError(t)}function Xo(e,t){return I(e)?e:t(e)}async function Zo(e,t){return I(e)?e:await t(e)}function en(e,t){return C(e)&&t(e),e}function tn(e,t){if(I(e))return e;let r=t(e);return B(r,X)}async function rn(e,t){if(I(e))return e;let r=await t(e);return B(r,X)}function on(e,t,r){let o,n="";return e!=null?(o=r(e),n=X):(o=t,n=Le),B(o,n)}async function nn(e,t,r){if(I(e))return B(t,Le);let o=await r(e);return B(o,X)}function sn(e,t,r){let o,n="";return e!=null?(o=r(e),n=X):(o=t(),n=ue),B(o,n)}async function an(e,t,r){let o,n="";return C(e)?(o=await r(e),n=X):(o=await t(),n=ue),B(o,n)}var Jp="Ok",pn="Err",cn=ae+pn,un=ae+Jp,ln="Carrying E in "+pn+" instead of throwing it directly. See .cause",Qt="an instance of Error of the current realm.",rO="The thrown value is not "+Qt,oO="The contained E should be "+Qt,mn="This .cause is not "+Qt;function E(e){return e.ok}function m(e){return{ok:!0,val:e,err:null}}function A(e){return!e.ok}function y(e){return{ok:!1,val:null,err:e}}function fe(e){return fn(e,cn)}function de(e){return dn(e,un)}function fn(e,t){if(A(e))throw new TypeError(t);return e.val}function dn(e,t){if(E(e))throw new TypeError(t);return e.err}function hn(e,t){return C(e)?m(e):y(t)}function En(e,t){if(C(e))return m(e);let r=t();return y(r)}async function yn(e,t){if(C(e))return m(e);let r=await t();return y(r)}function gn(e,t){return e??t()}async function Rn(e,t){return C(e)?e:await t()}function Nn(e){return I(e)?null:e}function xn(e){return I(e)?y(void 0):m(e)}function _n(e){return I(e)?m(void 0):y(e)}function bn(e){if(!I(e))return e}function Tn(e){return I(e)?m(e):(E(e),e)}function On(e,t){return C(e)?e:B(t,Le)}function wn(e,t){if(C(e))return e;let r=t();return B(r,ue)}async function kn(e,t){if(C(e))return e;let r=await t();return B(r,ue)}var Xp=Object.defineProperty,Zp=(e,t)=>{for(var r in t)Xp(e,r,{get:t[r],enumerable:!0})},ec={};Zp(ec,{andThen:()=>Xo,andThenAsync:()=>Zo,inspect:()=>en,map:()=>tn,mapAsync:()=>rn,mapOr:()=>on,mapOrAsync:()=>nn,mapOrElse:()=>sn,mapOrElseAsync:()=>an,okOr:()=>hn,okOrElse:()=>En,okOrElseAsync:()=>yn,orElse:()=>gn,orElseAsync:()=>Rn,toNullable:()=>Nn,toResultErr:()=>_n,toResultOk:()=>xn,toUndefinable:()=>bn,transposeToResult:()=>Tn,unwrapOr:()=>On,unwrapOrElse:()=>wn,unwrapOrElseAsync:()=>kn});var lt="null",Z=Oe+lt,tc=ae+lt,Fe=we+lt,le=ke+lt;function v(e){return e!==null}function D(e){return e===null}function j(e,t){if(v(e))return e;throw new TypeError(t)}function Ln(e,t){return D(e)?e:t(e)}async function Fn(e,t){return D(e)?null:await t(e)}function An(e,t){return v(e)&&t(e),e}function Pn(e,t){if(D(e))return e;let r=t(e);return j(r,Z)}async function vn(e,t){if(D(e))return null;let r=await t(e);return j(r,Z)}function Mn(e,t,r){let o,n="";return e!==null?(o=r(e),n=Z):(o=t,n=Fe),j(o,n)}async function Sn(e,t,r){if(D(e))return j(t,Fe);let o=await r(e);return j(o,Z)}function Un(e,t,r){let o,n="";return v(e)?(o=r(e),n=Z):(o=t(),n=le),j(o,n)}async function Cn(e,t,r){let o,n="";return v(e)?(o=await r(e),n=Z):(o=await t(),n=le),j(o,n)}function In(e,t){return v(e)?m(e):y(t)}function Bn(e,t){if(v(e))return m(e);let r=t();return y(r)}async function Dn(e,t){if(v(e))return m(e);let r=await t();return y(r)}function jn(e,t){return e!==null?e:t()}async function Hn(e,t){return v(e)?e:await t()}function qn(e){return D(e)?y(void 0):m(e)}function Vn(e){return D(e)?m(void 0):y(e)}function Gn(e){if(!D(e))return e}function $n(e){return D(e)?m(null):(E(e),e)}function Wn(e,t){return v(e)?e:j(t,Fe)}function Kn(e,t){if(v(e))return e;let r=t();return j(r,le)}async function Yn(e,t){if(v(e))return e;let r=await t();return j(r,le)}var rc=Object.defineProperty,oc=(e,t)=>{for(var r in t)rc(e,r,{get:t[r],enumerable:!0})},nc={};oc(nc,{andThen:()=>Ln,andThenAsync:()=>Fn,inspect:()=>An,map:()=>Pn,mapAsync:()=>vn,mapOr:()=>Mn,mapOrAsync:()=>Sn,mapOrElse:()=>Un,mapOrElseAsync:()=>Cn,okOr:()=>In,okOrElse:()=>Bn,okOrElseAsync:()=>Dn,orElse:()=>jn,orElseAsync:()=>Hn,toResultErr:()=>Vn,toResultOk:()=>qn,toUndefinable:()=>Gn,transposeToResult:()=>$n,unwrapOr:()=>Wn,unwrapOrElse:()=>Kn,unwrapOrElseAsync:()=>Yn});var mt="undefined",ee=Oe+mt,sc=ae+mt,Ae=we+mt,me=ke+mt;function H(e){return e!==void 0}function q(e){return e===void 0}function V(e,t){if(H(e))return e;throw new TypeError(t)}function zn(e,t){return q(e)?e:t(e)}async function Qn(e,t){return q(e)?void 0:await t(e)}function Jn(e,t){return H(e)&&t(e),e}function Xn(e,t){if(q(e))return e;let r=t(e);return V(r,ee)}async function Zn(e,t){if(q(e))return;let r=await t(e);return V(r,ee)}function es(e,t,r){let o,n="";return e!==void 0?(o=r(e),n=ee):(o=t,n=Ae),V(o,n)}async function ts(e,t,r){if(q(e))return V(t,Ae);let o=await r(e);return V(o,ee)}function rs(e,t,r){let o,n="";return e!==void 0?(o=r(e),n=ee):(o=t(),n=me),V(o,n)}async function os(e,t,r){let o,n="";return H(e)?(o=await r(e),n=ee):(o=await t(),n=me),V(o,n)}function ns(e,t){return H(e)?m(e):y(t)}function ss(e,t){if(H(e))return m(e);let r=t();return y(r)}async function is(e,t){if(H(e))return m(e);let r=await t();return y(r)}function as(e,t){return e!==void 0?e:t()}async function ps(e,t){return H(e)?e:await t()}function cs(e){return q(e)?null:e}function us(e){return q(e)?y(void 0):m(e)}function ls(e){return q(e)?m(void 0):y(e)}function ms(e){return q(e)?m(void 0):(E(e),e)}function fs(e,t){return H(e)?e:V(t,Ae)}function ds(e,t){if(H(e))return e;let r=t();return V(r,me)}async function hs(e,t){if(H(e))return e;let r=await t();return V(r,me)}var ic=Object.defineProperty,ac=(e,t)=>{for(var r in t)ic(e,r,{get:t[r],enumerable:!0})},pc={};ac(pc,{andThen:()=>zn,andThenAsync:()=>Qn,inspect:()=>Jn,map:()=>Xn,mapAsync:()=>Zn,mapOr:()=>es,mapOrAsync:()=>ts,mapOrElse:()=>rs,mapOrElseAsync:()=>os,okOr:()=>ns,okOrElse:()=>ss,okOrElseAsync:()=>is,orElse:()=>as,orElseAsync:()=>ps,toNullable:()=>cs,toResultErr:()=>ls,toResultOk:()=>us,transposeToResult:()=>ms,unwrapOr:()=>fs,unwrapOrElse:()=>ds,unwrapOrElseAsync:()=>hs});function T(e){return e.val}function w(e){return e.err}function ft(e,t){if(A(e))return e;let r=T(e);return t(r)}async function Es(e,t){if(A(e))return e;let r=T(e);return await t(r)}function cc(e){return e}function ys(e){return ft(e,cc)}function gs(e){let t=e.status;switch(t){case"fulfilled":{let r=e.value;return m(r)}case"rejected":{let r=e.reason;return y(r)}default:{let r=\PromiseSettledResult.status=${String(t)}\` is not supported;throw new TypeError(r)}}}function Rs(e,t){if(E(e)){let r=T(e);t(r)}return e}function Ns(e,t){if(A(e)){let r=w(e);t(r)}return e}function xs(e,t,r){if(E(e)){let o=T(e);t(o)}else{let o=w(e);r(o)}return e}function Jt(e,t){if(E(e))return!1;let r=w(e);return t(r)}function _s(e,t){return Jt(e,t)}function Xt(e,t){if(A(e))return!1;let r=T(e);return t(r)}function bs(e,t){return Xt(e,t)}function Ts(e,t){if(A(e))return e;let r=T(e),o=t(r);return m(o)}async function Os(e,t){if(A(e))return e;let r=T(e),o=await t(r);return m(o)}function ws(e,t){if(E(e))return e;let r=w(e),o=t(r);return y(o)}async function ks(e,t){if(E(e))return e;let r=w(e),o=await t(r);return y(o)}function Ls(e,t,r){if(E(e)){let o=T(e);return r(o)}return t}async function Fs(e,t,r){if(A(e))return t;let o=T(e);return await r(o)}function As(e,t,r){if(E(e)){let n=T(e);return r(n)}let o=w(e);return t(o)}async function Ps(e,t,r){if(E(e)){let n=T(e);return await r(n)}let o=w(e);return await t(o)}function vs(e,t){if(E(e))return e;let r=w(e);return t(r)}async function Ms(e,t){if(E(e))return e;let r=w(e);return await t(r)}function dt(e,t){return E(e)?t:w(e)}function Pe(e,t){return E(e)?T(e):t}function Ss(e){return Pe(e,null)}function Us(e){return dt(e,null)}function Cs(e){return Pe(e,void 0)}function Is(e){return dt(e,void 0)}function Bs(e){if(A(e))return e;let t=T(e);return D(t)?null:m(t)}function Ds(e){if(A(e))return e;let t=T(e);if(!q(t))return m(t)}function js(e){return e instanceof Error}var uc="UnknownCausalError",lc=class extends Error{constructor(e){super(mn,{cause:e}),this.name=uc}};function ht(e){return js(e)?e:new lc(e)}function Zt(e){try{let t=e();return m(t)}catch(t){return y(t)}}function Hs(e){let t=Zt(e);if(E(t))return t;let r=w(t),o=ht(r);return y(o)}async function er(e){let t;try{t=await e()}catch(r){return y(r)}return m(t)}async function qs(e){let t=await er(e);if(E(t))return t;let r=w(t),o=ht(r);return y(o)}function Vs(e,t){if(E(e))return T(e);let r=w(e);return t(r)}async function Gs(e,t){if(E(e))return T(e);let r=w(e);return await t(r)}var mc="CausalCarrierError",fc=class extends Error{constructor(e){super(ln,{cause:e}),this.name=mc}};function $s(e){if(E(e))return T(e);let t=w(e);throw new fc(t)}var dc=Object.defineProperty,hc=(e,t)=>{for(var r in t)dc(e,r,{get:tr,enumerable:!0})},Ec={};hc(Ec,{andThen:()=>ft,andThenAsync:()=>Es,flatten:()=>ys,fromPromiseSettledResult:()=>gs,inspectBoth:()=>xs,inspectErr:()=>Ns,inspectOk:()=>Rs,isErrAnd:()=>Jt,isErrAndWithEnsureType:()=>_s,isOkAnd:()=>Xt,isOkAndWithEnsureType:()=>bs,map:()=>Ts,mapAsync:()=>Os,mapErr:()=>ws,mapErrAsync:()=>ks,mapOr:()=>Ls,mapOrAsync:()=>Fs,mapOrElse:()=>As,mapOrElseAsync:()=>Ps,orElse:()=>vs,orElseAsync:()=>Ms,toNullableFromErr:()=>Us,toNullableFromOk:()=>Ss,toUndefinableFromErr:()=>Is,toUndefinableFromOk:()=>Cs,transposeToNullable:()=>Bs,transposeToUndefinable:()=>Ds,tryCatchInto:()=>Zt,tryCatchIntoAsync:()=>er,tryCatchIntoWithEnsureError:()=>Hs,tryCatchIntoWithEnsureErrorAsync:()=>qs,unwrapOr:()=>Pe,unwrapOrElse:()=>Vs,unwrapOrElseAsync:()=>Gs,unwrapOrThrow:()=>$s});var Et=class{#e=[];#t;#r;constructor(t){if(t<=0||!Number.isSafeInteger(t))throw new RangeError(size must be a positive safe integer, got ${t});this.#t=t,this.#r=t}get locked(){return this.#t===0}get waiterCount(){return this.#e.length}acquire(){if(this.#t>0)return this.#t-=1,Promise.resolve();{let{promise:t,resolve:r}=Promise.withResolvers();return this.#e.push(r),t}}release(){let t=this.#e.shift();t?t():this.#t<this.#r&&(this.#t+=1)}};var yt=class{#e;constructor(t){this.#e=new Et(t)}get locked(){return this.#e.locked}get waiterCount(){return this.#e.waiterCount}async lock(t){await this.#e.acquire();try{return await t()}finally{this.#e.release()}}};async function*Ws(e,t){if(e.length===0||e.every(({before:n,after:s})=>n===s))return;let r=fe(await _e()),o=new yt(5);try{yield*new ReadableStream({async start(n){let s=[];for(let i of e){if(i.before===i.after){n.enqueue({link:i,projectCount:0,replaced:0,done:!0});continue}let a=0,p=0,u=[];for(let c of new Set(t))u.push(o.lock(async()=>{let l=await yc(i,c,r);if(A(l)){n.error(gc(de(l)));return}a++,p+=fe(l),n.enqueue({link:i,projectCount:a,replaced:p,done:!1})}));s.push(Promise.all(u).then(()=>n.enqueue({link:i,projectCount:a,replaced:p,done:!0})))}await Promise.all(s),n.close()}})}finally{await be(r)}}var yc=async(e,t,r)=>{leto=await Promise.all([Ke(t,e.before,e.after),ct(t,e.before,(n,{persistent:s})=>{if(s)returne.after,...n.map(i=>i.text).slice(1)},{socket:r})]);return o},he=e=>e.split(`
).flatMap(t=>[...t.matchAll(/\[((?:[^\[!"#%&'()\*\+,\-\.\/\{\|\}<>_~] |.[^ ]*)[^\[\]]*)\]/g)]).map(([,t])=>t),gc=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var Ks=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(c=>[...c].length))+6}em};i(),s.addEventListener("input",i);let a=n.querySelector(".cancel"),p=n.querySelector(".replace"),u=new Promise(c=>{let l=()=>{c({convert:!1}),t.remove()};n.addEventListener("close",l),n.addEventListener("click",l),a.addEventListener("click",l),p.addEventListener("click",()=>{let R=s.value.split(`
);c({convert:!0,links:e.flatMap((M,F)=>M===R[F]||M===""||!R[F]?[]:[{before:M,after:R[F]??M}])}),t.remove()}),n.querySelector(".container").addEventListener("click",R=>{R.stopPropagation()})});return document.body.append(t),n.showModal(),u};var Ys=async(e,t)=>{let r=he(e),o=await Ks([...new Set(r)]);if(!o.convert||o.links.length===0)return;let n=new Map(o.links.map(s=>[s.before,Qe()]));for await(let{link:s,projectCount:i,replaced:a,done:p}of Ws(o.links,t)){let u=n.get(s.before);if(u){if(p){u.render({type:"check-circle"},{type:"text",text:"${s.after}", ${a}l. ${i}p.}),setTimeout(()=>u.dispose(),1e3);continue}u.render({type:"spinner"},{type:"text",text:"${s.after}", ${a}l. ${i}p.})}}};var zs=async(e,t)=>{let r=he(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}=Qe(),i=fe(await _e());try{n({type:"spinner"},{type:"text",text:Replacing links in ${t.length} projects...});let a=0,u=(await Promise.all(t.map(async c=>{let[l]=await Promise.all([Ke(c,r,o),ct(c,r,(R,{persistent:M})=>{if(M)return[o,...R.map(F=>F.text).slice(1)]},{socket:i})]);if(A(l))throw n({type:"exclamation-triangle"},{type:"text",text:${de(l).name} ${de(l).message}}),Rc(de(l));return a++,n({type:"spinner"},{type:"text",text:Replacing links in ${t.length-a} projects...}),fe(l)}))).reduce((c,l)=>c+l,0);n({type:"check-circle"},{type:"text",text:Successfully replaced ${u} links.`})}finally{await be(i),setTimeout(s,1e3)}},Rc=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var MM=e=>{let t=scrapbox.Project.name,...e;scrapbox.PopupMenu.addButton({title:r=>{let o=he(r).length;return o>1?"update links":o===1?"update a link":""},onClick:r=>{let o=he(r).length;o>1?Ys(r,t):o===1&&zs(r,t)}})};export{MM as setup};