@aiquants/markdown-explorer 0.12.0 → 0.13.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.
- package/CHANGELOG.md +26 -0
- package/README.md +20 -12
- package/dist/EditSurface-DheIbHJi.js +705 -0
- package/dist/EditSurface-omuATGni.cjs +2 -0
- package/dist/{ExplorerSplit-DekOjAUZ.cjs → ExplorerSplit-DMizcKaY.cjs} +1 -1
- package/dist/{ExplorerSplit-MPHjw3nW.js → ExplorerSplit-DvcNMIjl.js} +109 -109
- package/dist/{MultiLayout-DtSW4rEQ.js → MultiLayout-C2R85L4x.js} +25 -25
- package/dist/{MultiLayout-HMzVDYWq.cjs → MultiLayout-Cq4y1I1g.cjs} +1 -1
- package/dist/{NativeScrollBar-CNQr7JY1.js → NativeScrollBar-CKfD2qpM.js} +1 -1
- package/dist/{NativeScrollBar-B0AkVF3E.cjs → NativeScrollBar-qvtXkNTx.cjs} +1 -1
- package/dist/{TreeLayout-_XQR-9tV.cjs → TreeLayout-8_V4L9s6.cjs} +1 -1
- package/dist/{TreeLayout-CJO9tOPq.js → TreeLayout-FCp9WPFO.js} +3 -3
- package/dist/core/contracts.d.cts +7 -1
- package/dist/core/contracts.d.ts +7 -1
- package/dist/core/labels.d.cts +14 -1
- package/dist/core/labels.d.ts +14 -1
- package/dist/{dataRoute-CH3yOKR0.cjs → dataRoute-BONacTPi.cjs} +1 -1
- package/dist/{dataRoute-Pm_0ue_4.js → dataRoute-CObbjNxG.js} +14 -12
- package/dist/index-CdydPdP7.js +3463 -0
- package/dist/index-afZWk187.cjs +13 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +21 -21
- package/dist/{location-BUNWJ4eB.cjs → location-D6RE3wAN.cjs} +1 -1
- package/dist/{location-DWd6SQhN.js → location-IRD9h42r.js} +1 -1
- package/dist/{merge-DDJaJmMU.js → merge-Bb7YRgn4.js} +1 -1
- package/dist/{merge-Bs7o3GyP.cjs → merge-Dm_uFthw.cjs} +1 -1
- package/dist/{sanitizePolicy-djLC3fRN.js → sanitizePolicy-DlrakwA4.js} +1 -1
- package/dist/{sanitizePolicy-BfUlXI5E.cjs → sanitizePolicy-DrIMuYCb.cjs} +1 -1
- package/dist/sanitizeWorker.cjs +1 -1
- package/dist/sanitizeWorker.js +1 -1
- package/dist/server/ports.d.cts +3 -0
- package/dist/server/ports.d.ts +3 -0
- package/dist/server.cjs +1 -1
- package/dist/server.js +93 -83
- package/dist/styles/markdown-explorer.css +1 -1
- package/docs/behavior/dom-hooks.md +6 -5
- package/docs/behavior/layout.md +12 -2
- package/package.json +1 -1
- package/dist/EditSurface-BTAhzvHi.js +0 -509
- package/dist/EditSurface-Dfj6Sxxb.cjs +0 -2
- package/dist/index-DpIVKG8Y.cjs +0 -13
- package/dist/index-o6OpR4ND.js +0 -3358
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const i=require("@aiquants/markdown/embeds"),A=require("@aiquants/markdown/source-lines"),h=require("./dataRoute-
|
|
1
|
+
"use strict";const i=require("@aiquants/markdown/embeds"),A=require("@aiquants/markdown/source-lines"),h=require("./dataRoute-BONacTPi.cjs"),w=512;class R extends RangeError{constructor(s){super(`[markdown-explorer] the HTML nests deeper than ${String(s)} levels`),this.name="HtmlNestingLimitError"}}const O=["script","style","noscript","template","form","button","textarea","select","option","object","embed","base","meta","link","frame","frameset"],D=["srcdoc","formaction"],z=/^(?:(?:https?|mailto|tel):|[^a-z]|[a-z+.-]+(?:[^a-z+.:-]|$))/iu,H=new Set(["left","right","center","justify","start","end"]),M=new Set(["h1","h2","h3","h4","h5","h6"]),T=1,U=3,B=7,C=8,k=Object.freeze({a:Object.freeze(["target","data-link-kind","data-doc-path","data-doc-exists","data-footnote-ref","data-footnote-backref"]),area:Object.freeze(["target"]),img:Object.freeze(["data-asset-src","data-asset-exists"]),section:Object.freeze(["data-footnotes"]),iframe:Object.freeze(["allow","allowfullscreen","frameborder","referrerpolicy"])}),x=[...new Set([...Object.values(k).flatMap(t=>t.filter(s=>s.startsWith("data-"))),A.SOURCE_LINES_ATTRIBUTE])],j=new Set(["src","href","xlink:href"]),F=/^data:/iu,G=Object.freeze({FORBID_TAGS:O,FORBID_ATTR:D,ADD_TAGS:["iframe"],ADD_ATTR:(t,s)=>t===A.SOURCE_LINES_ATTRIBUTE||k[s]?.includes(t)===!0,ADD_URI_SAFE_ATTR:x,ALLOWED_URI_REGEXP:z,ALLOW_DATA_ATTR:!1}),y=t=>{let s=null;for(const c of t.split(";")){const n=c.indexOf(":");if(n<0||c.slice(0,n).trim().toLowerCase()!=="text-align")continue;const d=c.slice(n+1).trim().toLowerCase();H.has(d)&&(s=d)}return s===null?null:`text-align: ${s}`},V=t=>t.nodeType===U?{kind:"text",text:t.nodeValue??""}:t.nodeType===C||t.nodeType===B?{kind:"ignored"}:t.nodeType===T&&t.nodeName.toLowerCase()==="a"?{kind:"link",href:t.getAttribute("href")}:{kind:"element"},P=t=>{const s=t.getAttribute("type");return s!==null&&s.trim().toLowerCase()==="checkbox"&&t.hasAttribute("disabled")},W=(t,s,c,n)=>{if(t.isSupported!==!0)throw new Error("[markdown-explorer] the HTML sanitizer cannot run in this environment");if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`[markdown-explorer] the HTML sanitizer's depth limit must be a positive integer; got ${String(n)}`);const d=Object.freeze([...s]);let E=new WeakMap,m=new WeakMap,f;const p=r=>{const e=r.parentNode===null?void 0:E.get(r.parentNode),a=e===void 0?0:e+1;if(E.set(r,a),r.nodeType===T&&a>n)throw new R(n)},_=(r,e)=>{if(r.nodeType!==T)return;const a=r;(e.tagName==="input"&&!P(a)||e.tagName==="iframe"&&i.allowedFrameUrlOf(a.getAttribute("src")?.trim(),d)===null)&&a.parentNode?.removeChild(a)},N=(r,e)=>{const a=r.nodeName.toLowerCase();if(e.attrName==="style"){const o=y(e.attrValue);o===null?e.keepAttr=!1:e.attrValue=o}else if(e.attrName==="allow"&&a==="iframe"){const o=i.reduceFrameFeatures(e.attrValue);o===null?e.keepAttr=!1:e.attrValue=o}else if(e.attrName==="referrerpolicy"&&a==="iframe"){const o=e.attrValue.trim().toLowerCase();i.EMBED_FRAME_REFERRER_POLICIES.has(o)?e.attrValue=o:e.keepAttr=!1}else e.attrName===i.EMBED_LINK_ATTRIBUTE&&a==="p"?m.set(r,r.getAttribute(i.EMBED_LINK_ATTRIBUTE)):j.has(e.attrName)&&F.test(e.attrValue)||e.attrName===A.SOURCE_LINES_ATTRIBUTE&&A.parseSourceLines(e.attrValue)===null?e.keepAttr=!1:e.attrName==="id"&&M.has(a)&&(e.forceKeepAttr=!0)},g=r=>{const e=r.getAttribute("data-asset-src");e!==null&&(r.getAttribute("data-asset-exists")!=="false"&&h.isAcceptableDocumentPath(e)?r.setAttribute("src",h.explorerAssetHref(c,e,null)):r.removeAttribute("src"))},S=(r,e,a,o)=>{if(f===void 0)return;const u=r.getAttribute(a);if(u===null)return;const l=f({kind:e,path:u});l!==void 0&&r.setAttribute(o,String(l))},L=r=>{const e=r.parentNode;if(e===null)return;const a=m.get(e);a!=null&&i.placeholderLinkOf(a,[...e.childNodes].map(V))!==null&&e.setAttribute(i.EMBED_LINK_ATTRIBUTE,a)},b=r=>{if(r.nodeType!==T)return;const e=r,a=e.nodeName.toLowerCase();a==="img"?(S(e,"asset","data-asset-src","data-asset-exists"),g(e)):a==="a"&&(S(e,"doc","data-doc-path","data-doc-exists"),L(e));const o=e.getAttribute("target");if(o===null||o.trim().toLowerCase()==="_self")return;const u=e.getAttribute("rel"),l=new Set(u===null?[]:u.split(/\s+/u).filter(I=>I!==""));l.add("noopener"),l.add("noreferrer"),e.setAttribute("rel",[...l].join(" "))};return(r,e)=>{E=new WeakMap,m=new WeakMap,f=e,t.addHook("beforeSanitizeElements",p),t.addHook("uponSanitizeElement",_),t.addHook("uponSanitizeAttribute",N),t.addHook("afterSanitizeAttributes",b);try{return t.sanitize(r,G)}finally{t.removeHook("beforeSanitizeElements",p),t.removeHook("uponSanitizeElement",_),t.removeHook("uponSanitizeAttribute",N),t.removeHook("afterSanitizeAttributes",b),f=void 0}}};exports.HtmlNestingLimitError=R;exports.MAX_HTML_NESTING_DEPTH=w;exports.createHtmlSanitizer=W;
|
package/dist/sanitizeWorker.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const J=require("node:worker_threads"),W=require("isomorphic-dompurify"),M=require("./sanitizePolicy-
|
|
1
|
+
"use strict";const J=require("node:worker_threads"),W=require("isomorphic-dompurify"),M=require("./sanitizePolicy-DrIMuYCb.cjs"),A=require("parse5"),K=4096,P=1024,B=Symbol("placement"),G=2,Y=3,Z=new Set(["html","head","body"]),S=0,v=1,I=2,z=3,U=4,C=5,N=6,w=7,F=8,b=9,Q=10,m=-1,ee=0,te=1,re=2,ne=3,se=4,oe=5,q=6,ae=7,ie=t=>{switch(t){case 9:case 10:case 12:case 13:case 32:return ee;case 47:return te;case 62:return re;case 61:return ne;case 34:return se;case 39:return oe;default:return q}},ce=Uint8Array.from({length:128},(t,i)=>ie(i)),x=60,V=47,le=/[\t\n\f\r />="'<]/g,ue=/["<]/g,fe=/['<]/g,f=-1-I,de=Int8Array.from([[v,b,m,S,S,S,S],[v,b,m,f,f,f,f],[z,b,m,U,I,I,I],[z,b,m,U,f,f,f],[U,w,m,w,C,N,w],[C,C,C,C,F,C,C],[N,N,N,N,N,F,N],[v,w,m,w,w,w,w],[v,b,m,f,f,f,f],[v,b,m,f,f,f,f]].flat()),$=t=>t>=65&&t<=90||t>=97&&t<=122,Ee=(t,i)=>{let c=new Int32Array(Q),l=new Int32Array(Q),o=0,p=0,n=0;for(;n<t.length;){if(o===0){const u=t.indexOf("<",n);if(u<0)return!1;n=u+1,t.charCodeAt(n)===V&&(n+=1),$(t.charCodeAt(n))&&(c[S]=0,o=1<<S,n+=1);continue}if((o&-230)===0&&n>=p){const u=o===1<<C?ue:o===1<<N?fe:le;u.lastIndex=n;const _=u.exec(t);if(_===null)return!1;n=_.index,t.charCodeAt(n)===x&&(p=n+3)}const d=t.charCodeAt(n),g=d<128?ce[d]:q;let h=0;for(let u=o;u!==0;u&=u-1){const _=31-Math.clz32(u&-u);let T=de[_*ae+g],E=c[_];if(T<m&&(T=-1-T,E+=1,E>i))return!0;if(T===m)continue;const L=1<<T;((h&L)===0||E>l[T])&&(l[T]=E),h|=L}$(d)&&(t.charCodeAt(n-1)===x||t.charCodeAt(n-1)===V&&t.charCodeAt(n-2)===x)&&(h&1<<S)===0&&(l[S]=0,h|=1<<S);const y=c;c=l,l=y,o=h,n+=1}return!1};class O extends Error{status;constructor(i){super(`[markdown-explorer] the nesting guard stopped the parse: ${i}`),this.name="ParseStop",this.status=i}}const he=(t,i,c,l)=>{if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`[markdown-explorer] the nesting guard's depth limit must be a positive safe integer; got ${String(i)}`);if(!Number.isSafeInteger(c)||c<=0)throw new RangeError(`[markdown-explorer] the nesting guard's node budget must be a positive safe integer; got ${String(c)}`);if(!Number.isSafeInteger(l)||l<=0)throw new RangeError(`[markdown-explorer] the nesting guard's attribute character budget must be a positive safe integer; got ${String(l)}`);if(Ee(t,P))return{status:"too-many-attributes"};const o=i+G,p=t.length+Y;let n=null,d=0,g=0,h=0,y=0;const u=e=>{if(g+=e,g>c)throw new O("too-many-nodes")},_=e=>{for(const r of e)y+=r.name.length+r.value.length;if(y>l)throw new O("too-many-attribute-characters")},T=(e,r,s,a)=>{const D={node:e,above:null,levels:r,height:0,keepsChildren:s,attributes:a,first:null,next:null,previous:null},j=e;return j[B]=D,D},E=e=>{const s=e[B];if(s===void 0)throw new Error("[markdown-explorer] the nesting guard was handed a node it did not create");return s},L=(e,r)=>{let s=r;for(let a=e;a!==null&&s>a.height;a=a.above)a.height=s,s+=a.levels;if(n!==null&&n.height>o)throw new O("too-deep")},k=e=>{const r=e.above;r?.keepsChildren&&(e.previous===null?r.first=e.next:e.previous.next=e.next,e.next!==null&&(e.next.previous=e.previous)),e.above=null,e.next=null,e.previous=null},R=(e,r)=>{if(!A.defaultTreeAdapter.isElementNode(r))return;const s=E(r),a=E(e);k(s),s.above=a,a.keepsChildren&&(s.next=a.first,a.first!==null&&(a.first.previous=s),a.first=s),r.parentNode=e,L(a,s.height+s.levels)},X={...A.defaultTreeAdapter,createDocument:()=>{const e=A.defaultTreeAdapter.createDocument();return n=T(e,0,!1,0),e},createDocumentFragment:()=>{const e=A.defaultTreeAdapter.createDocumentFragment();return T(e,0,!1,0),e},createElement:(e,r,s)=>{if(d+=1,d>p)throw new O("too-many-elements");u(1+s.length),_(s);const a=A.defaultTreeAdapter.createElement(e,r,s);return T(a,1,!(r===A.html.NS.HTML&&Z.has(e)),s.length),a},createCommentNode:e=>{if(h+=1,h>K)throw new O("too-many-comments");return u(1),A.defaultTreeAdapter.createCommentNode(e)},setTemplateContent:(e,r)=>{A.defaultTreeAdapter.setTemplateContent(e,r);const s=E(r);s.above=E(e),L(s.above,s.height)},appendChild:R,insertBefore:(e,r)=>R(e,r),detachNode:e=>{A.defaultTreeAdapter.isElementNode(e)&&(k(E(e)),e.parentNode=null)},getFirstChild:e=>{const r=E(e);if(!r.keepsChildren)throw new Error("[markdown-explorer] the nesting guard was asked for the children of a node whose children it does not keep");return r.first===null?null:r.first.node},getChildNodes:()=>{throw new Error("[markdown-explorer] the nesting guard keeps no child lists for source locations")},onItemPop:e=>{const r=E(e);r.keepsChildren=!1,r.first=null},insertText:()=>{},insertTextBefore:()=>{},adoptAttributes:(e,r)=>{u(r.length),_(r);const s=E(e);if(s.attributes+=r.length,s.attributes>P)throw new O("too-many-attributes")}};let H;try{H=A.parse(t,{scriptingEnabled:!1,treeAdapter:X})}catch(e){if(e instanceof O)return{status:e.status};throw e}return{status:"within",depth:E(H).height-G,elements:d,nodes:g}},pe=t=>{if(t===null||typeof t!="object")return!1;const{id:i,input:c}=t;if(typeof i!="number"||c===null||typeof c!="object")return!1;const{html:l,iframeHosts:o,dataPath:p,maxNodes:n,maxAttributeChars:d,maxSanitizedChars:g}=c;return typeof l=="string"&&Array.isArray(o)&&o.every(h=>typeof h=="string")&&typeof p=="string"&&p!==""&&[n,d,g].every(h=>Number.isSafeInteger(h)&&h>0)},Te=()=>{const t=J.parentPort;if(t===null)throw new Error("[markdown-explorer] the sanitizer worker must run in a worker thread");const i=new Map;t.on("message",c=>{if(!pe(c))throw new TypeError("[markdown-explorer] the sanitizer worker received a message that is not a job");const{id:l,input:o}=c;let p;try{if(he(o.html,M.MAX_HTML_NESTING_DEPTH,o.maxNodes,o.maxAttributeChars).status!=="within"){t.postMessage({id:l,output:{status:"too-large"}});return}const n=JSON.stringify([o.iframeHosts,o.dataPath]);let d=i.get(n);d===void 0&&(d=M.createHtmlSanitizer(W,o.iframeHosts,o.dataPath,M.MAX_HTML_NESTING_DEPTH),i.set(n,d));const g=d(o.html);p=g.length>o.maxSanitizedChars?{status:"too-large"}:{status:"sanitized",html:g}}catch(n){p=n instanceof M.HtmlNestingLimitError?{status:"too-large"}:{status:"error",message:n instanceof Error?`${n.name}: ${n.message}`:String(n)}}t.postMessage({id:l,output:p})}),t.postMessage({ready:!0})};Te();
|
package/dist/sanitizeWorker.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { parentPort as W } from "node:worker_threads";
|
|
2
2
|
import q from "isomorphic-dompurify";
|
|
3
|
-
import { M as D, c as K, H as Y } from "./sanitizePolicy-
|
|
3
|
+
import { M as D, c as K, H as Y } from "./sanitizePolicy-DlrakwA4.js";
|
|
4
4
|
import { defaultTreeAdapter as w, parse as Z, html as ee } from "parse5";
|
|
5
5
|
const te = 4096, P = 1024, B = /* @__PURE__ */ Symbol("placement"), G = 2, re = 3, ne = /* @__PURE__ */ new Set(["html", "head", "body"]), A = 0, L = 1, M = 2, z = 3, U = 4, C = 5, N = 6, _ = 7, F = 8, b = 9, Q = 10, T = -1, oe = 0, se = 1, ae = 2, ie = 3, ce = 4, le = 5, j = 6, ue = 7, fe = (t) => {
|
|
6
6
|
switch (t) {
|
package/dist/server/ports.d.cts
CHANGED
|
@@ -88,6 +88,9 @@ export type ExplorerHostEditSource = {
|
|
|
88
88
|
readonly text: string;
|
|
89
89
|
readonly version: string;
|
|
90
90
|
readonly history: boolean;
|
|
91
|
+
} | {
|
|
92
|
+
readonly kind: "draft";
|
|
93
|
+
readonly text: string;
|
|
91
94
|
} | ExplorerGrantRequired;
|
|
92
95
|
export type ExplorerDraft = {
|
|
93
96
|
readonly text: string;
|
package/dist/server/ports.d.ts
CHANGED
|
@@ -88,6 +88,9 @@ export type ExplorerHostEditSource = {
|
|
|
88
88
|
readonly text: string;
|
|
89
89
|
readonly version: string;
|
|
90
90
|
readonly history: boolean;
|
|
91
|
+
} | {
|
|
92
|
+
readonly kind: "draft";
|
|
93
|
+
readonly text: string;
|
|
91
94
|
} | ExplorerGrantRequired;
|
|
92
95
|
export type ExplorerDraft = {
|
|
93
96
|
readonly text: string;
|
package/dist/server.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./dataRoute-CH3yOKR0.cjs"),wt=require("node:crypto"),Jt=require("@aiquants/markdown/server"),ke=require("@aiquants/request-isolation"),xe=require("react-router"),se=require("./location-BUNWJ4eB.cjs"),ie=require("node:fs"),ne=require("node:path"),Re=require("node:url"),Yt=require("node:worker_threads"),me=require("node:fs/promises"),Wt=require("node:stream");var _e=typeof document<"u"?document.currentScript:null;const Ue=Object.freeze({kind:"anonymous"}),Kt=Object.freeze({authenticate:async()=>({status:"signed-in",principal:Ue}),principalKey:()=>Ue.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),Vt="application/octet-stream",yt="application/pdf",Qt=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",yt]),gt="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",Et=`${gt}; sandbox`,Zt=`${gt}; sandbox allow-same-origin`,Xe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,qt=/^[\t\n\r ]+|[\t\n\r ]+$/gu,Le=/^[\t ]+|[\t ]+$/gu,er=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 a=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(a,n),n<e.length)continue}if(t.push(r.replace(Le,"")),r="",n>=e.length)return t;n+=1}},tr=e=>{const t=e.replace(qt,""),r=t.indexOf("/");if(r<0)return null;const n=t.slice(0,r),a=t.indexOf(";",r+1),i=t.slice(r+1,a<0?t.length:a).replace(/[\t\n\r ]+$/u,"");return Xe.test(n)&&Xe.test(i)?`${n}/${i}`.toLowerCase():null},rr=e=>{let t=null;for(const r of er(e)){const n=tr(r);n!==null&&n!=="*/*"&&(t=n)}return t},nr=/['()*]/gu,bt=e=>encodeURIComponent(e).replace(nr,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),or=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),sr=(e,t)=>{const r=rr(e),n=r!==null&&Qt.has(r),a=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Vt:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${bt(t)}`,...r===yt?{}:{"Content-Security-Policy":a?Zt:Et},"Cross-Origin-Resource-Policy":"same-origin"}}},ir="text/plain; charset=utf-8",ar=e=>({contentType:ir,inline:!0,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`inline; filename*=UTF-8''${bt(e)}`,"Content-Security-Policy":Et,"Cross-Origin-Resource-Policy":"same-origin"}}),cr=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,Ee=Object.freeze({kind:"whole"}),Ge=Object.freeze({kind:"unsatisfiable"}),ur=(e,t,r)=>{const n=e.get("Range");if(n===null)return Ee;const a=e.get("If-Range");if(a!==null&&a!==r)return Ee;const i=cr.exec(n);if(i===null)return Ee;const[,c,m,y]=i;if(y!==void 0){const g=Number(y);if(g===0)return Ge;const k=Math.max(0,t-g);return{kind:"partial",range:{offset:k,length:t-k}}}const O=Number(c),h=m===""?Number.POSITIVE_INFINITY:Number(m);return h<O?Ee:O>=t?Ge:{kind:"partial",range:{offset:O,length:Math.min(h,t-1)-O+1}}},Je="W/",lr=e=>{const t=[];let r=0,n=!1;for(let a=0;a<e.length;a+=1)e[a]==='"'?n=!n:e[a]===","&&!n&&(t.push(e.slice(r,a).replace(Le,"")),r=a+1);return t.push(e.slice(r).replace(Le,"")),t},Ye=e=>e.startsWith(Je)?e.slice(Je.length):e,dr=(e,t)=>{if(e===null)return!1;const r=lr(e);if(r.length===1&&r[0]==="*")return!0;const n=Ye(t);return r.some(a=>Ye(a)===n)},fr=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,a)=>{const i=n.byteLength>r?n.subarray(0,r):n;r-=i.byteLength,a.enqueue(i),r===0&&a.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},Ae=async(e,t,r,n,a)=>{if(n!==null&&r.set("Content-Length",String(n)),e.method.toUpperCase()==="HEAD")return new Response(null,{status:t,headers:r});const i=await a();return new Response(n===null?i:fr(i,n),{status:t,headers:r})},mr=(e,t)=>{const r=new Headers(e);for(const[n,a]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${t}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))r.set(n,a);return new Response(null,{status:416,headers:r})},pr=async(e,t,r,n)=>{const a=`"${t.version}"`,i=n==="text"?ar(t.name):sr(t.contentType,t.name),c=new Headers(r);for(const[O,h]of Object.entries({...i.headers,...or,ETag:a}))c.set(O,h);if(dr(e.headers.get("If-None-Match"),a))return new Response(null,{status:304,headers:c});if(c.set("Content-Type",i.contentType),t.size===null)return Ae(e,200,c,null,()=>t.open(null));if(t.size===0)return c.set("Content-Length","0"),new Response(null,{status:200,headers:c});c.set("Accept-Ranges","bytes");const m=ur(e.headers,t.size,a);if(m.kind==="unsatisfiable")return mr(r,t.size);if(m.kind==="whole")return Ae(e,200,c,t.size,()=>t.open(null));const{range:y}=m;return c.set("Content-Range",`bytes ${y.offset}-${y.offset+y.length-1}/${t.size}`),Ae(e,206,c,y.length,()=>t.open(y))},ve=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(a=>{let i;const c=setTimeout(()=>{a(e.late),i=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),m=()=>{clearTimeout(c),clearTimeout(i)};n.then(y=>{m(),a(y)},()=>{m(),a(e.late)})})},hr=Object.freeze({error:(e,t)=>{console.error(e,t)}}),Tt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class ye extends Error{reason;code;constructor(t,r={}){if(!w.isExplorerFailureReason(t))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);if(r.code!==void 0&&!w.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,Tt,{value:!0})}}const wr=e=>e instanceof Error&&Object.hasOwn(e,Tt)&&w.isExplorerFailureReason(e.reason),yr=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",$e=(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})}},oe=(e,t)=>$e(e,`[markdown-explorer] ${t.operation} failed`,t),gr=(e,t)=>$e(e,`[markdown-explorer] ${t.operation} left out an entry`,t),Ne=(e,t)=>$e(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),We=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},Y=(e,t,r,n)=>wr(e)?w.failureOf(e.reason,e.code):(yr(e)||r.aborted||oe(n,{...t,error:e}),{reason:"failed"}),Ke=2*1024*1024,Ve=256*1024*1024,Er=async(e,t)=>{const r=e.getReader(),n=new Uint8Array(t);let a=0;for(;a<t;){const{done:i,value:c}=await r.read();if(i)return n.subarray(0,a);const m=c.subarray(0,t-a);n.set(m,a),a+=m.byteLength}return r.cancel().catch(()=>{}),n},br=async(e,t)=>{if(e.size===0)return{text:"",truncated:!1};const r=e.size!==null&&e.size>t,n=e.size===null?t+1:Math.min(e.size,t),a=await Er(await e.open(r?{offset:0,length:t}:null),n);if(e.size!==null&&a.byteLength<n)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const i=r||a.byteLength>t,c=i?a.subarray(0,t):a;return c.includes(0)?null:{text:new TextDecoder("utf-8").decode(c,{stream:i}),truncated:i}},Qe=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},St=(e,t)=>{Qe("capacity",e),t!==void 0&&Qe("weight budget",t.max);const r=new Map;let n=0;const a=i=>{const c=r.get(i);c!==void 0&&(r.delete(i),n-=c.weight)};return{get:i=>{const c=r.get(i);if(c!==void 0)return r.delete(i),r.set(i,c),c.value},set:(i,c)=>{a(i);const m=t===void 0?0:t.of(i,c);if(!(t!==void 0&&m>t.max)){r.set(i,{value:c,weight:m}),n+=m;for(const y of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;a(y)}}},delete:a,size:()=>r.size,weight:()=>n}},kt=e=>Math.max(1,e-1),Tr=2147483647,Ze=Object.freeze({status:"aborted"}),le=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},fe=(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)}`)},Sr=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),kr=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,Or=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:a,heapLimits:i})=>{fe("size",t,Number.MAX_SAFE_INTEGER),fe("deadline",r,Tr),fe("jobsPerScope",n,Number.MAX_SAFE_INTEGER),fe("maxQueuedJobs",a,Number.MAX_SAFE_INTEGER),fe("maxOldGenerationSizeMb",i.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),fe("maxYoungGenerationSizeMb",i.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const c=Object.freeze({maxOldGenerationSizeMb:i.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:i.maxYoungGenerationSizeMb}),m=new Set,y=[],O=new Map,h=new Map,g=kt(t);let k=0;const A=(p,E)=>{const{job:b}=p;p.timer!==null&&clearTimeout(p.timer),p.timer=null,p.job=null,p.sent=!1,b!==null&&(le(O,b.scope,-1),le(h,b.scope,-1),b.settle(E))},$=p=>{const[E]=y.splice(p,1);E?.detach()},N=()=>{let p=-1,E=g,b=Number.POSITIVE_INFINITY;for(const[R,S]of y.entries()){const P=O.get(S.scope)??0,L=h.get(S.scope)??0;(P<E||P===E&&p>=0&&L<b)&&(p=R,E=P,b=L)}return p},_=(p,E)=>{m.has(p)&&(m.delete(p),A(p,E),p.worker.terminate().catch(()=>{}),F())},z=p=>{p.timer=setTimeout(()=>{_(p,{status:"timeout"})},r)},v=(p,E)=>p.sent?{status:"crashed",error:E}:{status:"unavailable",error:E},I=(p,E)=>{p.sent=!0,z(p);try{p.worker.postMessage({id:E.id,input:E.input})}catch(b){A(p,{status:"crashed",error:b}),p.worker.unref()}},C=()=>{const p={worker:new Yt.Worker(e,{resourceLimits:c}),job:null,sent:!1,timer:null,ready:!1};return p.worker.unref(),p.timer=setTimeout(()=>{_(p,{status:"unavailable",error:new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`)})},r),p.worker.on("message",E=>{if(!p.ready&&Sr(E)){p.ready=!0,p.timer!==null&&clearTimeout(p.timer),p.timer=null,p.job===null?p.worker.unref():I(p,p.job),p.job===null&&F();return}const{job:b}=p;if(b===null||!kr(E,b.id)){_(p,v(p,new Error("[markdown-explorer] a worker sent a message that answers no job")));return}A(p,{status:"done",output:E.output}),p.worker.unref(),F()}),p.worker.on("error",E=>{_(p,v(p,E))}),p.worker.on("messageerror",E=>{_(p,v(p,E))}),p.worker.on("exit",E=>{_(p,v(p,new Error(`[markdown-explorer] a worker exited with code ${String(E)}`)))}),m.add(p),p},F=()=>{for(;;){const p=N(),E=y[p];if(E===void 0)return;let b;for(const S of m)if(S.job===null){b=S;break}if(b===void 0&&m.size<t)try{b=C()}catch(S){$(p),le(h,E.scope,-1),E.settle({status:"unavailable",error:S});continue}if(b===void 0)return;$(p),le(O,E.scope,1);const R=b;R.job=E,R.worker.ref(),R.ready&&I(R,E)}};return{run:(p,{scope:E,signal:b})=>new Promise(R=>{if(b.aborted){R(Ze);return}if((h.get(E)??0)>=n){R({status:"refused",limit:"scope"});return}k+=1;const S={id:k,input:p,scope:E,settle:R,detach:()=>{}};y.push(S),le(h,E,1),F();const P=y.indexOf(S);if(P<0)return;if(y.length>a){$(P),le(h,E,-1),R({status:"refused",limit:"queue"});return}const L=()=>{const X=y.indexOf(S);X<0||($(X),le(h,E,-1),R(Ze))};b.addEventListener("abort",L,{once:!0}),S.detach=()=>{b.removeEventListener("abort",L)}}),workers:()=>m.size}},je=1024*1024,xr=3e4,Rr=4*je,_r=64*je,Ar=3,vr=2,Nr=(e,t)=>e+kt(t)+Ar,Pr=4,Ir=32,Mr=512,Lr=64,Dr=4096,$r=32,qe=4096,jr=4,Ot=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-Lr)*je-t*$r)/Dr),zr=({maxHtmlBytes:e})=>e,Cr=({maxHtmlBytes:e})=>jr*e,Hr=1024,Br=2147483647,Fr=64,Ur=2**29,Xr=1024*1024,Gr=64,et=Object.freeze({status:"rejected",reason:"too-large",cause:null}),Pe=Object.freeze({status:"rejected",reason:"failed",cause:null}),de=(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},Jr=(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:a,cacheBytes:i,workerHeapMb:c,jobsPerScope:m,maxQueuedJobs:y}=e??{},O=de("workers",r,vr,Fr),h=de("jobsPerScope",m,Nr(t,O),Number.MAX_SAFE_INTEGER),g=Object.freeze({workers:O,deadlineMs:de("deadlineMs",n,xr,Br),maxHtmlBytes:de("maxHtmlBytes",a,Rr,Ur),cacheBytes:de("cacheBytes",i,_r,Number.MAX_SAFE_INTEGER),workerHeapMb:de("workerHeapMb",c,Mr,Xr),jobsPerScope:h,maxQueuedJobs:de("maxQueuedJobs",y,Pr*h,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(Ot(g)<qe)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(g.workerHeapMb)} MiB) must leave room for ${String(qe)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(g.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return g},Yr=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:_e&&_e.tagName.toUpperCase()==="SCRIPT"&&_e.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${ne.extname(Re.fileURLToPath(e))}`,e);if(!ie.existsSync(Re.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${Re.fileURLToPath(t)}`);return t},tt=new Map,Wr=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=tt.get(r);return n===void 0&&(n=Or({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:Ir}}),tt.set(r,n)),n},Kr=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"},Vr=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",Qr=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const a=Object.freeze([...e]),i=Ot(r),c=zr(r),m=Cr(r),y=St(Hr,{max:r.cacheBytes,of:(N,_)=>2*N.length+(_.status==="sanitized"?2*_.html.length:Gr)}),O=new Map,h=new Map,g=N=>{O.get(N.key)===N&&O.delete(N.key);const _=h.get(N.hash);_?.delete(N),_?.size===0&&h.delete(N.hash)},k=async(N,_,z)=>{const v=await n.run({html:N,iframeHosts:a,dataPath:t,maxNodes:i,maxAttributeChars:c,maxSanitizedChars:m},{scope:_,signal:z});if(v.status==="refused"){const C=v.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(v.status==="aborted")return{outcome:Pe,lasting:!1};if(v.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(v.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:v.error})},lasting:!1};if(v.status==="crashed"&&Vr(v.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:v.error})},lasting:!0};if(v.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:v.error})},lasting:!0};const{output:I}=v;return Kr(I)?I.status==="too-large"?{outcome:et,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>m?{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(m)}`)},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}},A=(N,_,z,v)=>{let I=()=>{};const C=new Promise(E=>{I=E}),F={hash:_,key:z,outcome:C,answer:I,controller:new AbortController,waiters:0};O.set(z,F);const p=h.get(_);return p===void 0?h.set(_,new Set([F])):p.add(F),k(N,v,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:b})=>{if(g(F),F.answer(E),!b)return;const R=y.get(_),S=R??(E.status==="rejected"?{...E,cause:null}:E);R===void 0&&y.set(_,S);for(const P of h.get(_)??[])g(P),P.answer(S),P.controller.abort()}),F},$=(N,_)=>new Promise(z=>{N.waiters+=1;const v=()=>{N.waiters-=1,z(Pe),!(N.waiters>0)&&(g(N),N.controller.abort())};_.addEventListener("abort",v,{once:!0}),N.outcome.then(I=>{_.removeEventListener("abort",v),z(I)})});return(N,{scope:_,signal:z})=>{if(N.length>r.maxHtmlBytes||Buffer.byteLength(N,"utf8")>r.maxHtmlBytes)return Promise.resolve(et);const v=wt.createHash("sha256").update(N,"utf8").digest("base64"),I=y.get(v);if(I!==void 0)return Promise.resolve(I);if(z.aborted)return Promise.resolve(Pe);const C=`${v}\0${_}`,F=O.get(C);return $(F===void 0?A(N,v,C,_):F,z)}},Oe=e=>({result:e,json:JSON.stringify(e)}),Ie=Object.freeze(Oe(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),Zr=e=>e.status==="ok"&&e.entries.length>0,qr=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const a=St(t,{max:r,of:(h,g)=>2*g.tree.json.length}),i=new Map,c=new Map,m=(h,g)=>{const k=new AbortController,A={waiters:0,superseded:!1,started:!1,loadTree:g},$=c.get(h),N=(C,F)=>{const p=Oe(C);return!(A.superseded||k.signal.aborted)&&Zr(C)&&a.set(h,{tree:p,loadedAt:F}),p},z=(async()=>{if($!==void 0&&await $,k.signal.aborted)return Ie;const C=n();return A.started=!0,N(await A.loadTree(k.signal,C),C)})().finally(()=>{i.get(h)===v&&i.delete(h)}),v={promise:z,controller:k,state:A};i.set(h,v);const I=z.then(()=>{},()=>{});return c.set(h,I),I.then(()=>{c.get(h)===I&&c.delete(h)}),v},y=(h,g,k)=>{g.state.waiters+=1;const A=()=>{g.state.waiters-=1,!(g.state.waiters>0)&&(i.get(h)===g&&i.delete(h),g.controller.abort())};return k.addEventListener("abort",A,{once:!0}),g.promise.finally(()=>{k.removeEventListener("abort",A)})},O=h=>{a.delete(h);const g=i.get(h);g?.state.started&&(g.state.superseded=!0,i.delete(h))};return{load:(h,g,k)=>{if(g.aborted)return Promise.resolve(Ie);const A=a.get(h);if(A!==void 0){if(n()-A.loadedAt<e)return Promise.resolve(A.tree);a.delete(h)}const $=i.get(h);return y(h,$===void 0?m(h,k):$,g)},refresh:(h,g,k)=>{if(g.aborted)return Promise.resolve(Ie);O(h);const A=i.get(h);return A===void 0?y(h,m(h,k),g):(A.state.loadTree=k,y(h,A,g))},forget:O}},en=e=>({load:(t,r,n)=>n(r,e()).then(Oe),refresh:(t,r,n)=>n(r,e()).then(Oe),forget:()=>{}}),x=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},tn=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"}:w.isAcceptableDocumentPath(r)?null:{path:r,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},rn=(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 a=new Set;for(const i of e){if(typeof i!="string"||!w.isAcceptableDocumentPath(i))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(r.deniesPath(i))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!n(i))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(i===t)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(a.has(i))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");a.add(i)}return Object.freeze([...a])},nn=(e,t,r,n,a)=>{const i=new Set,c=y=>{if(!Array.isArray(y))return x("a source returned entries that are not an array");const O=[];for(const h of y){const g=m(h);g!==null&&O.push(g)}return O},m=y=>{const O=tn(y);if(O!==null)return n(O),null;const h=w.entryViolation(y);if(h!==null)return x(h);const g=y;if(i.has(g))return x("a source returned entries that contain themselves");const{name:k,path:A,type:$,mimeType:N,modifiedAt:_,children:z,lazy:v}=g;if(t.deniesName(k)||t.deniesPath(A))return null;if(!a(A))return n({path:A,reason:"a path outside the source's boundary"}),null;const I={name:k,path:A,...N===void 0?{}:{mimeType:N},..._===void 0?{}:{modifiedAt:_}};if($==="file")return{...I,type:$};if(v===!0)return r?{...I,type:$,lazy:!0,children:[]}:x("a lazy directory came from a source without a children function");if(z===void 0)return{...I,type:$};i.add(g);const C=c(z);return i.delete(g),{...I,type:$,children:C}};return c(e)},on=/^[\x21\x23-\x7E]{1,256}$/u,xt=e=>typeof e=="string"&&on.test(e),sn=new Set(["text","image","media","file"]),an=e=>typeof e=="string"&&sn.has(e),cn=(e,t,r)=>{if(e!==null&&typeof e=="object"){const i=e,{kind:c}=i;if(an(c)){if(Object.hasOwn(i,"url"))return x(`a ${c} document carries its version, not a url`);if(typeof i.name!="string")return x("a document needs a name string");if(!xt(i.version))return x(`a ${c} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const m=t(i.version);switch(c){case"image":case"file":return{kind:c,name:i.name,url:m};case"media":{const{mediaType:y}=i;return w.isExplorerMediaType(y)?{kind:c,name:i.name,url:m,mediaType:y}:x(`unknown media type ${typeof y=="string"?JSON.stringify(y.slice(0,64)):typeof y}`)}case"text":return typeof i.text!="string"||typeof i.truncated!="boolean"?x("a text document needs text and truncated"):{kind:c,name:i.name,text:i.text,truncated:i.truncated,url:m}}}}const n=w.documentViolation(e);if(n!==null)return x(n);const a=e;switch(a.kind){case"failure":{const{reason:i,code:c}=a.failure;return{kind:"failure",failure:w.failureOf(i,c)}}case"markdown":return a.headings.length>w.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:w.failureOf("too-large")}:a.edit?.kind==="inline"&&!r?x("a markdown document offers inline editing, but the server has no edit ports"):{kind:"unsanitized-markdown",name:a.name,html:a.htmlContent,headings:a.headings.map(({text:i,depth:c,id:m})=>({text:i,depth:c,id:m})),edit:un(a.edit)}}},un=e=>e===null?null:e.kind==="inline"?{kind:"inline"}:{kind:"external",href:e.href},ze=(e,t,r)=>typeof e!="string"?x(`${r} needs a text string`):e.includes("\0")?x(`${r} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>t?x(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`):e,Rt=e=>w.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:x("a grant needs a root-relative href"),ln=(e,t)=>{if(e===null||typeof e!="object")return x("an edit source must be an object");const r=e;return r.kind==="grant"?Rt(r):r.kind!=="edit"?x(`an edit source's kind must be "edit" or "grant"`):w.isExplorerEditToken(r.version)?typeof r.history!="boolean"?x("an edit source needs history"):{kind:"edit",text:ze(r.text,t,"an edit source"),version:r.version,history:r.history}:x("an edit source needs a version of 1 to 1024 characters")},dn=(e,t)=>{if(e===null||typeof e!="object")return x("a save result must be an object");const r=e;switch(r.kind){case"grant":return Rt(r);case"saved":return w.isExplorerEditToken(r.version)?{kind:"saved",version:r.version}:x("a saved result needs a version of 1 to 1024 characters");case"conflict":return w.isExplorerEditToken(r.version)?{kind:"conflict",version:r.version,text:ze(r.text,t,"a conflict's current text")}:x("a conflict needs the current version of 1 to 1024 characters");default:return x(`a save result's kind must be "saved", "conflict" or "grant"`)}},fn=e=>{if(e===null||typeof e!="object")return x("a preview must be an object");const{htmlContent:t,headings:r}=e;if(typeof t!="string"||!Array.isArray(r))return x("a preview needs htmlContent and headings");if(r.length>w.EXPLORER_MAX_HEADINGS)return{kind:"failure",failure:w.failureOf("too-large")};for(const n of r){const a=w.headingViolation(n);if(a!==null)return x(a)}return{html:t,headings:r.map(({text:n,depth:a,id:i})=>({text:n,depth:a,id:i}))}},mn=e=>{if(!Array.isArray(e))return x("revisions must be an array");const t=new Set;return e.map(r=>{const n=w.revisionViolation(r);if(n!==null)return x(n);const{id:a,modifiedAt:i,size:c,author:m,kept:y,current:O}=r;return t.has(a)?x(`two revisions share the id ${JSON.stringify(a.slice(0,64))}`):(t.add(a),{id:a,modifiedAt:i,size:c,author:m,kept:y,current:O})})},pn=(e,t)=>ze(e,t,"a revision"),rt=e=>{if(e===null||typeof e!="object")return x("an asset file must be an object");const{name:t,contentType:r,size:n,version:a,open:i}=e;return typeof t!="string"||t===""?x("an asset file needs a non-empty name"):typeof r!="string"?x("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?x("an asset file's size must be null or a non-negative safe integer"):xt(a)?typeof i!="function"?x("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:a,open:i}):x(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},hn=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return x("a notice must be an object");const{id:r,tone:n,title:a,body:i,action:c}=t;if(typeof r!="string"||r===""||typeof a!="string")return x("a notice needs an id and a title");if(!w.isExplorerNoticeTone(n))return x(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(i!==void 0&&typeof i!="string")return x("a notice body must be a string");const y={id:r,tone:n,title:a,...i===void 0?{}:{body:i}};if(c===void 0)return y;if(c===null||typeof c!="object")return x("a notice action must be an object");const{label:O,href:h}=c;return typeof O!="string"||!w.isAcceptableUrl(h,w.EXPLORER_LINK_PROTOCOLS)?x("a notice action needs a label and an http(s), mailto or relative href"):{...y,action:{label:O,href:h}}}):x("notices must be an array"),wn=4e3,be=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),nt=32,_t="private, no-store",yn=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":_t,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),gn=22,En=2147483647,Me=Object.freeze([]),bn=Object.freeze({status:"ok",source:null,ancestors:null}),ot=Object.freeze(["contains","confirm"]),st=Object.freeze({readOnly:!1}),Tn=Object.freeze({readOnly:!0}),V=(e,t,r)=>{if(!(r&&t===void 0)&&typeof t!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`)},pe=(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},Sn=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return se.revalidateExplorerConfig(e)},it=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)")}},at=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,kn=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<nt)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(nt)} characters; got ${String(e.length)}`);return e},On=(e,t)=>{if(!se.isPlainObject(t))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const r of Object.keys(t))if(!ot.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${ot.join(", ")}`);V(`${e}.boundary.contains`,t.contains,!1),V(`${e}.boundary.confirm`,t.confirm,!0)},xn=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,a]of t.entries()){if(a===null||typeof a!="object")throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);const{id:i,label:c,boundary:m,tree:y,children:O,ancestors:h,cacheScope:g}=a;if(!se.isExplorerSourceId(i))throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof i=="string"?JSON.stringify(i):typeof i}`);const k=`source ${JSON.stringify(i)}`;if(r.has(i))throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(i)} repeats at sources[${String(n)}]`);if(r.add(i),typeof c!="string"&&typeof c!="function")throw new TypeError(`[markdown-explorer] ${k}.label must be a string or a function`);if(typeof c=="string"&&c.trim()==="")throw new RangeError(`[markdown-explorer] ${k}.label must not be blank`);if(On(k,m),V(`${k}.tree`,y,!1),V(`${k}.children`,O,!0),V(`${k}.ancestors`,h,!0),g!==void 0&&g!=="principal"&&g!=="shared")throw new RangeError(`[markdown-explorer] ${k}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(g)}`)}return t},Rn=e=>{if(e===!1)return!1;if(e===void 0)return be;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?be.ttlMs:pe("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?be.maxEntries:pe("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?be.maxBytes:pe("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},ct=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},ut=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},lt=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return wt.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,gn)},_n=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],ue=(e,t)=>{const r=e.getAll(t),[n]=r;return r.length===1&&n!==void 0&&n!==""?n:null},K=(e,t,r,n={})=>{const a=new Headers(r);for(const[i,c]of Object.entries({...yn,...n}))a.set(i,c);return new Response(t,{status:e,headers:a})},j=(e,t,r)=>K(w.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),An=new Set(["refresh","save","preview"]),vn=new Set(["edit","save","preview","revisions","revision"]),dt=(e,t)=>{const r=An.has(t)?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:K(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},ft=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_REFRESH_PROOF&&ke.crossOriginRefusal(e,ke.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Nn=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_EDIT_PROOF&&ke.crossOriginRefusal(e,ke.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Pn=async(e,t)=>{const[r,...n]=(e.headers.get("Content-Type")??"").split(";").map(k=>k.trim().toLowerCase()),a=n.find(k=>k.startsWith("charset="));if(r!==w.EXPLORER_DRAFT_MEDIA_TYPE||a!==void 0&&a!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const i=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(i)&&i>t)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const c=e.body.getReader(),m=[];let y=0;for(;;){const{done:k,value:A}=await c.read();if(k)break;if(y+=A.byteLength,y>t)return await c.cancel(),{status:"error",failure:{reason:"too-large"}};m.push(A)}const O=new Uint8Array(y);let h=0;for(const k of m)O.set(k,h),h+=k.byteLength;let g;try{g=new TextDecoder("utf-8",{fatal:!0}).decode(O)}catch{return{status:"error",failure:{reason:"invalid"}}}return g.includes("\0")?{status:"error",failure:{reason:"invalid"}}:{status:"ok",text:g}},In=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"])V(`edit.${r}`,t[r],!1);return e},Mn=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,a=r===void 0?[e,t]:[e,t,r];for(const i of a)for(const[c,m]of i)c!=="set-cookie"&&n.set(c,m);return n},Ln=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=Sn(e.config),r=kn(e.scopeSecret);V("authenticate",e.authenticate,!1),V("principalKey",e.principalKey,!1),V("document",e.document,!1),V("asset",e.asset,!1),V("signedOutPage",e.signedOutPage,!1),V("forbiddenPage",e.forbiddenPage,!0),V("notices",e.notices,!0),V("onTreeRefreshed",e.onTreeRefreshed,!0);const n=xn(e.sources),a=se.withExplorerSources(t,n.map(o=>o.id)),i=e.logger;if(i!==void 0&&(i===null||typeof i!="object"||typeof i.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const c=e.logger===void 0?hr:e.logger,m=w.resolvePathRules(e.deny),y=e.deferredTimeoutMs===void 0?wn:pe("deferredTimeoutMs",e.deferredTimeoutMs,En),O=e.textMaxBytes===void 0?Ke:pe("textMaxBytes",e.textMaxBytes,Ve),h=In(e.edit);if(h===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const g=e.editMaxBytes===void 0?Ke:pe("editMaxBytes",e.editMaxBytes,Ve),k=Rn(e.treeCache),A=()=>Date.now(),$=k===!1?en(A):qr({...k,now:A}),N=Jr(e.sanitizer,t.multiView.maxPanels),_=Qr({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:N,pool:Wr(Yr(),N)}),z=new Map(n.map(o=>[o.id,o])),v=se.documentStyleNames(t),{authenticate:I,principalKey:C,signedOutPage:F,forbiddenPage:p,onTreeRefreshed:E}=e,b=(o,u)=>{if(typeof o.label=="string")return o.label;const s=o.label(u);if(typeof s!="string"||s.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(o.id)} must be a non-blank string`);return s},R=(o,u)=>o.cacheScope==="shared"?o.id:`${o.id}\0${u}`,S=(o,u)=>{const s=d=>oe(c,{operation:"boundary",sourceId:o.id,path:u,error:d});let l;try{l=o.boundary.contains(u)}catch(d){return s(d),!1}return typeof l=="boolean"?l:(We(l,s),s(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(o.id)} must return a boolean; got ${typeof l}`)),!1)},P=async(o,u,s)=>{const{confirm:l}=o.boundary;if(l===void 0)return{status:"inside",readPath:s};let d;try{d=await l(u,s)}catch(U){return{status:"error",failure:Y(U,{operation:"boundary",sourceId:o.id,path:s},u.signal,c)}}const f=U=>(oe(c,{operation:"boundary",sourceId:o.id,path:s,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} ${U}`)}),{status:"outside"});if(d===null||typeof d!="object")return f(`must resolve to { inside, readPath? }; got ${d===null?"null":typeof d}`);const{inside:T,readPath:M}=d;return T===!1?{status:"outside"}:T!==!0||typeof M!="string"?f("must resolve to { inside: false } or { inside: true, readPath: string }"):!w.isAcceptableDocumentPath(M)||m.deniesPath(M)?(oe(c,{operation:"boundary",sourceId:o.id,path:s,error:new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} answered a readPath the explorer does not serve (unacceptable or denied)`)}),{status:"error",failure:{reason:"failed"}}):{status:"inside",readPath:M}},L=async(o,u)=>{const s=n.filter(d=>S(d,u));if(s.length===0)return{status:"error",failure:{reason:"forbidden"}};if(s.some(d=>d.boundary.confirm===void 0))return{status:"inside",readPath:u};let l=null;for(const d of s){const f=await P(d,o,u);if(f.status==="inside")return f;f.status==="error"&&l===null&&(l=f.failure)}return{status:"error",failure:l===null?{reason:"forbidden"}:l}},X=(o,u,s)=>{const l=({path:d,reason:f})=>gr(c,{operation:s.operation,sourceId:s.sourceId,path:d,error:new TypeError(`[markdown-explorer] an entry with ${f} was left out`)});try{return{status:"ok",entries:nn(o,m,u.children!==void 0,l,d=>S(u,d))}}catch(d){return oe(c,{...s,error:d}),{status:"error",failure:{reason:"failed"}}}},D=async(o,u,s)=>{let l;try{l=await o.tree(u)}catch(f){return{status:"error",failure:Y(f,{operation:"tree",sourceId:o.id},u.signal,c)}}const d=X(l,o,{operation:"tree",sourceId:o.id});return d.status==="ok"?{status:"ok",entries:d.entries,loadedAt:s}:d},G=(o,u,s,l)=>(d,f)=>D(o,{principal:u,request:s,signal:d,refresh:l},f),Q=(o,u,s,l,d)=>$.load(R(o,s),d,G(o,u,l,!1)),J=(o,u,s,l)=>$.refresh(R(o,s),l.signal,G(o,u,l,!0)),ae=(o,u)=>{if(E===void 0)return;const s=l=>oe(c,{operation:"refresh",sourceId:o.id,error:l});try{We(E(u),s)}catch(l){s(l)}},H=async(o,u,s,l)=>{if(m.deniesPath(l)||!S(o,l))return{status:"error",failure:{reason:"forbidden"}};const d=await P(o,s,l);if(d.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(d.status==="error")return{status:"error",failure:d.failure};let f;try{f=await u(s,l,d.readPath)}catch(T){return{status:"error",failure:Y(T,{operation:"children",sourceId:o.id,path:l},s.signal,c)}}return X(f,o,{operation:"children",sourceId:o.id,path:l})},Z=async(o,u,s,l)=>{const d=await P(o,s,l);if(d.status==="outside")return{status:"ok",ancestors:null};if(d.status==="error")return{status:"error",failure:d.failure};let f;try{f=await u(s,l,d.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(T){return{status:"error",failure:Y(T,{operation:"ancestors",sourceId:o.id,path:l},s.signal,c)}}if(Array.isArray(f)&&f.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:rn(f,l,m,T=>S(o,T))}}catch(T){return oe(c,{operation:"ancestors",sourceId:o.id,path:l,error:T}),{status:"error",failure:{reason:"failed"}}}},q=async(o,u,s,l)=>m.deniesPath(l)?{status:"error",failure:{reason:"forbidden"}}:S(o,l)?Z(o,u,s,l):{status:"ok",ancestors:null},ee=async(o,u,s)=>{if(m.deniesPath(s))return{status:"error",failure:{reason:"forbidden"}};for(const l of[o,...n.filter(d=>d!==o)]){if(u.signal.aborted)break;const d=l.ancestors;if(d===void 0||!S(l,s))continue;const f=await Z(l,d,u,s);if(f.status==="ok"&&f.ancestors!==null)return{status:"ok",source:l.id,ancestors:f.ancestors}}return bn},ce=async(o,u,s)=>{if(m.deniesPath(s))return w.failureDocument("forbidden");const l=await L(o,s);if(l.status==="error")return{kind:"failure",failure:l.failure};let d;try{d=await e.document(o,s,l.readPath)}catch(M){return{kind:"failure",failure:Y(M,{operation:"document",path:s},o.signal,c)}}let f;try{f=cn(d,M=>w.explorerAssetHref(t.dataPath,s,M),h!==void 0)}catch(M){return oe(c,{operation:"document",path:s,error:M}),w.failureDocument("failed")}if(f.kind!=="unsanitized-markdown")return f;const T=await _(f.html,{scope:u,signal:o.signal});return T.status==="sanitized"?{kind:"markdown",name:f.name,htmlContent:T.html,headings:f.headings,edit:f.edit}:(T.cause!==null&&oe(c,{operation:"document",path:s,error:T.cause}),w.failureDocument(T.reason))},ge=async o=>{if(e.notices===void 0)return Me;try{return hn(await e.notices(o))}catch(u){return Y(u,{operation:"notices"},o.signal,c),Me}},Lt=async(o,u,s)=>{const l=ue(u,w.EXPLORER_DATA_QUERY.path);if(l===null||!w.isAcceptableDocumentPath(l))return j({reason:"invalid"},s);const d=w.readExplorerAssetDisplay(u);if(d===null)return j({reason:"invalid"},s);if(m.deniesPath(l))return Ne(c,{operation:"asset",path:l}),j({reason:"forbidden"},s);const f=await L(o,l);if(f.status==="error")return j(f.failure,s);try{const T=rt(await e.asset(o,l,f.readPath));return await pr(o.request,T,s,d)}catch(T){return j(Y(T,{operation:"asset",path:l},o.signal,c),s)}},Dt=async(o,u)=>{if(m.deniesPath(u))return Ne(c,{operation:"text",path:u}),w.failureDocument("forbidden");const s=await L(o,u);if(s.status==="error")return{kind:"failure",failure:s.failure};try{const l=rt(await e.asset(o,u,s.readPath)),d=await br(l,O);return d===null?w.failureDocument("unsupported"):{kind:"text",name:l.name,text:d.text,truncated:d.truncated,url:w.explorerAssetHref(t.dataPath,u,l.version)}}catch(l){return{kind:"failure",failure:Y(l,{operation:"text",path:u},o.signal,c)}}},he=async(o,u,s)=>m.deniesPath(s)?(Ne(c,{operation:u,path:s}),{status:"error",failure:{reason:"forbidden"}}):L(o,s),$t=async(o,u,s)=>{const l=await he(u,"edit",s);if(l.status==="error")return{kind:"failure",failure:l.failure};try{return ln(await o.source(u,s,l.readPath),g)}catch(d){return{kind:"failure",failure:Y(d,{operation:"edit",path:s},u.signal,c)}}},jt=async(o,u,s,l,d)=>{const f=await he(u,"save",s);if(f.status==="error")return{kind:"failure",failure:f.failure};try{return dn(await o.save(u,s,f.readPath,{text:d,baseVersion:l}),g)}catch(T){return{kind:"failure",failure:Y(T,{operation:"save",path:s},u.signal,c)}}},zt=async(o,u,s,l,d)=>{const f=await he(u,"preview",l);if(f.status==="error")return{kind:"failure",failure:f.failure};let T;try{T=fn(await o.preview(u,l,f.readPath,d))}catch(U){return{kind:"failure",failure:Y(U,{operation:"preview",path:l},u.signal,c)}}if("kind"in T)return T.kind==="failure"?T:w.failureDocument("failed");const M=await _(T.html,{scope:s,signal:u.signal});return M.status==="sanitized"?{kind:"preview",htmlContent:M.html,headings:T.headings}:(M.cause!==null&&oe(c,{operation:"preview",path:l,error:M.cause}),w.failureDocument(M.reason))},Ct=async(o,u,s)=>{const l=await he(u,"revisions",s);if(l.status==="error")return{kind:"failure",failure:l.failure};try{return{kind:"revisions",revisions:mn(await o.revisions(u,s,l.readPath))}}catch(d){return{kind:"failure",failure:Y(d,{operation:"revisions",path:s},u.signal,c)}}},Ht=async(o,u,s,l)=>{const d=await he(u,"revision",s);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return{kind:"revision",id:l,text:pn(await o.revision(u,s,d.readPath,l),g)}}catch(f){return{kind:"failure",failure:Y(f,{operation:"revision",path:s},u.signal,c)}}},Bt=async(o,u,s,l,d,f)=>{const T=ue(d,w.EXPLORER_DATA_QUERY.path);if(T===null||!w.isAcceptableDocumentPath(T))return j({reason:"invalid"},f);if(u==="edit")return K(200,JSON.stringify(await $t(o,s,T)),f);if(u==="revisions")return K(200,JSON.stringify(await Ct(o,s,T)),f);if(u==="revision"){const te=ue(d,w.EXPLORER_DATA_QUERY.revision);return w.isExplorerEditToken(te)?K(200,JSON.stringify(await Ht(o,s,T,te)),f):j({reason:"invalid"},f)}const M=ue(d,w.EXPLORER_DATA_QUERY.base);if(u==="save"&&!w.isExplorerEditToken(M))return j({reason:"invalid"},f);const U=await Pn(s.request,g);return U.status==="error"?j(U.failure,f):u==="preview"?K(200,JSON.stringify(await zt(o,s,l,T,U.text)),f):K(200,JSON.stringify(await jt(o,s,T,M,U.text)),f)},Ft=async({request:o,url:u,params:s})=>{const l=ct(await I(o,st)),d=it(l.headers);if(d.set("Cache-Control",_t),l.status==="signed-out")throw ut("signedOutPage",F(o,d));if(l.status==="forbidden")throw p===void 0?xe.data(null,{status:403,headers:d}):ut("forbiddenPage",p(o,d));const f=se.resolveExplorerLocation(a,s["*"],u.searchParams);if(f.kind==="redirect")throw xe.redirect(f.href,{headers:d});const{location:T}=f,{principal:M}=l,U=lt(r,C(M)),te=z.get(T.source);if(te===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(T.source)}`);const we={signal:o.signal,timeoutMs:y,late:null,handOverMs:y},re={scope:U,sources:n.map(B=>({id:B.id,label:b(B,M)})),settings:se.parseViewSettings(se.readCookieValue(o.headers.get("Cookie"),t.settingsCookie),v),tree:T.view==="single"?null:{sourceId:T.source,result:ve(we,B=>Q(te,M,U,o,B).then(W=>W.result))},documents:_n(T).map(B=>({path:B,document:ve(we,W=>ce({principal:M,request:o,signal:W,refresh:!1},U,B))})),notices:ve({signal:o.signal,timeoutMs:y,late:Me,handOverMs:0},B=>ge({principal:M,request:o,signal:B,refresh:!1}))};return xe.data(re,{headers:d})},Ce=async(o,u)=>{const s=ct(await I(o,u));return{authentication:s,headers:it(s.headers)}},Ut=async(o,u,s)=>{let l;try{l=await Ce(u,st)}catch(W){return j(Y(at(W),{operation:"authenticate"},u.signal,c))}const{authentication:d,headers:f}=l;if(d.status==="signed-out")return j({reason:"unauthorized"},f);if(d.status==="forbidden")return j({reason:"forbidden"},f);const{principal:T}=d;if(o==="asset")return Lt({principal:T,request:u,signal:u.signal,refresh:!1},s,f);const M=lt(r,C(T));f.set(w.EXPLORER_SCOPE_HEADER,M);const U={principal:T,request:u,signal:u.signal,refresh:!1},te=()=>j({reason:"invalid"},f);if(o==="document"){const W=ue(s,w.EXPLORER_DATA_QUERY.path);if(W===null||!w.isAcceptableDocumentPath(W))return te();const Fe=u.headers.has(w.EXPLORER_PROOF_HEADER);return Fe&&!ft(u)?j({reason:"forbidden"},f):K(200,JSON.stringify(await ce({...U,refresh:Fe},M,W)),f)}if(o==="text"){const W=ue(s,w.EXPLORER_DATA_QUERY.path);return W===null||!w.isAcceptableDocumentPath(W)?te():K(200,JSON.stringify(await Dt(U,W)),f)}if(o==="edit"||o==="save"||o==="preview"||o==="revisions"||o==="revision")return h===void 0?j({reason:"not-found"},f):Bt(h,o,U,M,s,f);const we=ue(s,w.EXPLORER_DATA_QUERY.source),re=ue(s,w.EXPLORER_DATA_QUERY.path);if(we===null||(o==="children"||o==="ancestors"||o==="reveal")&&(re===null||!w.isAcceptableDocumentPath(re)))return te();const B=z.get(we);if(B===void 0)return j({reason:"not-found"},f);if(o==="tree")return K(200,(await Q(B,T,M,u,u.signal)).json,f);if(o==="refresh"){const W=await J(B,T,M,u);return u.signal.aborted||ae(B,R(B,M)),K(200,W.json,f)}return o==="ancestors"?B.ancestors===void 0||re===null?j({reason:"not-found"},f):K(200,JSON.stringify(await q(B,B.ancestors,U,re)),f):o==="reveal"?re===null?te():K(200,JSON.stringify(await ee(B,U,re)),f):B.children===void 0||re===null?j({reason:"not-found"},f):K(200,JSON.stringify(await H(B,B.children,U,re)),f)},Xt=async o=>{const{authentication:u,headers:s}=await Ce(o,Tn);if(!s.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"},He=t.embeds.linkCardEndpoint===null?null:Jt.createLinkCardHandler({authorize:Xt}),Gt=async(o,u)=>{try{return await o(u)}catch(s){return j(Y(at(s),{operation:"authenticate"},u.signal,c))}},Be=async(o,u,s)=>{if(new URL(o.url).pathname.endsWith(".data"))return j({reason:"not-found"});if(!w.isExplorerDataOperation(s))return j({reason:"not-found"});if(s==="link-card"){if(He===null)return j({reason:"not-found"});const d=dt(o,s);return d!==null?d:Gt(He,o)}if(vn.has(s)&&h===void 0)return j({reason:"not-found"});const l=dt(o,s);if(l!==null)return l;if(s==="refresh"&&!ft(o))return j({reason:"forbidden"});if((s==="save"||s==="preview")&&!Nn(o))return j({reason:"forbidden"});try{return await Ut(s,o,u.searchParams)}catch(d){return j(Y(d,{operation:s},o.signal,c))}};return Object.freeze({loader:Ft,headers:Mn,dataLoader:({request:o,url:u,params:s})=>Be(o,u,s["*"]),dataAction:({request:o,url:u,params:s})=>Be(o,u,s["*"]),forgetTree:o=>{if(typeof o!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof o}`);$.forget(o)}})},Te=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),Dn=new Set(["md","markdown","mdx"]),At=new Map([...[["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"],["svg","image/svg+xml"],["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",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"}]]),$n=new Set(["txt","text","log","csv","tsv","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"]),jn=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),vt=typeof ie.constants.O_NOFOLLOW=="number"?ie.constants.O_NOFOLLOW:0,Nt=typeof ie.constants.O_NONBLOCK=="number"?ie.constants.O_NONBLOCK:0,mt=e=>`${e.size}-${e.mtimeNs}`,zn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),pt=e=>w.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(zn),Pt=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},Cn=e=>{const t=Pt(e);if(Dn.has(t))return{kind:"markdown"};const r=At.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image"}:{kind:"media",mediaType:r.mediaType};const n=e.toLowerCase();return $n.has(t)||!n.includes(".")&&jn.has(n)?{kind:"text"}:{kind:"file"}},De=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}},It=e=>{const t=De(e);return t===null?e:new ye(t)},Mt=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},Hn=async e=>{try{return Math.trunc((await me.lstat(e)).mtimeMs)}catch(t){if(Mt(t))return;throw t}},ht=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)},Bn=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},Fn=async(e,t,r,n)=>{let a;try{a=await me.open(e,ie.constants.O_RDONLY|vt|Nt);const y=await a.stat({bigint:!0});if(!y.isFile()||y.ino!==t.ino||y.dev!==t.dev||y.size!==t.size||y.mtimeNs!==t.mtimeNs)throw new ye("not-found")}catch(y){throw await a?.close(),It(y)}const i=a.createReadStream(Bn(r,t.size)),c=Wt.Readable.toWeb(i),m=()=>{i.destroy(n.reason)};return n.aborted?m():n.addEventListener("abort",m,{once:!0}),c},Un=(e,t)=>{const r=se.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},Xn=e=>{let t=0;const r=[];return async n=>{t<e?t+=1:await new Promise(a=>r.push(a));try{return await n()}finally{const a=r.shift();a===void 0?t-=1:a()}}},Gn=(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":w.isAcceptableDocumentPath(r)?w.isAcceptableDocumentPath(t)?null:"path-too-long":"control-character-or-backslash"},Jn=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","walkConcurrency","cacheScope","reportSkipped"]),Se=(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},Yn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");for(const b of Object.keys(e))if(!Jn.has(b))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(b)}`);const{id:t,label:r,root:n,parse:a}=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 a!="function")throw new TypeError("[markdown-explorer] a file-system source needs a parse function");if(typeof n!="string"||!ne.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let i;try{i=ie.statSync(n).isDirectory()}catch(b){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:b})}if(!i)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const c=ie.realpathSync(n),m=e.pathPrefix;if(typeof m!="string")throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');if(m!==""&&!(m.endsWith("/")&&pt(m.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(m)}`);const y=w.resolvePathRules(e.deny),O=Se("maxEntries",e.maxEntries,Te.maxEntries),h=Se("maxDocumentBytes",e.maxDocumentBytes,Te.maxDocumentBytes),g=Se("textPreviewBytes",e.textPreviewBytes,Te.textPreviewBytes),k=Se("walkConcurrency",e.walkConcurrency,Te.walkConcurrency),A=e.cacheScope===void 0?"principal":e.cacheScope;if(A!=="principal"&&A!=="shared")throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(A)}`);const $=e.reportSkipped;if($!==void 0&&typeof $!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const N=$===void 0?b=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(b.sourceId)} does not list ${JSON.stringify(b.path)}: ${b.reason}`)}:$,_=new Set,z=b=>{const R=ne.resolve(c,...b.split("/")),S=ne.relative(c,R);return S===""||S===".."||S.startsWith(`..${ne.sep}`)||ne.isAbsolute(S)?null:R},v=(b,R)=>{const S=`${R}\0${b}`;_.has(S)||_.size>=O||(_.add(S),N({sourceId:t,path:b,reason:R}))},I=async({signal:b})=>{b.throwIfAborted();const R=new AbortController,S=()=>{R.abort(b.reason)};b.addEventListener("abort",S,{once:!0});const P=Xn(k);let L=0;const X=async(D,G)=>{const Q=await P(async()=>{R.signal.throwIfAborted();try{return await me.readdir(D,{withFileTypes:!0})}catch(H){if(G===""||!Mt(H))throw H;return null}});if(R.signal.throwIfAborted(),Q===null)return v(`${m}${G}`,"unreadable-directory"),null;const J=[];for(const H of Q){if(y.deniesName(H.name))continue;const Z=G===""?H.name:`${G}/${H.name}`,q=`${m}${Z}`,ee=Gn(H,q);if(ee!==null){v(q,ee);continue}J.push({dirent:H,relativePath:Z,path:q})}if(L+=J.length,L>O)throw new ye("too-large");return J.sort((H,Z)=>Un(H.dirent.name,Z.dirent.name)),(await Promise.all(J.map(async({dirent:H,relativePath:Z,path:q})=>{const ee=await Hn(ne.join(D,H.name)),ce=ee===void 0?{}:{modifiedAt:ee};if(!H.isDirectory())return{name:H.name,path:q,type:"file",...ce};const ge=await X(ne.join(D,H.name),Z);return ge===null?null:{name:H.name,path:q,type:"directory",...ce,children:ge}}))).filter(H=>H!==null)};try{const D=await X(c,"");if(D===null)throw new Error("[markdown-explorer] the source's root could not be listed");return D}catch(D){throw R.abort(),D}finally{b.removeEventListener("abort",S)}},C=async b=>{if(!b.startsWith(m))return{status:"refused",reason:"not-found"};const R=b.slice(m.length);if(!pt(R))return{status:"refused",reason:"invalid"};if(y.deniesPath(R))return{status:"refused",reason:"forbidden"};const S=z(R);if(S===null)return{status:"refused",reason:"forbidden"};const P=await me.lstat(S,{bigint:!0});if(P.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!P.isFile())return{status:"refused",reason:"unsupported"};const L=await me.realpath(S);return L!==S||y.deniesPath(ne.relative(c,L).split(ne.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:S,name:R.slice(R.lastIndexOf("/")+1),stats:P}},F=async(b,R,S)=>{let P;try{const L=await C(S);if(L.status==="refused")return w.failureDocument(L.reason);const{target:X,name:D,stats:G}=L,Q=Cn(D),J=mt(G);if(Q.kind==="image")return{kind:"image",name:D,version:J};if(Q.kind==="media")return{kind:"media",name:D,mediaType:Q.mediaType,version:J};if(Q.kind==="file")return{kind:"file",name:D,version:J};P=await me.open(X,ie.constants.O_RDONLY|vt|Nt);const ae=await P.stat({bigint:!0});if(!ae.isFile()||ae.ino!==G.ino||ae.dev!==G.dev)return w.failureDocument("forbidden");if(Q.kind==="markdown"){if(ae.size>BigInt(h))return w.failureDocument("too-large");const ee=await ht(P,h+1);if(ee.length>h)return w.failureDocument("too-large");const ce=await a(new TextDecoder("utf-8").decode(ee),R);return{kind:"markdown",name:D,htmlContent:ce.htmlContent,headings:ce.headings,edit:null}}const H=await ht(P,g);if(H.includes(0))return{kind:"file",name:D,version:J};const Z=ae.size>BigInt(g),q=new TextDecoder("utf-8").decode(H,{stream:Z});return{kind:"text",name:D,text:q,truncated:Z,version:J}}catch(L){const X=De(L);if(X===null)throw L;return w.failureDocument(X)}finally{await P?.close()}},p=async(b,R,S)=>{let P;try{P=await C(S)}catch(J){throw It(J)}if(P.status==="refused")throw new ye(P.reason);const{target:L,name:X,stats:D}=P,G=At.get(Pt(X)),Q=G===void 0?"":G.contentType;return{name:X,contentType:Q,size:Number(D.size),version:mt(D),open:J=>Fn(L,D,J,b.signal)}},E=async(b,R,S)=>{let P;try{P=await C(S)}catch(D){if(De(D)!==null)return null;throw D}if(P.status==="refused")return null;const L=S.slice(m.length).split("/");if(L.some(D=>y.deniesName(D)))return null;const X=L.slice(0,-1);return X.map((D,G)=>`${m}${X.slice(0,G+1).join("/")}`)};return Object.freeze({id:t,label:r,cacheScope:A,boundary:Object.freeze({contains:b=>b.startsWith(m)}),tree:I,ancestors:E,document:F,asset:p})};exports.DEFAULT_DENIED_PATH_SEGMENTS=w.DEFAULT_DENIED_PATH_SEGMENTS;exports.MAX_DOCUMENT_PATH_LENGTH=w.MAX_DOCUMENT_PATH_LENGTH;exports.isAcceptableDocumentPath=w.isAcceptableDocumentPath;exports.isDeniedPath=w.isDeniedPath;exports.ExplorerError=ye;exports.anonymousAccess=Kt;exports.createFileSystemSource=Yn;exports.createMarkdownExplorer=Ln;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./dataRoute-BONacTPi.cjs"),wt=require("node:crypto"),Jt=require("@aiquants/markdown/server"),ke=require("@aiquants/request-isolation"),Re=require("react-router"),se=require("./location-D6RE3wAN.cjs"),ie=require("node:fs"),ne=require("node:path"),_e=require("node:url"),Yt=require("node:worker_threads"),me=require("node:fs/promises"),Wt=require("node:stream");var Ae=typeof document<"u"?document.currentScript:null;const Ue=Object.freeze({kind:"anonymous"}),Kt=Object.freeze({authenticate:async()=>({status:"signed-in",principal:Ue}),principalKey:()=>Ue.kind,signedOutPage:(e,t)=>new Response(null,{status:401,headers:t})}),Vt="application/octet-stream",yt="application/pdf",Qt=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",yt]),gt="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",Et=`${gt}; sandbox`,Zt=`${gt}; sandbox allow-same-origin`,Xe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,qt=/^[\t\n\r ]+|[\t\n\r ]+$/gu,De=/^[\t ]+|[\t ]+$/gu,er=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 a=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(a,n),n<e.length)continue}if(t.push(r.replace(De,"")),r="",n>=e.length)return t;n+=1}},tr=e=>{const t=e.replace(qt,""),r=t.indexOf("/");if(r<0)return null;const n=t.slice(0,r),a=t.indexOf(";",r+1),i=t.slice(r+1,a<0?t.length:a).replace(/[\t\n\r ]+$/u,"");return Xe.test(n)&&Xe.test(i)?`${n}/${i}`.toLowerCase():null},rr=e=>{let t=null;for(const r of er(e)){const n=tr(r);n!==null&&n!=="*/*"&&(t=n)}return t},nr=/['()*]/gu,bt=e=>encodeURIComponent(e).replace(nr,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),or=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),sr=(e,t)=>{const r=rr(e),n=r!==null&&Qt.has(r),a=n&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Vt:r,inline:n,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${n?"inline":"attachment"}; filename*=UTF-8''${bt(t)}`,...r===yt?{}:{"Content-Security-Policy":a?Zt:Et},"Cross-Origin-Resource-Policy":"same-origin"}}},ir="text/plain; charset=utf-8",ar=e=>({contentType:ir,inline:!0,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`inline; filename*=UTF-8''${bt(e)}`,"Content-Security-Policy":Et,"Cross-Origin-Resource-Policy":"same-origin"}}),cr=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,Ee=Object.freeze({kind:"whole"}),Ge=Object.freeze({kind:"unsatisfiable"}),ur=(e,t,r)=>{const n=e.get("Range");if(n===null)return Ee;const a=e.get("If-Range");if(a!==null&&a!==r)return Ee;const i=cr.exec(n);if(i===null)return Ee;const[,c,m,y]=i;if(y!==void 0){const g=Number(y);if(g===0)return Ge;const k=Math.max(0,t-g);return{kind:"partial",range:{offset:k,length:t-k}}}const x=Number(c),h=m===""?Number.POSITIVE_INFINITY:Number(m);return h<x?Ee:x>=t?Ge:{kind:"partial",range:{offset:x,length:Math.min(h,t-1)-x+1}}},Je="W/",dr=e=>{const t=[];let r=0,n=!1;for(let a=0;a<e.length;a+=1)e[a]==='"'?n=!n:e[a]===","&&!n&&(t.push(e.slice(r,a).replace(De,"")),r=a+1);return t.push(e.slice(r).replace(De,"")),t},Ye=e=>e.startsWith(Je)?e.slice(Je.length):e,lr=(e,t)=>{if(e===null)return!1;const r=dr(e);if(r.length===1&&r[0]==="*")return!0;const n=Ye(t);return r.some(a=>Ye(a)===n)},fr=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(n,a)=>{const i=n.byteLength>r?n.subarray(0,r):n;r-=i.byteLength,a.enqueue(i),r===0&&a.terminate()},flush:n=>{r>0&&n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},ve=async(e,t,r,n,a)=>{if(n!==null&&r.set("Content-Length",String(n)),e.method.toUpperCase()==="HEAD")return new Response(null,{status:t,headers:r});const i=await a();return new Response(n===null?i:fr(i,n),{status:t,headers:r})},mr=(e,t)=>{const r=new Headers(e);for(const[n,a]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${t}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))r.set(n,a);return new Response(null,{status:416,headers:r})},pr=async(e,t,r,n)=>{const a=`"${t.version}"`,i=n==="text"?ar(t.name):sr(t.contentType,t.name),c=new Headers(r);for(const[x,h]of Object.entries({...i.headers,...or,ETag:a}))c.set(x,h);if(lr(e.headers.get("If-None-Match"),a))return new Response(null,{status:304,headers:c});if(c.set("Content-Type",i.contentType),t.size===null)return ve(e,200,c,null,()=>t.open(null));if(t.size===0)return c.set("Content-Length","0"),new Response(null,{status:200,headers:c});c.set("Accept-Ranges","bytes");const m=ur(e.headers,t.size,a);if(m.kind==="unsatisfiable")return mr(r,t.size);if(m.kind==="whole")return ve(e,200,c,t.size,()=>t.open(null));const{range:y}=m;return c.set("Content-Range",`bytes ${y.offset}-${y.offset+y.length-1}/${t.size}`),ve(e,206,c,y.length,()=>t.open(y))},Ne=(e,t)=>{const r=new AbortController,n=t(AbortSignal.any([e.signal,r.signal]));return new Promise(a=>{let i;const c=setTimeout(()=>{a(e.late),i=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),m=()=>{clearTimeout(c),clearTimeout(i)};n.then(y=>{m(),a(y)},()=>{m(),a(e.late)})})},hr=Object.freeze({error:(e,t)=>{console.error(e,t)}}),Tt=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class ye extends Error{reason;code;constructor(t,r={}){if(!w.isExplorerFailureReason(t))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);if(r.code!==void 0&&!w.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,Tt,{value:!0})}}const wr=e=>e instanceof Error&&Object.hasOwn(e,Tt)&&w.isExplorerFailureReason(e.reason),yr=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",je=(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})}},oe=(e,t)=>je(e,`[markdown-explorer] ${t.operation} failed`,t),gr=(e,t)=>je(e,`[markdown-explorer] ${t.operation} left out an entry`,t),Pe=(e,t)=>je(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),We=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},Y=(e,t,r,n)=>wr(e)?w.failureOf(e.reason,e.code):(yr(e)||r.aborted||oe(n,{...t,error:e}),{reason:"failed"}),Ke=2*1024*1024,Ve=256*1024*1024,Er=async(e,t)=>{const r=e.getReader(),n=new Uint8Array(t);let a=0;for(;a<t;){const{done:i,value:c}=await r.read();if(i)return n.subarray(0,a);const m=c.subarray(0,t-a);n.set(m,a),a+=m.byteLength}return r.cancel().catch(()=>{}),n},br=async(e,t)=>{if(e.size===0)return{text:"",truncated:!1};const r=e.size!==null&&e.size>t,n=e.size===null?t+1:Math.min(e.size,t),a=await Er(await e.open(r?{offset:0,length:t}:null),n);if(e.size!==null&&a.byteLength<n)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const i=r||a.byteLength>t,c=i?a.subarray(0,t):a;return c.includes(0)?null:{text:new TextDecoder("utf-8").decode(c,{stream:i}),truncated:i}},Qe=(e,t)=>{if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`)},St=(e,t)=>{Qe("capacity",e),t!==void 0&&Qe("weight budget",t.max);const r=new Map;let n=0;const a=i=>{const c=r.get(i);c!==void 0&&(r.delete(i),n-=c.weight)};return{get:i=>{const c=r.get(i);if(c!==void 0)return r.delete(i),r.set(i,c),c.value},set:(i,c)=>{a(i);const m=t===void 0?0:t.of(i,c);if(!(t!==void 0&&m>t.max)){r.set(i,{value:c,weight:m}),n+=m;for(const y of r.keys()){if(r.size<=e&&(t===void 0||n<=t.max))break;a(y)}}},delete:a,size:()=>r.size,weight:()=>n}},kt=e=>Math.max(1,e-1),Tr=2147483647,Ze=Object.freeze({status:"aborted"}),de=(e,t,r)=>{const n=(e.get(t)??0)+r;n===0?e.delete(t):e.set(t,n)},fe=(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)}`)},Sr=e=>e!==null&&typeof e=="object"&&e.ready===!0&&!("id"in e),kr=(e,t)=>e!==null&&typeof e=="object"&&e.id===t&&"output"in e,xr=({url:e,size:t,deadlineMs:r,jobsPerScope:n,maxQueuedJobs:a,heapLimits:i})=>{fe("size",t,Number.MAX_SAFE_INTEGER),fe("deadline",r,Tr),fe("jobsPerScope",n,Number.MAX_SAFE_INTEGER),fe("maxQueuedJobs",a,Number.MAX_SAFE_INTEGER),fe("maxOldGenerationSizeMb",i.maxOldGenerationSizeMb,Number.MAX_SAFE_INTEGER),fe("maxYoungGenerationSizeMb",i.maxYoungGenerationSizeMb,Number.MAX_SAFE_INTEGER);const c=Object.freeze({maxOldGenerationSizeMb:i.maxOldGenerationSizeMb,maxYoungGenerationSizeMb:i.maxYoungGenerationSizeMb}),m=new Set,y=[],x=new Map,h=new Map,g=kt(t);let k=0;const A=(p,E)=>{const{job:b}=p;p.timer!==null&&clearTimeout(p.timer),p.timer=null,p.job=null,p.sent=!1,b!==null&&(de(x,b.scope,-1),de(h,b.scope,-1),b.settle(E))},$=p=>{const[E]=y.splice(p,1);E?.detach()},N=()=>{let p=-1,E=g,b=Number.POSITIVE_INFINITY;for(const[R,S]of y.entries()){const P=x.get(S.scope)??0,L=h.get(S.scope)??0;(P<E||P===E&&p>=0&&L<b)&&(p=R,E=P,b=L)}return p},_=(p,E)=>{m.has(p)&&(m.delete(p),A(p,E),p.worker.terminate().catch(()=>{}),F())},z=p=>{p.timer=setTimeout(()=>{_(p,{status:"timeout"})},r)},v=(p,E)=>p.sent?{status:"crashed",error:E}:{status:"unavailable",error:E},I=(p,E)=>{p.sent=!0,z(p);try{p.worker.postMessage({id:E.id,input:E.input})}catch(b){A(p,{status:"crashed",error:b}),p.worker.unref()}},C=()=>{const p={worker:new Yt.Worker(e,{resourceLimits:c}),job:null,sent:!1,timer:null,ready:!1};return p.worker.unref(),p.timer=setTimeout(()=>{_(p,{status:"unavailable",error:new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`)})},r),p.worker.on("message",E=>{if(!p.ready&&Sr(E)){p.ready=!0,p.timer!==null&&clearTimeout(p.timer),p.timer=null,p.job===null?p.worker.unref():I(p,p.job),p.job===null&&F();return}const{job:b}=p;if(b===null||!kr(E,b.id)){_(p,v(p,new Error("[markdown-explorer] a worker sent a message that answers no job")));return}A(p,{status:"done",output:E.output}),p.worker.unref(),F()}),p.worker.on("error",E=>{_(p,v(p,E))}),p.worker.on("messageerror",E=>{_(p,v(p,E))}),p.worker.on("exit",E=>{_(p,v(p,new Error(`[markdown-explorer] a worker exited with code ${String(E)}`)))}),m.add(p),p},F=()=>{for(;;){const p=N(),E=y[p];if(E===void 0)return;let b;for(const S of m)if(S.job===null){b=S;break}if(b===void 0&&m.size<t)try{b=C()}catch(S){$(p),de(h,E.scope,-1),E.settle({status:"unavailable",error:S});continue}if(b===void 0)return;$(p),de(x,E.scope,1);const R=b;R.job=E,R.worker.ref(),R.ready&&I(R,E)}};return{run:(p,{scope:E,signal:b})=>new Promise(R=>{if(b.aborted){R(Ze);return}if((h.get(E)??0)>=n){R({status:"refused",limit:"scope"});return}k+=1;const S={id:k,input:p,scope:E,settle:R,detach:()=>{}};y.push(S),de(h,E,1),F();const P=y.indexOf(S);if(P<0)return;if(y.length>a){$(P),de(h,E,-1),R({status:"refused",limit:"queue"});return}const L=()=>{const X=y.indexOf(S);X<0||($(X),de(h,E,-1),R(Ze))};b.addEventListener("abort",L,{once:!0}),S.detach=()=>{b.removeEventListener("abort",L)}}),workers:()=>m.size}},ze=1024*1024,Or=3e4,Rr=4*ze,_r=64*ze,Ar=3,vr=2,Nr=(e,t)=>e+kt(t)+Ar,Pr=4,Ir=32,Mr=512,Lr=64,Dr=4096,$r=32,qe=4096,jr=4,xt=({workerHeapMb:e,maxHtmlBytes:t})=>Math.floor(((e-Lr)*ze-t*$r)/Dr),zr=({maxHtmlBytes:e})=>e,Cr=({maxHtmlBytes:e})=>jr*e,Hr=1024,Br=2147483647,Fr=64,Ur=2**29,Xr=1024*1024,Gr=64,et=Object.freeze({status:"rejected",reason:"too-large",cause:null}),Ie=Object.freeze({status:"rejected",reason:"failed",cause:null}),le=(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},Jr=(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:a,cacheBytes:i,workerHeapMb:c,jobsPerScope:m,maxQueuedJobs:y}=e??{},x=le("workers",r,vr,Fr),h=le("jobsPerScope",m,Nr(t,x),Number.MAX_SAFE_INTEGER),g=Object.freeze({workers:x,deadlineMs:le("deadlineMs",n,Or,Br),maxHtmlBytes:le("maxHtmlBytes",a,Rr,Ur),cacheBytes:le("cacheBytes",i,_r,Number.MAX_SAFE_INTEGER),workerHeapMb:le("workerHeapMb",c,Mr,Xr),jobsPerScope:h,maxQueuedJobs:le("maxQueuedJobs",y,Pr*h,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(xt(g)<qe)throw new RangeError(`[markdown-explorer] sanitizer.workerHeapMb (${String(g.workerHeapMb)} MiB) must leave room for ${String(qe)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(g.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`);return g},Yr=()=>{const e=typeof document>"u"?require("url").pathToFileURL(__filename).href:Ae&&Ae.tagName.toUpperCase()==="SCRIPT"&&Ae.src||new URL("server.cjs",document.baseURI).href,t=new URL(`./sanitizeWorker${ne.extname(_e.fileURLToPath(e))}`,e);if(!ie.existsSync(_e.fileURLToPath(t)))throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${_e.fileURLToPath(t)}`);return t},tt=new Map,Wr=(e,t)=>{const r=[e.href,t.workers,t.deadlineMs,t.workerHeapMb,t.jobsPerScope,t.maxQueuedJobs].map(String).join("\0");let n=tt.get(r);return n===void 0&&(n=xr({url:e,size:t.workers,deadlineMs:t.deadlineMs,jobsPerScope:t.jobsPerScope,maxQueuedJobs:t.maxQueuedJobs,heapLimits:{maxOldGenerationSizeMb:t.workerHeapMb,maxYoungGenerationSizeMb:Ir}}),tt.set(r,n)),n},Kr=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"},Vr=e=>e instanceof Error&&e.code==="ERR_WORKER_OUT_OF_MEMORY",Qr=({iframeHosts:e,dataPath:t,options:r,pool:n})=>{const a=Object.freeze([...e]),i=xt(r),c=zr(r),m=Cr(r),y=St(Hr,{max:r.cacheBytes,of:(N,_)=>2*N.length+(_.status==="sanitized"?2*_.html.length:Gr)}),x=new Map,h=new Map,g=N=>{x.get(N.key)===N&&x.delete(N.key);const _=h.get(N.hash);_?.delete(N),_?.size===0&&h.delete(N.hash)},k=async(N,_,z)=>{const v=await n.run({html:N,iframeHosts:a,dataPath:t,maxNodes:i,maxAttributeChars:c,maxSanitizedChars:m},{scope:_,signal:z});if(v.status==="refused"){const C=v.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(v.status==="aborted")return{outcome:Ie,lasting:!1};if(v.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(v.status==="unavailable")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker could not start",{cause:v.error})},lasting:!1};if(v.status==="crashed"&&Vr(v.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:v.error})},lasting:!0};if(v.status==="crashed")return{outcome:{status:"rejected",reason:"failed",cause:new Error("[markdown-explorer] the HTML sanitizer worker failed",{cause:v.error})},lasting:!0};const{output:I}=v;return Kr(I)?I.status==="too-large"?{outcome:et,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>m?{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(m)}`)},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}},A=(N,_,z,v)=>{let I=()=>{};const C=new Promise(E=>{I=E}),F={hash:_,key:z,outcome:C,answer:I,controller:new AbortController,waiters:0};x.set(z,F);const p=h.get(_);return p===void 0?h.set(_,new Set([F])):p.add(F),k(N,v,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:b})=>{if(g(F),F.answer(E),!b)return;const R=y.get(_),S=R??(E.status==="rejected"?{...E,cause:null}:E);R===void 0&&y.set(_,S);for(const P of h.get(_)??[])g(P),P.answer(S),P.controller.abort()}),F},$=(N,_)=>new Promise(z=>{N.waiters+=1;const v=()=>{N.waiters-=1,z(Ie),!(N.waiters>0)&&(g(N),N.controller.abort())};_.addEventListener("abort",v,{once:!0}),N.outcome.then(I=>{_.removeEventListener("abort",v),z(I)})});return(N,{scope:_,signal:z})=>{if(N.length>r.maxHtmlBytes||Buffer.byteLength(N,"utf8")>r.maxHtmlBytes)return Promise.resolve(et);const v=wt.createHash("sha256").update(N,"utf8").digest("base64"),I=y.get(v);if(I!==void 0)return Promise.resolve(I);if(z.aborted)return Promise.resolve(Ie);const C=`${v}\0${_}`,F=x.get(C);return $(F===void 0?A(N,v,C,_):F,z)}},xe=e=>({result:e,json:JSON.stringify(e)}),Me=Object.freeze(xe(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),Zr=e=>e.status==="ok"&&e.entries.length>0,qr=({ttlMs:e,maxEntries:t,maxBytes:r,now:n})=>{const a=St(t,{max:r,of:(h,g)=>2*g.tree.json.length}),i=new Map,c=new Map,m=(h,g)=>{const k=new AbortController,A={waiters:0,superseded:!1,started:!1,loadTree:g},$=c.get(h),N=(C,F)=>{const p=xe(C);return!(A.superseded||k.signal.aborted)&&Zr(C)&&a.set(h,{tree:p,loadedAt:F}),p},z=(async()=>{if($!==void 0&&await $,k.signal.aborted)return Me;const C=n();return A.started=!0,N(await A.loadTree(k.signal,C),C)})().finally(()=>{i.get(h)===v&&i.delete(h)}),v={promise:z,controller:k,state:A};i.set(h,v);const I=z.then(()=>{},()=>{});return c.set(h,I),I.then(()=>{c.get(h)===I&&c.delete(h)}),v},y=(h,g,k)=>{g.state.waiters+=1;const A=()=>{g.state.waiters-=1,!(g.state.waiters>0)&&(i.get(h)===g&&i.delete(h),g.controller.abort())};return k.addEventListener("abort",A,{once:!0}),g.promise.finally(()=>{k.removeEventListener("abort",A)})},x=h=>{a.delete(h);const g=i.get(h);g?.state.started&&(g.state.superseded=!0,i.delete(h))};return{load:(h,g,k)=>{if(g.aborted)return Promise.resolve(Me);const A=a.get(h);if(A!==void 0){if(n()-A.loadedAt<e)return Promise.resolve(A.tree);a.delete(h)}const $=i.get(h);return y(h,$===void 0?m(h,k):$,g)},refresh:(h,g,k)=>{if(g.aborted)return Promise.resolve(Me);x(h);const A=i.get(h);return A===void 0?y(h,m(h,k),g):(A.state.loadTree=k,y(h,A,g))},forget:x}},en=e=>({load:(t,r,n)=>n(r,e()).then(xe),refresh:(t,r,n)=>n(r,e()).then(xe),forget:()=>{}}),O=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},tn=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"}:w.isAcceptableDocumentPath(r)?null:{path:r,reason:"a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)"}},rn=(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 a=new Set;for(const i of e){if(typeof i!="string"||!w.isAcceptableDocumentPath(i))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(r.deniesPath(i))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!n(i))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(i===t)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(a.has(i))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");a.add(i)}return Object.freeze([...a])},nn=(e,t,r,n,a)=>{const i=new Set,c=y=>{if(!Array.isArray(y))return O("a source returned entries that are not an array");const x=[];for(const h of y){const g=m(h);g!==null&&x.push(g)}return x},m=y=>{const x=tn(y);if(x!==null)return n(x),null;const h=w.entryViolation(y);if(h!==null)return O(h);const g=y;if(i.has(g))return O("a source returned entries that contain themselves");const{name:k,path:A,type:$,mimeType:N,modifiedAt:_,children:z,lazy:v}=g;if(t.deniesName(k)||t.deniesPath(A))return null;if(!a(A))return n({path:A,reason:"a path outside the source's boundary"}),null;const I={name:k,path:A,...N===void 0?{}:{mimeType:N},..._===void 0?{}:{modifiedAt:_}};if($==="file")return{...I,type:$};if(v===!0)return r?{...I,type:$,lazy:!0,children:[]}:O("a lazy directory came from a source without a children function");if(z===void 0)return{...I,type:$};i.add(g);const C=c(z);return i.delete(g),{...I,type:$,children:C}};return c(e)},on=/^[\x21\x23-\x7E]{1,256}$/u,Ot=e=>typeof e=="string"&&on.test(e),sn=new Set(["text","image","media","file"]),an=e=>typeof e=="string"&&sn.has(e),cn=(e,t,r)=>{if(e!==null&&typeof e=="object"){const i=e,{kind:c}=i;if(an(c)){if(Object.hasOwn(i,"url"))return O(`a ${c} document carries its version, not a url`);if(typeof i.name!="string")return O("a document needs a name string");if(!Ot(i.version))return O(`a ${c} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const m=t(i.version);switch(c){case"image":case"file":return{kind:c,name:i.name,url:m};case"media":{const{mediaType:y}=i;return w.isExplorerMediaType(y)?{kind:c,name:i.name,url:m,mediaType:y}:O(`unknown media type ${typeof y=="string"?JSON.stringify(y.slice(0,64)):typeof y}`)}case"text":return typeof i.text!="string"||typeof i.truncated!="boolean"?O("a text document needs text and truncated"):{kind:c,name:i.name,text:i.text,truncated:i.truncated,url:m}}}}const n=w.documentViolation(e);if(n!==null)return O(n);const a=e;switch(a.kind){case"failure":{const{reason:i,code:c}=a.failure;return{kind:"failure",failure:w.failureOf(i,c)}}case"markdown":return a.headings.length>w.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:w.failureOf("too-large")}:(a.edit?.kind==="inline"||a.edit?.kind==="draft")&&!r?O(`a markdown document offers ${a.edit.kind} editing, but the server has no edit ports`):{kind:"unsanitized-markdown",name:a.name,html:a.htmlContent,headings:a.headings.map(({text:i,depth:c,id:m})=>({text:i,depth:c,id:m})),edit:un(a.edit)}}},un=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}}},Oe=(e,t,r)=>typeof e!="string"?O(`${r} needs a text string`):e.includes("\0")?O(`${r} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>t?O(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`):e,Rt=e=>w.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:O("a grant needs a root-relative href"),dn=(e,t)=>{if(e===null||typeof e!="object")return O("an edit source must be an object");const r=e;return r.kind==="grant"?Rt(r):r.kind==="draft"?{kind:"draft",text:Oe(r.text,t,"a draft source")}:r.kind!=="edit"?O(`an edit source's kind must be "edit", "draft" or "grant"`):w.isExplorerEditToken(r.version)?typeof r.history!="boolean"?O("an edit source needs history"):{kind:"edit",text:Oe(r.text,t,"an edit source"),version:r.version,history:r.history}:O("an edit source needs a version of 1 to 1024 characters")},ln=(e,t)=>{if(e===null||typeof e!="object")return O("a save result must be an object");const r=e;switch(r.kind){case"grant":return Rt(r);case"saved":return w.isExplorerEditToken(r.version)?{kind:"saved",version:r.version}:O("a saved result needs a version of 1 to 1024 characters");case"conflict":return w.isExplorerEditToken(r.version)?{kind:"conflict",version:r.version,text:Oe(r.text,t,"a conflict's current text")}:O("a conflict needs the current version of 1 to 1024 characters");default:return O(`a save result's kind must be "saved", "conflict" or "grant"`)}},fn=e=>{if(e===null||typeof e!="object")return O("a preview must be an object");const{htmlContent:t,headings:r}=e;if(typeof t!="string"||!Array.isArray(r))return O("a preview needs htmlContent and headings");if(r.length>w.EXPLORER_MAX_HEADINGS)return{kind:"failure",failure:w.failureOf("too-large")};for(const n of r){const a=w.headingViolation(n);if(a!==null)return O(a)}return{html:t,headings:r.map(({text:n,depth:a,id:i})=>({text:n,depth:a,id:i}))}},mn=e=>{if(!Array.isArray(e))return O("revisions must be an array");const t=new Set;return e.map(r=>{const n=w.revisionViolation(r);if(n!==null)return O(n);const{id:a,modifiedAt:i,size:c,author:m,kept:y,current:x}=r;return t.has(a)?O(`two revisions share the id ${JSON.stringify(a.slice(0,64))}`):(t.add(a),{id:a,modifiedAt:i,size:c,author:m,kept:y,current:x})})},pn=(e,t)=>Oe(e,t,"a revision"),rt=e=>{if(e===null||typeof e!="object")return O("an asset file must be an object");const{name:t,contentType:r,size:n,version:a,open:i}=e;return typeof t!="string"||t===""?O("an asset file needs a non-empty name"):typeof r!="string"?O("an asset file needs a contentType string ('' when unknown)"):n!==null&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)?O("an asset file's size must be null or a non-negative safe integer"):Ot(a)?typeof i!="function"?O("an asset file needs an open function"):Object.freeze({name:t,contentType:r,size:n,version:a,open:i}):O(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`)},hn=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return O("a notice must be an object");const{id:r,tone:n,title:a,body:i,action:c}=t;if(typeof r!="string"||r===""||typeof a!="string")return O("a notice needs an id and a title");if(!w.isExplorerNoticeTone(n))return O(`unknown notice tone ${typeof n=="string"?JSON.stringify(n.slice(0,64)):typeof n}`);if(i!==void 0&&typeof i!="string")return O("a notice body must be a string");const y={id:r,tone:n,title:a,...i===void 0?{}:{body:i}};if(c===void 0)return y;if(c===null||typeof c!="object")return O("a notice action must be an object");const{label:x,href:h}=c;return typeof x!="string"||!w.isAcceptableUrl(h,w.EXPLORER_LINK_PROTOCOLS)?O("a notice action needs a label and an http(s), mailto or relative href"):{...y,action:{label:x,href:h}}}):O("notices must be an array"),wn=4e3,be=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),nt=32,_t="private, no-store",yn=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":_t,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),gn=22,En=2147483647,Le=Object.freeze([]),bn=Object.freeze({status:"ok",source:null,ancestors:null}),ot=Object.freeze(["contains","confirm"]),st=Object.freeze({readOnly:!1}),Tn=Object.freeze({readOnly:!0}),V=(e,t,r)=>{if(!(r&&t===void 0)&&typeof t!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`)},pe=(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},Sn=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return se.revalidateExplorerConfig(e)},it=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)")}},at=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,kn=e=>{if(typeof e!="string")throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);if(e.length<nt)throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(nt)} characters; got ${String(e.length)}`);return e},xn=(e,t)=>{if(!se.isPlainObject(t))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const r of Object.keys(t))if(!ot.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${ot.join(", ")}`);V(`${e}.boundary.contains`,t.contains,!1),V(`${e}.boundary.confirm`,t.confirm,!0)},On=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,a]of t.entries()){if(a===null||typeof a!="object")throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);const{id:i,label:c,boundary:m,tree:y,children:x,ancestors:h,cacheScope:g}=a;if(!se.isExplorerSourceId(i))throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof i=="string"?JSON.stringify(i):typeof i}`);const k=`source ${JSON.stringify(i)}`;if(r.has(i))throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(i)} repeats at sources[${String(n)}]`);if(r.add(i),typeof c!="string"&&typeof c!="function")throw new TypeError(`[markdown-explorer] ${k}.label must be a string or a function`);if(typeof c=="string"&&c.trim()==="")throw new RangeError(`[markdown-explorer] ${k}.label must not be blank`);if(xn(k,m),V(`${k}.tree`,y,!1),V(`${k}.children`,x,!0),V(`${k}.ancestors`,h,!0),g!==void 0&&g!=="principal"&&g!=="shared")throw new RangeError(`[markdown-explorer] ${k}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(g)}`)}return t},Rn=e=>{if(e===!1)return!1;if(e===void 0)return be;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?be.ttlMs:pe("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?be.maxEntries:pe("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:n===void 0?be.maxBytes:pe("treeCache.maxBytes",n,Number.MAX_SAFE_INTEGER)}},ct=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},ut=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},dt=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");return wt.createHmac("sha256",e).update(t,"utf8").digest("base64url").slice(0,gn)},_n=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],ue=(e,t)=>{const r=e.getAll(t),[n]=r;return r.length===1&&n!==void 0&&n!==""?n:null},K=(e,t,r,n={})=>{const a=new Headers(r);for(const[i,c]of Object.entries({...yn,...n}))a.set(i,c);return new Response(t,{status:e,headers:a})},j=(e,t,r)=>K(w.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),An=new Set(["refresh","save","preview"]),vn=new Set(["edit","save","preview","revisions","revision"]),lt=(e,t)=>{const r=An.has(t)?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:K(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},ft=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_REFRESH_PROOF&&ke.crossOriginRefusal(e,ke.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Nn=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_EDIT_PROOF&&ke.crossOriginRefusal(e,ke.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Pn=async(e,t)=>{const[r,...n]=(e.headers.get("Content-Type")??"").split(";").map(k=>k.trim().toLowerCase()),a=n.find(k=>k.startsWith("charset="));if(r!==w.EXPLORER_DRAFT_MEDIA_TYPE||a!==void 0&&a!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const i=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(i)&&i>t)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const c=e.body.getReader(),m=[];let y=0;for(;;){const{done:k,value:A}=await c.read();if(k)break;if(y+=A.byteLength,y>t)return await c.cancel(),{status:"error",failure:{reason:"too-large"}};m.push(A)}const x=new Uint8Array(y);let h=0;for(const k of m)x.set(k,h),h+=k.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}},In=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"])V(`edit.${r}`,t[r],!1);return e},Mn=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const n=new Headers,a=r===void 0?[e,t]:[e,t,r];for(const i of a)for(const[c,m]of i)c!=="set-cookie"&&n.set(c,m);return n},Ln=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const t=Sn(e.config),r=kn(e.scopeSecret);V("authenticate",e.authenticate,!1),V("principalKey",e.principalKey,!1),V("document",e.document,!1),V("asset",e.asset,!1),V("signedOutPage",e.signedOutPage,!1),V("forbiddenPage",e.forbiddenPage,!0),V("notices",e.notices,!0),V("onTreeRefreshed",e.onTreeRefreshed,!0);const n=On(e.sources),a=se.withExplorerSources(t,n.map(o=>o.id)),i=e.logger;if(i!==void 0&&(i===null||typeof i!="object"||typeof i.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const c=e.logger===void 0?hr:e.logger,m=w.resolvePathRules(e.deny),y=e.deferredTimeoutMs===void 0?wn:pe("deferredTimeoutMs",e.deferredTimeoutMs,En),x=e.textMaxBytes===void 0?Ke:pe("textMaxBytes",e.textMaxBytes,Ve),h=In(e.edit);if(h===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const g=e.editMaxBytes===void 0?Ke:pe("editMaxBytes",e.editMaxBytes,Ve),k=Rn(e.treeCache),A=()=>Date.now(),$=k===!1?en(A):qr({...k,now:A}),N=Jr(e.sanitizer,t.multiView.maxPanels),_=Qr({iframeHosts:t.iframeHosts,dataPath:t.dataPath,options:N,pool:Wr(Yr(),N)}),z=new Map(n.map(o=>[o.id,o])),v=se.documentStyleNames(t),{authenticate:I,principalKey:C,signedOutPage:F,forbiddenPage:p,onTreeRefreshed:E}=e,b=(o,u)=>{if(typeof o.label=="string")return o.label;const s=o.label(u);if(typeof s!="string"||s.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(o.id)} must be a non-blank string`);return s},R=(o,u)=>o.cacheScope==="shared"?o.id:`${o.id}\0${u}`,S=(o,u)=>{const s=l=>oe(c,{operation:"boundary",sourceId:o.id,path:u,error:l});let d;try{d=o.boundary.contains(u)}catch(l){return s(l),!1}return typeof d=="boolean"?d:(We(d,s),s(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(o.id)} must return a boolean; got ${typeof d}`)),!1)},P=async(o,u,s)=>{const{confirm:d}=o.boundary;if(d===void 0)return{status:"inside",readPath:s};let l;try{l=await d(u,s)}catch(U){return{status:"error",failure:Y(U,{operation:"boundary",sourceId:o.id,path:s},u.signal,c)}}const f=U=>(oe(c,{operation:"boundary",sourceId:o.id,path:s,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} ${U}`)}),{status:"outside"});if(l===null||typeof l!="object")return f(`must resolve to { inside, readPath? }; got ${l===null?"null":typeof l}`);const{inside:T,readPath:M}=l;return T===!1?{status:"outside"}:T!==!0||typeof M!="string"?f("must resolve to { inside: false } or { inside: true, readPath: string }"):!w.isAcceptableDocumentPath(M)||m.deniesPath(M)?(oe(c,{operation:"boundary",sourceId:o.id,path:s,error:new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} answered a readPath the explorer does not serve (unacceptable or denied)`)}),{status:"error",failure:{reason:"failed"}}):{status:"inside",readPath:M}},L=async(o,u)=>{const s=n.filter(l=>S(l,u));if(s.length===0)return{status:"error",failure:{reason:"forbidden"}};if(s.some(l=>l.boundary.confirm===void 0))return{status:"inside",readPath:u};let d=null;for(const l of s){const f=await P(l,o,u);if(f.status==="inside")return f;f.status==="error"&&d===null&&(d=f.failure)}return{status:"error",failure:d===null?{reason:"forbidden"}:d}},X=(o,u,s)=>{const d=({path:l,reason:f})=>gr(c,{operation:s.operation,sourceId:s.sourceId,path:l,error:new TypeError(`[markdown-explorer] an entry with ${f} was left out`)});try{return{status:"ok",entries:nn(o,m,u.children!==void 0,d,l=>S(u,l))}}catch(l){return oe(c,{...s,error:l}),{status:"error",failure:{reason:"failed"}}}},D=async(o,u,s)=>{let d;try{d=await o.tree(u)}catch(f){return{status:"error",failure:Y(f,{operation:"tree",sourceId:o.id},u.signal,c)}}const l=X(d,o,{operation:"tree",sourceId:o.id});return l.status==="ok"?{status:"ok",entries:l.entries,loadedAt:s}:l},G=(o,u,s,d)=>(l,f)=>D(o,{principal:u,request:s,signal:l,refresh:d},f),Q=(o,u,s,d,l)=>$.load(R(o,s),l,G(o,u,d,!1)),J=(o,u,s,d)=>$.refresh(R(o,s),d.signal,G(o,u,d,!0)),ae=(o,u)=>{if(E===void 0)return;const s=d=>oe(c,{operation:"refresh",sourceId:o.id,error:d});try{We(E(u),s)}catch(d){s(d)}},H=async(o,u,s,d)=>{if(m.deniesPath(d)||!S(o,d))return{status:"error",failure:{reason:"forbidden"}};const l=await P(o,s,d);if(l.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(l.status==="error")return{status:"error",failure:l.failure};let f;try{f=await u(s,d,l.readPath)}catch(T){return{status:"error",failure:Y(T,{operation:"children",sourceId:o.id,path:d},s.signal,c)}}return X(f,o,{operation:"children",sourceId:o.id,path:d})},Z=async(o,u,s,d)=>{const l=await P(o,s,d);if(l.status==="outside")return{status:"ok",ancestors:null};if(l.status==="error")return{status:"error",failure:l.failure};let f;try{f=await u(s,d,l.readPath,{maxDepth:t.revealDocument.maxDepth})}catch(T){return{status:"error",failure:Y(T,{operation:"ancestors",sourceId:o.id,path:d},s.signal,c)}}if(Array.isArray(f)&&f.length>t.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:rn(f,d,m,T=>S(o,T))}}catch(T){return oe(c,{operation:"ancestors",sourceId:o.id,path:d,error:T}),{status:"error",failure:{reason:"failed"}}}},q=async(o,u,s,d)=>m.deniesPath(d)?{status:"error",failure:{reason:"forbidden"}}:S(o,d)?Z(o,u,s,d):{status:"ok",ancestors:null},ee=async(o,u,s)=>{if(m.deniesPath(s))return{status:"error",failure:{reason:"forbidden"}};for(const d of[o,...n.filter(l=>l!==o)]){if(u.signal.aborted)break;const l=d.ancestors;if(l===void 0||!S(d,s))continue;const f=await Z(d,l,u,s);if(f.status==="ok"&&f.ancestors!==null)return{status:"ok",source:d.id,ancestors:f.ancestors}}return bn},ce=async(o,u,s)=>{if(m.deniesPath(s))return w.failureDocument("forbidden");const d=await L(o,s);if(d.status==="error")return{kind:"failure",failure:d.failure};let l;try{l=await e.document(o,s,d.readPath)}catch(M){return{kind:"failure",failure:Y(M,{operation:"document",path:s},o.signal,c)}}let f;try{f=cn(l,M=>w.explorerAssetHref(t.dataPath,s,M),h!==void 0)}catch(M){return oe(c,{operation:"document",path:s,error:M}),w.failureDocument("failed")}if(f.kind!=="unsanitized-markdown")return f;const T=await _(f.html,{scope:u,signal:o.signal});return T.status==="sanitized"?{kind:"markdown",name:f.name,htmlContent:T.html,headings:f.headings,edit:f.edit}:(T.cause!==null&&oe(c,{operation:"document",path:s,error:T.cause}),w.failureDocument(T.reason))},ge=async o=>{if(e.notices===void 0)return Le;try{return hn(await e.notices(o))}catch(u){return Y(u,{operation:"notices"},o.signal,c),Le}},Lt=async(o,u,s)=>{const d=ue(u,w.EXPLORER_DATA_QUERY.path);if(d===null||!w.isAcceptableDocumentPath(d))return j({reason:"invalid"},s);const l=w.readExplorerAssetDisplay(u);if(l===null)return j({reason:"invalid"},s);if(m.deniesPath(d))return Pe(c,{operation:"asset",path:d}),j({reason:"forbidden"},s);const f=await L(o,d);if(f.status==="error")return j(f.failure,s);try{const T=rt(await e.asset(o,d,f.readPath));return await pr(o.request,T,s,l)}catch(T){return j(Y(T,{operation:"asset",path:d},o.signal,c),s)}},Dt=async(o,u)=>{if(m.deniesPath(u))return Pe(c,{operation:"text",path:u}),w.failureDocument("forbidden");const s=await L(o,u);if(s.status==="error")return{kind:"failure",failure:s.failure};try{const d=rt(await e.asset(o,u,s.readPath)),l=await br(d,x);return l===null?w.failureDocument("unsupported"):{kind:"text",name:d.name,text:l.text,truncated:l.truncated,url:w.explorerAssetHref(t.dataPath,u,d.version)}}catch(d){return{kind:"failure",failure:Y(d,{operation:"text",path:u},o.signal,c)}}},he=async(o,u,s)=>m.deniesPath(s)?(Pe(c,{operation:u,path:s}),{status:"error",failure:{reason:"forbidden"}}):L(o,s),$t=async(o,u,s)=>{const d=await he(u,"edit",s);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return dn(await o.source(u,s,d.readPath),g)}catch(l){return{kind:"failure",failure:Y(l,{operation:"edit",path:s},u.signal,c)}}},jt=async(o,u,s,d,l)=>{const f=await he(u,"save",s);if(f.status==="error")return{kind:"failure",failure:f.failure};try{return ln(await o.save(u,s,f.readPath,{text:l,baseVersion:d}),g)}catch(T){return{kind:"failure",failure:Y(T,{operation:"save",path:s},u.signal,c)}}},zt=async(o,u,s,d,l)=>{const f=await he(u,"preview",d);if(f.status==="error")return{kind:"failure",failure:f.failure};let T;try{T=fn(await o.preview(u,d,f.readPath,l))}catch(U){return{kind:"failure",failure:Y(U,{operation:"preview",path:d},u.signal,c)}}if("kind"in T)return T.kind==="failure"?T:w.failureDocument("failed");const M=await _(T.html,{scope:s,signal:u.signal});return M.status==="sanitized"?{kind:"preview",htmlContent:M.html,headings:T.headings}:(M.cause!==null&&oe(c,{operation:"preview",path:d,error:M.cause}),w.failureDocument(M.reason))},Ct=async(o,u,s)=>{const d=await he(u,"revisions",s);if(d.status==="error")return{kind:"failure",failure:d.failure};try{return{kind:"revisions",revisions:mn(await o.revisions(u,s,d.readPath))}}catch(l){return{kind:"failure",failure:Y(l,{operation:"revisions",path:s},u.signal,c)}}},Ht=async(o,u,s,d)=>{const l=await he(u,"revision",s);if(l.status==="error")return{kind:"failure",failure:l.failure};try{return{kind:"revision",id:d,text:pn(await o.revision(u,s,l.readPath,d),g)}}catch(f){return{kind:"failure",failure:Y(f,{operation:"revision",path:s},u.signal,c)}}},Bt=async(o,u,s,d,l,f)=>{const T=ue(l,w.EXPLORER_DATA_QUERY.path);if(T===null||!w.isAcceptableDocumentPath(T))return j({reason:"invalid"},f);if(u==="edit")return K(200,JSON.stringify(await $t(o,s,T)),f);if(u==="revisions")return K(200,JSON.stringify(await Ct(o,s,T)),f);if(u==="revision"){const te=ue(l,w.EXPLORER_DATA_QUERY.revision);return w.isExplorerEditToken(te)?K(200,JSON.stringify(await Ht(o,s,T,te)),f):j({reason:"invalid"},f)}const M=ue(l,w.EXPLORER_DATA_QUERY.base);if(u==="save"&&!w.isExplorerEditToken(M))return j({reason:"invalid"},f);const U=await Pn(s.request,g);return U.status==="error"?j(U.failure,f):u==="preview"?K(200,JSON.stringify(await zt(o,s,d,T,U.text)),f):K(200,JSON.stringify(await jt(o,s,T,M,U.text)),f)},Ft=async({request:o,url:u,params:s})=>{const d=ct(await I(o,st)),l=it(d.headers);if(l.set("Cache-Control",_t),d.status==="signed-out")throw ut("signedOutPage",F(o,l));if(d.status==="forbidden")throw p===void 0?Re.data(null,{status:403,headers:l}):ut("forbiddenPage",p(o,l));const f=se.resolveExplorerLocation(a,s["*"],u.searchParams);if(f.kind==="redirect")throw Re.redirect(f.href,{headers:l});const{location:T}=f,{principal:M}=d,U=dt(r,C(M)),te=z.get(T.source);if(te===void 0)throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(T.source)}`);const we={signal:o.signal,timeoutMs:y,late:null,handOverMs:y},re={scope:U,sources:n.map(B=>({id:B.id,label:b(B,M)})),settings:se.parseViewSettings(se.readCookieValue(o.headers.get("Cookie"),t.settingsCookie),v),tree:T.view==="single"?null:{sourceId:T.source,result:Ne(we,B=>Q(te,M,U,o,B).then(W=>W.result))},documents:_n(T).map(B=>({path:B,document:Ne(we,W=>ce({principal:M,request:o,signal:W,refresh:!1},U,B))})),notices:Ne({signal:o.signal,timeoutMs:y,late:Le,handOverMs:0},B=>ge({principal:M,request:o,signal:B,refresh:!1}))};return Re.data(re,{headers:l})},Ce=async(o,u)=>{const s=ct(await I(o,u));return{authentication:s,headers:it(s.headers)}},Ut=async(o,u,s)=>{let d;try{d=await Ce(u,st)}catch(W){return j(Y(at(W),{operation:"authenticate"},u.signal,c))}const{authentication:l,headers:f}=d;if(l.status==="signed-out")return j({reason:"unauthorized"},f);if(l.status==="forbidden")return j({reason:"forbidden"},f);const{principal:T}=l;if(o==="asset")return Lt({principal:T,request:u,signal:u.signal,refresh:!1},s,f);const M=dt(r,C(T));f.set(w.EXPLORER_SCOPE_HEADER,M);const U={principal:T,request:u,signal:u.signal,refresh:!1},te=()=>j({reason:"invalid"},f);if(o==="document"){const W=ue(s,w.EXPLORER_DATA_QUERY.path);if(W===null||!w.isAcceptableDocumentPath(W))return te();const Fe=u.headers.has(w.EXPLORER_PROOF_HEADER);return Fe&&!ft(u)?j({reason:"forbidden"},f):K(200,JSON.stringify(await ce({...U,refresh:Fe},M,W)),f)}if(o==="text"){const W=ue(s,w.EXPLORER_DATA_QUERY.path);return W===null||!w.isAcceptableDocumentPath(W)?te():K(200,JSON.stringify(await Dt(U,W)),f)}if(o==="edit"||o==="save"||o==="preview"||o==="revisions"||o==="revision")return h===void 0?j({reason:"not-found"},f):Bt(h,o,U,M,s,f);const we=ue(s,w.EXPLORER_DATA_QUERY.source),re=ue(s,w.EXPLORER_DATA_QUERY.path);if(we===null||(o==="children"||o==="ancestors"||o==="reveal")&&(re===null||!w.isAcceptableDocumentPath(re)))return te();const B=z.get(we);if(B===void 0)return j({reason:"not-found"},f);if(o==="tree")return K(200,(await Q(B,T,M,u,u.signal)).json,f);if(o==="refresh"){const W=await J(B,T,M,u);return u.signal.aborted||ae(B,R(B,M)),K(200,W.json,f)}return o==="ancestors"?B.ancestors===void 0||re===null?j({reason:"not-found"},f):K(200,JSON.stringify(await q(B,B.ancestors,U,re)),f):o==="reveal"?re===null?te():K(200,JSON.stringify(await ee(B,U,re)),f):B.children===void 0||re===null?j({reason:"not-found"},f):K(200,JSON.stringify(await H(B,B.children,U,re)),f)},Xt=async o=>{const{authentication:u,headers:s}=await Ce(o,Tn);if(!s.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"},He=t.embeds.linkCardEndpoint===null?null:Jt.createLinkCardHandler({authorize:Xt}),Gt=async(o,u)=>{try{return await o(u)}catch(s){return j(Y(at(s),{operation:"authenticate"},u.signal,c))}},Be=async(o,u,s)=>{if(new URL(o.url).pathname.endsWith(".data"))return j({reason:"not-found"});if(!w.isExplorerDataOperation(s))return j({reason:"not-found"});if(s==="link-card"){if(He===null)return j({reason:"not-found"});const l=lt(o,s);return l!==null?l:Gt(He,o)}if(vn.has(s)&&h===void 0)return j({reason:"not-found"});const d=lt(o,s);if(d!==null)return d;if(s==="refresh"&&!ft(o))return j({reason:"forbidden"});if((s==="save"||s==="preview")&&!Nn(o))return j({reason:"forbidden"});try{return await Ut(s,o,u.searchParams)}catch(l){return j(Y(l,{operation:s},o.signal,c))}};return Object.freeze({loader:Ft,headers:Mn,dataLoader:({request:o,url:u,params:s})=>Be(o,u,s["*"]),dataAction:({request:o,url:u,params:s})=>Be(o,u,s["*"]),forgetTree:o=>{if(typeof o!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof o}`);$.forget(o)}})},Te=Object.freeze({maxEntries:2e4,maxDocumentBytes:2*1024*1024,textPreviewBytes:8*1024,walkConcurrency:8}),Dn=new Set(["md","markdown","mdx"]),At=new Map([...[["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"],["svg","image/svg+xml"],["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",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"}]]),$n=new Set(["txt","text","log","csv","tsv","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"]),jn=new Set(["readme","license","licence","copying","notice","authors","contributors","changelog","changes","todo","makefile","dockerfile","containerfile","procfile","gemfile","rakefile","vagrantfile","jenkinsfile","brewfile","codeowners"]),vt=typeof ie.constants.O_NOFOLLOW=="number"?ie.constants.O_NOFOLLOW:0,Nt=typeof ie.constants.O_NONBLOCK=="number"?ie.constants.O_NONBLOCK:0,mt=e=>`${e.size}-${e.mtimeNs}`,zn=e=>e!==""&&e!=="."&&e!==".."&&!e.includes(":")&&!e.endsWith(".")&&!e.endsWith(" "),pt=e=>w.isAcceptableDocumentPath(e)&&e===e.normalize("NFC")&&e.split("/").every(zn),Pt=e=>{const t=e.toLowerCase(),r=t.lastIndexOf(".");return r<0?"":t.slice(r+1)},Cn=e=>{const t=Pt(e);if(Dn.has(t))return{kind:"markdown"};const r=At.get(t);if(r!==void 0)return r.kind==="image"?{kind:"image"}:{kind:"media",mediaType:r.mediaType};const n=e.toLowerCase();return $n.has(t)||!n.includes(".")&&jn.has(n)?{kind:"text"}:{kind:"file"}},$e=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}},It=e=>{const t=$e(e);return t===null?e:new ye(t)},Mt=e=>{const t=typeof e=="object"&&e!==null?e.code:void 0;return t==="EACCES"||t==="EPERM"||t==="ENOENT"||t==="ENOTDIR"},Hn=async e=>{try{return Math.trunc((await me.lstat(e)).mtimeMs)}catch(t){if(Mt(t))return;throw t}},ht=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)},Bn=(e,t)=>e!==null?{start:e.offset,end:e.offset+e.length-1}:t===0n?{}:{start:0,end:Number(t)-1},Fn=async(e,t,r,n)=>{let a;try{a=await me.open(e,ie.constants.O_RDONLY|vt|Nt);const y=await a.stat({bigint:!0});if(!y.isFile()||y.ino!==t.ino||y.dev!==t.dev||y.size!==t.size||y.mtimeNs!==t.mtimeNs)throw new ye("not-found")}catch(y){throw await a?.close(),It(y)}const i=a.createReadStream(Bn(r,t.size)),c=Wt.Readable.toWeb(i),m=()=>{i.destroy(n.reason)};return n.aborted?m():n.addEventListener("abort",m,{once:!0}),c},Un=(e,t)=>{const r=se.NAME_COLLATOR.compare(e,t);return r!==0?r:e===t?0:e<t?-1:1},Xn=e=>{let t=0;const r=[];return async n=>{t<e?t+=1:await new Promise(a=>r.push(a));try{return await n()}finally{const a=r.shift();a===void 0?t-=1:a()}}},Gn=(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":w.isAcceptableDocumentPath(r)?w.isAcceptableDocumentPath(t)?null:"path-too-long":"control-character-or-backslash"},Jn=new Set(["id","label","root","pathPrefix","parse","deny","maxEntries","maxDocumentBytes","textPreviewBytes","walkConcurrency","cacheScope","reportSkipped"]),Se=(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},Yn=e=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");for(const b of Object.keys(e))if(!Jn.has(b))throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(b)}`);const{id:t,label:r,root:n,parse:a}=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 a!="function")throw new TypeError("[markdown-explorer] a file-system source needs a parse function");if(typeof n!="string"||!ne.isAbsolute(n))throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);let i;try{i=ie.statSync(n).isDirectory()}catch(b){throw new RangeError(`[markdown-explorer] root does not exist: ${n}`,{cause:b})}if(!i)throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);const c=ie.realpathSync(n),m=e.pathPrefix;if(typeof m!="string")throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');if(m!==""&&!(m.endsWith("/")&&pt(m.slice(0,-1))))throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(m)}`);const y=w.resolvePathRules(e.deny),x=Se("maxEntries",e.maxEntries,Te.maxEntries),h=Se("maxDocumentBytes",e.maxDocumentBytes,Te.maxDocumentBytes),g=Se("textPreviewBytes",e.textPreviewBytes,Te.textPreviewBytes),k=Se("walkConcurrency",e.walkConcurrency,Te.walkConcurrency),A=e.cacheScope===void 0?"principal":e.cacheScope;if(A!=="principal"&&A!=="shared")throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(A)}`);const $=e.reportSkipped;if($!==void 0&&typeof $!="function")throw new TypeError("[markdown-explorer] reportSkipped must be a function");const N=$===void 0?b=>{console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(b.sourceId)} does not list ${JSON.stringify(b.path)}: ${b.reason}`)}:$,_=new Set,z=b=>{const R=ne.resolve(c,...b.split("/")),S=ne.relative(c,R);return S===""||S===".."||S.startsWith(`..${ne.sep}`)||ne.isAbsolute(S)?null:R},v=(b,R)=>{const S=`${R}\0${b}`;_.has(S)||_.size>=x||(_.add(S),N({sourceId:t,path:b,reason:R}))},I=async({signal:b})=>{b.throwIfAborted();const R=new AbortController,S=()=>{R.abort(b.reason)};b.addEventListener("abort",S,{once:!0});const P=Xn(k);let L=0;const X=async(D,G)=>{const Q=await P(async()=>{R.signal.throwIfAborted();try{return await me.readdir(D,{withFileTypes:!0})}catch(H){if(G===""||!Mt(H))throw H;return null}});if(R.signal.throwIfAborted(),Q===null)return v(`${m}${G}`,"unreadable-directory"),null;const J=[];for(const H of Q){if(y.deniesName(H.name))continue;const Z=G===""?H.name:`${G}/${H.name}`,q=`${m}${Z}`,ee=Gn(H,q);if(ee!==null){v(q,ee);continue}J.push({dirent:H,relativePath:Z,path:q})}if(L+=J.length,L>x)throw new ye("too-large");return J.sort((H,Z)=>Un(H.dirent.name,Z.dirent.name)),(await Promise.all(J.map(async({dirent:H,relativePath:Z,path:q})=>{const ee=await Hn(ne.join(D,H.name)),ce=ee===void 0?{}:{modifiedAt:ee};if(!H.isDirectory())return{name:H.name,path:q,type:"file",...ce};const ge=await X(ne.join(D,H.name),Z);return ge===null?null:{name:H.name,path:q,type:"directory",...ce,children:ge}}))).filter(H=>H!==null)};try{const D=await X(c,"");if(D===null)throw new Error("[markdown-explorer] the source's root could not be listed");return D}catch(D){throw R.abort(),D}finally{b.removeEventListener("abort",S)}},C=async b=>{if(!b.startsWith(m))return{status:"refused",reason:"not-found"};const R=b.slice(m.length);if(!pt(R))return{status:"refused",reason:"invalid"};if(y.deniesPath(R))return{status:"refused",reason:"forbidden"};const S=z(R);if(S===null)return{status:"refused",reason:"forbidden"};const P=await me.lstat(S,{bigint:!0});if(P.isSymbolicLink())return{status:"refused",reason:"forbidden"};if(!P.isFile())return{status:"refused",reason:"unsupported"};const L=await me.realpath(S);return L!==S||y.deniesPath(ne.relative(c,L).split(ne.sep).join("/"))?{status:"refused",reason:"forbidden"}:{status:"file",target:S,name:R.slice(R.lastIndexOf("/")+1),stats:P}},F=async(b,R,S)=>{let P;try{const L=await C(S);if(L.status==="refused")return w.failureDocument(L.reason);const{target:X,name:D,stats:G}=L,Q=Cn(D),J=mt(G);if(Q.kind==="image")return{kind:"image",name:D,version:J};if(Q.kind==="media")return{kind:"media",name:D,mediaType:Q.mediaType,version:J};if(Q.kind==="file")return{kind:"file",name:D,version:J};P=await me.open(X,ie.constants.O_RDONLY|vt|Nt);const ae=await P.stat({bigint:!0});if(!ae.isFile()||ae.ino!==G.ino||ae.dev!==G.dev)return w.failureDocument("forbidden");if(Q.kind==="markdown"){if(ae.size>BigInt(h))return w.failureDocument("too-large");const ee=await ht(P,h+1);if(ee.length>h)return w.failureDocument("too-large");const ce=await a(new TextDecoder("utf-8").decode(ee),R);return{kind:"markdown",name:D,htmlContent:ce.htmlContent,headings:ce.headings,edit:null}}const H=await ht(P,g);if(H.includes(0))return{kind:"file",name:D,version:J};const Z=ae.size>BigInt(g),q=new TextDecoder("utf-8").decode(H,{stream:Z});return{kind:"text",name:D,text:q,truncated:Z,version:J}}catch(L){const X=$e(L);if(X===null)throw L;return w.failureDocument(X)}finally{await P?.close()}},p=async(b,R,S)=>{let P;try{P=await C(S)}catch(J){throw It(J)}if(P.status==="refused")throw new ye(P.reason);const{target:L,name:X,stats:D}=P,G=At.get(Pt(X)),Q=G===void 0?"":G.contentType;return{name:X,contentType:Q,size:Number(D.size),version:mt(D),open:J=>Fn(L,D,J,b.signal)}},E=async(b,R,S)=>{let P;try{P=await C(S)}catch(D){if($e(D)!==null)return null;throw D}if(P.status==="refused")return null;const L=S.slice(m.length).split("/");if(L.some(D=>y.deniesName(D)))return null;const X=L.slice(0,-1);return X.map((D,G)=>`${m}${X.slice(0,G+1).join("/")}`)};return Object.freeze({id:t,label:r,cacheScope:A,boundary:Object.freeze({contains:b=>b.startsWith(m)}),tree:I,ancestors:E,document:F,asset:p})};exports.DEFAULT_DENIED_PATH_SEGMENTS=w.DEFAULT_DENIED_PATH_SEGMENTS;exports.MAX_DOCUMENT_PATH_LENGTH=w.MAX_DOCUMENT_PATH_LENGTH;exports.isAcceptableDocumentPath=w.isAcceptableDocumentPath;exports.isDeniedPath=w.isDeniedPath;exports.ExplorerError=ye;exports.anonymousAccess=Kt;exports.createFileSystemSource=Yn;exports.createMarkdownExplorer=Ln;
|