script.jsconst setDefaults=e=>{const{fetch:t=globalThis.fetch,hostName:n="scrapbox.io",...r}=e;return{fetch:t,hostName:n,...r}},isNone=e=>e==null,isString=e=>typeof e=="string",isNumber=e=>typeof e=="number",isObject=e=>typeof e=="object"&&e!==null,isErrorLike=e=>isObject(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,tryToErrorLike=e=>{try{const t=typeof e=="string"?JSON.parse(e):e;return isErrorLike(t)?t:!1}catch(t){if(t instanceof SyntaxError)return!1;throw t}};class UnexpectedResponseError extends Error{name;constructor(t){super(`${t.status} ${t.statusText} when fetching ${t.url}`),this.response=t,this.name="UnexpectedResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,UnexpectedResponseError)}response}const makeError=async e=>{const t=e.clone(),n=await t.text(),r=tryToErrorLike(n);if(!r)throw new UnexpectedResponseError(t);return{ok:!1,value:r}},cookie=e=>`connect.sid=${e}`,getProfile=async e=>{const{sid:t,hostName:n,fetch:r}=setDefaults(e??{}),o=new Request(`https://${n}/api/users/me`,t?{headers:{Cookie:cookie(t)}}:void 0),i=await r(o);if(!i.ok)throw new UnexpectedResponseError(i);return await i.json()},toTitleLc=e=>e.replaceAll(" ","_").toLowerCase(),encodeTitleURI=e=>[...e].map((t,n)=>t===" "?"_":!noEncodeChars.includes(t)||n===e.length-1&&noTailChars.includes(t)?encodeURIComponent(t):t).join(""),noEncodeChars='@$&+=:;",',noTailChars=':;",',getPage_toRequest=(e,t,n)=>{const{sid:r,hostName:o,followRename:i,projects:l}=setDefaults(n??{}),c=new URLSearchParams;c.append("followRename",`${i??!0}`);for(const p of l??[])c.append("projects",p);const u=`https://${o}/api/pages/${e}/${encodeTitleURI(t)}?${c.toString()}`;return new Request(u,r?{headers:{Cookie:cookie(r)}}:void 0)},getPage_fromResponse=async e=>{if(!e.ok)return e.status===414?{ok:!1,value:{name:"TooLongURIError",message:"project ids may be too much."}}:makeError(e);const t=await e.json();return{ok:!0,value:t}},getPage=async(e,t,n)=>{const{fetch:r}=setDefaults(n??{}),o=getPage_toRequest(e,t,n),i=await r(o);return await getPage_fromResponse(i)};getPage.toRequest=getPage_toRequest,getPage.fromResponse=getPage_fromResponse;const listPages_toRequest=(e,t)=>{const{sid:n,hostName:r,sort:o,limit:i,skip:l}=setDefaults(t??{}),c=new URLSearchParams;o!==void 0&&c.append("sort",o),i!==void 0&&c.append("limit",`${i}`),l!==void 0&&c.append("skip",`${l}`);const u=`https://${r}/api/pages/${e}?${c.toString()}`;return new Request(u,n?{headers:{Cookie:cookie(n)}}:void 0)},listPages_fromResponse=async e=>{if(!e.ok)return makeError(e);const t=await e.json();return{ok:!0,value:t}},listPages=async(e,t)=>{const{fetch:n}=setDefaults(t??{}),r=await n(listPages_toRequest(e,t));return await listPages_fromResponse(r)};listPages.toRequest=listPages_toRequest,listPages.fromResponse=listPages_fromResponse;const getProject_toRequest=(e,t)=>{const{sid:n,hostName:r}=setDefaults(t??{});return new Request(`https://${r}/api/projects/${e}`,n?{headers:{Cookie:cookie(n)}}:void 0)},getProject_fromResponse=async e=>{if(!e.ok)return makeError(e);const t=await e.json();return{ok:!0,value:t}},getProject=async(e,t)=>{const{fetch:n}=setDefaults(t??{}),r=getProject_toRequest(e,t),o=await n(r);return getProject_fromResponse(o)};getProject.toRequest=getProject_toRequest,getProject.fromResponse=getProject_fromResponse;const ListProject_toRequest=(e,t)=>{const{sid:n,hostName:r}=setDefaults(t??{}),o=new URLSearchParams;for(const i of e)o.append("ids",i);return new Request(`https://${r}/api/projects?${o.toString()}`,n?{headers:{Cookie:cookie(n)}}:void 0)},ListProject_fromResponse=async e=>{if(!e.ok)return makeError(e);const t=await e.json();return{ok:!0,value:t}},listProjects=async(e,t)=>{const{fetch:n}=setDefaults(t??{}),r=await n(ListProject_toRequest(e,t));return ListProject_fromResponse(r)};listProjects.toRequest=ListProject_toRequest,listProjects.fromResponse=ListProject_fromResponse;const ensureArray=(e,t)=>{if(!Array.isArray(e))throw new TypeError(`"${t}" must be an array but actual is "${e}"`)},ensureHTMLDivElement=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError(`"${t}" must be HTMLDivElememt but actual is "${e}"`)},statusBar=()=>checkDiv(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),checkDiv=(e,t)=>{if(!!e)return ensureHTMLDivElement(e,t),e},getLineId=e=>{if(isNone(e))return;if(isNumber(e))return getLine(e)?.id;if(isString(e))return e.startsWith("L")?e.slice(1):e;if(e.classList.contains("line"))return e.id.slice(1);const t=e.closest(".line");if(t)return t.id.slice(1)},getLine=e=>{if(isNone(e))return;if(isNumber(e))return getLines()[e];const t=getLineId(e);return t?getLines().find(n=>n.id===t):void 0},getLines=()=>(ensureArray(scrapbox.Page.lines,"scrapbox.Page.lines"),scrapbox.Page.lines),useStatusBar=()=>{const e=statusBar();if(!e)throw new Error("div.status-bar can't be found");const t=document.createElement("div");return e.append(t),{render:(...n)=>{t.textContent="";const r=makeGroup(...n);r&&t.append(r)},dispose:()=>t.remove()}},makeGroup=(...e)=>{const t=e.flatMap(r=>{switch(r.type){case"spinner":return[makeSpinner()];case"check-circle":return[makeCheckCircle()];case"exclamation-triangle":return[makeExclamationTriangle()];case"text":return[makeItem(r.text)];case"group":{const o=makeGroup(...r.items);return o?[o]:[]}}});if(t.length===0)return;if(t.length===1)return t[0];const n=document.createElement("span");return n.classList.add("item-group"),n.append(...t),n},makeItem=e=>{const t=document.createElement("span");return t.classList.add("item"),t.append(e),t},makeSpinner=()=>{const e=document.createElement("i");return e.classList.add("fa","fa-spinner"),makeItem(e)},makeCheckCircle=()=>{const e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),makeItem(e)},makeExclamationTriangle=()=>{const e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),makeItem(e)},version="4.2.0";async function socketIO(){const t=(await importSocketIO())("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"]});return await new Promise((n,r)=>{const o=i=>r(i);t.once("connect",()=>{t.off("disconnect",o),n()}),t.once("disconnect",o)}),t}function importSocketIO(){const e=`https://cdnjs.cloudflare.com/ajax/libs/socket.io/${version}/socket.io.min.js`;if(document.querySelector(`script[src="${e}"]`))return Promise.resolve(window.io);const t=document.createElement("script");return t.src=e,new Promise((n,r)=>{t.onload=()=>n(window.io),t.onerror=o=>r(o),document.head.append(t)})}function wrap(e,t=9e4){function n(o,i){let l;return new Promise((c,u)=>{const p=f=>{clearTimeout(l),u(new Error(f))};e.emit(o,i,f=>{clearTimeout(l),e.off("disconnect",p),f.error&&u(new Error(JSON.stringify(f.error))),"data"in f?c(f?.data):c(void 0)}),l=setTimeout(()=>{e.off("disconnect",p),u(new Error(`Timeout: exceeded ${t}ms`))},t),e.once("disconnect",p)})}async function*r(...o){let i;const l=()=>new Promise(u=>i=u),c=u=>{i?.(u)};for(const u of o)e.on(u,c);try{for(;;)yield await l()}finally{for(const u of o)e.off(u,c)}}return{request:n,response:r}}const connect=async e=>{if(e.connected)return;const t=new Promise(n=>e.once("connect",()=>n()));e.connect(),await t},disconnect=async e=>{if(e.disconnected)return;const t=new Promise(n=>{const r=o=>{o==="io client disconnect"&&(n(),e.off("disconnect",r))};e.on("disconnect",r)});e.disconnect(),await t};let userId;const getUserId=async()=>{if(userId!==void 0)return userId;const e=await getProfile();if(e.isGuest)throw new Error("this script can only be executed by Logged in users");return userId=e.id,userId},projectMap=new Map,getProjectId=async e=>{const t=projectMap.get(e);if(t!==void 0)return t;const n=await getProject(e);if(!n.ok){const{name:o,message:i}=n.value;throw new Error(`${o} ${i}`)}const{id:r}=n.value;return projectMap.set(e,r),r},zero=e=>e.padStart(8,"0"),createNewLineId=e=>{const t=Math.floor(new Date().getTime()/1e3).toString(16),n=Math.floor(16777214*Math.random()).toString(16);return`${zero(t).slice(-8)}${e.slice(-6)}0000${zero(n)}`},diff=(e,t)=>{const n=e.length>t.length,r=n?t:e,o=n?e:t,i=r.length+1,l=r.length+o.length+3,c=new Array(l);c.fill(-1);const u=[];function p(g,Z,we){let J=Math.max(Z,we),je=J-g;for(;je<r.length&&J<o.length&&r[je]===o[J];)++je,++J;return c[g+i]=u.length,u.push([{x:je,y:J},c[g+(Z>we?-1:1)+i]]),J}const f=new Array(l);f.fill(-1);let A=-1;const m=o.length-r.length;do{++A;for(let g=-A;g<=m-1;++g)f[g+i]=p(g,f[g-1+i]+1,f[g+1+i]);for(let g=m+A;g>=m+1;--g)f[g+i]=p(g,f[g-1+i]+1,f[g+1+i]);f[m+i]=p(m,f[m-1+i]+1,f[m+1+i])}while(f[m+i]!==o.length);const N=[];let K=c[m+i];for(;K!==-1;)N.push(u[K][0]),K=u[K][1];return{from:e,to:t,editDistance:m+A*2,buildSES:function*(){let g=0,Z=0;for(const{x:we,y:J}of reverse(N))for(;g<we||Z<J;)J-we>Z-g?(yield{value:o[Z],type:n?"deleted":"added"},++Z):J-we<Z-g?(yield{value:r[g],type:n?"added":"deleted"},++g):(yield{value:r[g],type:"common"},++g,++Z)}}};function*toExtendedChanges(e){let t=[],n=[];function*r(){if(t.length>n.length){for(let o=0;o<n.length;o++)yield makeReplaced(t[o],n[o]);for(let o=n.length;o<t.length;o++)yield t[o]}else{for(let o=0;o<t.length;o++)yield makeReplaced(t[o],n[o]);for(let o=t.length;o<n.length;o++)yield n[o]}t=[],n=[]}for(const o of e)switch(o.type){case"added":t.push(o);break;case"deleted":n.push(o);break;case"common":yield*r(),yield o;break}yield*r()}const makeReplaced=(e,t)=>({value:e.value,oldValue:t.value,type:"replaced"});function*reverse(e){for(let t=e.length-1;t>=0;t--)yield e[t]}function*diffToChanges(e,t,{userId:n}){const{buildSES:r}=diff(e.map(({text:l})=>l),t);let o=0,i=e[0].id;for(const l of toExtendedChanges(r())){switch(l.type){case"added":yield{_insert:i,lines:{id:createNewLineId(n),text:l.value}};continue;case"deleted":yield{_delete:i,lines:-1};break;case"replaced":yield{_update:i,lines:{text:l.value}};break}o++,i=e[o]?.id??"_end"}}var v=e=>({type:"title",text:e.rows[0].text}),y=e=>{let{rows:[t,...n]}=e,{indent:r=0,text:o=""}=t??{},i=o.replace(/^\s*code:/,"");return{indent:r,type:"codeBlock",fileName:i,content:n.map(l=>l.text.substring(r+1)).join(`
`)}},s=(e,{parseOnNested:t,parseOnQuoted:n,patterns:r})=>(o,i,l)=>{var c,u,p,f,A,m;if(!t&&i.nested)return(c=l?.())!==null&&c!==void 0?c:[];if(!n&&i.quoted)return(u=l?.())!==null&&u!==void 0?u:[];for(let N of r){let K=N.exec(o);if(K===null)continue;let g=o.substring(0,K.index),Z=o.substring(K.index+((f=(p=K[0])===null||p===void 0?void 0:p.length)!==null&&f!==void 0?f:0)),we=e((A=K[0])!==null&&A!==void 0?A:"",i);return[...d(g,i),...we,...d(Z,i)]}return(m=l?.())!==null&&m!==void 0?m:[]},a=e=>[{type:"plain",raw:e,text:e}],T=s(a,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]}),V=/^>.*$/,X=(e,t)=>t.context==="table"?a(e,t):[{type:"quote",raw:e,nodes:d(e.substring(1),{...t,quoted:!0})}],O=s(X,{parseOnNested:!1,parseOnQuoted:!1,patterns:[V]}),Y=/^\? .+$/,w=(e,t)=>t.context==="table"?a(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],I=s(w,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Y]}),ee=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)\]\]/i,te=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,oe=(e,t)=>{if(t.context==="table")return a(e,t);let n=e.substring(2,e.length-2),r=/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(n);return[{type:"strongImage",raw:e,src:r?`${n}/thumb/1000`:n}]},R=s(oe,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ee,te]}),re=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/;function x(e){return(t,n)=>{if(e==="strongIcon"&&n.context==="table")return a(t,n);let r=e==="icon"?t.substring(1,t.length-1):t.substring(2,t.length-2),o=r.lastIndexOf(".icon"),i=r.substring(0,o),l=i.startsWith("/")?"root":"relative",c=r.substring(o+5,r.length),u=c.startsWith("*")?parseInt(c.substring(1),10):1;return new Array(u).fill({}).map(()=>({path:i,pathType:l,type:e,raw:t}))}}var ne=x("icon"),E=s(ne,{parseOnNested:!0,parseOnQuoted:!0,patterns:[re]}),se=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,ae=x("strongIcon"),k=s(ae,{parseOnNested:!1,parseOnQuoted:!0,patterns:[se]}),ce=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,ie=(e,t)=>t.context==="table"?a(e,t):[{type:"strong",raw:e,nodes:d(e.substring(2,e.length-2),{...t,nested:!0})}],$=s(ie,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ce]}),de=/\[\$ .+? \]/,pe=/\[\$ [^\]]+\]/,le=(e,t)=>t.context==="table"?a(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],S=s(le,{parseOnNested:!1,parseOnQuoted:!0,patterns:[de,pe]}),me=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,ue=(e,t)=>{if(t.context==="table")return a(e,t);let n=e.indexOf(" "),r=e.substring(1,n),o=e.substring(n+1,e.length-1),i=new Set(r);if(i.has("*")){let l=r.split("*").length-1;i.delete("*"),i.add(`*-${Math.min(l,10)}`)}return[{type:"decoration",raw:e,rawDecos:r,decos:Array.from(i),nodes:d(o,{...t,nested:!0})}]},z=s(ue,{parseOnNested:!1,parseOnQuoted:!0,patterns:[me]}),ge=/`.*?`/,fe=(e,t)=>t.context==="table"?a(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],Q=s(fe,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ge]}),Ne=/^[$%] .+$/,xe=(e,t)=>{var n;if(t.context==="table")return a(e,t);let r=(n=e[0])!==null&&n!==void 0?n:"",o=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:o}]},L=s(xe,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Ne]}),he=/\[\s+\]/,be=(e,t)=>t.context==="table"?a(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],_=s(be,{parseOnNested:!1,parseOnQuoted:!0,patterns:[he]}),Pe=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,ve=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?\]/i,ye=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,Te=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,Oe=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg)(\?[^\]\s]+)?$/i.test(e)||Ie(e),Ie=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),Re=(e,t)=>{if(t.context==="table")return a(e,t);let n=e.search(/\s/),r=n!==-1?e.substring(1,n):e.substring(1,e.length-1),o=n!==-1?e.substring(n,e.length-1).trimLeft():"",[i,l]=Oe(o)?[o,r]:[r,o];return[{type:"image",raw:e,src:/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(i)?`${i}/thumb/1000`:i,link:l}]},F=s(Re,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Pe,ve,ye,Te]}),Ee=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,ke=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,$e=/\[https?:\/\/[^\s\]]+\]/,Se=/https?:\/\/[^\s]+/,ze=(e,t)=>{if(t.context==="table")return a(e,t);let n=e.startsWith("[")&&e.endsWith("]")?e.substring(1,e.length-1):e,r=/^https?:\/\/[^\s\]]/.test(n),o=(r?/^https?:\/\/[^\s\]]+/:/https?:\/\/[^\s\]]+$/).exec(n);if(o?.[0]===void 0)return[];let i=r?n.substring(o[0].length):n.substring(0,o.index-1);return[{type:"link",raw:e,pathType:"absolute",href:o[0],content:i.trim()}]},C=s(ze,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Ee,ke,$e,Se]}),W=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,B=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,Qe=e=>{let[t="",n="",r=""]=e.split(","),o=parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),i=parseFloat(n.replace(/^E/,"").replace(/^W/,"-")),l=/^Z\d+$/.test(r)?parseInt(r.replace(/^Z/,""),10):14;return{latitude:o,longitude:i,zoom:l}},Le=(e,t)=>{var n;if(t.context==="table")return a(e,t);let r=(n=e.match(W))!==null&&n!==void 0?n:e.match(B);if(r===null)return[];let o=e.startsWith("[N")||e.startsWith("[S"),[,i="",l=""]=o?r:[r[0],r[2],r[1]],{latitude:c,longitude:u,zoom:p}=Qe(i),f=l!==""?`https://www.google.com/maps/place/${encodeURIComponent(l)}/@${c},${u},${p}z`:`https://www.google.com/maps/@${c},${u},${p}z`;return[{type:"googleMap",raw:e,latitude:c,longitude:u,zoom:p,place:l,url:f}]},G=s(Le,{parseOnNested:!1,parseOnQuoted:!0,patterns:[W,B]}),_e=/\[\/?[^[\]]+\]/,Fe=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},H=s(Fe,{parseOnNested:!0,parseOnQuoted:!0,patterns:[_e]}),Ce=/(?:^|\s)#\S+/,We=(e,t)=>{if(t.context==="table")return a(e,t);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let n=e.substring(0,1),r=e.substring(1);return[...a(n,t),{type:"hashTag",raw:r,href:r.substring(1)}]},M=s(We,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Ce]}),Be=/^[0-9]+\. .*$/,Ge=(e,t)=>{if(t.context==="table")return a(e,t);let n=e.indexOf(" "),r=e.substring(0,n-1),o=parseInt(r,10),i=e.substring(n+1,e.length);return[{type:"numberList",raw:e,rawNumber:r,number:o,nodes:d(i,{...t,nested:!0})}]},U=s(Ge,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Be]}),He=(e,t,n)=>{var r;return e===""?[]:(r=n?.())!==null&&r!==void 0?r:[]},Me=(...e)=>(t,n)=>e.reduceRight((r,o)=>()=>o(t,n,r),()=>T(t,n))(),d=Me(He,O,I,Q,L,S,_,z,R,k,$,F,C,E,G,H,M,U),q=e=>{let{rows:[t,...n]}=e,{indent:r=0,text:o=""}=t??{},i=o.replace(/^\s*table:/,"");return{indent:r,type:"table",fileName:i,cells:n.map(l=>l.text.substring(r+1)).map(l=>l.split(" ").map(c=>d(c,{nested:!1,quoted:!1,context:"table"})))}},j=e=>{let{indent:t,text:n}=e.rows[0];return{indent:t,type:"line",nodes:d(n.substring(t),{nested:!1,quoted:!1,context:"line"})}},h=e=>{switch(e.type){case"title":return v(e);case"codeBlock":return y(e);case"table":return q(e);case"line":return j(e)}},b=e=>e.split(`
`).map(t=>{var n,r,o;return{indent:(o=(r=(n=/^\s+/.exec(t))===null||n===void 0?void 0:n[0])===null||r===void 0?void 0:r.length)!==null&&o!==void 0?o:0,text:t}}),Ue=(e,t)=>{var n,r;return(e.type==="codeBlock"||e.type==="table")&&t.indent>((r=(n=e.rows[0])===null||n===void 0?void 0:n.indent)!==null&&r!==void 0?r:0)},D=(e,t)=>{let n=e[e.length-1];return n!==void 0&&Ue(n,t)?(n.rows.push(t),e):(e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e)},P=(e,t)=>{var n;if(!((n=t.hasTitle)!==null&&n!==void 0)||n){let[r,...o]=e;return r===void 0?[]:[{type:"title",rows:[r]},...o.reduce(D,[])]}return e.reduce(D,[])};const youtubeRegExp=/https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/,youtubeDotBeRegExp=/https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/,youtubeShortRegExp=/https?:\/\/(?:www\.|)youtube\.com\/shorts\/([a-zA-Z\d_-]+)(?:\?([^\s]+)|)/,youtubeListRegExp=/https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/,parseYoutube=e=>{if(youtubeRegExp.test(e)){const t=new URL(e).searchParams,n=t.get("v");if(n)return{pathType:"com",videoId:n,params:t}}{const t=e.match(youtubeDotBeRegExp);if(t){const[,n,r]=t;return{videoId:n,params:new URLSearchParams(r),pathType:"dotbe"}}}{const t=e.match(youtubeShortRegExp);if(t){const[,n,r]=t;return{videoId:n,params:new URLSearchParams(r),pathType:"short"}}}{const t=e.match(youtubeListRegExp);if(t){const[,n,r]=t;return{listId:r,params:new URLSearchParams(n),pathType:"list"}}}};function*makeChanges(e,t,{userId:n,head:r}){const o=t.flatMap(p=>p.split(`
`));for(const p of diffToChanges(e,o,{userId:n}))yield p;(e[0].text!==o[0]||!r.persistent)&&(yield{title:o[0]});const i=e.slice(1,6).map(p=>p.text),l=o.slice(1,6);i.join("")!==l.join("")&&(yield{descriptions:l});const[c,u]=findLinksAndImage(o.join(`
`));(r.links.length!==c.length||!r.links.every(p=>c.includes(p)))&&(yield{links:c}),r.image!==u&&(yield{image:u})}const findLinksAndImage=e=>{const t=b(e),n=P(t,{hasTitle:!0}).flatMap(c=>{switch(c.type){case"codeBlock":case"title":return[];case"line":case"table":return[h(c)]}}),r=new Map,o=[];let i=null;const l=c=>{switch(c.type){case"hashTag":if(r.has(toTitleLc(c.href)))return;r.set(toTitleLc(c.href),!1),o.push(c.href);return;case"link":switch(c.pathType){case"relative":if(r.get(toTitleLc(c.href)))return;r.set(toTitleLc(c.href),!0),o.push(c.href);return;case"absolute":{const u=parseYoutube(c.href);if(!u||u.pathType==="list")return;i??=`https://i.ytimg.com/vi/${u.videoId}/mqdefault.jpg`;return}default:return}case"image":case"strongImage":{i??=c.src.endsWith("/thumb/1000")?c.src.replace(/\/thumb\/1000$/,"/raw"):c.src;return}case"strong":case"quote":case"decoration":{for(const u of c.nodes)l(u);return}default:return}};for(const c of blocksToNodes(n))l(c);return[o,i]};function*blocksToNodes(e){for(const t of e)switch(t.type){case"codeBlock":case"title":continue;case"line":for(const n of t.nodes)yield n;continue;case"table":{for(const n of t.cells)for(const r of n)for(const o of r)yield o;continue}}}const pull=async(e,t)=>{const n=await getPage(e,t);if(!n.ok)throw new Error(`You have no privilege of editing "/${e}/${t}".`);const{commitId:r,persistent:o,image:i,links:l,lines:c,id:u,pin:p}=n.value;return{commitId:r,pageId:u,persistent:o,image:i,links:l,pin:p,lines:c}},pushCommit=async(e,t,n)=>t.length===0?{commitId:n.parentId}:await e("socket.io-request",{method:"commit",data:{kind:"page",...n,changes:t,cursor:null,freeze:!0}}),pushWithRetry=async(e,t,{project:n,title:r,retry:o=3,parentId:i,...l})=>{try{i=(await pushCommit(e,t,{parentId:i,...l})).commitId}catch{console.log("Faild to push a commit. Retry after pulling new commits");for(let u=0;u<o;u++){const{commitId:p}=await pull(n,r);i=p;try{i=(await pushCommit(e,t,{parentId:i,...l})).commitId,console.log("Success in retrying");break}catch{continue}}throw Error("Faild to retry pushing.")}return i},patch=async(e,t,n,r)=>{const[o,i,l]=await Promise.all([pull(e,t),getProjectId(e),getUserId()]);let c=o;const u=r?.socket,p=u??await socketIO();await connect(p);try{const{request:f}=wrap(p);for(let A=0;A<3;A++)try{const m=n(c.lines,c),N=m instanceof Promise?await m:m;if(!N)return;N.length===0&&await pushWithRetry(f,[{deleted:!0}],{projectId:i,pageId:c.pageId,parentId:c.commitId,userId:l,project:e,title:t});const K=[...makeChanges(c.lines,N,{userId:l,head:c})];await pushCommit(f,K,{parentId:c.commitId,projectId:i,pageId:c.pageId,userId:l});break}catch{if(A===2)throw Error("Faild to retry pushing.");console.log("Faild to push a commit. Retry after pulling new commits");try{c=await pull(e,t)}catch(N){throw N}}}finally{u||await disconnect(p)}};function createNewPromise(){let e,t;return{promise:new Promise((r,o)=>{[e,t]=[r,o]}),resolve:e||(()=>{}),reject:t||(()=>{})}}function toCSSText(e){let t="";for(const[n,r]of Object.entries(e))t+=generateRuleText(r,n);return t}function generateRuleText(e,t){let n="";const r=[],o=[];for(const[i,l]of Object.entries(e))typeof l=="number"||typeof l=="string"?o.push({name:i,value:l}):r.push({name:i,style:l});if(o.length>0){const i=t;let l="";for(const c of o)l+=`${c.name}:${c.value};`;n+=`${i}{${l}}`}if(r.length>0)for(const i of r){const l=makeSelector(i.name,t);n+=generateRuleText(i.style,l)}return n}function makeSelector(e,t){const n=t===void 0?"":t.trim(),r=e.trim();return r.includes("&")?r.replace("&",n):n+" "+r}const alertStyle={"#background":{position:"fixed","z-index":2e3,top:"40px",width:"100%",height:"100%","background-color":"hsl(0deg 0% 0% / 50%)"},".alert-bg":{position:"absolute",display:"block",width:"100%",height:"100%","background-color":"transparent"},".container":{position:"absolute",display:"flex","max-width":"50em",top:"60px",left:"1em",right:"1em",margin:"auto",padding:"1em 1.2em 1.2em","font-size":"15px",border:"1px solid black","border-radius":"10px","flex-direction":"column","background-color":"hsl(0deg 0% 100% / 85%)",".title":{margin:"0 0 5px","font-size":"1.2em","font-weight":900},".description":{margin:"0 0 5px"},".input-area":{textarea:{width:"100%",height:"5em"}},".button-area":{display:"flex","flex-direction":"row","justify-content":"space-evenly",button:{padding:"5px","min-width":"5em",border:"solid 2px hsl(0deg 0% 42%)","border-radius":"10px"}}}},buildInButtons={OK:{label:"OK",useInputForm:!1,onClick:()=>({button:"OK"}),className:"button-OK"},CANCEL:{label:"\u30AD\u30E3\u30F3\u30BB\u30EB",useInputForm:!1,onClick:()=>({button:"CANCEL"}),className:"button-CANCEL"},YES:{label:"\u306F\u3044",useInputForm:!1,onClick:()=>({button:"YES"}),className:"button-YES"},NO:{label:"\u3044\u3044\u3048",useInputForm:!1,onClick:()=>({button:"NO"}),className:"button-NO"},ENTER:{label:"\u6C7A\u5B9A",useInputForm:!0,onClick:e=>({button:"ENTER",inputValue:e.InputValue}),className:"button-ENTER"}},eventLisnersInDocument=[];function addEventListenerToDocument(e){const{type:t,listener:n}=e;document.addEventListener(t,n),eventLisnersInDocument.push({type:t,listener:n})}function removeAllEventListenerFromDocument(){for(const e of eventLisnersInDocument)document.removeEventListener(e.type,e.listener)}const shadowDomId="scrapbox-alert",buildInAlertModes={OK:{buttons:[buildInButtons.OK],priorityCancelButtonIndex:0},OK_CANCEL:{buttons:[buildInButtons.OK,buildInButtons.CANCEL],priorityCancelButtonIndex:1},YES_NO:{buttons:[buildInButtons.YES,buildInButtons.NO]},YES_NO_CANCEL:{buttons:[buildInButtons.YES,buildInButtons.NO,buildInButtons.CANCEL],priorityCancelButtonIndex:2},ENTER:{buttons:[buildInButtons.ENTER],priorityEnterButtonIndex:0}};async function scrapboxAlert(e=buildInAlertModes.OK,t,n,r){const{background:o,inputArea:i,buttonArea:l}=renderAlertBase(t,n),c=document.createElement("textarea"),u=createNewPromise();isNeedInputForm(e.buttons)&&(r&&(c.textContent=r),i.append(c));const p=createButtonElements(e.buttons,u,c);l.append(...p);const f=e.priorityEnterButtonIndex?e.priorityEnterButtonIndex:0,A=p[f],m=e.priorityCancelButtonIndex?p[e.priorityCancelButtonIndex]:void 0;return c.addEventListener("keydown",N=>{N.key==="Enter"&&N.ctrlKey&&!N.shiftKey&&!N.altKey&&!N.metaKey&&A.click()}),o.onclick=()=>{m&&m.click()},m&&addEventListenerToDocument({type:"keydown",listener:N=>{N.key==="Escape"&&!N.ctrlKey&&!N.shiftKey&&!N.altKey&&!N.metaKey&&m.click()}}),u.promise}function renderAlertBase(e,t){const n=document.createElement("div");n.id=shadowDomId,document.body.append(n);const r=n.attachShadow({mode:"open"}),o=document.createElement("div");o.id="background";const i=document.createElement("style");i.textContent=toCSSText(alertStyle);const l=document.createElement("div");l.className="alert-bg";const c=document.createElement("div");c.className="container";const u=document.createElement("p");u.className="title",u.textContent=e||"";const p=document.createElement("div");if(p.className="description",t){const m=t.split(`
`);for(const N of m){const K=document.createElement("span");K.textContent=N;const g=document.createElement("br");p.append(K,g)}}const f=document.createElement("div");f.className="input-area";const A=document.createElement("div");return A.className="button-area",c.append(u,p,f,A),o.append(l,c,i),r.append(o),{background:l,inputArea:f,buttonArea:A}}function removeAlert(){const e=document.getElementById(shadowDomId);e!==null&&(removeAllEventListenerFromDocument(),e.remove())}function createButtonElements(e,t,n){const r=[];for(const o of e){const i=document.createElement("button");i.textContent=o.label,o.className&&i.classList.add(o.className),i.onclick=()=>{function l(){return o.useInputForm?(console.log(`textContent: ${n?.value}`),n?.value?o.onClick({InputValue:n?.value}):o.onClick({InputValue:""})):o.onClick(void 0)}t.resolve(l()),removeAlert()},r.push(i)}return r}function isNeedInputForm(e){for(const t of e)if(t.useInputForm)return!0;return!1}scrapbox.PageMenu.addMenu({title:"UpdateUserCSS",image:"https://i.gyazo.com/95e1d28e25db16bf7c4fdeeb16452179.png",onClick:async()=>{const t=(await scrapboxAlert(buildInAlertModes.ENTER,"\u66F4\u65B0\u5F8C\u306ECSS\u3092\u9001\u4FE1\u3057\u3066\u304F\u3060\u3055\u3044\u3002")).inputValue;t===void 0||t.trim()===""||await updateCodeBlock(t,"Mijinko","\u958B\u767A\u4E2D\u306ESettings_20230126-")}});async function updateCodeBlock(e,t,n){const r=e.split(`
`),o=l=>{const c=l.findIndex(u=>/^\s*code:style\.css\s*$/i.test(u.text));if(c===-1){const u=l.map(f=>f.text),p=r.map(f=>" "+f);return u.concat(["code:style.css"]).concat(p)}else{const u=l[c].text.match(/^\s*/),p=u!==null?u[0]:"",f=l.slice(0,c+1).map(m=>m.text),A=r.map(m=>p+" "+m);return f.concat(A)}},i=useStatusBar();i.render({type:"group",items:[{type:"spinner"},{type:"text",text:"CSS\u3092\u53CD\u6620\u3057\u3066\u3044\u307E\u3059\u2026"}]}),await patch(t,n,o),i.render({type:"group",items:[{type:"check-circle"},{type:"text",text:"CSS\u306E\u53CD\u6620\u304C\u5B8C\u4E86\u3057\u307E\u3057\u305F\u3002"}]}),setTimeout(()=>i.dispose(),2e3)}