@aiquants/markdown-explorer 0.9.0 → 0.10.0

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