@aiquants/markdown-explorer 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +12 -8
  3. package/dist/{EditSurface-Cw0kbedj.cjs → EditSurface-BPqqykro.cjs} +3 -3
  4. package/dist/{EditSurface-DY1VNM9L.js → EditSurface-BmbDSrrw.js} +187 -187
  5. package/dist/{ExplorerSplit-x9Qkldh6.cjs → ExplorerSplit-CQxr6b0v.cjs} +1 -1
  6. package/dist/{ExplorerSplit-D3f1FiZ7.js → ExplorerSplit-DPuXOBqs.js} +4 -4
  7. package/dist/{MultiLayout-B0dfZlpx.js → MultiLayout-DKgZ1sBK.js} +238 -232
  8. package/dist/MultiLayout-TXbet9k3.cjs +1 -0
  9. package/dist/{NativeScrollBar-C4vkvdGz.js → NativeScrollBar-C1CtjwBm.js} +2 -2
  10. package/dist/{NativeScrollBar-C2UoYO3i.cjs → NativeScrollBar-UpjxjLlB.cjs} +1 -1
  11. package/dist/{TreeLayout-Bak1y1m4.js → TreeLayout-BpazybVQ.js} +3 -3
  12. package/dist/{TreeLayout-DsFH17x_.cjs → TreeLayout-C0O1OGi4.cjs} +1 -1
  13. package/dist/core/config.d.cts +2 -0
  14. package/dist/core/config.d.ts +2 -0
  15. package/dist/core/labels.d.cts +7 -0
  16. package/dist/core/labels.d.ts +7 -0
  17. package/dist/{index-auQVKY4M.js → index-CcXMPCRS.js} +919 -903
  18. package/dist/{index-DgaTEKsI.cjs → index-DSkK8iLE.cjs} +6 -6
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +6 -6
  21. package/dist/location-BxiJRTyw.cjs +1 -0
  22. package/dist/{location-CKuabtKl.js → location-perTmwct.js} +253 -245
  23. package/dist/{merge-D1jbIOPw.js → merge-3xGYZqbE.js} +1 -1
  24. package/dist/{merge-BEa-lale.cjs → merge-DZI4pkWI.cjs} +1 -1
  25. package/dist/server.cjs +1 -1
  26. package/dist/server.js +2 -2
  27. package/dist/{tapScrollCircle-BSb6lisN.cjs → tapScrollCircle-Cbf17x8g.cjs} +1 -1
  28. package/dist/{tapScrollCircle-DYQ8P2ag.js → tapScrollCircle-DacgW2F_.js} +1 -1
  29. package/dist/{useSplitPersistence-Bf4M35Il.js → useSplitPersistence-Du01PHNg.js} +1 -1
  30. package/dist/{useSplitPersistence-9Nu6J1WF.cjs → useSplitPersistence-pPmE4GTT.cjs} +1 -1
  31. package/docs/behavior/layout.md +19 -9
  32. package/docs/behavior/localization.md +4 -4
  33. package/docs/behavior/url-contract.md +1 -1
  34. package/package.json +12 -12
  35. package/dist/MultiLayout-BXr2UAvl.cjs +0 -1
  36. package/dist/location-l_HysaZR.cjs +0 -1
@@ -1,5 +1,5 @@
1
1
  import { diff3Merge as d } from "node-diff3";
2
- import { C, a as R, b as u } from "./index-auQVKY4M.js";
2
+ import { C, a as R, b as u } from "./index-CcXMPCRS.js";
3
3
  const g = (n, o, e, l) => {
4
4
  if (o === n || o === e) return { kind: "clean", text: e };
5
5
  if (e === n) return { kind: "clean", text: o };
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("node-diff3"),r=require("./index-DgaTEKsI.cjs"),R=(n,t,i,l)=>{if(t===n||t===i)return{kind:"clean",text:i};if(i===n)return{kind:"clean",text:t};const d=g.diff3Merge(t.split(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("node-diff3"),r=require("./index-DSkK8iLE.cjs"),R=(n,t,i,l)=>{if(t===n||t===i)return{kind:"clean",text:i};if(i===n)return{kind:"clean",text:t};const d=g.diff3Merge(t.split(`
2
2
  `),n.split(`
3
3
  `),i.split(`
4
4
  `),{excludeFalseConflicts:!0}),o=[];let c=0;const u=s(l.ours),a=s(l.theirs);for(const e of d)e.ok!==void 0?o.push(...e.ok):e.conflict!==void 0&&(c+=1,o.push(`${r.CONFLICT_OURS_MARKER} ${u}`,...e.conflict.a,r.CONFLICT_SEPARATOR,...e.conflict.b,`${r.CONFLICT_THEIRS_MARKER} ${a}`));const f=o.join(`
package/dist/server.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./dataRoute-DwYtgyt6.cjs"),J=require("./location-l_HysaZR.cjs"),St=require("node:crypto"),nr=require("@aiquants/markdown/server"),Ae=require("@aiquants/request-isolation"),Pe=require("react-router"),ue=require("node:fs"),ie=require("node:path"),Ie=require("node:url"),or=require("node:worker_threads"),we=require("node:fs/promises"),sr=require("node:stream");var Le=typeof document<"u"?document.currentScript:null;const Ke=Object.freeze({kind:"anonymous"}),ir=Object.freeze({authenticate:async()=>({status:"signed-in",principal:Ke}),principalKey:()=>Ke.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),Ot="application/octet-stream",Rt="application/pdf",ar=new Set(["image/png","image/apng","image/jpeg","image/gif","image/webp","image/avif","image/bmp","image/x-icon","image/vnd.microsoft.icon","audio/mpeg","audio/mp4","audio/aac","audio/ogg","audio/opus","audio/wav","audio/wave","audio/x-wav","audio/webm","audio/flac","audio/x-flac","audio/x-m4a","video/mp4","video/webm","video/ogg","video/quicktime",Rt]),_t="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",At=`${_t}; sandbox`,cr=`${_t}; sandbox allow-same-origin`,Qe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,ur=/^[\t\n\r ]+|[\t\n\r ]+$/gu,Ce=/^[\t ]+|[\t ]+$/gu,dr=e=>{const t=[];let r="",n=0;for(;;){for(;n<e.length&&e[n]!=='"'&&e[n]!==",";)r+=e[n],n+=1;if(n<e.length&&e[n]==='"'){const i=n;for(n+=1;n<e.length&&e[n]!=='"';)n+=e[n]==="\\"?2:1;if(n=Math.min(n+1,e.length),r+=e.slice(i,n),n<e.length)continue}if(t.push(r.replace(Ce,"")),r="",n>=e.length)return t;n+=1}},lr=e=>{const t=e.replace(ur,""),r=t.indexOf("/");if(r<0)return null;const n=t.slice(0,r),i=t.indexOf(";",r+1),o=t.slice(r+1,i<0?t.length:i).replace(/[\t\n\r ]+$/u,"");return Qe.test(n)&&Qe.test(o)?`${n}/${o}`.toLowerCase():null},fr=e=>{let t=null;for(const r of dr(e)){const n=lr(r);n!==null&&n!=="*/*"&&(t=n)}return t},mr=/['()*]/gu,vt=e=>encodeURIComponent(e).replace(mr,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Fe=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),Nt=(e,t)=>{const r=fr(e),n=r!==null&&ar.has(r),i=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Ot:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${vt(t)}`,...r===Rt?{}:{"Content-Security-Policy":i?cr:At},"Cross-Origin-Resource-Policy":"same-origin"}}},_e=64*1024,ke=e=>`text/plain; charset=${e}`,pr=e=>({"X-Content-Type-Options":"nosniff","Content-Disposition":`inline; filename*=UTF-8''${vt(e)}`,"Content-Security-Policy":At,"Cross-Origin-Resource-Policy":"same-origin"}),hr=(e,t)=>`${t===null?"":t};${e}`,wr=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,xe=Object.freeze({kind:"whole"}),Ze=Object.freeze({kind:"unsatisfiable"}),Pt=(e,t,r)=>{const n=e.get("Range");if(n===null)return xe;const i=e.get("If-Range");if(i!==null&&i!==r)return xe;const o=wr.exec(n);if(o===null)return xe;const[,c,l,f]=o;if(f!==void 0){const g=Number(f);if(g===0)return Ze;const b=Math.max(0,t-g);return{kind:"partial",range:{offset:b,length:t-b}}}const x=Number(c),w=l===""?Number.POSITIVE_INFINITY:Number(l);return w<x?xe:x>=t?Ze:{kind:"partial",range:{offset:x,length:Math.min(w,t-1)-x+1}}},qe="W/",yr=e=>{const t=[];let r=0,n=!1;for(let i=0;i<e.length;i+=1)e[i]==='"'?n=!n:e[i]===","&&!n&&(t.push(e.slice(r,i).replace(Ce,"")),r=i+1);return t.push(e.slice(r).replace(Ce,"")),t},et=e=>e.startsWith(qe)?e.slice(qe.length):e,Ue=(e,t)=>{if(e===null)return!1;const r=yr(e);if(r.length===1&&r[0]==="*")return!0;const n=et(t);return r.some(i=>et(i)===n)},gr=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,i)=>{const o=n.byteLength>r?n.subarray(0,r):n;r-=o.byteLength,i.enqueue(o),r===0&&i.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},pe=async(e,t,r,n,i)=>{if(n!==null&&r.set("Content-Length",String(n)),e.method.toUpperCase()==="HEAD")return new Response(null,{status:t,headers:r});const o=await i();return new Response(n===null?o:gr(o,n),{status:t,headers:r})},It=(e,t)=>{const r=new Headers(e);for(const[n,i]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${t}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))r.set(n,i);return new Response(null,{status:416,headers:r})},Er=async(e,t,r)=>{const n=`"${t.version}"`,i=Nt(t.contentType,t.name),o=new Headers(r);for(const[f,x]of Object.entries({...i.headers,...Fe,ETag:n}))o.set(f,x);if(Ue(e.headers.get("If-None-Match"),n))return new Response(null,{status:304,headers:o});if(o.set("Content-Type",i.contentType),t.size===null)return pe(e,200,o,null,()=>t.open(null));if(t.size===0)return o.set("Content-Length","0"),new Response(null,{status:200,headers:o});o.set("Accept-Ranges","bytes");const c=Pt(e.headers,t.size,n);if(c.kind==="unsatisfiable")return It(r,t.size);if(c.kind==="whole")return pe(e,200,o,t.size,()=>t.open(null));const{range:l}=c;return o.set("Content-Range",`bytes ${l.offset}-${l.offset+l.length-1}/${t.size}`),pe(e,206,o,l.length,()=>t.open(l))},br=(e,t)=>{const r=new Uint8Array(t);let n=0;for(const i of e){if(n===t)break;const o=i.subarray(0,t-n);r.set(o,n),n+=o.byteLength}return r},Tr=(e,t,r)=>new ReadableStream({start:n=>{for(const i of e)n.enqueue(i);t&&n.close()},pull:async n=>{const{done:i,value:o}=await r.read();i?n.close():n.enqueue(o)},cancel:n=>r.cancel(n)},{highWaterMark:0}),Lt=async(e,t,r)=>{const n=e.getReader(),i=t===null?_e:Math.min(t,_e),o=t===null?i+1:i,c=[];let l=0,f=!1;try{for(;l<o;){const{done:g,value:b}=await n.read();if(g){f=!0;break}c.push(b),l+=b.byteLength}if(f&&t!==null&&l<i)throw new RangeError("[markdown-explorer] the asset ended before its declared length");const x=t===null?f:t<=_e;return{encoding:J.textEncodingOf(br(c,Math.min(l,i)),x,r),body:Tr(c,f,n)}}catch(x){throw n.cancel(x).catch(()=>{}),x}},tt=async(e,t)=>{const r=await Lt(await e.open(e.size===null?null:{offset:0,length:Math.min(e.size,_e)}),e.size,t);return r.body.cancel().catch(()=>{}),r.encoding},kr=async(e,t,r,n)=>{const i=`"${hr(t.version,n)}"`,o=new Headers(r);for(const[l,f]of Object.entries({...pr(t.name),...Fe,ETag:i}))o.set(l,f);if(Ue(e.headers.get("If-None-Match"),i))return new Response(null,{status:304,headers:o});if(t.size===0)return o.set("Content-Type",ke(J.textEncodingOf(new Uint8Array(0),!0,n))),o.set("Content-Length","0"),new Response(null,{status:200,headers:o});if(t.size!==null){o.set("Accept-Ranges","bytes");const l=Pt(e.headers,t.size,i);if(l.kind==="unsatisfiable")return It(r,t.size);if(l.kind==="partial"){const{range:f}=l;return o.set("Content-Type",ke(await tt(t,n))),o.set("Content-Range",`bytes ${f.offset}-${f.offset+f.length-1}/${t.size}`),pe(e,206,o,f.length,()=>t.open(f))}}if(e.method.toUpperCase()==="HEAD")return o.set("Content-Type",ke(await tt(t,n))),pe(e,200,o,t.size,()=>t.open(null));const c=await Lt(await t.open(null),t.size,n);return o.set("Content-Type",ke(c.encoding)),pe(e,200,o,t.size,async()=>c.body)},xr=e=>`workbook;${e}`,Sr=async(e,t,r)=>{const n=`"${xr(t.version)}"`,i=Nt(Ot,t.name),o=new Headers(r);for(const[c,l]of Object.entries({...i.headers,...Fe,ETag:n}))o.set(c,l);return Ue(e.headers.get("If-None-Match"),n)?new Response(null,{status:304,headers:o}):(o.set("Content-Type",i.contentType),pe(e,200,o,t.size,()=>t.open(null)))},Or=Object.freeze({"Cache-Control":"private, no-store","Referrer-Policy":"no-referrer"}),Rr=(e,t)=>{const r=new Headers(t);for(const[n,i]of Object.entries(Or))r.set(n,i);return r.set("Location",e),new Response(null,{status:302,headers:r})},Me=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(i=>{let o;const c=setTimeout(()=>{i(e.late),o=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),l=()=>{clearTimeout(c),clearTimeout(o)};n.then(f=>{l(),i(f)},()=>{l(),i(e.late)})})},_r=Object.freeze({error:(e,t)=>{console.error(e,t)}}),Mt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class be extends Error{reason;code;constructor(t,r={}){if(!y.isExplorerFailureReason(t))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);if(r.code!==void 0&&!y.isExplorerFailureCode(r.code))throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${JSON.stringify(r.code)}`);super(`[markdown-explorer] ${t}`,r.cause===void 0?void 0:{cause:r.cause}),this.name="ExplorerError",this.reason=t,this.code=r.code,Object.defineProperty(this,Mt,{value:!0})}}const Ar=e=>e instanceof Error&&Object.hasOwn(e,Mt)&&y.isExplorerFailureReason(e.reason),vr=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",Xe=(e,t,r)=>{try{e.error(t,r)}catch(n){console.error("[markdown-explorer] the logger threw while reporting a failure",{operation:r.operation,error:n})}},ae=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} failed`,t),Nr=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} left out an entry`,t),$e=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),rt=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},V=(e,t,r,n)=>Ar(e)?y.failureOf(e.reason,e.code):(vr(e)||r.aborted||ae(n,{...t,error:e}),{reason:"failed"}),nt=2*1024*1024,ot=256*1024*1024,Pr=async(e,t)=>{const r=e.getReader(),n=new Uint8Array(t);let i=0;for(;i<t;){const{done:o,value:c}=await r.read();if(o)return n.subarray(0,i);const l=c.subarray(0,t-i);n.set(l,i),i+=l.byteLength}return r.cancel().catch(()=>{}),n},Ir=async(e,t,r)=>{if(e.size===0)return{text:"",truncated:!1};const n=e.size!==null&&e.size>t,i=e.size===null?t+1:Math.min(e.size,t),o=await Pr(await e.open(n?{offset:0,length:t}:null),i);if(e.size!==null&&o.byteLength<i)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const c=n||o.byteLength>t,l=c?o.subarray(0,t):o,f=J.decodeTextLeniently(l,!c,r);return f.includes("\0")?null:{text:f,truncated:c}},st=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},$t=(e,t)=>{st("capacity",e),t!==void 0&&st("weight budget",t.max);const r=new Map;let n=0;const i=o=>{const c=r.get(o);c!==void 0&&(r.delete(o),n-=c.weight)};return{get:o=>{const c=r.get(o);if(c!==void 0)return r.delete(o),r.set(o,c),c.value},set:(o,c)=>{i(o);const l=t===void 0?0:t.of(o,c);if(!(t!==void 0&&l>t.max)){r.set(o,{value:c,weight:l}),n+=l;for(const f of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;i(f)}}},delete:i,size:()=>r.size,weight:()=>n}},Dt=e=>Math.max(1,e-1),Lr=2147483647,it=Object.freeze({status:"aborted"}),fe=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},he=(e,t,r)=>{if(!Number.isSafeInteger(t)||t<=0||t>r)throw new RangeError(`[markdown-explorer] a worker pool's ${e} must be an integer in 1..${String(r)}; got ${String(t)}`)},Mr=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),$r=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,Dr=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:i,heapLimits:o})=>{he("size",t,Number.MAX_SAFE_INTEGER),he("deadline",r,Lr),he("jobsPerScope",n,Number.MAX_SAFE_INTEGER),he("maxQueuedJobs",i,Number.MAX_SAFE_INTEGER),he("maxOldGenerationSizeMb",o.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),he("maxYoungGenerationSizeMb",o.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const c=Object.freeze({maxOldGenerationSizeMb:o.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:o.maxYoungGenerationSizeMb}),l=new Set,f=[],x=new Map,w=new Map,g=Dt(t);let b=0;const v=(h,E)=>{const{job:M}=h;h.timer!==null&&clearTimeout(h.timer),h.timer=null,h.job=null,h.sent=!1,M!==null&&(fe(x,M.scope,-1),fe(w,M.scope,-1),M.settle(E))},j=h=>{const[E]=f.splice(h,1);E?.detach()},O=()=>{let h=-1,E=g,M=Number.POSITIVE_INFINITY;for(const[U,T]of f.entries()){const N=x.get(T.scope)??0,P=w.get(T.scope)??0;(N<E||N===E&&h>=0&&P<M)&&(h=U,E=N,M=P)}return h},R=(h,E)=>{l.has(h)&&(l.delete(h),v(h,E),h.worker.terminate().catch(()=>{}),F())},z=h=>{h.timer=setTimeout(()=>{R(h,{status:"timeout"})},r)},_=(h,E)=>h.sent?{status:"crashed",error:E}:{status:"unavailable",error:E},I=(h,E)=>{h.sent=!0,z(h);try{h.worker.postMessage({id:E.id,input:E.input})}catch(M){v(h,{status:"crashed",error:M}),h.worker.unref()}},C=()=>{const h={worker:new or.Worker(e,{resourceLimits:c}),job:null,sent:!1,timer:null,ready:!1};return h.worker.unref(),h.timer=setTimeout(()=>{R(h,{status:"unavailable",error:new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`)})},r),h.worker.on("message",E=>{if(!h.ready&&Mr(E)){h.ready=!0,h.timer!==null&&clearTimeout(h.timer),h.timer=null,h.job===null?h.worker.unref():I(h,h.job),h.job===null&&F();return}const{job:M}=h;if(M===null||!$r(E,M.id)){R(h,_(h,new Error("[markdown-explorer] a worker sent a message that answers no job")));return}v(h,{status:"done",output:E.output}),h.worker.unref(),F()}),h.worker.on("error",E=>{R(h,_(h,E))}),h.worker.on("messageerror",E=>{R(h,_(h,E))}),h.worker.on("exit",E=>{R(h,_(h,new Error(`[markdown-explorer] a worker exited with code ${String(E)}`)))}),l.add(h),h},F=()=>{for(;;){const h=O(),E=f[h];if(E===void 0)return;let M;for(const T of l)if(T.job===null){M=T;break}if(M===void 0&&l.size<t)try{M=C()}catch(T){j(h),fe(w,E.scope,-1),E.settle({status:"unavailable",error:T});continue}if(M===void 0)return;j(h),fe(x,E.scope,1);const U=M;U.job=E,U.worker.ref(),U.ready&&I(U,E)}};return{run:(h,{scope:E,signal:M})=>new Promise(U=>{if(M.aborted){U(it);return}if((w.get(E)??0)>=n){U({status:"refused",limit:"scope"});return}b+=1;const T={id:b,input:h,scope:E,settle:U,detach:()=>{}};f.push(T),fe(w,E,1),F();const N=f.indexOf(T);if(N<0)return;if(f.length>i){j(N),fe(w,E,-1),U({status:"refused",limit:"queue"});return}const P=()=>{const D=f.indexOf(T);D<0||(j(D),fe(w,E,-1),U(it))};M.addEventListener("abort",P,{once:!0}),T.detach=()=>{M.removeEventListener("abort",P)}}),workers:()=>l.size}},Ge=1024*1024,jr=3e4,zr=4*Ge,Cr=64*Ge,Hr=3,Br=2,Fr=(e,t)=>e+Dt(t)+Hr,Ur=4,Xr=32,Gr=512,Jr=64,Yr=4096,Wr=32,at=4096,Vr=4,jt=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-Jr)*Ge-t*Wr)/Yr),Kr=({maxHtmlBytes:e})=>e,Qr=({maxHtmlBytes:e})=>Vr*e,Zr=1024,qr=2147483647,en=64,tn=2**29,rn=1024*1024,nn=64,ct=Object.freeze({status:"rejected",reason:"too-large",cause:null}),De=Object.freeze({status:"rejected",reason:"failed",cause:null}),me=(e,t,r,n)=>{if(t===void 0)return r;if(typeof t!="number")throw new TypeError(`[markdown-explorer] sanitizer.${e} must be a number; got ${typeof t}`);if(!Number.isSafeInteger(t)||t<=0||t>n)throw new RangeError(`[markdown-explorer] sanitizer.${e} must be an integer in 1..${String(n)}; got ${String(t)}`);return t},on=(e,t)=>{if(e!==void 0&&(e===null||typeof e!="object"))throw new TypeError("[markdown-explorer] sanitizer must be an object of { workers, deadlineMs, maxHtmlBytes, cacheBytes, workerHeapMb, jobsPerScope, maxQueuedJobs }");const{workers:r,deadlineMs:n,maxHtmlBytes:i,cacheBytes:o,workerHeapMb:c,jobsPerScope:l,maxQueuedJobs:f}=e??{},x=me("workers",r,Br,en),w=me("jobsPerScope",l,Fr(t,x),Number.MAX_SAFE_INTEGER),g=Object.freeze({workers:x,deadlineMs:me("deadlineMs",n,jr,qr),maxHtmlBytes:me("maxHtmlBytes",i,zr,tn),cacheBytes:me("cacheBytes",o,Cr,Number.MAX_SAFE_INTEGER),workerHeapMb:me("workerHeapMb",c,Gr,rn),jobsPerScope:w,maxQueuedJobs:me("maxQueuedJobs",f,Ur*w,Number.MAX_SAFE_INTEGER)});if(g.jobsPerScope<t)throw new RangeError(`[markdown-explorer] sanitizer.jobsPerScope must be at least multiView.maxPanels (${String(t)}), because a page sends the document of every panel to the sanitizer at once for one reader; got ${String(g.jobsPerScope)}`);if(g.maxQueuedJobs<t)throw new RangeError(`[markdown-explorer] sanitizer.maxQueuedJobs must be at least multiView.maxPanels (${String(t)}), because a reader whose page finds every worker busy waits with the document of every panel; got ${String(g.maxQueuedJobs)}`);if(jt(g)<at)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(g.workerHeapMb)} MiB) must leave room for ${String(at)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(g.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return g},sn=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${ie.extname(Ie.fileURLToPath(e))}`,e);if(!ue.existsSync(Ie.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${Ie.fileURLToPath(t)}`);return t},ut=new Map,an=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=ut.get(r);return n===void 0&&(n=Dr({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:Xr}}),ut.set(r,n)),n},cn=e=>{if(e===null||typeof e!="object")return!1;const{status:t,html:r,message:n}=e;return t==="sanitized"&&typeof r=="string"||t==="too-large"||t==="error"&&typeof n=="string"},un=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",dn=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const i=Object.freeze([...e]),o=jt(r),c=Kr(r),l=Qr(r),f=$t(Zr,{max:r.cacheBytes,of:(O,R)=>2*O.length+(R.status==="sanitized"?2*R.html.length:nn)}),x=new Map,w=new Map,g=O=>{x.get(O.key)===O&&x.delete(O.key);const R=w.get(O.hash);R?.delete(O),R?.size===0&&w.delete(O.hash)},b=async(O,R,z)=>{const _=await n.run({html:O,iframeHosts:i,dataPath:t,maxNodes:o,maxAttributeChars:c,maxSanitizedChars:l},{scope:R,signal:z});if(_.status==="refused"){const C=_.limit==="scope"?`its reader already has ${String(r.jobsPerScope)} documents being sanitized or waiting`:`${String(r.maxQueuedJobs)} documents are already waiting`;return{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer refused a document: ${C}`)},lasting:!1}}if(_.status==="aborted")return{outcome:De,lasting:!1};if(_.status==="timeout")return{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer did not finish within ${String(r.deadlineMs)} ms`)},lasting:!0};if(_.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:_.error})},lasting:!1};if(_.status==="crashed"&&un(_.error))return{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer ran out of its ${String(r.workerHeapMb)} MiB worker heap`,{cause:_.error})},lasting:!0};if(_.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:_.error})},lasting:!0};const{output:I}=_;return cn(I)?I.status==="too-large"?{outcome:ct,lasting:!0}:I.status==="error"?{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer failed: ${I.message}`)},lasting:!0}:I.html.length>l?{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(I.html.length)} characters exceeds its limit of ${String(l)}`)},lasting:!0}:{outcome:{status:"sanitized",html:I.html},lasting:!0}:{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome")},lasting:!0}},v=(O,R,z,_)=>{let I=()=>{};const C=new Promise(E=>{I=E}),F={hash:R,key:z,outcome:C,answer:I,controller:new AbortController,waiters:0};x.set(z,F);const h=w.get(R);return h===void 0?w.set(R,new Set([F])):h.add(F),b(O,_,F.controller.signal).catch(E=>({outcome:{status:"rejected",reason:"failed",cause:E instanceof Error?E:new Error(String(E))},lasting:!0})).then(({outcome:E,lasting:M})=>{if(g(F),F.answer(E),!M)return;const U=f.get(R),T=U??(E.status==="rejected"?{...E,cause:null}:E);U===void 0&&f.set(R,T);for(const N of w.get(R)??[])g(N),N.answer(T),N.controller.abort()}),F},j=(O,R)=>new Promise(z=>{O.waiters+=1;const _=()=>{O.waiters-=1,z(De),!(O.waiters>0)&&(g(O),O.controller.abort())};R.addEventListener("abort",_,{once:!0}),O.outcome.then(I=>{R.removeEventListener("abort",_),z(I)})});return(O,{scope:R,signal:z})=>{if(O.length>r.maxHtmlBytes||Buffer.byteLength(O,"utf8")>r.maxHtmlBytes)return Promise.resolve(ct);const _=St.createHash("sha256").update(O,"utf8").digest("base64"),I=f.get(_);if(I!==void 0)return Promise.resolve(I);if(z.aborted)return Promise.resolve(De);const C=`${_}\0${R}`,F=x.get(C);return j(F===void 0?v(O,_,C,R):F,z)}},ve=e=>({result:e,json:JSON.stringify(e)}),je=Object.freeze(ve(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),ln=e=>e.status==="ok"&&e.entries.length>0,fn=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const i=$t(t,{max:r,of:(w,g)=>2*g.tree.json.length}),o=new Map,c=new Map,l=(w,g)=>{const b=new AbortController,v={waiters:0,superseded:!1,started:!1,loadTree:g},j=c.get(w),O=(C,F)=>{const h=ve(C);return!(v.superseded||b.signal.aborted)&&ln(C)&&i.set(w,{tree:h,loadedAt:F}),h},z=(async()=>{if(j!==void 0&&await j,b.signal.aborted)return je;const C=n();return v.started=!0,O(await v.loadTree(b.signal,C),C)})().finally(()=>{o.get(w)===_&&o.delete(w)}),_={promise:z,controller:b,state:v};o.set(w,_);const I=z.then(()=>{},()=>{});return c.set(w,I),I.then(()=>{c.get(w)===I&&c.delete(w)}),_},f=(w,g,b)=>{g.state.waiters+=1;const v=()=>{g.state.waiters-=1,!(g.state.waiters>0)&&(o.get(w)===g&&o.delete(w),g.controller.abort())};return b.addEventListener("abort",v,{once:!0}),g.promise.finally(()=>{b.removeEventListener("abort",v)})},x=w=>{i.delete(w);const g=o.get(w);g?.state.started&&(g.state.superseded=!0,o.delete(w))};return{load:(w,g,b)=>{if(g.aborted)return Promise.resolve(je);const v=i.get(w);if(v!==void 0){if(n()-v.loadedAt<e)return Promise.resolve(v.tree);i.delete(w)}const j=o.get(w);return f(w,j===void 0?l(w,b):j,g)},refresh:(w,g,b)=>{if(g.aborted)return Promise.resolve(je);x(w);const v=o.get(w);return v===void 0?f(w,l(w,b),g):(v.state.loadTree=b,f(w,v,g))},forget:x}},mn=e=>({load:(t,r,n)=>n(r,e()).then(ve),refresh:(t,r,n)=>n(r,e()).then(ve),forget:()=>{}}),S=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},pn=e=>{if(e===null||typeof e!="object")return null;const{name:t,path:r}=e;return typeof t!="string"||typeof r!="string"?null:t===""?{path:r,reason:"an empty name"}:y.isAcceptableDocumentPath(r)?null:{path:r,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},hn=(e,t,r,n)=>{if(e===null)return null;if(!Array.isArray(e))throw new TypeError(`[markdown-explorer] a source's ancestors must be null or an array of folder paths; got ${typeof e}`);const i=new Set;for(const o of e){if(typeof o!="string"||!y.isAcceptableDocumentPath(o))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(r.deniesPath(o))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!n(o))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(o===t)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(i.has(o))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");i.add(o)}return Object.freeze([...i])},wn=(e,t,r,n,i)=>{const o=new Set,c=f=>{if(!Array.isArray(f))return S("a source returned entries that are not an array");const x=[];for(const w of f){const g=l(w);g!==null&&x.push(g)}return x},l=f=>{const x=pn(f);if(x!==null)return n(x),null;const w=y.entryViolation(f);if(w!==null)return S(w);const g=f;if(o.has(g))return S("a source returned entries that contain themselves");const{name:b,path:v,type:j,mimeType:O,modifiedAt:R,children:z,lazy:_}=g;if(t.deniesName(b)||t.deniesPath(v))return null;if(!i(v))return n({path:v,reason:"a path outside the source's boundary"}),null;const I={name:b,path:v,...O===void 0?{}:{mimeType:O},...R===void 0?{}:{modifiedAt:R}};if(j==="file")return{...I,type:j};if(_===!0)return r?{...I,type:j,lazy:!0,children:[]}:S("a lazy directory came from a source without a children function");if(z===void 0)return{...I,type:j};o.add(g);const C=c(z);return o.delete(g),{...I,type:j,children:C}};return c(e)},yn=/^[\x21\x23-\x7E]{1,256}$/u,zt=e=>typeof e=="string"&&yn.test(e),gn=new Set(["text","image","media","spreadsheet","file"]),En=e=>typeof e=="string"&&gn.has(e),bn=(e,t,r)=>{if(e!==null&&typeof e=="object"){const o=e,{kind:c}=o;if(En(c)){if(Object.hasOwn(o,"url"))return S(`a ${c} document carries its version, not a url`);if(typeof o.name!="string")return S("a document needs a name string");if(!zt(o.version))return S(`a ${c} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const l=t(o.version);switch(c){case"image":{const{imageType:f}=o;return y.isExplorerImageType(f)?{kind:c,name:o.name,url:l,imageType:f}:S(`unknown image type ${typeof f=="string"?JSON.stringify(f.slice(0,64)):typeof f}`)}case"file":return{kind:c,name:o.name,url:l};case"media":{const{mediaType:f}=o;return y.isExplorerMediaType(f)?{kind:c,name:o.name,url:l,mediaType:f}:S(`unknown media type ${typeof f=="string"?JSON.stringify(f.slice(0,64)):typeof f}`)}case"text":return typeof o.text!="string"||typeof o.truncated!="boolean"?S("a text document needs text and truncated"):{kind:c,name:o.name,text:o.text,truncated:o.truncated,url:l};case"spreadsheet":{const f=y.spreadsheetFieldsViolation(o);if(f!==null)return S(f);const{format:x,firstSheetText:w,edit:g}=o;return{kind:c,name:o.name,url:l,format:x,firstSheetText:w,edit:kn(g)}}}}}const n=y.documentViolation(e);if(n!==null)return S(n);const i=e;switch(i.kind){case"failure":{const{reason:o,code:c}=i.failure;return{kind:"failure",failure:y.failureOf(o,c)}}case"markdown":return i.headings.length>y.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:y.failureOf("too-large")}:(i.edit?.kind==="inline"||i.edit?.kind==="draft")&&!r?S(`a markdown document offers ${i.edit.kind} editing, but the server has no edit ports`):{kind:"unsanitized-markdown",name:i.name,html:i.htmlContent,headings:i.headings.map(({text:o,depth:c,id:l})=>({text:o,depth:c,id:l})),edit:Tn(i.edit)}}},Tn=e=>{if(e===null)return null;switch(e.kind){case"inline":return{kind:"inline"};case"draft":return{kind:"draft"};case"external":return{kind:"external",href:e.href}}},kn=e=>e===null?null:{kind:"external",href:e.href},Ne=(e,t,r)=>typeof e!="string"?S(`${r} needs a text string`):e.includes("\0")?S(`${r} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>t?S(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`):e,Ct=e=>y.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:S("a grant needs a root-relative href"),xn=(e,t)=>{if(e===null||typeof e!="object")return S("an edit source must be an object");const r=e;return r.kind==="grant"?Ct(r):r.kind==="draft"?{kind:"draft",text:Ne(r.text,t,"a draft source")}:r.kind!=="edit"?S(`an edit source's kind must be "edit", "draft" or "grant"`):y.isExplorerEditToken(r.version)?typeof r.history!="boolean"?S("an edit source needs history"):{kind:"edit",text:Ne(r.text,t,"an edit source"),version:r.version,history:r.history}:S("an edit source needs a version of 1 to 1024 characters")},Sn=(e,t)=>{if(e===null||typeof e!="object")return S("a save result must be an object");const r=e;switch(r.kind){case"grant":return Ct(r);case"saved":return y.isExplorerEditToken(r.version)?{kind:"saved",version:r.version}:S("a saved result needs a version of 1 to 1024 characters");case"conflict":return y.isExplorerEditToken(r.version)?{kind:"conflict",version:r.version,text:Ne(r.text,t,"a conflict's current text")}:S("a conflict needs the current version of 1 to 1024 characters");default:return S(`a save result's kind must be "saved", "conflict" or "grant"`)}},On=e=>{if(e===null||typeof e!="object")return S("a preview must be an object");const{htmlContent:t,headings:r}=e;if(typeof t!="string"||!Array.isArray(r))return S("a preview needs htmlContent and headings");if(r.length>y.EXPLORER_MAX_HEADINGS)return{kind:"failure",failure:y.failureOf("too-large")};for(const n of r){const i=y.headingViolation(n);if(i!==null)return S(i)}return{html:t,headings:r.map(({text:n,depth:i,id:o})=>({text:n,depth:i,id:o}))}},Rn=e=>{if(!Array.isArray(e))return S("revisions must be an array");const t=new Set;return e.map(r=>{const n=y.revisionViolation(r);if(n!==null)return S(n);const{id:i,modifiedAt:o,size:c,author:l,kept:f,current:x}=r;return t.has(i)?S(`two revisions share the id ${JSON.stringify(i.slice(0,64))}`):(t.add(i),{id:i,modifiedAt:o,size:c,author:l,kept:f,current:x})})},_n=(e,t)=>Ne(e,t,"a revision"),He=e=>{if(e===null||typeof e!="object")return S("an asset file must be an object");const{name:t,contentType:r,size:n,version:i,open:o,kind:c}=e;return c!==void 0?S(c==="redirect"?"an asset redirect answers only a request for the stored file (options.delivery file), never one that reads the bytes":'an asset file has no kind (the only kind is "redirect")'):typeof t!="string"||t===""?S("an asset file needs a non-empty name"):typeof r!="string"?S("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?S("an asset file's size must be null or a non-negative safe integer"):zt(i)?typeof o!="function"?S("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:i,open:o}):S(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},An=e=>{if(e===null||typeof e!="object"||e.kind!=="redirect")return He(e);const{url:t}=e;if(typeof t!="string"||!URL.canParse(t))return S("an asset redirect needs an absolute https URL");const r=new URL(t);return r.protocol!=="https:"||r.username!==""||r.password!==""?S("an asset redirect's URL must be https and carry no credentials"):Object.freeze({kind:"redirect",url:r.href})},vn=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return S("a notice must be an object");const{id:r,tone:n,title:i,body:o,action:c}=t;if(typeof r!="string"||r===""||typeof i!="string")return S("a notice needs an id and a title");if(!y.isExplorerNoticeTone(n))return S(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(o!==void 0&&typeof o!="string")return S("a notice body must be a string");const f={id:r,tone:n,title:i,...o===void 0?{}:{body:o}};if(c===void 0)return f;if(c===null||typeof c!="object")return S("a notice action must be an object");const{label:x,href:w}=c;return typeof x!="string"||!y.isAcceptableUrl(w,y.EXPLORER_LINK_PROTOCOLS)?S("a notice action needs a label and an http(s), mailto or relative href"):{...f,action:{label:x,href:w}}}):S("notices must be an array"),Nn=4e3,Se=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),dt=32,Ht="private, no-store",Pn=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":Ht,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),In=22,Ln=2147483647,ze=Object.freeze([]),Mn=Object.freeze({status:"ok",source:null,ancestors:null}),lt=Object.freeze(["contains","confirm"]),ft=Object.freeze({readOnly:!1}),$n=Object.freeze({readOnly:!0}),ee=(e,t,r)=>{if(!(r&&t===void 0)&&typeof t!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`)},ye=(e,t,r)=>{if(typeof t!="number")throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${typeof t}`);if(!Number.isSafeInteger(t)||t<=0||t>r)throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(r)}; got ${String(t)}`);return t},Dn=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return J.revalidateExplorerConfig(e)},mt=e=>{try{return new Headers(e)}catch{throw new TypeError("[markdown-explorer] authenticate returned headers that are not a valid headers init (their values are not logged)")}},pt=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,jn=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<dt)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(dt)} characters; got ${String(e.length)}`);return e},zn=(e,t)=>{if(!J.isPlainObject(t))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const r of Object.keys(t))if(!lt.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${lt.join(", ")}`);ee(`${e}.boundary.contains`,t.contains,!1),ee(`${e}.boundary.confirm`,t.confirm,!0)},Cn=e=>{if(!Array.isArray(e))throw new TypeError("[markdown-explorer] sources must be an array");const t=e;if(t.length===0)throw new RangeError("[markdown-explorer] sources must hold at least one source");const r=new Set;for(const[n,i]of t.entries()){if(i===null||typeof i!="object")throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);const{id:o,label:c,boundary:l,tree:f,children:x,ancestors:w,cacheScope:g}=i;if(!J.isExplorerSourceId(o))throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof o=="string"?JSON.stringify(o):typeof o}`);const b=`source ${JSON.stringify(o)}`;if(r.has(o))throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(o)} repeats at sources[${String(n)}]`);if(r.add(o),typeof c!="string"&&typeof c!="function")throw new TypeError(`[markdown-explorer] ${b}.label must be a string or a function`);if(typeof c=="string"&&c.trim()==="")throw new RangeError(`[markdown-explorer] ${b}.label must not be blank`);if(zn(b,l),ee(`${b}.tree`,f,!1),ee(`${b}.children`,x,!0),ee(`${b}.ancestors`,w,!0),g!==void 0&&g!=="principal"&&g!=="shared")throw new RangeError(`[markdown-explorer] ${b}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(g)}`)}return t},Hn=e=>{if(e===!1)return!1;if(e===void 0)return Se;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] treeCache must be { ttlMs, maxEntries, maxBytes } or false");const{ttlMs:t,maxEntries:r,maxBytes:n}=e;return{ttlMs:t===void 0?Se.ttlMs:ye("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?Se.maxEntries:ye("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?Se.maxBytes:ye("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},ht=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] authenticate must resolve to { status, ... }");const{status:t}=e;if(t!=="signed-in"&&t!=="signed-out"&&t!=="forbidden")throw new TypeError(`[markdown-explorer] authenticate resolved to an unknown status ${JSON.stringify(t)}`);return e},wt=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},yt=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return St.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,In)},Bn=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],de=(e,t)=>{const r=e.getAll(t),[n]=r;return r.length===1&&n!==void 0&&n!==""?n:null},q=(e,t,r,n={})=>{const i=new Headers(r);for(const[o,c]of Object.entries({...Pn,...n}))i.set(o,c);return new Response(t,{status:e,headers:i})},$=(e,t,r)=>q(y.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),Fn=new Set(["refresh","save","preview"]),Un=new Set(["edit","save","preview","revisions","revision"]),gt=(e,t)=>{const r=Fn.has(t)?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:q(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},Et=e=>e.headers.get(y.EXPLORER_PROOF_HEADER)===y.EXPLORER_REFRESH_PROOF&&Ae.crossOriginRefusal(e,Ae.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Xn=e=>e.headers.get(y.EXPLORER_PROOF_HEADER)===y.EXPLORER_EDIT_PROOF&&Ae.crossOriginRefusal(e,Ae.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Gn=async(e,t)=>{const[r,...n]=(e.headers.get("Content-Type")??"").split(";").map(b=>b.trim().toLowerCase()),i=n.find(b=>b.startsWith("charset="));if(r!==y.EXPLORER_DRAFT_MEDIA_TYPE||i!==void 0&&i!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const o=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(o)&&o>t)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const c=e.body.getReader(),l=[];let f=0;for(;;){const{done:b,value:v}=await c.read();if(b)break;if(f+=v.byteLength,f>t)return await c.cancel(),{status:"error",failure:{reason:"too-large"}};l.push(v)}const x=new Uint8Array(f);let w=0;for(const b of l)x.set(b,w),w+=b.byteLength;let g;try{g=new TextDecoder("utf-8",{fatal:!0}).decode(x)}catch{return{status:"error",failure:{reason:"invalid"}}}return g.includes("\0")?{status:"error",failure:{reason:"invalid"}}:{status:"ok",text:g}},Jn=e=>{if(e===void 0)return;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] edit must be an object of the editor's ports");const t=e;for(const r of["source","save","preview","revisions","revision"])ee(`edit.${r}`,t[r],!1);return e},Yn=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,i=r===void 0?[e,t]:[e,t,r];for(const o of i)for(const[c,l]of o)c!=="set-cookie"&&n.set(c,l);return n},Wn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=Dn(e.config),r=jn(e.scopeSecret);ee("authenticate",e.authenticate,!1),ee("principalKey",e.principalKey,!1),ee("document",e.document,!1),ee("asset",e.asset,!1),ee("signedOutPage",e.signedOutPage,!1),ee("forbiddenPage",e.forbiddenPage,!0),ee("notices",e.notices,!0),ee("onTreeRefreshed",e.onTreeRefreshed,!0);const n=Cn(e.sources),i=J.withExplorerSources(t,n.map(s=>s.id)),o=e.logger;if(o!==void 0&&(o===null||typeof o!="object"||typeof o.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const c=e.logger===void 0?_r:e.logger,l=y.resolvePathRules(e.deny),f=e.deferredTimeoutMs===void 0?Nn:ye("deferredTimeoutMs",e.deferredTimeoutMs,Ln),x=e.textMaxBytes===void 0?nt:ye("textMaxBytes",e.textMaxBytes,ot),w=Jn(e.edit);if(w===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const g=e.editMaxBytes===void 0?nt:ye("editMaxBytes",e.editMaxBytes,ot),b=Hn(e.treeCache),v=()=>Date.now(),j=b===!1?mn(v):fn({...b,now:v}),O=on(e.sanitizer,t.multiView.maxPanels),R=dn({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:O,pool:an(sn(),O)}),z=new Map(n.map(s=>[s.id,s])),_=J.documentStyleNames(t),{authenticate:I,principalKey:C,signedOutPage:F,forbiddenPage:h,onTreeRefreshed:E}=e,M=(s,u)=>{if(typeof s.label=="string")return s.label;const a=s.label(u);if(typeof a!="string"||a.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(s.id)} must be a non-blank string`);return a},U=(s,u)=>s.cacheScope==="shared"?s.id:`${s.id}\0${u}`,T=(s,u)=>{const a=m=>ae(c,{operation:"boundary",sourceId:s.id,path:u,error:m});let d;try{d=s.boundary.contains(u)}catch(m){return a(m),!1}return typeof d=="boolean"?d:(rt(d,a),a(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(s.id)} must return a boolean; got ${typeof d}`)),!1)},N=async(s,u,a)=>{const{confirm:d}=s.boundary;if(d===void 0)return{status:"inside",readPath:a};let m;try{m=await d(u,a)}catch(X){return{status:"error",failure:V(X,{operation:"boundary",sourceId:s.id,path:a},u.signal,c)}}const p=X=>(ae(c,{operation:"boundary",sourceId:s.id,path:a,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} ${X}`)}),{status:"outside"});if(m===null||typeof m!="object")return p(`must resolve to { inside, readPath? }; got ${m===null?"null":typeof m}`);const{inside:k,readPath:A}=m;return k===!1?{status:"outside"}:k!==!0||typeof A!="string"?p("must resolve to { inside: false } or { inside: true, readPath: string }"):!y.isAcceptableDocumentPath(A)||l.deniesPath(A)?(ae(c,{operation:"boundary",sourceId:s.id,path:a,error:new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} answered a readPath the explorer does not serve (unacceptable or denied)`)}),{status:"error",failure:{reason:"failed"}}):{status:"inside",readPath:A}},P=async(s,u)=>{const a=n.filter(m=>T(m,u));if(a.length===0)return{status:"error",failure:{reason:"forbidden"}};if(a.some(m=>m.boundary.confirm===void 0))return{status:"inside",readPath:u};let d=null;for(const m of a){const p=await N(m,s,u);if(p.status==="inside")return p;p.status==="error"&&d===null&&(d=p.failure)}return{status:"error",failure:d===null?{reason:"forbidden"}:d}},D=(s,u,a)=>{const d=({path:m,reason:p})=>Nr(c,{operation:a.operation,sourceId:a.sourceId,path:m,error:new TypeError(`[markdown-explorer] an entry with ${p} was left out`)});try{return{status:"ok",entries:wn(s,l,u.children!==void 0,d,m=>T(u,m))}}catch(m){return ae(c,{...a,error:m}),{status:"error",failure:{reason:"failed"}}}},G=async(s,u,a)=>{let d;try{d=await s.tree(u)}catch(p){return{status:"error",failure:V(p,{operation:"tree",sourceId:s.id},u.signal,c)}}const m=D(d,s,{operation:"tree",sourceId:s.id});return m.status==="ok"?{status:"ok",entries:m.entries,loadedAt:a}:m},W=(s,u,a,d)=>(m,p)=>G(s,{principal:u,request:a,signal:m,refresh:d},p),L=(s,u,a,d,m)=>j.load(U(s,a),m,W(s,u,d,!1)),K=(s,u,a,d)=>j.refresh(U(s,a),d.signal,W(s,u,d,!0)),Q=(s,u)=>{if(E===void 0)return;const a=d=>ae(c,{operation:"refresh",sourceId:s.id,error:d});try{rt(E(u),a)}catch(d){a(d)}},Y=async(s,u,a,d)=>{if(l.deniesPath(d)||!T(s,d))return{status:"error",failure:{reason:"forbidden"}};const m=await N(s,a,d);if(m.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(m.status==="error")return{status:"error",failure:m.failure};let p;try{p=await u(a,d,m.readPath)}catch(k){return{status:"error",failure:V(k,{operation:"children",sourceId:s.id,path:d},a.signal,c)}}return D(p,s,{operation:"children",sourceId:s.id,path:d})},ce=async(s,u,a,d)=>{const m=await N(s,a,d);if(m.status==="outside")return{status:"ok",ancestors:null};if(m.status==="error")return{status:"error",failure:m.failure};let p;try{p=await u(a,d,m.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(k){return{status:"error",failure:V(k,{operation:"ancestors",sourceId:s.id,path:d},a.signal,c)}}if(Array.isArray(p)&&p.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:hn(p,d,l,k=>T(s,k))}}catch(k){return ae(c,{operation:"ancestors",sourceId:s.id,path:d,error:k}),{status:"error",failure:{reason:"failed"}}}},H=async(s,u,a,d)=>l.deniesPath(d)?{status:"error",failure:{reason:"forbidden"}}:T(s,d)?ce(s,u,a,d):{status:"ok",ancestors:null},re=async(s,u,a)=>{if(l.deniesPath(a))return{status:"error",failure:{reason:"forbidden"}};for(const d of[s,...n.filter(m=>m!==s)]){if(u.signal.aborted)break;const m=d.ancestors;if(m===void 0||!T(d,a))continue;const p=await ce(d,m,u,a);if(p.status==="ok"&&p.ancestors!==null)return{status:"ok",source:d.id,ancestors:p.ancestors}}return Mn},te=async(s,u,a)=>{if(l.deniesPath(a))return y.failureDocument("forbidden");const d=await P(s,a);if(d.status==="error")return{kind:"failure",failure:d.failure};let m;try{m=await e.document(s,a,d.readPath)}catch(A){return{kind:"failure",failure:V(A,{operation:"document",path:a},s.signal,c)}}let p;try{p=bn(m,A=>y.explorerAssetHref(t.dataPath,a,A),w!==void 0)}catch(A){return ae(c,{operation:"document",path:a,error:A}),y.failureDocument("failed")}if(p.kind!=="unsanitized-markdown")return p;const k=await R(p.html,{scope:u,signal:s.signal});return k.status==="sanitized"?{kind:"markdown",name:p.name,htmlContent:k.html,headings:p.headings,edit:p.edit}:(k.cause!==null&&ae(c,{operation:"document",path:a,error:k.cause}),y.failureDocument(k.reason))},ne=async s=>{if(e.notices===void 0)return ze;try{return vn(await e.notices(s))}catch(u){return V(u,{operation:"notices"},s.signal,c),ze}},le=async(s,u,a)=>{const d=de(u,y.EXPLORER_DATA_QUERY.path);if(d===null||!y.isAcceptableDocumentPath(d))return $({reason:"invalid"},a);const m=y.readExplorerAssetDisplay(u);if(m===null)return $({reason:"invalid"},a);if(l.deniesPath(d))return $e(c,{operation:"asset",path:d}),$({reason:"forbidden"},a);const p=await P(s,d);if(p.status==="error")return $(p.failure,a);try{const k=await e.asset(s,d,p.readPath,{delivery:m}),A=m==="file"?An(k):He(k);return"kind"in A?Rr(A.url,a):m==="text"?await kr(s.request,A,a,t.legacyTextEncoding):m==="workbook"?await Sr(s.request,A,a):await Er(s.request,A,a)}catch(k){return $(V(k,{operation:"asset",path:d},s.signal,c),a)}},Te=async(s,u)=>{if(l.deniesPath(u))return $e(c,{operation:"text",path:u}),y.failureDocument("forbidden");const a=await P(s,u);if(a.status==="error")return{kind:"failure",failure:a.failure};try{const d=He(await e.asset(s,u,a.readPath,{delivery:"text"})),m=await Ir(d,x,t.legacyTextEncoding);return m===null?y.failureDocument("unsupported"):{kind:"text",name:d.name,text:m.text,truncated:m.truncated,url:y.explorerAssetHref(t.dataPath,u,d.version)}}catch(d){return{kind:"failure",failure:V(d,{operation:"text",path:u},s.signal,c)}}},ge=async(s,u,a)=>l.deniesPath(a)?($e(c,{operation:u,path:a}),{status:"error",failure:{reason:"forbidden"}}):P(s,a),Yt=async(s,u,a)=>{const d=await ge(u,"edit",a);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return xn(await s.source(u,a,d.readPath),g)}catch(m){return{kind:"failure",failure:V(m,{operation:"edit",path:a},u.signal,c)}}},Wt=async(s,u,a,d,m)=>{const p=await ge(u,"save",a);if(p.status==="error")return{kind:"failure",failure:p.failure};try{return Sn(await s.save(u,a,p.readPath,{text:m,baseVersion:d}),g)}catch(k){return{kind:"failure",failure:V(k,{operation:"save",path:a},u.signal,c)}}},Vt=async(s,u,a,d,m)=>{const p=await ge(u,"preview",d);if(p.status==="error")return{kind:"failure",failure:p.failure};let k;try{k=On(await s.preview(u,d,p.readPath,m))}catch(X){return{kind:"failure",failure:V(X,{operation:"preview",path:d},u.signal,c)}}if("kind"in k)return k.kind==="failure"?k:y.failureDocument("failed");const A=await R(k.html,{scope:a,signal:u.signal});return A.status==="sanitized"?{kind:"preview",htmlContent:A.html,headings:k.headings}:(A.cause!==null&&ae(c,{operation:"preview",path:d,error:A.cause}),y.failureDocument(A.reason))},Kt=async(s,u,a)=>{const d=await ge(u,"revisions",a);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return{kind:"revisions",revisions:Rn(await s.revisions(u,a,d.readPath))}}catch(m){return{kind:"failure",failure:V(m,{operation:"revisions",path:a},u.signal,c)}}},Qt=async(s,u,a,d)=>{const m=await ge(u,"revision",a);if(m.status==="error")return{kind:"failure",failure:m.failure};try{return{kind:"revision",id:d,text:_n(await s.revision(u,a,m.readPath,d),g)}}catch(p){return{kind:"failure",failure:V(p,{operation:"revision",path:a},u.signal,c)}}},Zt=async(s,u,a,d,m,p)=>{const k=de(m,y.EXPLORER_DATA_QUERY.path);if(k===null||!y.isAcceptableDocumentPath(k))return $({reason:"invalid"},p);if(u==="edit")return q(200,JSON.stringify(await Yt(s,a,k)),p);if(u==="revisions")return q(200,JSON.stringify(await Kt(s,a,k)),p);if(u==="revision"){const oe=de(m,y.EXPLORER_DATA_QUERY.revision);return y.isExplorerEditToken(oe)?q(200,JSON.stringify(await Qt(s,a,k,oe)),p):$({reason:"invalid"},p)}const A=de(m,y.EXPLORER_DATA_QUERY.base);if(u==="save"&&!y.isExplorerEditToken(A))return $({reason:"invalid"},p);const X=await Gn(a.request,g);return X.status==="error"?$(X.failure,p):u==="preview"?q(200,JSON.stringify(await Vt(s,a,d,k,X.text)),p):q(200,JSON.stringify(await Wt(s,a,k,A,X.text)),p)},qt=async({request:s,url:u,params:a})=>{const d=ht(await I(s,ft)),m=mt(d.headers);if(m.set("Cache-Control",Ht),d.status==="signed-out")throw wt("signedOutPage",F(s,m));if(d.status==="forbidden")throw h===void 0?Pe.data(null,{status:403,headers:m}):wt("forbiddenPage",h(s,m));const p=J.resolveExplorerLocation(i,a["*"],u.searchParams);if(p.kind==="redirect")throw Pe.redirect(p.href,{headers:m});const{location:k}=p,{principal:A}=d,X=yt(r,C(A)),oe=z.get(k.source);if(oe===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(k.source)}`);const Ee={signal:s.signal,timeoutMs:f,late:null,handOverMs:f},se={scope:X,sources:n.map(B=>({id:B.id,label:M(B,A)})),settings:J.parseViewSettings(J.readCookieValue(s.headers.get("Cookie"),t.settingsCookie),_),tree:k.view==="single"?null:{sourceId:k.source,result:Me(Ee,B=>L(oe,A,X,s,B).then(Z=>Z.result))},documents:Bn(k).map(B=>({path:B,document:Me(Ee,Z=>te({principal:A,request:s,signal:Z,refresh:!1},X,B))})),notices:Me({signal:s.signal,timeoutMs:f,late:ze,handOverMs:0},B=>ne({principal:A,request:s,signal:B,refresh:!1}))};return Pe.data(se,{headers:m})},Je=async(s,u)=>{const a=ht(await I(s,u));return{authentication:a,headers:mt(a.headers)}},er=async(s,u,a)=>{let d;try{d=await Je(u,ft)}catch(Z){return $(V(pt(Z),{operation:"authenticate"},u.signal,c))}const{authentication:m,headers:p}=d;if(m.status==="signed-out")return $({reason:"unauthorized"},p);if(m.status==="forbidden")return $({reason:"forbidden"},p);const{principal:k}=m;if(s==="asset")return le({principal:k,request:u,signal:u.signal,refresh:!1},a,p);const A=yt(r,C(k));p.set(y.EXPLORER_SCOPE_HEADER,A);const X={principal:k,request:u,signal:u.signal,refresh:!1},oe=()=>$({reason:"invalid"},p);if(s==="document"){const Z=de(a,y.EXPLORER_DATA_QUERY.path);if(Z===null||!y.isAcceptableDocumentPath(Z))return oe();const Ve=u.headers.has(y.EXPLORER_PROOF_HEADER);return Ve&&!Et(u)?$({reason:"forbidden"},p):q(200,JSON.stringify(await te({...X,refresh:Ve},A,Z)),p)}if(s==="text"){const Z=de(a,y.EXPLORER_DATA_QUERY.path);return Z===null||!y.isAcceptableDocumentPath(Z)?oe():q(200,JSON.stringify(await Te(X,Z)),p)}if(s==="edit"||s==="save"||s==="preview"||s==="revisions"||s==="revision")return w===void 0?$({reason:"not-found"},p):Zt(w,s,X,A,a,p);const Ee=de(a,y.EXPLORER_DATA_QUERY.source),se=de(a,y.EXPLORER_DATA_QUERY.path);if(Ee===null||(s==="children"||s==="ancestors"||s==="reveal")&&(se===null||!y.isAcceptableDocumentPath(se)))return oe();const B=z.get(Ee);if(B===void 0)return $({reason:"not-found"},p);if(s==="tree")return q(200,(await L(B,k,A,u,u.signal)).json,p);if(s==="refresh"){const Z=await K(B,k,A,u);return u.signal.aborted||Q(B,U(B,A)),q(200,Z.json,p)}return s==="ancestors"?B.ancestors===void 0||se===null?$({reason:"not-found"},p):q(200,JSON.stringify(await H(B,B.ancestors,X,se)),p):s==="reveal"?se===null?oe():q(200,JSON.stringify(await re(B,X,se)),p):B.children===void 0||se===null?$({reason:"not-found"},p):q(200,JSON.stringify(await Y(B,B.children,X,se)),p)},tr=async s=>{const{authentication:u,headers:a}=await Je(s,$n);if(!a.keys().next().done)throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");return u.status==="signed-in"},Ye=t.embeds.linkCardEndpoint===null?null:nr.createLinkCardHandler({authorize:tr}),rr=async(s,u)=>{try{return await s(u)}catch(a){return $(V(pt(a),{operation:"authenticate"},u.signal,c))}},We=async(s,u,a)=>{if(new URL(s.url).pathname.endsWith(".data"))return $({reason:"not-found"});if(!y.isExplorerDataOperation(a))return $({reason:"not-found"});if(a==="link-card"){if(Ye===null)return $({reason:"not-found"});const m=gt(s,a);return m!==null?m:rr(Ye,s)}if(Un.has(a)&&w===void 0)return $({reason:"not-found"});const d=gt(s,a);if(d!==null)return d;if(a==="refresh"&&!Et(s))return $({reason:"forbidden"});if((a==="save"||a==="preview")&&!Xn(s))return $({reason:"forbidden"});try{return await er(a,s,u.searchParams)}catch(m){return $(V(m,{operation:a},s.signal,c))}};return Object.freeze({loader:qt,headers:Yn,dataLoader:({request:s,url:u,params:a})=>We(s,u,a["*"]),dataAction:({request:s,url:u,params:a})=>We(s,u,a["*"]),forgetTree:s=>{if(typeof s!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof s}`);j.forget(s)}})},Oe=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),Vn=new Set(["md","markdown","mdx"]),bt="image/svg+xml",Bt=new Map([...[["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"],["svg",bt],["webp","image/webp"],["ico","image/x-icon"],["bmp","image/bmp"],["tif","image/tiff"],["tiff","image/tiff"],["avif","image/avif"]].map(([e,t])=>[e,{kind:"image",imageType:t===bt?"svg":"raster",contentType:t}]),...[["mp4","video/mp4"],["m4v","video/mp4"],["webm","video/webm"],["mov","video/quicktime"],["avi","video/x-msvideo"],["mkv","video/x-matroska"],["ogv","video/ogg"]].map(([e,t])=>[e,{kind:"media",mediaType:"video",contentType:t}]),...[["mp3","audio/mpeg"],["wav","audio/wav"],["ogg","audio/ogg"],["oga","audio/ogg"],["opus","audio/ogg"],["m4a","audio/mp4"],["flac","audio/flac"],["aac","audio/aac"],["wma","audio/x-ms-wma"]].map(([e,t])=>[e,{kind:"media",mediaType:"audio",contentType:t}]),["pdf",{kind:"media",mediaType:"pdf",contentType:"application/pdf"}]]),Kn=new Map([["csv","csv"],["tsv","tsv"],["tab","tsv"],["xlsx","workbook"],["xlsm","workbook"],["ods","workbook"]]),Qn=new Set(["txt","text","log","json","jsonc","json5","ndjson","yaml","yml","toml","ini","cfg","conf","properties","xml","xsl","xsd","dtd","html","htm","xhtml","css","scss","sass","less","styl","js","mjs","cjs","jsx","ts","mts","cts","tsx","vue","svelte","astro","py","pyi","rb","go","rs","java","kt","kts","scala","groovy","gradle","c","h","cc","cpp","cxx","hpp","hh","hxx","cs","fs","vb","swift","m","mm","php","pl","pm","r","jl","lua","dart","ex","exs","erl","hrl","hs","ml","mli","clj","cljs","elm","nim","zig","v","sol","tf","hcl","nix","sh","bash","zsh","fish","ps1","psm1","bat","cmd","sql","graphql","gql","proto","thrift","avsc","rst","adoc","asciidoc","tex","bib","org","textile","diff","patch","srt","vtt","ics","vcf","gitignore","gitattributes","editorconfig","dockerignore","npmignore","prettierrc","eslintrc","babelrc","mailmap"]),Zn=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),Ft=typeof ue.constants.O_NOFOLLOW=="number"?ue.constants.O_NOFOLLOW:0,Ut=typeof ue.constants.O_NONBLOCK=="number"?ue.constants.O_NONBLOCK:0,Tt=e=>`${e.size}-${e.mtimeNs}`,qn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),kt=e=>y.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(qn),Xt=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},eo=e=>{const t=Xt(e);if(Vn.has(t))return{kind:"markdown"};const r=Bt.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image",imageType:r.imageType}:{kind:"media",mediaType:r.mediaType};const n=Kn.get(t);if(n!==void 0)return{kind:"spreadsheet",format:n};const i=e.toLowerCase();return Qn.has(t)||!i.includes(".")&&Zn.has(i)?{kind:"text"}:{kind:"file"}},Be=e=>{switch(typeof e=="object"&&e!==null?e.code:void 0){case"ENOENT":case"ENOTDIR":return"not-found";case"ELOOP":case"EACCES":case"EPERM":return"forbidden";case"ENAMETOOLONG":return"invalid";case"EISDIR":return"unsupported";default:return null}},Gt=e=>{const t=Be(e);return t===null?e:new be(t)},Jt=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},to=async e=>{try{return Math.trunc((await we.lstat(e)).mtimeMs)}catch(t){if(Jt(t))return;throw t}},xt=async(e,t)=>{const r=[];for await(const n of e.createReadStream({start:0,end:t-1,autoClose:!1}))r.push(n);return Buffer.concat(r)},ro=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},no=async(e,t,r,n)=>{let i;try{i=await we.open(e,ue.constants.O_RDONLY|Ft|Ut);const f=await i.stat({bigint:!0});if(!f.isFile()||f.ino!==t.ino||f.dev!==t.dev||f.size!==t.size||f.mtimeNs!==t.mtimeNs)throw new be("not-found")}catch(f){throw await i?.close(),Gt(f)}const o=i.createReadStream(ro(r,t.size)),c=sr.Readable.toWeb(o),l=()=>{o.destroy(n.reason)};return n.aborted?l():n.addEventListener("abort",l,{once:!0}),c},oo=(e,t)=>{const r=J.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},so=e=>{let t=0;const r=[];return async n=>{t<e?t+=1:await new Promise(i=>r.push(i));try{return await n()}finally{const i=r.shift();i===void 0?t-=1:i()}}},io=(e,t)=>{if(e.isSymbolicLink())return"symbolic-link";if(!(e.isDirectory()||e.isFile()))return"special-file";const{name:r}=e;return r!==r.normalize("NFC")?"not-nfc":r.includes(":")?"colon":r.endsWith(".")||r.endsWith(" ")?"trailing-dot-or-space":y.isAcceptableDocumentPath(r)?y.isAcceptableDocumentPath(t)?null:"path-too-long":"control-character-or-backslash"},ao=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","legacyTextEncoding","walkConcurrency","cacheScope","reportSkipped"]),Re=(e,t,r)=>{if(t===void 0)return r;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] ${e} must be a positive integer; got ${String(t)}`);return t},co=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");for(const T of Object.keys(e))if(!ao.has(T))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(T)}`);const{id:t,label:r,root:n,parse:i}=e;if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-empty id");if(typeof r!="string"||r.trim()==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-blank label");if(typeof i!="function")throw new TypeError("[markdown-explorer] a file-system source needs a parse function");if(typeof n!="string"||!ie.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let o;try{o=ue.statSync(n).isDirectory()}catch(T){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:T})}if(!o)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const c=ue.realpathSync(n),l=e.pathPrefix;if(typeof l!="string")throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');if(l!==""&&!(l.endsWith("/")&&kt(l.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(l)}`);const f=y.resolvePathRules(e.deny),x=Re("maxEntries",e.maxEntries,Oe.maxEntries),w=Re("maxDocumentBytes",e.maxDocumentBytes,Oe.maxDocumentBytes),g=Re("textPreviewBytes",e.textPreviewBytes,Oe.textPreviewBytes),b=e.legacyTextEncoding;if(b!=null&&typeof b!="string")throw new TypeError("[markdown-explorer] legacyTextEncoding must be a string or null");const v=typeof b=="string"?J.legacyTextEncodingOf(b):null,j=Re("walkConcurrency",e.walkConcurrency,Oe.walkConcurrency),O=e.cacheScope===void 0?"principal":e.cacheScope;if(O!=="principal"&&O!=="shared")throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(O)}`);const R=e.reportSkipped;if(R!==void 0&&typeof R!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const z=R===void 0?T=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(T.sourceId)} does not list ${JSON.stringify(T.path)}: ${T.reason}`)}:R,_=new Set,I=T=>{const N=ie.resolve(c,...T.split("/")),P=ie.relative(c,N);return P===""||P===".."||P.startsWith(`..${ie.sep}`)||ie.isAbsolute(P)?null:N},C=(T,N)=>{const P=`${N}\0${T}`;_.has(P)||_.size>=x||(_.add(P),z({sourceId:t,path:T,reason:N}))},F=async({signal:T})=>{T.throwIfAborted();const N=new AbortController,P=()=>{N.abort(T.reason)};T.addEventListener("abort",P,{once:!0});const D=so(j);let G=0;const W=async(L,K)=>{const Q=await D(async()=>{N.signal.throwIfAborted();try{return await we.readdir(L,{withFileTypes:!0})}catch(H){if(K===""||!Jt(H))throw H;return null}});if(N.signal.throwIfAborted(),Q===null)return C(`${l}${K}`,"unreadable-directory"),null;const Y=[];for(const H of Q){if(f.deniesName(H.name))continue;const re=K===""?H.name:`${K}/${H.name}`,te=`${l}${re}`,ne=io(H,te);if(ne!==null){C(te,ne);continue}Y.push({dirent:H,relativePath:re,path:te})}if(G+=Y.length,G>x)throw new be("too-large");return Y.sort((H,re)=>oo(H.dirent.name,re.dirent.name)),(await Promise.all(Y.map(async({dirent:H,relativePath:re,path:te})=>{const ne=await to(ie.join(L,H.name)),le=ne===void 0?{}:{modifiedAt:ne};if(!H.isDirectory())return{name:H.name,path:te,type:"file",...le};const Te=await W(ie.join(L,H.name),re);return Te===null?null:{name:H.name,path:te,type:"directory",...le,children:Te}}))).filter(H=>H!==null)};try{const L=await W(c,"");if(L===null)throw new Error("[markdown-explorer] the source's root could not be listed");return L}catch(L){throw N.abort(),L}finally{T.removeEventListener("abort",P)}},h=async T=>{if(!T.startsWith(l))return{status:"refused",reason:"not-found"};const N=T.slice(l.length);if(!kt(N))return{status:"refused",reason:"invalid"};if(f.deniesPath(N))return{status:"refused",reason:"forbidden"};const P=I(N);if(P===null)return{status:"refused",reason:"forbidden"};const D=await we.lstat(P,{bigint:!0});if(D.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!D.isFile())return{status:"refused",reason:"unsupported"};const G=await we.realpath(P);return G!==P||f.deniesPath(ie.relative(c,G).split(ie.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:P,name:N.slice(N.lastIndexOf("/")+1),stats:D}},E=async(T,N,P)=>{let D;try{const G=await h(P);if(G.status==="refused")return y.failureDocument(G.reason);const{target:W,name:L,stats:K}=G,Q=eo(L),Y=Tt(K);if(Q.kind==="image")return{kind:"image",name:L,imageType:Q.imageType,version:Y};if(Q.kind==="media")return{kind:"media",name:L,mediaType:Q.mediaType,version:Y};if(Q.kind==="spreadsheet")return{kind:"spreadsheet",name:L,format:Q.format,firstSheetText:null,edit:null,version:Y};if(Q.kind==="file")return{kind:"file",name:L,version:Y};D=await we.open(W,ue.constants.O_RDONLY|Ft|Ut);const ce=await D.stat({bigint:!0});if(!ce.isFile()||ce.ino!==K.ino||ce.dev!==K.dev)return y.failureDocument("forbidden");if(Q.kind==="markdown"){if(ce.size>BigInt(w))return y.failureDocument("too-large");const ne=await xt(D,w+1);if(ne.length>w)return y.failureDocument("too-large");const le=await i(J.decodeTextLeniently(ne,!0,v),N);return{kind:"markdown",name:L,htmlContent:le.htmlContent,headings:le.headings,edit:null}}const H=await xt(D,g),re=ce.size>BigInt(g),te=J.decodeTextLeniently(H,!re,v);return te.includes("\0")?{kind:"file",name:L,version:Y}:{kind:"text",name:L,text:te,truncated:re,version:Y}}catch(G){const W=Be(G);if(W===null)throw G;return y.failureDocument(W)}finally{await D?.close()}},M=async(T,N,P)=>{let D;try{D=await h(P)}catch(Y){throw Gt(Y)}if(D.status==="refused")throw new be(D.reason);const{target:G,name:W,stats:L}=D,K=Bt.get(Xt(W)),Q=K===void 0?"":K.contentType;return{name:W,contentType:Q,size:Number(L.size),version:Tt(L),open:Y=>no(G,L,Y,T.signal)}},U=async(T,N,P)=>{let D;try{D=await h(P)}catch(L){if(Be(L)!==null)return null;throw L}if(D.status==="refused")return null;const G=P.slice(l.length).split("/");if(G.some(L=>f.deniesName(L)))return null;const W=G.slice(0,-1);return W.map((L,K)=>`${l}${W.slice(0,K+1).join("/")}`)};return Object.freeze({id:t,label:r,cacheScope:O,boundary:Object.freeze({contains:T=>T.startsWith(l)}),tree:F,ancestors:U,document:E,asset:M})};exports.DEFAULT_DENIED_PATH_SEGMENTS=y.DEFAULT_DENIED_PATH_SEGMENTS;exports.MAX_DOCUMENT_PATH_LENGTH=y.MAX_DOCUMENT_PATH_LENGTH;exports.isAcceptableDocumentPath=y.isAcceptableDocumentPath;exports.isDeniedPath=y.isDeniedPath;exports.decodeText=J.decodeText;exports.decodeTextLeniently=J.decodeTextLeniently;exports.legacyTextEncodingOf=J.legacyTextEncodingOf;exports.ExplorerError=be;exports.anonymousAccess=ir;exports.createFileSystemSource=co;exports.createMarkdownExplorer=Wn;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./dataRoute-DwYtgyt6.cjs"),J=require("./location-BxiJRTyw.cjs"),St=require("node:crypto"),nr=require("@aiquants/markdown/server"),Ae=require("@aiquants/request-isolation"),Pe=require("react-router"),ue=require("node:fs"),ie=require("node:path"),Ie=require("node:url"),or=require("node:worker_threads"),we=require("node:fs/promises"),sr=require("node:stream");var Le=typeof document<"u"?document.currentScript:null;const Ke=Object.freeze({kind:"anonymous"}),ir=Object.freeze({authenticate:async()=>({status:"signed-in",principal:Ke}),principalKey:()=>Ke.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),Ot="application/octet-stream",Rt="application/pdf",ar=new Set(["image/png","image/apng","image/jpeg","image/gif","image/webp","image/avif","image/bmp","image/x-icon","image/vnd.microsoft.icon","audio/mpeg","audio/mp4","audio/aac","audio/ogg","audio/opus","audio/wav","audio/wave","audio/x-wav","audio/webm","audio/flac","audio/x-flac","audio/x-m4a","video/mp4","video/webm","video/ogg","video/quicktime",Rt]),_t="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",At=`${_t}; sandbox`,cr=`${_t}; sandbox allow-same-origin`,Qe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,ur=/^[\t\n\r ]+|[\t\n\r ]+$/gu,Ce=/^[\t ]+|[\t ]+$/gu,dr=e=>{const t=[];let r="",n=0;for(;;){for(;n<e.length&&e[n]!=='"'&&e[n]!==",";)r+=e[n],n+=1;if(n<e.length&&e[n]==='"'){const i=n;for(n+=1;n<e.length&&e[n]!=='"';)n+=e[n]==="\\"?2:1;if(n=Math.min(n+1,e.length),r+=e.slice(i,n),n<e.length)continue}if(t.push(r.replace(Ce,"")),r="",n>=e.length)return t;n+=1}},lr=e=>{const t=e.replace(ur,""),r=t.indexOf("/");if(r<0)return null;const n=t.slice(0,r),i=t.indexOf(";",r+1),o=t.slice(r+1,i<0?t.length:i).replace(/[\t\n\r ]+$/u,"");return Qe.test(n)&&Qe.test(o)?`${n}/${o}`.toLowerCase():null},fr=e=>{let t=null;for(const r of dr(e)){const n=lr(r);n!==null&&n!=="*/*"&&(t=n)}return t},mr=/['()*]/gu,vt=e=>encodeURIComponent(e).replace(mr,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Fe=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),Nt=(e,t)=>{const r=fr(e),n=r!==null&&ar.has(r),i=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Ot:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${vt(t)}`,...r===Rt?{}:{"Content-Security-Policy":i?cr:At},"Cross-Origin-Resource-Policy":"same-origin"}}},_e=64*1024,ke=e=>`text/plain; charset=${e}`,pr=e=>({"X-Content-Type-Options":"nosniff","Content-Disposition":`inline; filename*=UTF-8''${vt(e)}`,"Content-Security-Policy":At,"Cross-Origin-Resource-Policy":"same-origin"}),hr=(e,t)=>`${t===null?"":t};${e}`,wr=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,xe=Object.freeze({kind:"whole"}),Ze=Object.freeze({kind:"unsatisfiable"}),Pt=(e,t,r)=>{const n=e.get("Range");if(n===null)return xe;const i=e.get("If-Range");if(i!==null&&i!==r)return xe;const o=wr.exec(n);if(o===null)return xe;const[,c,l,f]=o;if(f!==void 0){const g=Number(f);if(g===0)return Ze;const b=Math.max(0,t-g);return{kind:"partial",range:{offset:b,length:t-b}}}const x=Number(c),w=l===""?Number.POSITIVE_INFINITY:Number(l);return w<x?xe:x>=t?Ze:{kind:"partial",range:{offset:x,length:Math.min(w,t-1)-x+1}}},qe="W/",yr=e=>{const t=[];let r=0,n=!1;for(let i=0;i<e.length;i+=1)e[i]==='"'?n=!n:e[i]===","&&!n&&(t.push(e.slice(r,i).replace(Ce,"")),r=i+1);return t.push(e.slice(r).replace(Ce,"")),t},et=e=>e.startsWith(qe)?e.slice(qe.length):e,Ue=(e,t)=>{if(e===null)return!1;const r=yr(e);if(r.length===1&&r[0]==="*")return!0;const n=et(t);return r.some(i=>et(i)===n)},gr=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,i)=>{const o=n.byteLength>r?n.subarray(0,r):n;r-=o.byteLength,i.enqueue(o),r===0&&i.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},pe=async(e,t,r,n,i)=>{if(n!==null&&r.set("Content-Length",String(n)),e.method.toUpperCase()==="HEAD")return new Response(null,{status:t,headers:r});const o=await i();return new Response(n===null?o:gr(o,n),{status:t,headers:r})},It=(e,t)=>{const r=new Headers(e);for(const[n,i]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${t}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))r.set(n,i);return new Response(null,{status:416,headers:r})},Er=async(e,t,r)=>{const n=`"${t.version}"`,i=Nt(t.contentType,t.name),o=new Headers(r);for(const[f,x]of Object.entries({...i.headers,...Fe,ETag:n}))o.set(f,x);if(Ue(e.headers.get("If-None-Match"),n))return new Response(null,{status:304,headers:o});if(o.set("Content-Type",i.contentType),t.size===null)return pe(e,200,o,null,()=>t.open(null));if(t.size===0)return o.set("Content-Length","0"),new Response(null,{status:200,headers:o});o.set("Accept-Ranges","bytes");const c=Pt(e.headers,t.size,n);if(c.kind==="unsatisfiable")return It(r,t.size);if(c.kind==="whole")return pe(e,200,o,t.size,()=>t.open(null));const{range:l}=c;return o.set("Content-Range",`bytes ${l.offset}-${l.offset+l.length-1}/${t.size}`),pe(e,206,o,l.length,()=>t.open(l))},br=(e,t)=>{const r=new Uint8Array(t);let n=0;for(const i of e){if(n===t)break;const o=i.subarray(0,t-n);r.set(o,n),n+=o.byteLength}return r},Tr=(e,t,r)=>new ReadableStream({start:n=>{for(const i of e)n.enqueue(i);t&&n.close()},pull:async n=>{const{done:i,value:o}=await r.read();i?n.close():n.enqueue(o)},cancel:n=>r.cancel(n)},{highWaterMark:0}),Lt=async(e,t,r)=>{const n=e.getReader(),i=t===null?_e:Math.min(t,_e),o=t===null?i+1:i,c=[];let l=0,f=!1;try{for(;l<o;){const{done:g,value:b}=await n.read();if(g){f=!0;break}c.push(b),l+=b.byteLength}if(f&&t!==null&&l<i)throw new RangeError("[markdown-explorer] the asset ended before its declared length");const x=t===null?f:t<=_e;return{encoding:J.textEncodingOf(br(c,Math.min(l,i)),x,r),body:Tr(c,f,n)}}catch(x){throw n.cancel(x).catch(()=>{}),x}},tt=async(e,t)=>{const r=await Lt(await e.open(e.size===null?null:{offset:0,length:Math.min(e.size,_e)}),e.size,t);return r.body.cancel().catch(()=>{}),r.encoding},kr=async(e,t,r,n)=>{const i=`"${hr(t.version,n)}"`,o=new Headers(r);for(const[l,f]of Object.entries({...pr(t.name),...Fe,ETag:i}))o.set(l,f);if(Ue(e.headers.get("If-None-Match"),i))return new Response(null,{status:304,headers:o});if(t.size===0)return o.set("Content-Type",ke(J.textEncodingOf(new Uint8Array(0),!0,n))),o.set("Content-Length","0"),new Response(null,{status:200,headers:o});if(t.size!==null){o.set("Accept-Ranges","bytes");const l=Pt(e.headers,t.size,i);if(l.kind==="unsatisfiable")return It(r,t.size);if(l.kind==="partial"){const{range:f}=l;return o.set("Content-Type",ke(await tt(t,n))),o.set("Content-Range",`bytes ${f.offset}-${f.offset+f.length-1}/${t.size}`),pe(e,206,o,f.length,()=>t.open(f))}}if(e.method.toUpperCase()==="HEAD")return o.set("Content-Type",ke(await tt(t,n))),pe(e,200,o,t.size,()=>t.open(null));const c=await Lt(await t.open(null),t.size,n);return o.set("Content-Type",ke(c.encoding)),pe(e,200,o,t.size,async()=>c.body)},xr=e=>`workbook;${e}`,Sr=async(e,t,r)=>{const n=`"${xr(t.version)}"`,i=Nt(Ot,t.name),o=new Headers(r);for(const[c,l]of Object.entries({...i.headers,...Fe,ETag:n}))o.set(c,l);return Ue(e.headers.get("If-None-Match"),n)?new Response(null,{status:304,headers:o}):(o.set("Content-Type",i.contentType),pe(e,200,o,t.size,()=>t.open(null)))},Or=Object.freeze({"Cache-Control":"private, no-store","Referrer-Policy":"no-referrer"}),Rr=(e,t)=>{const r=new Headers(t);for(const[n,i]of Object.entries(Or))r.set(n,i);return r.set("Location",e),new Response(null,{status:302,headers:r})},Me=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(i=>{let o;const c=setTimeout(()=>{i(e.late),o=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),l=()=>{clearTimeout(c),clearTimeout(o)};n.then(f=>{l(),i(f)},()=>{l(),i(e.late)})})},_r=Object.freeze({error:(e,t)=>{console.error(e,t)}}),Mt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class be extends Error{reason;code;constructor(t,r={}){if(!y.isExplorerFailureReason(t))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);if(r.code!==void 0&&!y.isExplorerFailureCode(r.code))throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${JSON.stringify(r.code)}`);super(`[markdown-explorer] ${t}`,r.cause===void 0?void 0:{cause:r.cause}),this.name="ExplorerError",this.reason=t,this.code=r.code,Object.defineProperty(this,Mt,{value:!0})}}const Ar=e=>e instanceof Error&&Object.hasOwn(e,Mt)&&y.isExplorerFailureReason(e.reason),vr=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",Xe=(e,t,r)=>{try{e.error(t,r)}catch(n){console.error("[markdown-explorer] the logger threw while reporting a failure",{operation:r.operation,error:n})}},ae=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} failed`,t),Nr=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} left out an entry`,t),$e=(e,t)=>Xe(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),rt=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},V=(e,t,r,n)=>Ar(e)?y.failureOf(e.reason,e.code):(vr(e)||r.aborted||ae(n,{...t,error:e}),{reason:"failed"}),nt=2*1024*1024,ot=256*1024*1024,Pr=async(e,t)=>{const r=e.getReader(),n=new Uint8Array(t);let i=0;for(;i<t;){const{done:o,value:c}=await r.read();if(o)return n.subarray(0,i);const l=c.subarray(0,t-i);n.set(l,i),i+=l.byteLength}return r.cancel().catch(()=>{}),n},Ir=async(e,t,r)=>{if(e.size===0)return{text:"",truncated:!1};const n=e.size!==null&&e.size>t,i=e.size===null?t+1:Math.min(e.size,t),o=await Pr(await e.open(n?{offset:0,length:t}:null),i);if(e.size!==null&&o.byteLength<i)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const c=n||o.byteLength>t,l=c?o.subarray(0,t):o,f=J.decodeTextLeniently(l,!c,r);return f.includes("\0")?null:{text:f,truncated:c}},st=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},$t=(e,t)=>{st("capacity",e),t!==void 0&&st("weight budget",t.max);const r=new Map;let n=0;const i=o=>{const c=r.get(o);c!==void 0&&(r.delete(o),n-=c.weight)};return{get:o=>{const c=r.get(o);if(c!==void 0)return r.delete(o),r.set(o,c),c.value},set:(o,c)=>{i(o);const l=t===void 0?0:t.of(o,c);if(!(t!==void 0&&l>t.max)){r.set(o,{value:c,weight:l}),n+=l;for(const f of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;i(f)}}},delete:i,size:()=>r.size,weight:()=>n}},Dt=e=>Math.max(1,e-1),Lr=2147483647,it=Object.freeze({status:"aborted"}),fe=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},he=(e,t,r)=>{if(!Number.isSafeInteger(t)||t<=0||t>r)throw new RangeError(`[markdown-explorer] a worker pool's ${e} must be an integer in 1..${String(r)}; got ${String(t)}`)},Mr=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),$r=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,Dr=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:i,heapLimits:o})=>{he("size",t,Number.MAX_SAFE_INTEGER),he("deadline",r,Lr),he("jobsPerScope",n,Number.MAX_SAFE_INTEGER),he("maxQueuedJobs",i,Number.MAX_SAFE_INTEGER),he("maxOldGenerationSizeMb",o.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),he("maxYoungGenerationSizeMb",o.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const c=Object.freeze({maxOldGenerationSizeMb:o.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:o.maxYoungGenerationSizeMb}),l=new Set,f=[],x=new Map,w=new Map,g=Dt(t);let b=0;const v=(h,E)=>{const{job:M}=h;h.timer!==null&&clearTimeout(h.timer),h.timer=null,h.job=null,h.sent=!1,M!==null&&(fe(x,M.scope,-1),fe(w,M.scope,-1),M.settle(E))},j=h=>{const[E]=f.splice(h,1);E?.detach()},O=()=>{let h=-1,E=g,M=Number.POSITIVE_INFINITY;for(const[U,T]of f.entries()){const N=x.get(T.scope)??0,P=w.get(T.scope)??0;(N<E||N===E&&h>=0&&P<M)&&(h=U,E=N,M=P)}return h},R=(h,E)=>{l.has(h)&&(l.delete(h),v(h,E),h.worker.terminate().catch(()=>{}),F())},z=h=>{h.timer=setTimeout(()=>{R(h,{status:"timeout"})},r)},_=(h,E)=>h.sent?{status:"crashed",error:E}:{status:"unavailable",error:E},I=(h,E)=>{h.sent=!0,z(h);try{h.worker.postMessage({id:E.id,input:E.input})}catch(M){v(h,{status:"crashed",error:M}),h.worker.unref()}},C=()=>{const h={worker:new or.Worker(e,{resourceLimits:c}),job:null,sent:!1,timer:null,ready:!1};return h.worker.unref(),h.timer=setTimeout(()=>{R(h,{status:"unavailable",error:new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`)})},r),h.worker.on("message",E=>{if(!h.ready&&Mr(E)){h.ready=!0,h.timer!==null&&clearTimeout(h.timer),h.timer=null,h.job===null?h.worker.unref():I(h,h.job),h.job===null&&F();return}const{job:M}=h;if(M===null||!$r(E,M.id)){R(h,_(h,new Error("[markdown-explorer] a worker sent a message that answers no job")));return}v(h,{status:"done",output:E.output}),h.worker.unref(),F()}),h.worker.on("error",E=>{R(h,_(h,E))}),h.worker.on("messageerror",E=>{R(h,_(h,E))}),h.worker.on("exit",E=>{R(h,_(h,new Error(`[markdown-explorer] a worker exited with code ${String(E)}`)))}),l.add(h),h},F=()=>{for(;;){const h=O(),E=f[h];if(E===void 0)return;let M;for(const T of l)if(T.job===null){M=T;break}if(M===void 0&&l.size<t)try{M=C()}catch(T){j(h),fe(w,E.scope,-1),E.settle({status:"unavailable",error:T});continue}if(M===void 0)return;j(h),fe(x,E.scope,1);const U=M;U.job=E,U.worker.ref(),U.ready&&I(U,E)}};return{run:(h,{scope:E,signal:M})=>new Promise(U=>{if(M.aborted){U(it);return}if((w.get(E)??0)>=n){U({status:"refused",limit:"scope"});return}b+=1;const T={id:b,input:h,scope:E,settle:U,detach:()=>{}};f.push(T),fe(w,E,1),F();const N=f.indexOf(T);if(N<0)return;if(f.length>i){j(N),fe(w,E,-1),U({status:"refused",limit:"queue"});return}const P=()=>{const D=f.indexOf(T);D<0||(j(D),fe(w,E,-1),U(it))};M.addEventListener("abort",P,{once:!0}),T.detach=()=>{M.removeEventListener("abort",P)}}),workers:()=>l.size}},Ge=1024*1024,jr=3e4,zr=4*Ge,Cr=64*Ge,Hr=3,Br=2,Fr=(e,t)=>e+Dt(t)+Hr,Ur=4,Xr=32,Gr=512,Jr=64,Yr=4096,Wr=32,at=4096,Vr=4,jt=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-Jr)*Ge-t*Wr)/Yr),Kr=({maxHtmlBytes:e})=>e,Qr=({maxHtmlBytes:e})=>Vr*e,Zr=1024,qr=2147483647,en=64,tn=2**29,rn=1024*1024,nn=64,ct=Object.freeze({status:"rejected",reason:"too-large",cause:null}),De=Object.freeze({status:"rejected",reason:"failed",cause:null}),me=(e,t,r,n)=>{if(t===void 0)return r;if(typeof t!="number")throw new TypeError(`[markdown-explorer] sanitizer.${e} must be a number; got ${typeof t}`);if(!Number.isSafeInteger(t)||t<=0||t>n)throw new RangeError(`[markdown-explorer] sanitizer.${e} must be an integer in 1..${String(n)}; got ${String(t)}`);return t},on=(e,t)=>{if(e!==void 0&&(e===null||typeof e!="object"))throw new TypeError("[markdown-explorer] sanitizer must be an object of { workers, deadlineMs, maxHtmlBytes, cacheBytes, workerHeapMb, jobsPerScope, maxQueuedJobs }");const{workers:r,deadlineMs:n,maxHtmlBytes:i,cacheBytes:o,workerHeapMb:c,jobsPerScope:l,maxQueuedJobs:f}=e??{},x=me("workers",r,Br,en),w=me("jobsPerScope",l,Fr(t,x),Number.MAX_SAFE_INTEGER),g=Object.freeze({workers:x,deadlineMs:me("deadlineMs",n,jr,qr),maxHtmlBytes:me("maxHtmlBytes",i,zr,tn),cacheBytes:me("cacheBytes",o,Cr,Number.MAX_SAFE_INTEGER),workerHeapMb:me("workerHeapMb",c,Gr,rn),jobsPerScope:w,maxQueuedJobs:me("maxQueuedJobs",f,Ur*w,Number.MAX_SAFE_INTEGER)});if(g.jobsPerScope<t)throw new RangeError(`[markdown-explorer] sanitizer.jobsPerScope must be at least multiView.maxPanels (${String(t)}), because a page sends the document of every panel to the sanitizer at once for one reader; got ${String(g.jobsPerScope)}`);if(g.maxQueuedJobs<t)throw new RangeError(`[markdown-explorer] sanitizer.maxQueuedJobs must be at least multiView.maxPanels (${String(t)}), because a reader whose page finds every worker busy waits with the document of every panel; got ${String(g.maxQueuedJobs)}`);if(jt(g)<at)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(g.workerHeapMb)} MiB) must leave room for ${String(at)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(g.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return g},sn=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${ie.extname(Ie.fileURLToPath(e))}`,e);if(!ue.existsSync(Ie.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${Ie.fileURLToPath(t)}`);return t},ut=new Map,an=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=ut.get(r);return n===void 0&&(n=Dr({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:Xr}}),ut.set(r,n)),n},cn=e=>{if(e===null||typeof e!="object")return!1;const{status:t,html:r,message:n}=e;return t==="sanitized"&&typeof r=="string"||t==="too-large"||t==="error"&&typeof n=="string"},un=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",dn=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const i=Object.freeze([...e]),o=jt(r),c=Kr(r),l=Qr(r),f=$t(Zr,{max:r.cacheBytes,of:(O,R)=>2*O.length+(R.status==="sanitized"?2*R.html.length:nn)}),x=new Map,w=new Map,g=O=>{x.get(O.key)===O&&x.delete(O.key);const R=w.get(O.hash);R?.delete(O),R?.size===0&&w.delete(O.hash)},b=async(O,R,z)=>{const _=await n.run({html:O,iframeHosts:i,dataPath:t,maxNodes:o,maxAttributeChars:c,maxSanitizedChars:l},{scope:R,signal:z});if(_.status==="refused"){const C=_.limit==="scope"?`its reader already has ${String(r.jobsPerScope)} documents being sanitized or waiting`:`${String(r.maxQueuedJobs)} documents are already waiting`;return{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer refused a document: ${C}`)},lasting:!1}}if(_.status==="aborted")return{outcome:De,lasting:!1};if(_.status==="timeout")return{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer did not finish within ${String(r.deadlineMs)} ms`)},lasting:!0};if(_.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:_.error})},lasting:!1};if(_.status==="crashed"&&un(_.error))return{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer ran out of its ${String(r.workerHeapMb)} MiB worker heap`,{cause:_.error})},lasting:!0};if(_.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:_.error})},lasting:!0};const{output:I}=_;return cn(I)?I.status==="too-large"?{outcome:ct,lasting:!0}:I.status==="error"?{outcome:{status:"rejected",reason:"failed",cause:new Error(`[markdown-explorer] the HTML sanitizer failed: ${I.message}`)},lasting:!0}:I.html.length>l?{outcome:{status:"rejected",reason:"too-large",cause:new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(I.html.length)} characters exceeds its limit of ${String(l)}`)},lasting:!0}:{outcome:{status:"sanitized",html:I.html},lasting:!0}:{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome")},lasting:!0}},v=(O,R,z,_)=>{let I=()=>{};const C=new Promise(E=>{I=E}),F={hash:R,key:z,outcome:C,answer:I,controller:new AbortController,waiters:0};x.set(z,F);const h=w.get(R);return h===void 0?w.set(R,new Set([F])):h.add(F),b(O,_,F.controller.signal).catch(E=>({outcome:{status:"rejected",reason:"failed",cause:E instanceof Error?E:new Error(String(E))},lasting:!0})).then(({outcome:E,lasting:M})=>{if(g(F),F.answer(E),!M)return;const U=f.get(R),T=U??(E.status==="rejected"?{...E,cause:null}:E);U===void 0&&f.set(R,T);for(const N of w.get(R)??[])g(N),N.answer(T),N.controller.abort()}),F},j=(O,R)=>new Promise(z=>{O.waiters+=1;const _=()=>{O.waiters-=1,z(De),!(O.waiters>0)&&(g(O),O.controller.abort())};R.addEventListener("abort",_,{once:!0}),O.outcome.then(I=>{R.removeEventListener("abort",_),z(I)})});return(O,{scope:R,signal:z})=>{if(O.length>r.maxHtmlBytes||Buffer.byteLength(O,"utf8")>r.maxHtmlBytes)return Promise.resolve(ct);const _=St.createHash("sha256").update(O,"utf8").digest("base64"),I=f.get(_);if(I!==void 0)return Promise.resolve(I);if(z.aborted)return Promise.resolve(De);const C=`${_}\0${R}`,F=x.get(C);return j(F===void 0?v(O,_,C,R):F,z)}},ve=e=>({result:e,json:JSON.stringify(e)}),je=Object.freeze(ve(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),ln=e=>e.status==="ok"&&e.entries.length>0,fn=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const i=$t(t,{max:r,of:(w,g)=>2*g.tree.json.length}),o=new Map,c=new Map,l=(w,g)=>{const b=new AbortController,v={waiters:0,superseded:!1,started:!1,loadTree:g},j=c.get(w),O=(C,F)=>{const h=ve(C);return!(v.superseded||b.signal.aborted)&&ln(C)&&i.set(w,{tree:h,loadedAt:F}),h},z=(async()=>{if(j!==void 0&&await j,b.signal.aborted)return je;const C=n();return v.started=!0,O(await v.loadTree(b.signal,C),C)})().finally(()=>{o.get(w)===_&&o.delete(w)}),_={promise:z,controller:b,state:v};o.set(w,_);const I=z.then(()=>{},()=>{});return c.set(w,I),I.then(()=>{c.get(w)===I&&c.delete(w)}),_},f=(w,g,b)=>{g.state.waiters+=1;const v=()=>{g.state.waiters-=1,!(g.state.waiters>0)&&(o.get(w)===g&&o.delete(w),g.controller.abort())};return b.addEventListener("abort",v,{once:!0}),g.promise.finally(()=>{b.removeEventListener("abort",v)})},x=w=>{i.delete(w);const g=o.get(w);g?.state.started&&(g.state.superseded=!0,o.delete(w))};return{load:(w,g,b)=>{if(g.aborted)return Promise.resolve(je);const v=i.get(w);if(v!==void 0){if(n()-v.loadedAt<e)return Promise.resolve(v.tree);i.delete(w)}const j=o.get(w);return f(w,j===void 0?l(w,b):j,g)},refresh:(w,g,b)=>{if(g.aborted)return Promise.resolve(je);x(w);const v=o.get(w);return v===void 0?f(w,l(w,b),g):(v.state.loadTree=b,f(w,v,g))},forget:x}},mn=e=>({load:(t,r,n)=>n(r,e()).then(ve),refresh:(t,r,n)=>n(r,e()).then(ve),forget:()=>{}}),S=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},pn=e=>{if(e===null||typeof e!="object")return null;const{name:t,path:r}=e;return typeof t!="string"||typeof r!="string"?null:t===""?{path:r,reason:"an empty name"}:y.isAcceptableDocumentPath(r)?null:{path:r,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},hn=(e,t,r,n)=>{if(e===null)return null;if(!Array.isArray(e))throw new TypeError(`[markdown-explorer] a source's ancestors must be null or an array of folder paths; got ${typeof e}`);const i=new Set;for(const o of e){if(typeof o!="string"||!y.isAcceptableDocumentPath(o))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(r.deniesPath(o))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!n(o))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(o===t)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(i.has(o))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");i.add(o)}return Object.freeze([...i])},wn=(e,t,r,n,i)=>{const o=new Set,c=f=>{if(!Array.isArray(f))return S("a source returned entries that are not an array");const x=[];for(const w of f){const g=l(w);g!==null&&x.push(g)}return x},l=f=>{const x=pn(f);if(x!==null)return n(x),null;const w=y.entryViolation(f);if(w!==null)return S(w);const g=f;if(o.has(g))return S("a source returned entries that contain themselves");const{name:b,path:v,type:j,mimeType:O,modifiedAt:R,children:z,lazy:_}=g;if(t.deniesName(b)||t.deniesPath(v))return null;if(!i(v))return n({path:v,reason:"a path outside the source's boundary"}),null;const I={name:b,path:v,...O===void 0?{}:{mimeType:O},...R===void 0?{}:{modifiedAt:R}};if(j==="file")return{...I,type:j};if(_===!0)return r?{...I,type:j,lazy:!0,children:[]}:S("a lazy directory came from a source without a children function");if(z===void 0)return{...I,type:j};o.add(g);const C=c(z);return o.delete(g),{...I,type:j,children:C}};return c(e)},yn=/^[\x21\x23-\x7E]{1,256}$/u,zt=e=>typeof e=="string"&&yn.test(e),gn=new Set(["text","image","media","spreadsheet","file"]),En=e=>typeof e=="string"&&gn.has(e),bn=(e,t,r)=>{if(e!==null&&typeof e=="object"){const o=e,{kind:c}=o;if(En(c)){if(Object.hasOwn(o,"url"))return S(`a ${c} document carries its version, not a url`);if(typeof o.name!="string")return S("a document needs a name string");if(!zt(o.version))return S(`a ${c} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const l=t(o.version);switch(c){case"image":{const{imageType:f}=o;return y.isExplorerImageType(f)?{kind:c,name:o.name,url:l,imageType:f}:S(`unknown image type ${typeof f=="string"?JSON.stringify(f.slice(0,64)):typeof f}`)}case"file":return{kind:c,name:o.name,url:l};case"media":{const{mediaType:f}=o;return y.isExplorerMediaType(f)?{kind:c,name:o.name,url:l,mediaType:f}:S(`unknown media type ${typeof f=="string"?JSON.stringify(f.slice(0,64)):typeof f}`)}case"text":return typeof o.text!="string"||typeof o.truncated!="boolean"?S("a text document needs text and truncated"):{kind:c,name:o.name,text:o.text,truncated:o.truncated,url:l};case"spreadsheet":{const f=y.spreadsheetFieldsViolation(o);if(f!==null)return S(f);const{format:x,firstSheetText:w,edit:g}=o;return{kind:c,name:o.name,url:l,format:x,firstSheetText:w,edit:kn(g)}}}}}const n=y.documentViolation(e);if(n!==null)return S(n);const i=e;switch(i.kind){case"failure":{const{reason:o,code:c}=i.failure;return{kind:"failure",failure:y.failureOf(o,c)}}case"markdown":return i.headings.length>y.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:y.failureOf("too-large")}:(i.edit?.kind==="inline"||i.edit?.kind==="draft")&&!r?S(`a markdown document offers ${i.edit.kind} editing, but the server has no edit ports`):{kind:"unsanitized-markdown",name:i.name,html:i.htmlContent,headings:i.headings.map(({text:o,depth:c,id:l})=>({text:o,depth:c,id:l})),edit:Tn(i.edit)}}},Tn=e=>{if(e===null)return null;switch(e.kind){case"inline":return{kind:"inline"};case"draft":return{kind:"draft"};case"external":return{kind:"external",href:e.href}}},kn=e=>e===null?null:{kind:"external",href:e.href},Ne=(e,t,r)=>typeof e!="string"?S(`${r} needs a text string`):e.includes("\0")?S(`${r} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>t?S(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`):e,Ct=e=>y.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:S("a grant needs a root-relative href"),xn=(e,t)=>{if(e===null||typeof e!="object")return S("an edit source must be an object");const r=e;return r.kind==="grant"?Ct(r):r.kind==="draft"?{kind:"draft",text:Ne(r.text,t,"a draft source")}:r.kind!=="edit"?S(`an edit source's kind must be "edit", "draft" or "grant"`):y.isExplorerEditToken(r.version)?typeof r.history!="boolean"?S("an edit source needs history"):{kind:"edit",text:Ne(r.text,t,"an edit source"),version:r.version,history:r.history}:S("an edit source needs a version of 1 to 1024 characters")},Sn=(e,t)=>{if(e===null||typeof e!="object")return S("a save result must be an object");const r=e;switch(r.kind){case"grant":return Ct(r);case"saved":return y.isExplorerEditToken(r.version)?{kind:"saved",version:r.version}:S("a saved result needs a version of 1 to 1024 characters");case"conflict":return y.isExplorerEditToken(r.version)?{kind:"conflict",version:r.version,text:Ne(r.text,t,"a conflict's current text")}:S("a conflict needs the current version of 1 to 1024 characters");default:return S(`a save result's kind must be "saved", "conflict" or "grant"`)}},On=e=>{if(e===null||typeof e!="object")return S("a preview must be an object");const{htmlContent:t,headings:r}=e;if(typeof t!="string"||!Array.isArray(r))return S("a preview needs htmlContent and headings");if(r.length>y.EXPLORER_MAX_HEADINGS)return{kind:"failure",failure:y.failureOf("too-large")};for(const n of r){const i=y.headingViolation(n);if(i!==null)return S(i)}return{html:t,headings:r.map(({text:n,depth:i,id:o})=>({text:n,depth:i,id:o}))}},Rn=e=>{if(!Array.isArray(e))return S("revisions must be an array");const t=new Set;return e.map(r=>{const n=y.revisionViolation(r);if(n!==null)return S(n);const{id:i,modifiedAt:o,size:c,author:l,kept:f,current:x}=r;return t.has(i)?S(`two revisions share the id ${JSON.stringify(i.slice(0,64))}`):(t.add(i),{id:i,modifiedAt:o,size:c,author:l,kept:f,current:x})})},_n=(e,t)=>Ne(e,t,"a revision"),He=e=>{if(e===null||typeof e!="object")return S("an asset file must be an object");const{name:t,contentType:r,size:n,version:i,open:o,kind:c}=e;return c!==void 0?S(c==="redirect"?"an asset redirect answers only a request for the stored file (options.delivery file), never one that reads the bytes":'an asset file has no kind (the only kind is "redirect")'):typeof t!="string"||t===""?S("an asset file needs a non-empty name"):typeof r!="string"?S("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?S("an asset file's size must be null or a non-negative safe integer"):zt(i)?typeof o!="function"?S("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:i,open:o}):S(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},An=e=>{if(e===null||typeof e!="object"||e.kind!=="redirect")return He(e);const{url:t}=e;if(typeof t!="string"||!URL.canParse(t))return S("an asset redirect needs an absolute https URL");const r=new URL(t);return r.protocol!=="https:"||r.username!==""||r.password!==""?S("an asset redirect's URL must be https and carry no credentials"):Object.freeze({kind:"redirect",url:r.href})},vn=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return S("a notice must be an object");const{id:r,tone:n,title:i,body:o,action:c}=t;if(typeof r!="string"||r===""||typeof i!="string")return S("a notice needs an id and a title");if(!y.isExplorerNoticeTone(n))return S(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(o!==void 0&&typeof o!="string")return S("a notice body must be a string");const f={id:r,tone:n,title:i,...o===void 0?{}:{body:o}};if(c===void 0)return f;if(c===null||typeof c!="object")return S("a notice action must be an object");const{label:x,href:w}=c;return typeof x!="string"||!y.isAcceptableUrl(w,y.EXPLORER_LINK_PROTOCOLS)?S("a notice action needs a label and an http(s), mailto or relative href"):{...f,action:{label:x,href:w}}}):S("notices must be an array"),Nn=4e3,Se=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),dt=32,Ht="private, no-store",Pn=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":Ht,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),In=22,Ln=2147483647,ze=Object.freeze([]),Mn=Object.freeze({status:"ok",source:null,ancestors:null}),lt=Object.freeze(["contains","confirm"]),ft=Object.freeze({readOnly:!1}),$n=Object.freeze({readOnly:!0}),ee=(e,t,r)=>{if(!(r&&t===void 0)&&typeof t!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`)},ye=(e,t,r)=>{if(typeof t!="number")throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${typeof t}`);if(!Number.isSafeInteger(t)||t<=0||t>r)throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(r)}; got ${String(t)}`);return t},Dn=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return J.revalidateExplorerConfig(e)},mt=e=>{try{return new Headers(e)}catch{throw new TypeError("[markdown-explorer] authenticate returned headers that are not a valid headers init (their values are not logged)")}},pt=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,jn=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<dt)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(dt)} characters; got ${String(e.length)}`);return e},zn=(e,t)=>{if(!J.isPlainObject(t))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const r of Object.keys(t))if(!lt.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${lt.join(", ")}`);ee(`${e}.boundary.contains`,t.contains,!1),ee(`${e}.boundary.confirm`,t.confirm,!0)},Cn=e=>{if(!Array.isArray(e))throw new TypeError("[markdown-explorer] sources must be an array");const t=e;if(t.length===0)throw new RangeError("[markdown-explorer] sources must hold at least one source");const r=new Set;for(const[n,i]of t.entries()){if(i===null||typeof i!="object")throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);const{id:o,label:c,boundary:l,tree:f,children:x,ancestors:w,cacheScope:g}=i;if(!J.isExplorerSourceId(o))throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof o=="string"?JSON.stringify(o):typeof o}`);const b=`source ${JSON.stringify(o)}`;if(r.has(o))throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(o)} repeats at sources[${String(n)}]`);if(r.add(o),typeof c!="string"&&typeof c!="function")throw new TypeError(`[markdown-explorer] ${b}.label must be a string or a function`);if(typeof c=="string"&&c.trim()==="")throw new RangeError(`[markdown-explorer] ${b}.label must not be blank`);if(zn(b,l),ee(`${b}.tree`,f,!1),ee(`${b}.children`,x,!0),ee(`${b}.ancestors`,w,!0),g!==void 0&&g!=="principal"&&g!=="shared")throw new RangeError(`[markdown-explorer] ${b}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(g)}`)}return t},Hn=e=>{if(e===!1)return!1;if(e===void 0)return Se;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] treeCache must be { ttlMs, maxEntries, maxBytes } or false");const{ttlMs:t,maxEntries:r,maxBytes:n}=e;return{ttlMs:t===void 0?Se.ttlMs:ye("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?Se.maxEntries:ye("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?Se.maxBytes:ye("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},ht=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] authenticate must resolve to { status, ... }");const{status:t}=e;if(t!=="signed-in"&&t!=="signed-out"&&t!=="forbidden")throw new TypeError(`[markdown-explorer] authenticate resolved to an unknown status ${JSON.stringify(t)}`);return e},wt=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},yt=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return St.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,In)},Bn=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],de=(e,t)=>{const r=e.getAll(t),[n]=r;return r.length===1&&n!==void 0&&n!==""?n:null},q=(e,t,r,n={})=>{const i=new Headers(r);for(const[o,c]of Object.entries({...Pn,...n}))i.set(o,c);return new Response(t,{status:e,headers:i})},$=(e,t,r)=>q(y.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),Fn=new Set(["refresh","save","preview"]),Un=new Set(["edit","save","preview","revisions","revision"]),gt=(e,t)=>{const r=Fn.has(t)?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:q(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},Et=e=>e.headers.get(y.EXPLORER_PROOF_HEADER)===y.EXPLORER_REFRESH_PROOF&&Ae.crossOriginRefusal(e,Ae.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Xn=e=>e.headers.get(y.EXPLORER_PROOF_HEADER)===y.EXPLORER_EDIT_PROOF&&Ae.crossOriginRefusal(e,Ae.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Gn=async(e,t)=>{const[r,...n]=(e.headers.get("Content-Type")??"").split(";").map(b=>b.trim().toLowerCase()),i=n.find(b=>b.startsWith("charset="));if(r!==y.EXPLORER_DRAFT_MEDIA_TYPE||i!==void 0&&i!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const o=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(o)&&o>t)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const c=e.body.getReader(),l=[];let f=0;for(;;){const{done:b,value:v}=await c.read();if(b)break;if(f+=v.byteLength,f>t)return await c.cancel(),{status:"error",failure:{reason:"too-large"}};l.push(v)}const x=new Uint8Array(f);let w=0;for(const b of l)x.set(b,w),w+=b.byteLength;let g;try{g=new TextDecoder("utf-8",{fatal:!0}).decode(x)}catch{return{status:"error",failure:{reason:"invalid"}}}return g.includes("\0")?{status:"error",failure:{reason:"invalid"}}:{status:"ok",text:g}},Jn=e=>{if(e===void 0)return;if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] edit must be an object of the editor's ports");const t=e;for(const r of["source","save","preview","revisions","revision"])ee(`edit.${r}`,t[r],!1);return e},Yn=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,i=r===void 0?[e,t]:[e,t,r];for(const o of i)for(const[c,l]of o)c!=="set-cookie"&&n.set(c,l);return n},Wn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=Dn(e.config),r=jn(e.scopeSecret);ee("authenticate",e.authenticate,!1),ee("principalKey",e.principalKey,!1),ee("document",e.document,!1),ee("asset",e.asset,!1),ee("signedOutPage",e.signedOutPage,!1),ee("forbiddenPage",e.forbiddenPage,!0),ee("notices",e.notices,!0),ee("onTreeRefreshed",e.onTreeRefreshed,!0);const n=Cn(e.sources),i=J.withExplorerSources(t,n.map(s=>s.id)),o=e.logger;if(o!==void 0&&(o===null||typeof o!="object"||typeof o.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const c=e.logger===void 0?_r:e.logger,l=y.resolvePathRules(e.deny),f=e.deferredTimeoutMs===void 0?Nn:ye("deferredTimeoutMs",e.deferredTimeoutMs,Ln),x=e.textMaxBytes===void 0?nt:ye("textMaxBytes",e.textMaxBytes,ot),w=Jn(e.edit);if(w===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const g=e.editMaxBytes===void 0?nt:ye("editMaxBytes",e.editMaxBytes,ot),b=Hn(e.treeCache),v=()=>Date.now(),j=b===!1?mn(v):fn({...b,now:v}),O=on(e.sanitizer,t.multiView.maxPanels),R=dn({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:O,pool:an(sn(),O)}),z=new Map(n.map(s=>[s.id,s])),_=J.documentStyleNames(t),{authenticate:I,principalKey:C,signedOutPage:F,forbiddenPage:h,onTreeRefreshed:E}=e,M=(s,u)=>{if(typeof s.label=="string")return s.label;const a=s.label(u);if(typeof a!="string"||a.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(s.id)} must be a non-blank string`);return a},U=(s,u)=>s.cacheScope==="shared"?s.id:`${s.id}\0${u}`,T=(s,u)=>{const a=m=>ae(c,{operation:"boundary",sourceId:s.id,path:u,error:m});let d;try{d=s.boundary.contains(u)}catch(m){return a(m),!1}return typeof d=="boolean"?d:(rt(d,a),a(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(s.id)} must return a boolean; got ${typeof d}`)),!1)},N=async(s,u,a)=>{const{confirm:d}=s.boundary;if(d===void 0)return{status:"inside",readPath:a};let m;try{m=await d(u,a)}catch(X){return{status:"error",failure:V(X,{operation:"boundary",sourceId:s.id,path:a},u.signal,c)}}const p=X=>(ae(c,{operation:"boundary",sourceId:s.id,path:a,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} ${X}`)}),{status:"outside"});if(m===null||typeof m!="object")return p(`must resolve to { inside, readPath? }; got ${m===null?"null":typeof m}`);const{inside:k,readPath:A}=m;return k===!1?{status:"outside"}:k!==!0||typeof A!="string"?p("must resolve to { inside: false } or { inside: true, readPath: string }"):!y.isAcceptableDocumentPath(A)||l.deniesPath(A)?(ae(c,{operation:"boundary",sourceId:s.id,path:a,error:new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} answered a readPath the explorer does not serve (unacceptable or denied)`)}),{status:"error",failure:{reason:"failed"}}):{status:"inside",readPath:A}},P=async(s,u)=>{const a=n.filter(m=>T(m,u));if(a.length===0)return{status:"error",failure:{reason:"forbidden"}};if(a.some(m=>m.boundary.confirm===void 0))return{status:"inside",readPath:u};let d=null;for(const m of a){const p=await N(m,s,u);if(p.status==="inside")return p;p.status==="error"&&d===null&&(d=p.failure)}return{status:"error",failure:d===null?{reason:"forbidden"}:d}},D=(s,u,a)=>{const d=({path:m,reason:p})=>Nr(c,{operation:a.operation,sourceId:a.sourceId,path:m,error:new TypeError(`[markdown-explorer] an entry with ${p} was left out`)});try{return{status:"ok",entries:wn(s,l,u.children!==void 0,d,m=>T(u,m))}}catch(m){return ae(c,{...a,error:m}),{status:"error",failure:{reason:"failed"}}}},G=async(s,u,a)=>{let d;try{d=await s.tree(u)}catch(p){return{status:"error",failure:V(p,{operation:"tree",sourceId:s.id},u.signal,c)}}const m=D(d,s,{operation:"tree",sourceId:s.id});return m.status==="ok"?{status:"ok",entries:m.entries,loadedAt:a}:m},W=(s,u,a,d)=>(m,p)=>G(s,{principal:u,request:a,signal:m,refresh:d},p),L=(s,u,a,d,m)=>j.load(U(s,a),m,W(s,u,d,!1)),K=(s,u,a,d)=>j.refresh(U(s,a),d.signal,W(s,u,d,!0)),Q=(s,u)=>{if(E===void 0)return;const a=d=>ae(c,{operation:"refresh",sourceId:s.id,error:d});try{rt(E(u),a)}catch(d){a(d)}},Y=async(s,u,a,d)=>{if(l.deniesPath(d)||!T(s,d))return{status:"error",failure:{reason:"forbidden"}};const m=await N(s,a,d);if(m.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(m.status==="error")return{status:"error",failure:m.failure};let p;try{p=await u(a,d,m.readPath)}catch(k){return{status:"error",failure:V(k,{operation:"children",sourceId:s.id,path:d},a.signal,c)}}return D(p,s,{operation:"children",sourceId:s.id,path:d})},ce=async(s,u,a,d)=>{const m=await N(s,a,d);if(m.status==="outside")return{status:"ok",ancestors:null};if(m.status==="error")return{status:"error",failure:m.failure};let p;try{p=await u(a,d,m.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(k){return{status:"error",failure:V(k,{operation:"ancestors",sourceId:s.id,path:d},a.signal,c)}}if(Array.isArray(p)&&p.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:hn(p,d,l,k=>T(s,k))}}catch(k){return ae(c,{operation:"ancestors",sourceId:s.id,path:d,error:k}),{status:"error",failure:{reason:"failed"}}}},H=async(s,u,a,d)=>l.deniesPath(d)?{status:"error",failure:{reason:"forbidden"}}:T(s,d)?ce(s,u,a,d):{status:"ok",ancestors:null},re=async(s,u,a)=>{if(l.deniesPath(a))return{status:"error",failure:{reason:"forbidden"}};for(const d of[s,...n.filter(m=>m!==s)]){if(u.signal.aborted)break;const m=d.ancestors;if(m===void 0||!T(d,a))continue;const p=await ce(d,m,u,a);if(p.status==="ok"&&p.ancestors!==null)return{status:"ok",source:d.id,ancestors:p.ancestors}}return Mn},te=async(s,u,a)=>{if(l.deniesPath(a))return y.failureDocument("forbidden");const d=await P(s,a);if(d.status==="error")return{kind:"failure",failure:d.failure};let m;try{m=await e.document(s,a,d.readPath)}catch(A){return{kind:"failure",failure:V(A,{operation:"document",path:a},s.signal,c)}}let p;try{p=bn(m,A=>y.explorerAssetHref(t.dataPath,a,A),w!==void 0)}catch(A){return ae(c,{operation:"document",path:a,error:A}),y.failureDocument("failed")}if(p.kind!=="unsanitized-markdown")return p;const k=await R(p.html,{scope:u,signal:s.signal});return k.status==="sanitized"?{kind:"markdown",name:p.name,htmlContent:k.html,headings:p.headings,edit:p.edit}:(k.cause!==null&&ae(c,{operation:"document",path:a,error:k.cause}),y.failureDocument(k.reason))},ne=async s=>{if(e.notices===void 0)return ze;try{return vn(await e.notices(s))}catch(u){return V(u,{operation:"notices"},s.signal,c),ze}},le=async(s,u,a)=>{const d=de(u,y.EXPLORER_DATA_QUERY.path);if(d===null||!y.isAcceptableDocumentPath(d))return $({reason:"invalid"},a);const m=y.readExplorerAssetDisplay(u);if(m===null)return $({reason:"invalid"},a);if(l.deniesPath(d))return $e(c,{operation:"asset",path:d}),$({reason:"forbidden"},a);const p=await P(s,d);if(p.status==="error")return $(p.failure,a);try{const k=await e.asset(s,d,p.readPath,{delivery:m}),A=m==="file"?An(k):He(k);return"kind"in A?Rr(A.url,a):m==="text"?await kr(s.request,A,a,t.legacyTextEncoding):m==="workbook"?await Sr(s.request,A,a):await Er(s.request,A,a)}catch(k){return $(V(k,{operation:"asset",path:d},s.signal,c),a)}},Te=async(s,u)=>{if(l.deniesPath(u))return $e(c,{operation:"text",path:u}),y.failureDocument("forbidden");const a=await P(s,u);if(a.status==="error")return{kind:"failure",failure:a.failure};try{const d=He(await e.asset(s,u,a.readPath,{delivery:"text"})),m=await Ir(d,x,t.legacyTextEncoding);return m===null?y.failureDocument("unsupported"):{kind:"text",name:d.name,text:m.text,truncated:m.truncated,url:y.explorerAssetHref(t.dataPath,u,d.version)}}catch(d){return{kind:"failure",failure:V(d,{operation:"text",path:u},s.signal,c)}}},ge=async(s,u,a)=>l.deniesPath(a)?($e(c,{operation:u,path:a}),{status:"error",failure:{reason:"forbidden"}}):P(s,a),Yt=async(s,u,a)=>{const d=await ge(u,"edit",a);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return xn(await s.source(u,a,d.readPath),g)}catch(m){return{kind:"failure",failure:V(m,{operation:"edit",path:a},u.signal,c)}}},Wt=async(s,u,a,d,m)=>{const p=await ge(u,"save",a);if(p.status==="error")return{kind:"failure",failure:p.failure};try{return Sn(await s.save(u,a,p.readPath,{text:m,baseVersion:d}),g)}catch(k){return{kind:"failure",failure:V(k,{operation:"save",path:a},u.signal,c)}}},Vt=async(s,u,a,d,m)=>{const p=await ge(u,"preview",d);if(p.status==="error")return{kind:"failure",failure:p.failure};let k;try{k=On(await s.preview(u,d,p.readPath,m))}catch(X){return{kind:"failure",failure:V(X,{operation:"preview",path:d},u.signal,c)}}if("kind"in k)return k.kind==="failure"?k:y.failureDocument("failed");const A=await R(k.html,{scope:a,signal:u.signal});return A.status==="sanitized"?{kind:"preview",htmlContent:A.html,headings:k.headings}:(A.cause!==null&&ae(c,{operation:"preview",path:d,error:A.cause}),y.failureDocument(A.reason))},Kt=async(s,u,a)=>{const d=await ge(u,"revisions",a);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return{kind:"revisions",revisions:Rn(await s.revisions(u,a,d.readPath))}}catch(m){return{kind:"failure",failure:V(m,{operation:"revisions",path:a},u.signal,c)}}},Qt=async(s,u,a,d)=>{const m=await ge(u,"revision",a);if(m.status==="error")return{kind:"failure",failure:m.failure};try{return{kind:"revision",id:d,text:_n(await s.revision(u,a,m.readPath,d),g)}}catch(p){return{kind:"failure",failure:V(p,{operation:"revision",path:a},u.signal,c)}}},Zt=async(s,u,a,d,m,p)=>{const k=de(m,y.EXPLORER_DATA_QUERY.path);if(k===null||!y.isAcceptableDocumentPath(k))return $({reason:"invalid"},p);if(u==="edit")return q(200,JSON.stringify(await Yt(s,a,k)),p);if(u==="revisions")return q(200,JSON.stringify(await Kt(s,a,k)),p);if(u==="revision"){const oe=de(m,y.EXPLORER_DATA_QUERY.revision);return y.isExplorerEditToken(oe)?q(200,JSON.stringify(await Qt(s,a,k,oe)),p):$({reason:"invalid"},p)}const A=de(m,y.EXPLORER_DATA_QUERY.base);if(u==="save"&&!y.isExplorerEditToken(A))return $({reason:"invalid"},p);const X=await Gn(a.request,g);return X.status==="error"?$(X.failure,p):u==="preview"?q(200,JSON.stringify(await Vt(s,a,d,k,X.text)),p):q(200,JSON.stringify(await Wt(s,a,k,A,X.text)),p)},qt=async({request:s,url:u,params:a})=>{const d=ht(await I(s,ft)),m=mt(d.headers);if(m.set("Cache-Control",Ht),d.status==="signed-out")throw wt("signedOutPage",F(s,m));if(d.status==="forbidden")throw h===void 0?Pe.data(null,{status:403,headers:m}):wt("forbiddenPage",h(s,m));const p=J.resolveExplorerLocation(i,a["*"],u.searchParams);if(p.kind==="redirect")throw Pe.redirect(p.href,{headers:m});const{location:k}=p,{principal:A}=d,X=yt(r,C(A)),oe=z.get(k.source);if(oe===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(k.source)}`);const Ee={signal:s.signal,timeoutMs:f,late:null,handOverMs:f},se={scope:X,sources:n.map(B=>({id:B.id,label:M(B,A)})),settings:J.parseViewSettings(J.readCookieValue(s.headers.get("Cookie"),t.settingsCookie),_),tree:k.view==="single"?null:{sourceId:k.source,result:Me(Ee,B=>L(oe,A,X,s,B).then(Z=>Z.result))},documents:Bn(k).map(B=>({path:B,document:Me(Ee,Z=>te({principal:A,request:s,signal:Z,refresh:!1},X,B))})),notices:Me({signal:s.signal,timeoutMs:f,late:ze,handOverMs:0},B=>ne({principal:A,request:s,signal:B,refresh:!1}))};return Pe.data(se,{headers:m})},Je=async(s,u)=>{const a=ht(await I(s,u));return{authentication:a,headers:mt(a.headers)}},er=async(s,u,a)=>{let d;try{d=await Je(u,ft)}catch(Z){return $(V(pt(Z),{operation:"authenticate"},u.signal,c))}const{authentication:m,headers:p}=d;if(m.status==="signed-out")return $({reason:"unauthorized"},p);if(m.status==="forbidden")return $({reason:"forbidden"},p);const{principal:k}=m;if(s==="asset")return le({principal:k,request:u,signal:u.signal,refresh:!1},a,p);const A=yt(r,C(k));p.set(y.EXPLORER_SCOPE_HEADER,A);const X={principal:k,request:u,signal:u.signal,refresh:!1},oe=()=>$({reason:"invalid"},p);if(s==="document"){const Z=de(a,y.EXPLORER_DATA_QUERY.path);if(Z===null||!y.isAcceptableDocumentPath(Z))return oe();const Ve=u.headers.has(y.EXPLORER_PROOF_HEADER);return Ve&&!Et(u)?$({reason:"forbidden"},p):q(200,JSON.stringify(await te({...X,refresh:Ve},A,Z)),p)}if(s==="text"){const Z=de(a,y.EXPLORER_DATA_QUERY.path);return Z===null||!y.isAcceptableDocumentPath(Z)?oe():q(200,JSON.stringify(await Te(X,Z)),p)}if(s==="edit"||s==="save"||s==="preview"||s==="revisions"||s==="revision")return w===void 0?$({reason:"not-found"},p):Zt(w,s,X,A,a,p);const Ee=de(a,y.EXPLORER_DATA_QUERY.source),se=de(a,y.EXPLORER_DATA_QUERY.path);if(Ee===null||(s==="children"||s==="ancestors"||s==="reveal")&&(se===null||!y.isAcceptableDocumentPath(se)))return oe();const B=z.get(Ee);if(B===void 0)return $({reason:"not-found"},p);if(s==="tree")return q(200,(await L(B,k,A,u,u.signal)).json,p);if(s==="refresh"){const Z=await K(B,k,A,u);return u.signal.aborted||Q(B,U(B,A)),q(200,Z.json,p)}return s==="ancestors"?B.ancestors===void 0||se===null?$({reason:"not-found"},p):q(200,JSON.stringify(await H(B,B.ancestors,X,se)),p):s==="reveal"?se===null?oe():q(200,JSON.stringify(await re(B,X,se)),p):B.children===void 0||se===null?$({reason:"not-found"},p):q(200,JSON.stringify(await Y(B,B.children,X,se)),p)},tr=async s=>{const{authentication:u,headers:a}=await Je(s,$n);if(!a.keys().next().done)throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");return u.status==="signed-in"},Ye=t.embeds.linkCardEndpoint===null?null:nr.createLinkCardHandler({authorize:tr}),rr=async(s,u)=>{try{return await s(u)}catch(a){return $(V(pt(a),{operation:"authenticate"},u.signal,c))}},We=async(s,u,a)=>{if(new URL(s.url).pathname.endsWith(".data"))return $({reason:"not-found"});if(!y.isExplorerDataOperation(a))return $({reason:"not-found"});if(a==="link-card"){if(Ye===null)return $({reason:"not-found"});const m=gt(s,a);return m!==null?m:rr(Ye,s)}if(Un.has(a)&&w===void 0)return $({reason:"not-found"});const d=gt(s,a);if(d!==null)return d;if(a==="refresh"&&!Et(s))return $({reason:"forbidden"});if((a==="save"||a==="preview")&&!Xn(s))return $({reason:"forbidden"});try{return await er(a,s,u.searchParams)}catch(m){return $(V(m,{operation:a},s.signal,c))}};return Object.freeze({loader:qt,headers:Yn,dataLoader:({request:s,url:u,params:a})=>We(s,u,a["*"]),dataAction:({request:s,url:u,params:a})=>We(s,u,a["*"]),forgetTree:s=>{if(typeof s!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof s}`);j.forget(s)}})},Oe=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),Vn=new Set(["md","markdown","mdx"]),bt="image/svg+xml",Bt=new Map([...[["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"],["svg",bt],["webp","image/webp"],["ico","image/x-icon"],["bmp","image/bmp"],["tif","image/tiff"],["tiff","image/tiff"],["avif","image/avif"]].map(([e,t])=>[e,{kind:"image",imageType:t===bt?"svg":"raster",contentType:t}]),...[["mp4","video/mp4"],["m4v","video/mp4"],["webm","video/webm"],["mov","video/quicktime"],["avi","video/x-msvideo"],["mkv","video/x-matroska"],["ogv","video/ogg"]].map(([e,t])=>[e,{kind:"media",mediaType:"video",contentType:t}]),...[["mp3","audio/mpeg"],["wav","audio/wav"],["ogg","audio/ogg"],["oga","audio/ogg"],["opus","audio/ogg"],["m4a","audio/mp4"],["flac","audio/flac"],["aac","audio/aac"],["wma","audio/x-ms-wma"]].map(([e,t])=>[e,{kind:"media",mediaType:"audio",contentType:t}]),["pdf",{kind:"media",mediaType:"pdf",contentType:"application/pdf"}]]),Kn=new Map([["csv","csv"],["tsv","tsv"],["tab","tsv"],["xlsx","workbook"],["xlsm","workbook"],["ods","workbook"]]),Qn=new Set(["txt","text","log","json","jsonc","json5","ndjson","yaml","yml","toml","ini","cfg","conf","properties","xml","xsl","xsd","dtd","html","htm","xhtml","css","scss","sass","less","styl","js","mjs","cjs","jsx","ts","mts","cts","tsx","vue","svelte","astro","py","pyi","rb","go","rs","java","kt","kts","scala","groovy","gradle","c","h","cc","cpp","cxx","hpp","hh","hxx","cs","fs","vb","swift","m","mm","php","pl","pm","r","jl","lua","dart","ex","exs","erl","hrl","hs","ml","mli","clj","cljs","elm","nim","zig","v","sol","tf","hcl","nix","sh","bash","zsh","fish","ps1","psm1","bat","cmd","sql","graphql","gql","proto","thrift","avsc","rst","adoc","asciidoc","tex","bib","org","textile","diff","patch","srt","vtt","ics","vcf","gitignore","gitattributes","editorconfig","dockerignore","npmignore","prettierrc","eslintrc","babelrc","mailmap"]),Zn=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),Ft=typeof ue.constants.O_NOFOLLOW=="number"?ue.constants.O_NOFOLLOW:0,Ut=typeof ue.constants.O_NONBLOCK=="number"?ue.constants.O_NONBLOCK:0,Tt=e=>`${e.size}-${e.mtimeNs}`,qn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),kt=e=>y.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(qn),Xt=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},eo=e=>{const t=Xt(e);if(Vn.has(t))return{kind:"markdown"};const r=Bt.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image",imageType:r.imageType}:{kind:"media",mediaType:r.mediaType};const n=Kn.get(t);if(n!==void 0)return{kind:"spreadsheet",format:n};const i=e.toLowerCase();return Qn.has(t)||!i.includes(".")&&Zn.has(i)?{kind:"text"}:{kind:"file"}},Be=e=>{switch(typeof e=="object"&&e!==null?e.code:void 0){case"ENOENT":case"ENOTDIR":return"not-found";case"ELOOP":case"EACCES":case"EPERM":return"forbidden";case"ENAMETOOLONG":return"invalid";case"EISDIR":return"unsupported";default:return null}},Gt=e=>{const t=Be(e);return t===null?e:new be(t)},Jt=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},to=async e=>{try{return Math.trunc((await we.lstat(e)).mtimeMs)}catch(t){if(Jt(t))return;throw t}},xt=async(e,t)=>{const r=[];for await(const n of e.createReadStream({start:0,end:t-1,autoClose:!1}))r.push(n);return Buffer.concat(r)},ro=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},no=async(e,t,r,n)=>{let i;try{i=await we.open(e,ue.constants.O_RDONLY|Ft|Ut);const f=await i.stat({bigint:!0});if(!f.isFile()||f.ino!==t.ino||f.dev!==t.dev||f.size!==t.size||f.mtimeNs!==t.mtimeNs)throw new be("not-found")}catch(f){throw await i?.close(),Gt(f)}const o=i.createReadStream(ro(r,t.size)),c=sr.Readable.toWeb(o),l=()=>{o.destroy(n.reason)};return n.aborted?l():n.addEventListener("abort",l,{once:!0}),c},oo=(e,t)=>{const r=J.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},so=e=>{let t=0;const r=[];return async n=>{t<e?t+=1:await new Promise(i=>r.push(i));try{return await n()}finally{const i=r.shift();i===void 0?t-=1:i()}}},io=(e,t)=>{if(e.isSymbolicLink())return"symbolic-link";if(!(e.isDirectory()||e.isFile()))return"special-file";const{name:r}=e;return r!==r.normalize("NFC")?"not-nfc":r.includes(":")?"colon":r.endsWith(".")||r.endsWith(" ")?"trailing-dot-or-space":y.isAcceptableDocumentPath(r)?y.isAcceptableDocumentPath(t)?null:"path-too-long":"control-character-or-backslash"},ao=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","legacyTextEncoding","walkConcurrency","cacheScope","reportSkipped"]),Re=(e,t,r)=>{if(t===void 0)return r;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] ${e} must be a positive integer; got ${String(t)}`);return t},co=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");for(const T of Object.keys(e))if(!ao.has(T))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(T)}`);const{id:t,label:r,root:n,parse:i}=e;if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-empty id");if(typeof r!="string"||r.trim()==="")throw new TypeError("[markdown-explorer] a file-system source needs a non-blank label");if(typeof i!="function")throw new TypeError("[markdown-explorer] a file-system source needs a parse function");if(typeof n!="string"||!ie.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let o;try{o=ue.statSync(n).isDirectory()}catch(T){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:T})}if(!o)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const c=ue.realpathSync(n),l=e.pathPrefix;if(typeof l!="string")throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');if(l!==""&&!(l.endsWith("/")&&kt(l.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(l)}`);const f=y.resolvePathRules(e.deny),x=Re("maxEntries",e.maxEntries,Oe.maxEntries),w=Re("maxDocumentBytes",e.maxDocumentBytes,Oe.maxDocumentBytes),g=Re("textPreviewBytes",e.textPreviewBytes,Oe.textPreviewBytes),b=e.legacyTextEncoding;if(b!=null&&typeof b!="string")throw new TypeError("[markdown-explorer] legacyTextEncoding must be a string or null");const v=typeof b=="string"?J.legacyTextEncodingOf(b):null,j=Re("walkConcurrency",e.walkConcurrency,Oe.walkConcurrency),O=e.cacheScope===void 0?"principal":e.cacheScope;if(O!=="principal"&&O!=="shared")throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(O)}`);const R=e.reportSkipped;if(R!==void 0&&typeof R!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const z=R===void 0?T=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(T.sourceId)} does not list ${JSON.stringify(T.path)}: ${T.reason}`)}:R,_=new Set,I=T=>{const N=ie.resolve(c,...T.split("/")),P=ie.relative(c,N);return P===""||P===".."||P.startsWith(`..${ie.sep}`)||ie.isAbsolute(P)?null:N},C=(T,N)=>{const P=`${N}\0${T}`;_.has(P)||_.size>=x||(_.add(P),z({sourceId:t,path:T,reason:N}))},F=async({signal:T})=>{T.throwIfAborted();const N=new AbortController,P=()=>{N.abort(T.reason)};T.addEventListener("abort",P,{once:!0});const D=so(j);let G=0;const W=async(L,K)=>{const Q=await D(async()=>{N.signal.throwIfAborted();try{return await we.readdir(L,{withFileTypes:!0})}catch(H){if(K===""||!Jt(H))throw H;return null}});if(N.signal.throwIfAborted(),Q===null)return C(`${l}${K}`,"unreadable-directory"),null;const Y=[];for(const H of Q){if(f.deniesName(H.name))continue;const re=K===""?H.name:`${K}/${H.name}`,te=`${l}${re}`,ne=io(H,te);if(ne!==null){C(te,ne);continue}Y.push({dirent:H,relativePath:re,path:te})}if(G+=Y.length,G>x)throw new be("too-large");return Y.sort((H,re)=>oo(H.dirent.name,re.dirent.name)),(await Promise.all(Y.map(async({dirent:H,relativePath:re,path:te})=>{const ne=await to(ie.join(L,H.name)),le=ne===void 0?{}:{modifiedAt:ne};if(!H.isDirectory())return{name:H.name,path:te,type:"file",...le};const Te=await W(ie.join(L,H.name),re);return Te===null?null:{name:H.name,path:te,type:"directory",...le,children:Te}}))).filter(H=>H!==null)};try{const L=await W(c,"");if(L===null)throw new Error("[markdown-explorer] the source's root could not be listed");return L}catch(L){throw N.abort(),L}finally{T.removeEventListener("abort",P)}},h=async T=>{if(!T.startsWith(l))return{status:"refused",reason:"not-found"};const N=T.slice(l.length);if(!kt(N))return{status:"refused",reason:"invalid"};if(f.deniesPath(N))return{status:"refused",reason:"forbidden"};const P=I(N);if(P===null)return{status:"refused",reason:"forbidden"};const D=await we.lstat(P,{bigint:!0});if(D.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!D.isFile())return{status:"refused",reason:"unsupported"};const G=await we.realpath(P);return G!==P||f.deniesPath(ie.relative(c,G).split(ie.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:P,name:N.slice(N.lastIndexOf("/")+1),stats:D}},E=async(T,N,P)=>{let D;try{const G=await h(P);if(G.status==="refused")return y.failureDocument(G.reason);const{target:W,name:L,stats:K}=G,Q=eo(L),Y=Tt(K);if(Q.kind==="image")return{kind:"image",name:L,imageType:Q.imageType,version:Y};if(Q.kind==="media")return{kind:"media",name:L,mediaType:Q.mediaType,version:Y};if(Q.kind==="spreadsheet")return{kind:"spreadsheet",name:L,format:Q.format,firstSheetText:null,edit:null,version:Y};if(Q.kind==="file")return{kind:"file",name:L,version:Y};D=await we.open(W,ue.constants.O_RDONLY|Ft|Ut);const ce=await D.stat({bigint:!0});if(!ce.isFile()||ce.ino!==K.ino||ce.dev!==K.dev)return y.failureDocument("forbidden");if(Q.kind==="markdown"){if(ce.size>BigInt(w))return y.failureDocument("too-large");const ne=await xt(D,w+1);if(ne.length>w)return y.failureDocument("too-large");const le=await i(J.decodeTextLeniently(ne,!0,v),N);return{kind:"markdown",name:L,htmlContent:le.htmlContent,headings:le.headings,edit:null}}const H=await xt(D,g),re=ce.size>BigInt(g),te=J.decodeTextLeniently(H,!re,v);return te.includes("\0")?{kind:"file",name:L,version:Y}:{kind:"text",name:L,text:te,truncated:re,version:Y}}catch(G){const W=Be(G);if(W===null)throw G;return y.failureDocument(W)}finally{await D?.close()}},M=async(T,N,P)=>{let D;try{D=await h(P)}catch(Y){throw Gt(Y)}if(D.status==="refused")throw new be(D.reason);const{target:G,name:W,stats:L}=D,K=Bt.get(Xt(W)),Q=K===void 0?"":K.contentType;return{name:W,contentType:Q,size:Number(L.size),version:Tt(L),open:Y=>no(G,L,Y,T.signal)}},U=async(T,N,P)=>{let D;try{D=await h(P)}catch(L){if(Be(L)!==null)return null;throw L}if(D.status==="refused")return null;const G=P.slice(l.length).split("/");if(G.some(L=>f.deniesName(L)))return null;const W=G.slice(0,-1);return W.map((L,K)=>`${l}${W.slice(0,K+1).join("/")}`)};return Object.freeze({id:t,label:r,cacheScope:O,boundary:Object.freeze({contains:T=>T.startsWith(l)}),tree:F,ancestors:U,document:E,asset:M})};exports.DEFAULT_DENIED_PATH_SEGMENTS=y.DEFAULT_DENIED_PATH_SEGMENTS;exports.MAX_DOCUMENT_PATH_LENGTH=y.MAX_DOCUMENT_PATH_LENGTH;exports.isAcceptableDocumentPath=y.isAcceptableDocumentPath;exports.isDeniedPath=y.isDeniedPath;exports.decodeText=J.decodeText;exports.decodeTextLeniently=J.decodeTextLeniently;exports.legacyTextEncodingOf=J.legacyTextEncodingOf;exports.ExplorerError=be;exports.anonymousAccess=ir;exports.createFileSystemSource=co;exports.createMarkdownExplorer=Wn;
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { b as Nt, c as hr, f as ve, g as yr, h as gr, s as Er, j as br, k as Tr, l as kr, E as It, m as Ee, r as xr, n as Sr, i as re, o as Or, p as Rr, q as vr, t as Pt, u as _r, v as Ar, w as Be, x as Nr, y as Ir, z as Pr, A as ce, B as ee, e as Ke, C as Mr, D as $r } from "./dataRoute-DLhQfdoW.js";
2
2
  import { F as xs, M as Ss, G as Os } from "./dataRoute-DLhQfdoW.js";
3
- import { t as Mt, f as ze, w as Lr, g as jr, r as zr, i as Cr, h as Dr, p as Hr, j as Br, k as Fr, l as Ur, N as Xr } from "./location-CKuabtKl.js";
4
- import { m as vs } from "./location-CKuabtKl.js";
3
+ import { t as Mt, f as ze, w as Lr, g as jr, r as zr, i as Cr, h as Dr, p as Hr, j as Br, k as Fr, l as Ur, N as Xr } from "./location-perTmwct.js";
4
+ import { m as vs } from "./location-perTmwct.js";
5
5
  import { createHash as Jr, createHmac as Gr } from "node:crypto";
6
6
  import { createLinkCardHandler as Wr } from "@aiquants/markdown/server";
7
7
  import { crossOriginRefusal as $t, NO_CROSS_ORIGIN_NAVIGATION as Lt } from "@aiquants/request-isolation";
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("@aiquants/virtualscroll"),e=require("./index-DgaTEKsI.cjs"),L=Object.freeze({renderVisual:C.tapScrollCircleSampleVisual,...e.TAP_SCROLL_CIRCLE_SPEED_RANGE,size:e.TAP_SCROLL_CIRCLE_SIZE,offsetX:e.TAP_SCROLL_CIRCLE_OFFSET_X}),_=Object.freeze({enabled:!1});exports.NO_TAP_SCROLL_CIRCLE=_;exports.TAP_SCROLL_CIRCLE=L;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("@aiquants/virtualscroll"),e=require("./index-DSkK8iLE.cjs"),L=Object.freeze({renderVisual:C.tapScrollCircleSampleVisual,...e.TAP_SCROLL_CIRCLE_SPEED_RANGE,size:e.TAP_SCROLL_CIRCLE_SIZE,offsetX:e.TAP_SCROLL_CIRCLE_OFFSET_X}),_=Object.freeze({enabled:!1});exports.NO_TAP_SCROLL_CIRCLE=_;exports.TAP_SCROLL_CIRCLE=L;
@@ -1,5 +1,5 @@
1
1
  import { tapScrollCircleSampleVisual as e } from "@aiquants/virtualscroll";
2
- import { T as C, c as _, d as L } from "./index-auQVKY4M.js";
2
+ import { T as C, c as _, d as L } from "./index-CcXMPCRS.js";
3
3
  const s = Object.freeze({
4
4
  renderVisual: e,
5
5
  ...L,
@@ -1,5 +1,5 @@
1
1
  import { useSyncExternalStore as d, useRef as c, useLayoutEffect as E, useCallback as a, useEffect as S, useMemo as h } from "react";
2
- import { S as y } from "./location-CKuabtKl.js";
2
+ import { S as y } from "./location-perTmwct.js";
3
3
  const m = "(pointer: coarse)", C = (e) => {
4
4
  const t = window.matchMedia(m);
5
5
  return t.addEventListener("change", e), () => t.removeEventListener("change", e);
@@ -1 +1 @@
1
- "use strict";const e=require("react"),d=require("./location-l_HysaZR.cjs"),f="(pointer: coarse)",E=r=>{const n=window.matchMedia(f);return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},S=()=>window.matchMedia(f).matches,m=()=>!1,C=()=>e.useSyncExternalStore(E,S,m),R=r=>{const n=e.useRef(r);e.useLayoutEffect(()=>{n.current=r},[r]);const c=e.useRef(null),t=e.useRef(null),s=e.useRef(!1),u=e.useCallback(()=>{t.current!==null&&clearTimeout(t.current),t.current=setTimeout(()=>{t.current=null,c.current!==null&&n.current(c.current)},d.SPLIT_PERSIST_DELAY_MS)},[]);e.useEffect(()=>()=>{t.current!==null&&clearTimeout(t.current)},[]);const a=e.useCallback((o,l)=>{c.current=o,l.source==="keyboard"?u():l.source==="pointer"&&(s.current=!0)},[u]),i=e.useCallback(o=>{if(o){s.current=!1;return}s.current&&(s.current=!1,u())},[u]);return e.useMemo(()=>({layoutChanged:a,draggingChanged:i}),[a,i])};exports.useCoarsePointer=C;exports.useSplitPersistence=R;
1
+ "use strict";const e=require("react"),d=require("./location-BxiJRTyw.cjs"),f="(pointer: coarse)",E=r=>{const n=window.matchMedia(f);return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},S=()=>window.matchMedia(f).matches,m=()=>!1,C=()=>e.useSyncExternalStore(E,S,m),R=r=>{const n=e.useRef(r);e.useLayoutEffect(()=>{n.current=r},[r]);const c=e.useRef(null),t=e.useRef(null),s=e.useRef(!1),u=e.useCallback(()=>{t.current!==null&&clearTimeout(t.current),t.current=setTimeout(()=>{t.current=null,c.current!==null&&n.current(c.current)},d.SPLIT_PERSIST_DELAY_MS)},[]);e.useEffect(()=>()=>{t.current!==null&&clearTimeout(t.current)},[]);const a=e.useCallback((o,l)=>{c.current=o,l.source==="keyboard"?u():l.source==="pointer"&&(s.current=!0)},[u]),i=e.useCallback(o=>{if(o){s.current=!1;return}s.current&&(s.current=!1,u())},[u]);return e.useMemo(()=>({layoutChanged:a,draggingChanged:i}),[a,i])};exports.useCoarsePointer=C;exports.useSplitPersistence=R;
@@ -76,9 +76,11 @@ Documents in the multi-panel view sit in `multiView.columns` logical columns (4
76
76
  - **Hysteresis.** A width hovering at a threshold does not flip the count: it grows only once one more column fits with a margin of g/φ (A ≥ (n + 1)m + ng + g/φ) and shrinks only once the current count no longer fits (A < nm + (n − 1)g). The count is frozen while a panel is maximized and while the reader drags the explorer's handle.
77
77
  - **Projection.** When fewer columns are visible than exist, visible column i shows the logical columns ⌊iN/n⌋ to ⌊(i + 1)N/n⌋ − 1, stacked in order. Reading order is kept, and the original arrangement returns unchanged as soon as the width allows.
78
78
  - **Rearranging while projected.** When the reader drags or moves panels while fewer columns are visible, the new arrangement is mapped back onto the logical columns by dynamic programming: the cut points inside each visible column are chosen so that the largest number of panels keeps its previous logical column (the earliest cuts win a tie). Rearranging is idempotent: applying the arrangement that is already shown changes nothing.
79
- - **Moving without a drag.** Each panel's header (drawn by `@aiquants/drag-drop-panels`) has a move menu: its button, Move the panel (`panelMove`), opens a menu of the moves the stage offers. On a stage that shows two or more columns they are four — Move to the previous column, Move to the next column, Move up and Move down (`panelMovePreviousColumn`, `panelMoveNextColumn`, `panelMoveUp`, `panelMoveDown`); on a stage that shows one column (a phone, a narrow window), where no panel can change column, only Move up and Move down.
79
+ - **Moving without a drag.** Each panel's header (drawn by `@aiquants/drag-drop-panels`) has a move menu: its button, Move the panel (`panelMove`), opens a menu of the moves the stage offers (on a header too narrow for every button, the moves are the first items of the header's overflow menu instead, see Panel headers).
80
+ On a stage that shows two or more columns they are four — Move to the previous column, Move to the next column, Move up and Move down (`panelMovePreviousColumn`, `panelMoveNextColumn`, `panelMoveUp`, `panelMoveDown`); on a stage that shows one column (a phone, a narrow window), where no panel can change column, only Move up and Move down.
80
81
  A move that is impossible from where the panel sits stays in the menu as `aria-disabled`, focusable, and choosing it moves nothing and announces that the panel cannot make it (`panelMoveUnavailable`). A click, Enter or Space opens the menu on its first item (ArrowDown on the first, ArrowUp on the last); ArrowDown and ArrowUp go through the items (wrapping around), Home and End to the ends, Enter, Space or a click chooses, Escape closes the menu with the focus back on its button, and Tab closes it and goes on from the button.
81
82
  The menu opens in the top layer through the Popover API, so in a browser without that API it does not open and the shortcuts below move the panel.
83
+ It opens below its button, or above it when it fits only there; on a viewport too low for it on either side (a phone in landscape), it opens on the side with more room, held to that room, and its items scroll inside it.
82
84
  The header's buttons show while the panel is hovered or one of them holds the focus, and always on a device that cannot hover (touch), so panels move with them on a touch screen as well.
83
85
  The same moves are keyboard shortcuts while the focus is in the panel: Alt + Shift + ← / → / ↑ / ↓ (Alt + ← / → alone stay the browser's Back / Forward). A held chord moves once, and the shortcuts are ignored in text inputs and editable content, with Ctrl or ⌘, while a panel is maximized and during a drag. A move to another visible column keeps the panel's position among that column's shown panels (its end when the column has fewer); up and down swap the panel with the neighbouring shown panel, and hidden panels keep their place.
84
86
  The layout computes a move on the visible columns the stage shows and reports it as their next arrangement; the stage maps it back like a drop, which refreshes the column memory, and the layout then shows exactly the arrangement it asked for, so it announces the move from its own live region (`panelMoved`).
@@ -93,7 +95,7 @@ Documents in the multi-panel view sit in `multiView.columns` logical columns (4
93
95
  - **Document refresh in a panel.** `@aiquants/drag-drop-panels` draws the panel's header and takes no content of the explorer's into it, so a panel's Refresh document (see [Busy and unavailable controls](#busy-and-unavailable-controls)) sits in a thin bar that is the first row of the panel's body, inside its scroll area, at the bar's inline end.
94
96
  The bar is pinned to the top of the scroll area (sticky, on the panel's surface) while the document scrolls under it, so the reader reaches the button from anywhere in the document — with a pointer or with Tab — without the panel scrolling, and the refresh keeps the place they were reading.
95
97
  The frame measures the bar, a failure notice it shows included, and the document's elements add its block size to their block-start scroll margin, so a fragment's target and a focused element land below the bar, never under it (a scroll padding on the area would count the bar's own button as covered, and focusing it would scroll the panel); the reading position a rebuilt panel brings back is taken below the bar. It keeps a focus ring's extent around the button, so the button's ring is drawn whole inside the scroll area.
96
- The panel's height bounds count the bar with the header, so the body's floor of three lines of text lies below it. A double-click on the button is two presses and never maximizes the panel; a double-click elsewhere on the body still does.
98
+ The panel's height bounds count the bar with the header, so the body's floor of three lines of text lies below it. A double-click on the button is two presses and never maximizes the panel; a double-click elsewhere on the body still does, except inside a block of the document shown full screen, which is the block's own (see the viewer's full screen below).
97
99
  - **Stage spacing.** The stage keeps 21 px above and below its columns and 13 px at the sides, and 13 px between columns (Fibonacci, in rem: `--aqmx-space-7` and `--aqmx-space-6`), set through drag-drop-panels' neutral properties (`--aqdd-stage-padding-block`, `--aqdd-stage-padding-inline`, `--aqdd-column-gap`), which the stage binds to the explorer's tokens. The column plan reads the actual gap and padding, so it always matches what is drawn.
98
100
  - **Reading position.** When the column count changes, every panel is rebuilt at its new width; the element that was at the top of what the reader saw of a panel (below the document bar the panel pins) is brought back to the same place, so the reader keeps their line even though the text wraps differently: an element that crossed that top keeps the same share of its height above it, since the rewrap makes it taller or shorter, and one that started below it keeps its distance.
99
101
  Every change of the panel's width puts the reader's place back at the new width — a rebuilt panel only gets its new width after the rebuild, and the explorer's handle resizes the columns live — overriding the browser's own re-anchoring of the rewrapped text, which keeps a distance rather than a share.
@@ -103,10 +105,14 @@ Documents in the multi-panel view sit in `multiView.columns` logical columns (4
103
105
  The frame that receives the focus in the multi view's hand-offs (closing or hiding a panel, opening documents in panels, and the fallback above) is a `group` named after the panel's document, so a screen reader names the document; the document region inside stays the panel's only landmark.
104
106
  Rebuilding a panel requests nothing: its document is reused as it is. A panel that follows a link starts the new document at its top (or at the link's fragment), and brings that start into the stage's view with the panel when the stage had scrolled the panel's header out of it (see [The document region](#the-document-region)); a remembered position is only ever restored into the document it was taken in.
105
107
  - **Panel headers.** A panel's header (drawn by `@aiquants/drag-drop-panels` and named in the explorer's language, see [Localization](localization.md)) holds the panel's title and, after it, the custom drag mode's badge and at most five buttons: the move menu (see Moving without a drag; absent while the panel is maximized), the drag-mode toggle, Hide (absent while the panel is maximized), Maximize or Restore, and Close.
106
- On a device without any fine pointer (a touch-only phone or tablet, `not (any-pointer: fine)`) the toggle of a panel in the normal mode is not shown: touch and pen drag a panel by a long-press on its header in both modes, so there it could only stop the panel's text selection; a panel in the custom mode keeps it, so the reader can return to the normal mode, and a toggle that held the focus when it went away passes it to the header's next shown button (Hide, or Restore while the panel is maximized). The header has one or more lines.
107
- Every button, and every item of the move menu, is a target of at least 44 × 44 px under every pointer (WCAG 2.2 enhanced target size); rows of buttons that wrap sit 22 px apart, and Close keeps 22 px from every other button however they wrap.
108
- The header keeps every button wholly inside the panel at any width and text size, a phone width with 200 % text included, and keeps the title readable. On a device that can hover (a mouse or a touchpad, whatever the primary pointer), where the buttons show while the pointer is over the panel or one of them holds the focus, the badge and the buttons sit beside the title, and when the title would get less than the width of a few characters (5em) there they wrap to the next line of the header, at its end, and the title takes the whole first line.
109
- On a device that cannot hover (`(hover: none)`, a phone or a tablet), where the buttons always show, they take a line of their own below the title (the badge a line of its own above them), so the title keeps the header's whole width. A title longer than its line is cut with an ellipsis.
108
+ When the header's row has no room for all of them, the leading ones move, in that order and as few as let the row fit, into an overflow menu whose button, More actions (`panelMoreActions`), leads the row. The menu lists them in groups in header order — the moves (while it holds the move menu), then the toggle, Hide and Maximize or Restore, then Close in a group of its own — under the same keys and placement as the move menu, each item named as the button it stands for, and choosing one acts as that button does, the focus included.
109
+ On a device without any fine pointer (a touch-only phone or tablet, `not (any-pointer: fine)`) the toggle of a panel in the normal mode is not shown: touch and pen drag a panel by a long-press on its header in both modes, so there it could only stop the panel's text selection; a panel in the custom mode keeps it, so the reader can return to the normal mode, and a toggle that held the focus when it went away passes it to the header's next shown button (Hide, or Restore while the panel is maximized).
110
+ A toggle that is not shown is not an item of the overflow menu either. The header has one or more lines.
111
+ Every button, and every item of the move and overflow menus, is a target of at least 44 × 44 px under every pointer (WCAG 2.2 enhanced target size).
112
+ Close keeps 22 px from every other button and from every other item of the overflow menu, and rows of buttons that wrap (only while the layout has not measured the header, such as in a server render) sit 22 px apart.
113
+ The header keeps every button wholly inside the panel at any width and text size, a phone width with 200 % text included, and keeps the title readable.
114
+ On a device that can hover (a mouse or a touchpad, whatever the primary pointer), where the buttons show while the pointer is over the panel or one of them holds the focus, the badge and the buttons sit beside the title on one line: rather than leave the title less than the width of a few characters (5em), the leading buttons move into the overflow menu, and only when even the overflow button alone has no room there do the badge and the button wrap to the next line of the header, at its end, the title taking the whole first line.
115
+ On a device that cannot hover (`(hover: none)`, a phone or a tablet), where the buttons always show, they take a line of their own below the title (the badge a line of its own above them), so the title keeps the header's whole width, and the leading buttons move into the overflow menu when that line is narrower than the buttons. A title longer than its line is cut with an ellipsis.
110
116
  The stage binds the header's colours to the explorer's tokens through drag-drop-panels' neutral properties, so they follow `theme` rather than a host's `dark` class: the panel's surface, border and title are `--aqmx-surface`, `--aqmx-border` and `--aqmx-text`; the icons are `--aqmx-text-muted` (`--aqmx-text` over `--aqmx-surface-sunken` on hover); the badge and the pressed custom-mode toggle are `--aqmx-warning-text` on `--aqmx-warning-surface` — at least 3:1 for the icons and 7:1 for the title and the badge in both colour schemes.
111
117
  The bar of hidden panels, an empty column's notice and a hidden panel's stand-in during a drag take the same surface, border and text.
112
118
  The bar's restore buttons are `--aqmx-surface` on `--aqmx-accent` (`--aqmx-info-text` while hovered), and the drop placeholders of a drag draw their text, icon and dashed border in `--aqmx-accent` on `--aqmx-surface`, the placeholder a drop would land on on `--aqmx-accent-surface` — at least 4.5:1 for that text and 3:1 for the dashed border against the stage in both colour schemes. The whole header, on one line or two, stays the panel's drag handle (a long-press outside its buttons for touch and pen), and a double-click on it outside its buttons toggles maximize.
@@ -171,6 +177,8 @@ Documents in the multi-panel view sit in `multiView.columns` logical columns (4
171
177
  The toolbar's buttons — alignment, style and table of contents — form one row in that visual and Tab order, spaced in rem, so at any text size they never overlap and each stays at least 44 × 44 CSS px under every pointer.
172
178
  The document's column fills its pane (the viewer's `[data-aqmd-content]` takes the track's full width): the explorer gives the viewer a `width` or `maxWidth` only where a single-view embed asks for one (`?width=` / `?maxWidth=`), each capped at the pane's width (`min(<value>, 100%)`, so a width wider than the pane never makes every line scroll sideways), so the alignment button, which places only a column narrower than its track, shows only there; the tree view, a single view without those parameters and a maximized panel show the style and table-of-contents buttons.
173
179
  A Mermaid gantt chart is drawn at the width of its slot (and again, after a short debounce, when a split or the window changes that width), so it keeps its natural height.
180
+ A block `@aiquants/markdown` shows full screen — a ```spreadsheets table, a Mermaid diagram or a storage SVG image alone in a paragraph, each from the full-screen toggle that ends its toolbar — becomes a modal dialog over the page, named for full screen (see [Localization](localization.md)), which no pane or panel clips, and carries `data-aqmd-fullscreen` while it is.
181
+ Everything inside it is then the block's: a double-click there neither opens the editor nor maximizes the panel behind it, the editing surface leaves its keys alone (see **Editing a Markdown document** below), and Escape leaves full screen without restoring a maximized panel.
174
182
  Where the toolbar covers the inline extent of the document's content — in the tree view and a maximized panel at every width, where the content spans the pane, and in the single view unless its `width` or `maxWidth` leaves room beside the content — the viewer reserves the depth it covers as the top padding and the `scroll-padding-block-start` of its scroll container and publishes it as `--aqmd-toolbar-block-overlap` on `[data-aqmd-scroll-container]`: the first line and every fragment's element start below the buttons. Where the toolbar covers none of the content the band is `0px`.
175
183
  An open, unpinned menu of the toolbar (the table of contents, the style or the alignment menu) closes on Escape while the focus is inside it and returns the focus to its button; the viewer marks that keydown handled (`preventDefault()`). In a panel every part of the document (failure callout, image, media) takes its content height, and an embedded PDF is 1 : √2.
176
184
  - A file header (the toolbar of an image, a medium, a text or a table file: its name, the zoom controls or Copy the text, Open in a new tab — for a text and a table file, the whole file as UTF-8 plain text, which a browser shows instead of downloading — and Download) wraps its controls onto more lines instead of letting any of them run out of the pane or the panel at a narrow width or a large text size; the name takes what the controls leave on the first line and is cut with an ellipsis.
@@ -209,7 +217,8 @@ Documents in the multi-panel view sit in `multiView.columns` logical columns (4
209
217
  The first sheet shows first, and a reading again (Refresh document, a retry, a new answer) shows the sheet the reader chose, found by its name, or the first when the workbook no longer has it. Each sheet is read when first shown (its placeholder `spreadsheetSheetLoading` meanwhile) and kept for the workbook read, so going back shows it at once; its table is named after the file and the sheet (`spreadsheetSheetName(name, sheet)`), a sheet without data shows `spreadsheetSheetEmpty`, and a sheet the reader cannot read its note with the download.
210
218
  Notes above the tabs count the sheets left out (`spreadsheetUnshownSheets`) and say how many are listed when the workbook has more than the reader lists (`spreadsheetUnlistedSheets`). A workbook the reader refuses shows its note with the download in place of the tabs: `spreadsheetWorkbookEncrypted`, `spreadsheetNotWorkbook` (a legacy `.xls` included) or `spreadsheetWorkbookTooLarge`.
211
219
  When the document names its first sheet as text (`firstSheetText`, `csv` or `tsv`: a storage that converts the file on read, such as a Google Sheets spreadsheet) and the delivery brings no workbook package within the budget — the storage's own text when it could not convert the workbook — or one the reader refuses, the view reads that text (`as=text`) instead and shows it as a table file's table, below the note `spreadsheetWorkbookFirstSheet`.
212
- - **Source of an SVG image inside a document.** In a rendered Markdown document — a page view's pane, a panel and the editor's preview alike — every storage SVG image that stands alone in a paragraph (as `@aiquants/markdown`'s viewer picks them: an image the converter wrote with `data-asset-src`, not inside a link or beside text) has a toolbar above it at the row's end (`viewerSvgImageToolbar`) holding Copy (`viewerSvgImageCopy`) and then the Source toggle (`viewerSvgImageSource`, `aria-pressed`), which swaps the image for its SVG as written and back, keeping the focus on the toggle.
220
+ - **Source of an SVG image inside a document.** In a rendered Markdown document — a page view's pane, a panel and the editor's preview alike — every storage SVG image that stands alone in a paragraph (as `@aiquants/markdown`'s viewer picks them: an image the converter wrote with `data-asset-src`, not inside a link or beside text) has a toolbar above it at the row's end (`viewerSvgImageToolbar`) holding Copy (`viewerSvgImageCopy`), the Source toggle (`viewerSvgImageSource`, `aria-pressed`), which swaps the image for its SVG as written and back, keeping the focus on the toggle,
221
+ and last the full-screen toggle (`viewerSvgImageFullscreen`, `viewerSvgImageExitFullscreen` while full screen), which shows the block — its toolbar, the image or its SVG, and its notice — full screen, in a dialog named after the image (`viewerSvgImageFullscreenDialog`), and back.
213
222
  The explorer reads the SVG through the same `text` operation as a document's source, only while the source shows or when Copy is pressed on the image (a read the reader leaves is aborted), so it is refused and admitted exactly as the image itself; the block shows a loading line (`viewerSvgImageLoading`), the text named after the image (`viewerSvgImageSourceRegion`), the note `viewerSvgImageTruncated` under a file cut at `textMaxBytes`,
214
223
  and a failure (`viewerSvgImageFailed`) with Try again (`viewerSvgImageRetry`) for a `failed` read. Copy shows while the image shows, where it reads the file and copies the image as a PNG that pastes as an image (`viewerSvgImageCopyImage`, its outcome `viewerSvgImageCopiedImage` or `viewerSvgImageCopyImageFailed`), and while the whole file shows, where it copies the SVG as written (`viewerSvgImageCopy`, its outcome `viewerSvgImageCopied` or `viewerSvgImageCopyFailed`); a file cut at `textMaxBytes` is never copied.
215
224
  The choice is the block's own and is not part of the URL: a reload or another document shows the image, while a render that keeps the image's paragraph (a revalidation, the preview's next draft) keeps the choice. A double-click inside the shown SVG selects its text: it never opens the editor of a document the reader may edit, as a double-click on the document's words does (see **Editing a Markdown document** below).
@@ -218,8 +227,9 @@ Documents in the multi-panel view sit in `multiView.columns` logical columns (4
218
227
  Alone, both sit in the grid's one cell: the hidden pane is invisible and inert but keeps its layout and its scroll position, kept in step by the scroll sync below, so switching only changes which pane shows and the block at the top of the view stays the same, by the next frame. The preview is mounted once it was shown or the reader leaned toward it (pointing at or focusing the Preview choice), and keeps rendering while hidden.
219
228
  A panel that is not maximized offers the editor and the preview, one at a time: the hidden pane leaves the layout, and switching puts the next pane at the same place on screen, as opening and closing the editor do (the preview's block at the editor's top line, the editor's text at the preview's top block).
220
229
  Ctrl+E (⌘E on Apple's platforms, where Ctrl+E stays the editor's move to the line's end) switches between the editor and the preview from the editor, the preview or the view switch — from side by side, to the preview alone — and moves the focus to the pane it shows (the preview's scroller, which then scrolls with the keys; the editor at its cursor), or to the switch's checked choice when pressed there. The preview's scroller is a Tab stop and takes the focus on a click, so after a click in the preview the keys scroll it and Ctrl+E reaches it.
221
- A ```spreadsheets table shown full screen keeps its keys: Ctrl+E does nothing behind it, and Escape leaves full screen (the editing goes on).
222
- A double-click on a word of the preview shown alone opens the editor with the cursor on that word, at the same place on screen, except inside an editable table (every table with source lines in the preview) or a table shown full screen, where a double-click edits a cell; a read-only table of the rendered document opens the editor like any other block. Where the bar is narrower than the width from which the side-by-side surface has two columns (a phone; see [The editor's split](#the-editors-split)), the view switch drops its words and keeps its 44 px targets.
230
+ A block shown full screen (a ```spreadsheets table, a Mermaid diagram or an SVG image) keeps its keys: Ctrl+E does nothing behind it, and Escape leaves full screen (the editing goes on).
231
+ A double-click on a word of the preview shown alone opens the editor with the cursor on that word, at the same place on screen, except inside an editable table (every table with source lines in the preview), where a double-click edits a cell, and inside a block shown full screen, where it is the block's (an editable table's edits a cell); a read-only table of the rendered document opens the editor like any other block unless it is shown full screen.
232
+ Where the bar is narrower than the width from which the side-by-side surface has two columns (a phone; see [The editor's split](#the-editors-split)), the view switch drops its words and keeps its 44 px targets.
223
233
  A draft session (a document edited without saving) has the same surface and view switch; its bar shows the draft's status without Save or History.
224
234
  Places on screen are kept through the converter's source lines, text matched to text (the top of a word's or a block's first glyphs, since the rendered prose and the editor have different line heights): Edit puts the block at the top of the reader's view, and a double-click the word, exactly where it was; closing puts the editor's top line — the first non-empty one in view — back at the same place in the rendered document, and again on the fresh copy a save made the pane read, unless the reader scrolled, pressed a key or a pointer meanwhile;
225
235
  the editor and the preview scroll together, both ways, through a map of the blocks that carry source lines: the top of a block's first line goes with the top of its box and the bottom of its last line with the bottom of its box, positions in between are linear, both tops go together and both bottoms together, and a block whose place differs between the source and the rendering (a footnote, rendered at the end) is left out, so either pane moves continuously and on whenever the other does, crossing a block taller on its side faster.
@@ -9,16 +9,16 @@ This page is part of the host-facing contract of `@aiquants/markdown-explorer`;
9
9
  - The explorer passes its document-viewer strings to `@aiquants/markdown`, which names every control and status text of the viewer with them, so the viewer follows the same language:
10
10
  its status texts (`viewerLoading`, `viewerErrorPrefix`, `viewerErrorTitle`, `viewerMissingImage`, and `viewerBlockFailed`, the notice in place of a block that cannot render), its toolbar's buttons (`viewerSelectAlign`, `viewerSelectStyle`, `viewerOpenToc`), the alignment and style menus (`viewerAlignTitle`, `viewerAlignLeft`, `viewerAlignCenter`, `viewerAlignRight`, `viewerPinAlign`, `viewerUnpinAlign`, `viewerStyleTitle`, `viewerPinStyle`, `viewerUnpinStyle`), the table of contents (`viewerTocTitle`, which also names its navigation, `viewerPinToc`, `viewerUnpinToc`)
11
11
  and every Mermaid diagram's controls (`viewerMermaidInteractionMode` for the mouse-interaction menu and its button, `viewerMermaidModeNone`, `viewerMermaidModeZoom`, `viewerMermaidModePan`, `viewerMermaidModePanShift`, `viewerMermaidModeBoth`, `viewerMermaidModeBothShift` for its modes, `viewerMermaidInteractionModeTouch` for the same menu and button under a coarse pointer, `viewerMermaidModeNoneTouch`, `viewerMermaidModeZoomTouch`, `viewerMermaidModePanTouch`, `viewerMermaidModeBothTouch` for its touch items, `viewerMermaidZoomIn`, `viewerMermaidZoomOut`, `viewerMermaidResetView`,
12
- `viewerMermaidPanUp`, `viewerMermaidPanDown`, `viewerMermaidPanLeft`, `viewerMermaidPanRight` for the buttons that move the view while the drawing overflows its frame, `viewerMermaidRetry`, and `viewerMermaidDiagram`, the name of the diagram's focusable frame),
12
+ `viewerMermaidPanUp`, `viewerMermaidPanDown`, `viewerMermaidPanLeft`, `viewerMermaidPanRight` for the buttons that move the view while the drawing overflows its frame, `viewerMermaidRetry`, `viewerMermaidDiagram`, the name of the diagram's focusable frame, and `viewerMermaidFullscreen`, `viewerMermaidExitFullscreen` and `viewerMermaidFullscreenDialog` for the full-screen toggle, the same toggle while the diagram is shown full screen, and the full-screen dialog's name),
13
13
  the toolbar of a storage SVG image that stands alone in a paragraph (`viewerSvgImageToolbar` naming the toolbar, `viewerSvgImageSource` its Source toggle, `viewerSvgImageSourceRegion` the shown SVG, `viewerSvgImageLoading`, `viewerSvgImageFailed` and `viewerSvgImageRetry` while it is read, `viewerSvgImageTruncated` under a file cut at `textMaxBytes`, `viewerSvgImageCopy`, `viewerSvgImageCopied` and `viewerSvgImageCopyFailed` for its Copy button and its outcomes while the source shows, and `viewerSvgImageCopyImage`,
14
- `viewerSvgImageCopiedImage` and `viewerSvgImageCopyImageFailed` for its Copy button and its outcomes while the image shows)
14
+ `viewerSvgImageCopiedImage` and `viewerSvgImageCopyImageFailed` for its Copy button and its outcomes while the image shows, and `viewerSvgImageFullscreen`, `viewerSvgImageExitFullscreen` and `viewerSvgImageFullscreenDialog` for its full-screen toggle, the same toggle while the image is shown full screen, and the full-screen dialog's name)
15
15
  and the titles of embedded frames (`viewerEmbeddedVideo` and `viewerEmbeddedPost` after a provider's name, as in "YouTube: embedded video", and `viewerEmbeddedFrame` before the host of an iframe written in a document without a title).
16
16
  A label the viewer receives carries no `lang` of its own, so it is read in the page's language.
17
17
  - Every ```spreadsheets table's labels are `@aiquants/markdown`'s own, derived rather than copied: each label of its table block (`SPREADSHEET_BLOCK_LABEL_CATALOGS` of `@aiquants/markdown/code-blocks`, see its README) is a key prefixed with `viewerSpreadsheet` (`zoomIn` → `viewerSpreadsheetZoomIn`, `cellAnnouncement` → `viewerSpreadsheetCellAnnouncement`), its built-in text is the block's catalog of the UI language, and its placeholders are the block's (`SPREADSHEET_BLOCK_LABEL_PLACEHOLDERS`).
18
18
  The explorer passes the viewer only the table labels a host replaced, so every other one keeps the block's text marked with the block's language, and the grid takes `locale` as its own locale, which picks the language of its own catalog, its data-validation messages and its scroll bar.
19
19
  A label added to the block becomes a key of the explorer with it. Where the viewer's own built-in label is in a catalog's language, the catalog repeats it word for word (the English catalog the viewer's English labels, such as `Display Style` and `Zoom In`; the Japanese catalog its Japanese ones, such as `目次を開く`), writing a full-width form in half-width (`拡大縮小+移動 (左ドラッグ)` for the viewer's `拡大縮小+移動 (左ドラッグ)`).
20
20
  - The explorer passes `treeEntryKindDirectory` and `treeEntryKindFile` (the kind words in the rows' accessible names) and `treeScrollUp`, `treeScrollDown`, `treeScrollToTop` and `treeScrollToBottom` (the tree's scroll bar) to `@aiquants/directory-tree`.
21
- - The explorer passes every string the multi view's drag-and-drop layout shows to `@aiquants/drag-drop-panels`: the panel headers' buttons (`panelMove`, `panelSwitchToCustomDrag`, `panelSwitchToNormalDrag`, `panelHide`, `panelMaximize`, `panelRestore`, `panelClose`), the items of their move menus (`panelMovePreviousColumn`, `panelMoveNextColumn`, `panelMoveUp`, `panelMoveDown`) and the custom drag mode's badge (`panelCustomDragBadge`),
21
+ - The explorer passes every string the multi view's drag-and-drop layout shows to `@aiquants/drag-drop-panels`: the panel headers' buttons (`panelMoreActions` for the overflow button, `panelMove`, `panelSwitchToCustomDrag`, `panelSwitchToNormalDrag`, `panelHide`, `panelMaximize`, `panelRestore`, `panelClose`), the items of their move menus (`panelMovePreviousColumn`, `panelMoveNextColumn`, `panelMoveUp`, `panelMoveDown`; the items of the overflow menu keep the names of the moves and the buttons they stand for) and the custom drag mode's badge (`panelCustomDragBadge`),
22
22
  the move announcements (`panelMoved`, `panelMoveUnavailable`), a touch or pen drag's lift and cancel announcements (`panelDragStarted`, `panelDragCancelled`), the bar of hidden panels (`hiddenPanelsTitle`)
23
23
  , a hidden panel's stand-in while a panel is dragged (`hiddenPanelBadge`, `hiddenPanelNotice`), the drop placeholders (`panelDropHere`), an empty column's text (`multiColumnEmpty`) and the name of each column's region (`multiColumnRegion`).
24
24
  The stage never lets the reader resize its columns, so the layout renders no column resize handle and the catalog has no key for that handle's name. A label the layout receives carries no `lang` of its own, so it is read in the page's language, like the explorer's other strings.
@@ -58,7 +58,7 @@ const HANDBOOK_LABELS = {
58
58
  the path's last segment and the failure's title — the text of the matching `failure…Title` label, not the reason's code), `imageZoomLevel(percent)`, `treeRefreshFailed(reason)`, `documentRefreshed(name)`, `documentRefreshFailed(reason)`, `refreshDocumentNamed(name)` (a multi-view panel's icon-only Refresh document: its accessible name and tooltip, `name` being the panel title),
59
59
  `showMarkupNamed(name)` (a multi-view panel's icon-only Source toggle: its accessible name and tooltip, `name` being the panel title), `panelLimit(max)`, `panelOpened(name)`, `panelClosed(name)`, `panelAlreadyOpen(name)`, `panelHidden(name)`, `panelShown(name)`, `panelMaximized(name)`, `panelRestored(name)` — so each language can place the value where its grammar needs it.
60
60
  - The labels `@aiquants/drag-drop-panels` fills itself are templates instead, strings whose `{name}` placeholders mark where each value goes: `panelMoved` (`{title}` the panel's name, `{column}` its visible column, `{position}` its place among that column's shown panels), `panelMoveUnavailable` (`{title}`, and `{move}` the name of the move, one of the `panelMove…` labels), `panelDragStarted` and `panelDragCancelled` (`{title}`) and `multiColumnRegion` (`{column}`); columns and positions count from 1.
61
- So are the table labels `@aiquants/markdown` fills, with the block's placeholders (`viewerSpreadsheetSize` with `{rows}` and `{cols}`, `viewerSpreadsheetCellAnnouncement` with `{cell}` and `{value}`, and so on; `SPREADSHEET_BLOCK_LABEL_PLACEHOLDERS` lists them), and `viewerSvgImageSourceRegion`, whose `{name}` is the SVG image's name (its alternative text, else its file name).
61
+ So are the table labels `@aiquants/markdown` fills, with the block's placeholders (`viewerSpreadsheetSize` with `{rows}` and `{cols}`, `viewerSpreadsheetCellAnnouncement` with `{cell}` and `{value}`, and so on; `SPREADSHEET_BLOCK_LABEL_PLACEHOLDERS` lists them), and `viewerSvgImageSourceRegion` and `viewerSvgImageFullscreenDialog`, whose `{name}` is the SVG image's name (its alternative text, else its file name).
62
62
  `MARKDOWN_EXPLORER_LABEL_TEMPLATES` lists each template's placeholders, and braces in every other label are literal text.
63
63
  - `labels` must be a plain object. An unknown key throws a `RangeError` that lists the valid keys, a value of the wrong type (a string where a function is expected, or the reverse) throws a `TypeError`, and a blank string throws a `RangeError`, because a blank name is neither shown nor announced. A template that uses a placeholder its key does not offer (`{name}` for `{title}`, say) throws a `RangeError` naming the placeholders it accepts, because a placeholder that is never filled would be read out as it is. A key set to `undefined` keeps the catalog's string.
64
64
  - The overrides are compared by value, key by key: writing `labels={{ … }}` inline does not re-render the explorer on every render of the host, but a function created inline is a new value each time — hoist it, or memoize the object.