@aiquants/markdown-explorer 0.35.0 → 0.37.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 (93) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/README.md +105 -13
  3. package/dist/{EditSurface-D2j1kCEE.js → EditSurface-BQgwRUrR.js} +250 -245
  4. package/dist/EditSurface-Xvk5wZu7.cjs +6 -0
  5. package/dist/ExplorerSplit-C_3FChSt.cjs +2 -0
  6. package/dist/ExplorerSplit-C_kaEnyM.js +1619 -0
  7. package/dist/{MultiLayout-CxV5SI7f.cjs → MultiLayout-BZNj1GYo.cjs} +1 -1
  8. package/dist/{MultiLayout-BeJ5Lubb.js → MultiLayout-DROxkTdD.js} +24 -24
  9. package/dist/{NativeScrollBar-RWXpVhbI.cjs → NativeScrollBar-BDF9A1sc.cjs} +1 -1
  10. package/dist/{NativeScrollBar-BM5NULzg.js → NativeScrollBar-DvdOpwIW.js} +2 -2
  11. package/dist/TreeLayout-Cc-ykewY.js +103 -0
  12. package/dist/TreeLayout-D_DYV64_.cjs +1 -0
  13. package/dist/client/MarkdownExplorer.d.cts +4 -5
  14. package/dist/client/MarkdownExplorer.d.ts +4 -5
  15. package/dist/client/hostContract.d.cts +1 -8
  16. package/dist/client/hostContract.d.ts +1 -8
  17. package/dist/core/config.d.cts +6 -0
  18. package/dist/core/config.d.ts +6 -0
  19. package/dist/core/contracts.d.cts +21 -0
  20. package/dist/core/contracts.d.ts +21 -0
  21. package/dist/core/dataRoute.d.cts +5 -1
  22. package/dist/core/dataRoute.d.ts +5 -1
  23. package/dist/core/documentId.d.cts +6 -0
  24. package/dist/core/documentId.d.ts +6 -0
  25. package/dist/core/labels.d.cts +10 -9
  26. package/dist/core/labels.d.ts +10 -9
  27. package/dist/core/location.d.cts +21 -0
  28. package/dist/core/location.d.ts +21 -0
  29. package/dist/explorerCore-DivWkFQF.cjs +1 -0
  30. package/dist/explorerCore-EkU0mwdW.js +1085 -0
  31. package/dist/index-BmOU3xcK.cjs +18 -0
  32. package/dist/{index-C1YMH-yI.js → index-dtjghDWY.js} +2647 -2466
  33. package/dist/index.cjs +1 -1
  34. package/dist/index.d.cts +3 -2
  35. package/dist/index.d.ts +3 -2
  36. package/dist/index.js +49 -45
  37. package/dist/location-Dh6K-y7w.js +761 -0
  38. package/dist/location-DrOP6t1F.cjs +1 -0
  39. package/dist/{merge-DQUYEGCx.cjs → merge-BCFCL1cF.cjs} +1 -1
  40. package/dist/{merge-Bb_HpPhe.js → merge-DC_h-t31.js} +1 -1
  41. package/dist/ownUrls-BTPGNhBt.cjs +1 -0
  42. package/dist/ownUrls-DD0cSCsF.js +409 -0
  43. package/dist/{sanitizeJob-BYRk17nr.js → sanitizeJob-BYqzjFJC.js} +1 -1
  44. package/dist/{sanitizeJob-Cs9o3Vpl.cjs → sanitizeJob-CudE1RUP.cjs} +1 -1
  45. package/dist/{sanitizePolicy-CiQfnxyd.cjs → sanitizePolicy-C-ehd0J_.cjs} +1 -1
  46. package/dist/{sanitizePolicy-CEMdaLUB.js → sanitizePolicy-DAPnUUVm.js} +1 -1
  47. package/dist/sanitizeWorker.cjs +1 -1
  48. package/dist/sanitizeWorker.js +3 -3
  49. package/dist/{sanitizerService-KWXv7bPm.js → sanitizerService-B8v4ap9t.js} +1 -1
  50. package/dist/{sanitizerService-BY4CPCoA.cjs → sanitizerService-DomN7lwC.cjs} +1 -1
  51. package/dist/server/anonymous.d.cts +2 -2
  52. package/dist/server/anonymous.d.ts +2 -2
  53. package/dist/server/errors.d.cts +1 -1
  54. package/dist/server/errors.d.ts +1 -1
  55. package/dist/server/ports.d.cts +24 -2
  56. package/dist/server/ports.d.ts +24 -2
  57. package/dist/server.cjs +1 -1
  58. package/dist/server.d.cts +1 -1
  59. package/dist/server.d.ts +1 -1
  60. package/dist/server.js +16 -16
  61. package/dist/serverBrowser.cjs +1 -1
  62. package/dist/serverBrowser.js +3 -3
  63. package/dist/serverCore.cjs +1 -1
  64. package/dist/serverCore.d.cts +1 -1
  65. package/dist/serverCore.d.ts +1 -1
  66. package/dist/serverCore.js +4 -4
  67. package/dist/styles/markdown-explorer.css +1 -1
  68. package/dist/{tapScrollCircle-BEydRn0y.js → tapScrollCircle-CqMZzWjo.js} +1 -1
  69. package/dist/{tapScrollCircle-DdX0Wri0.cjs → tapScrollCircle-DVNlszeF.cjs} +1 -1
  70. package/dist/testing.cjs +1 -1
  71. package/dist/testing.d.cts +5 -0
  72. package/dist/testing.d.ts +5 -0
  73. package/dist/testing.js +80 -2
  74. package/dist/{useSplitPersistence-B2Fj508K.cjs → useSplitPersistence-BUa_KMsV.cjs} +1 -1
  75. package/dist/{useSplitPersistence-Fkqak8G8.js → useSplitPersistence-pnb21dsr.js} +1 -1
  76. package/docs/behavior/dom-hooks.md +11 -2
  77. package/docs/behavior/hosting.md +1 -1
  78. package/docs/behavior/localization.md +2 -2
  79. package/docs/behavior/security.md +24 -3
  80. package/docs/behavior/url-contract.md +26 -0
  81. package/package.json +6 -4
  82. package/dist/EditSurface-CLG70Vnn.cjs +0 -6
  83. package/dist/ExplorerSplit-CfP1smbT.js +0 -1589
  84. package/dist/ExplorerSplit-D_0VohOv.cjs +0 -2
  85. package/dist/TreeLayout-AxLw-36S.js +0 -103
  86. package/dist/TreeLayout-Bg2YH-EY.cjs +0 -1
  87. package/dist/explorerCore-DLpDuSev.js +0 -998
  88. package/dist/explorerCore-DYrxS9ez.cjs +0 -1
  89. package/dist/index-LQWQfpAf.cjs +0 -18
  90. package/dist/location--KvTA0Ri.js +0 -726
  91. package/dist/location-D8DyDkuA.cjs +0 -1
  92. package/dist/ownUrls-B259RGgd.cjs +0 -1
  93. package/dist/ownUrls-Dh5g6ZJi.js +0 -370
@@ -1 +0,0 @@
1
- "use strict";const re=require("@aiquants/request-isolation"),ue=require("react-router"),C=require("./location-D8DyDkuA.cjs"),w=require("./ownUrls-B259RGgd.cjs"),A=require("./describeValue-Ccvhbt36.cjs"),ge=require("./lru-SGmUyBQU.cjs"),Qe="application/octet-stream",Ze="application/pdf",jt=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",Ze]),Le="default-src 'none'; media-src 'self'; style-src 'unsafe-inline'",ne=Object.freeze({sandboxed:`${Le}; sandbox`,mediaDocument:`${Le}; sandbox allow-same-origin`}),$e=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u,Mt=/^[\t\n\r ]+|[\t\n\r ]+$/gu,we=/^[\t ]+|[\t ]+$/gu,Ct=e=>{const t=[];let r="",s=0;for(;;){for(;s<e.length&&e[s]!=='"'&&e[s]!==",";)r+=e[s],s+=1;if(s<e.length&&e[s]==='"'){const a=s;for(s+=1;s<e.length&&e[s]!=='"';)s+=e[s]==="\\"?2:1;if(s=Math.min(s+1,e.length),r+=e.slice(a,s),s<e.length)continue}if(t.push(r.replace(we,"")),r="",s>=e.length)return t;s+=1}},zt=e=>{const t=e.replace(Mt,""),r=t.indexOf("/");if(r<0)return null;const s=t.slice(0,r),a=t.indexOf(";",r+1),d=t.slice(r+1,a<0?t.length:a).replace(/[\t\n\r ]+$/u,"");return $e.test(s)&&$e.test(d)?`${s}/${d}`.toLowerCase():null},Vt=e=>{let t=null;for(const r of Ct(e)){const s=zt(r);s!==null&&s!=="*/*"&&(t=s)}return t},Ut=/['()*]/gu,qe=e=>encodeURIComponent(e).replace(Ut,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Ee=Object.freeze({"Cache-Control":"private, max-age=60, stale-while-revalidate=600, no-transform",Vary:"Cookie"}),et=(e,t)=>{const r=Vt(e),s=r!==null&&jt.has(r),a=s&&(r.startsWith("audio/")||r.startsWith("video/"));return{contentType:r===null?Qe:r,inline:s,headers:{"X-Content-Type-Options":"nosniff","Content-Disposition":`${s?"inline":"attachment"}; filename*=UTF-8''${qe(t)}`,...r===Ze?{}:{"Content-Security-Policy":a?ne.mediaDocument:ne.sandboxed},"Cross-Origin-Resource-Policy":"same-origin"}}},te=64*1024,tt=e=>`text/plain; charset=${e}`,Ft=e=>({"X-Content-Type-Options":"nosniff","Content-Disposition":`inline; filename*=UTF-8''${qe(e)}`,"Content-Security-Policy":ne.sandboxed,"Cross-Origin-Resource-Policy":"same-origin"}),Xt=(e,t)=>`${t===null?"":t};${e}`,Ht=/^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu,q=Object.freeze({kind:"whole"}),Ne=Object.freeze({kind:"unsatisfiable"}),rt=(e,t,r,s)=>{const a=e.get("Range");if(a===null)return q;const d=e.get("If-Range");if(d!==null&&d!==r)return q;const l=Ht.exec(a);if(l===null)return q;const[,f,h,R]=l;if(R!==void 0){const b=Number(R);if(b===0)return Ne;const x=Math.max(0,t-b);return je(x,t-x,s)}const y=Number(f),E=h===""?Number.POSITIVE_INFINITY:Number(h);return E<y?q:y>=t?Ne:je(y,Math.min(E,t-1)-y+1,s)},je=(e,t,r)=>({kind:"partial",range:{offset:e,length:r===null?t:Math.min(t,r)}}),Me="W/",Bt=e=>{const t=[];let r=0,s=!1;for(let a=0;a<e.length;a+=1)e[a]==='"'?s=!s:e[a]===","&&!s&&(t.push(e.slice(r,a).replace(we,"")),r=a+1);return t.push(e.slice(r).replace(we,"")),t},Ce=e=>e.startsWith(Me)?e.slice(Me.length):e,be=(e,t)=>{if(e===null)return!1;const r=Bt(e);if(r.length===1&&r[0]==="*")return!0;const s=Ce(t);return r.some(a=>Ce(a)===s)},Yt=(e,t)=>{let r=t;return e.pipeThrough(new TransformStream({transform:(s,a)=>{const d=s.byteLength>r?s.subarray(0,r):s;r-=d.byteLength,a.enqueue(d),r===0&&a.terminate()},flush:s=>{r>0&&s.error(new RangeError("[markdown-explorer] the asset ended before its declared length"))}}))},H=(e,t,r,s,a)=>(a!==null&&r.set("Content-Length",String(a)),{head:e.method.toUpperCase()==="HEAD",status:t,headers:r,range:s,length:a}),J=({head:e,status:t,headers:r,range:s,length:a})=>e?{kind:"respond",response:new Response(null,{status:t,headers:r})}:{kind:"stream",status:t,headers:r,range:s,length:a},se=async(e,t)=>{if(e.kind==="respond")return e.response;const r=await t(e.range);return new Response(e.length===null?r:Yt(r,e.length),{status:e.status,headers:e.headers})},nt=(e,t)=>{const r=new Headers(e);for(const[s,a]of Object.entries({"Accept-Ranges":"bytes","Content-Range":`bytes */${t}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff"}))r.set(s,a);return new Response(null,{status:416,headers:r})},st=(e,t,r,s)=>{const a=`"${t.version}"`,d=et(t.contentType,t.name),l=new Headers(r);for(const[R,y]of Object.entries({...d.headers,...Ee,ETag:a}))l.set(R,y);if(be(e.headers.get("If-None-Match"),a))return{kind:"respond",response:new Response(null,{status:304,headers:l})};if(l.set("Content-Type",d.contentType),t.size===null)return J(H(e,200,l,null,null));if(t.size===0)return l.set("Content-Length","0"),{kind:"respond",response:new Response(null,{status:200,headers:l})};l.set("Accept-Ranges","bytes");const f=rt(e.headers,t.size,a,s);if(f.kind==="unsatisfiable")return{kind:"respond",response:nt(r,t.size)};if(f.kind==="whole")return J(H(e,200,l,null,t.size));const{range:h}=f;return l.set("Content-Range",`bytes ${h.offset}-${h.offset+h.length-1}/${t.size}`),J(H(e,206,l,h,h.length))},Gt=async(e,t,r,s)=>se(st(e,t,r,s),a=>t.open(a)),Wt=(e,t)=>{const r=new Uint8Array(t);let s=0;for(const a of e){if(s===t)break;const d=a.subarray(0,t-s);r.set(d,s),s+=d.byteLength}return r},Kt=(e,t,r)=>new ReadableStream({start:s=>{for(const a of e)s.enqueue(a);t&&s.close()},pull:async s=>{const{done:a,value:d}=await r.read();a?s.close():s.enqueue(d)},cancel:s=>r.cancel(s)},{highWaterMark:0}),ot=async(e,t,r)=>{const s=e.getReader(),a=t===null?te:Math.min(t,te),d=t===null?a+1:a,l=[];let f=0,h=!1;try{for(;f<d;){const{done:E,value:b}=await s.read();if(E){h=!0;break}l.push(b),f+=b.byteLength}if(h&&t!==null&&f<a)throw new RangeError("[markdown-explorer] the asset ended before its declared length");const R=t===null?h:t<=te;return{encoding:C.textEncodingOf(Wt(l,Math.min(f,a)),R,r),body:Kt(l,h,s)}}catch(R){throw s.cancel(R).catch(()=>{}),R}},at=async(e,t)=>{const r=await ot(await e.open(e.size===null?null:{offset:0,length:Math.min(e.size,te)}),e.size,t);return r.body.cancel().catch(()=>{}),r.encoding},it=(e,t,r,s,a)=>{const d=`"${Xt(t.version,s)}"`,l=new Headers(r);for(const[R,y]of Object.entries({...Ft(t.name),...Ee,ETag:d}))l.set(R,y);if(be(e.headers.get("If-None-Match"),d))return{kind:"respond",response:new Response(null,{status:304,headers:l})};if(t.size===0)return l.set("Content-Type",tt(C.textEncodingOf(new Uint8Array(0),!0,s))),l.set("Content-Length","0"),{kind:"respond",response:new Response(null,{status:200,headers:l})};if(t.size===null)return{kind:"needs-encoding",selection:H(e,200,l,null,null)};l.set("Accept-Ranges","bytes");const f=rt(e.headers,t.size,d,a);if(f.kind==="unsatisfiable")return{kind:"respond",response:nt(r,t.size)};if(f.kind==="whole")return{kind:"needs-encoding",selection:H(e,200,l,null,t.size)};const{range:h}=f;return l.set("Content-Range",`bytes ${h.offset}-${h.offset+h.length-1}/${t.size}`),{kind:"needs-encoding",selection:H(e,206,l,h,h.length)}},ye=(e,t)=>{const r=new Headers(e.headers);return r.set("Content-Type",tt(t)),J({...e,headers:r})},Jt=async(e,t,r,s,a)=>{const d=it(e,t,r,s,a);if(d.kind==="respond")return d.response;const{selection:l}=d;if(l.head||l.range!==null)return se(ye(l,await at(t,s)),h=>t.open(h));const f=await ot(await t.open(null),t.size,s);return se(ye(l,f.encoding),async()=>f.body)},Qt=e=>`workbook;${e}`,Zt=async(e,t,r)=>{const s=`"${Qt(t.version)}"`,a=et(Qe,t.name),d=new Headers(r);for(const[l,f]of Object.entries({...a.headers,...Ee,ETag:s}))d.set(l,f);return be(e.headers.get("If-None-Match"),s)?new Response(null,{status:304,headers:d}):(d.set("Content-Type",a.contentType),se(J(H(e,200,d,null,t.size)),l=>t.open(l)))},qt=Object.freeze({"Cache-Control":"private, no-store","Referrer-Policy":"no-referrer"}),er=(e,t)=>{const r=new Headers(t);for(const[s,a]of Object.entries(qt))r.set(s,a);return r.set("Location",e),new Response(null,{status:302,headers:r})},le=(e,t)=>{const r=new AbortController,s=t(AbortSignal.any([e.signal,r.signal]));return new Promise(a=>{let d;const l=setTimeout(()=>{a(e.late),d=setTimeout(()=>r.abort(),e.handOverMs)},e.timeoutMs),f=()=>{clearTimeout(l),clearTimeout(d)};s.then(h=>{f(),a(h)},()=>{f(),a(e.late)})})},tr=Object.freeze({error:(e,t)=>{console.error(e,t)}}),ct=Symbol.for("@aiquants/markdown-explorer:ExplorerError");class rr extends Error{reason;code;constructor(t,r={}){if(!w.isExplorerFailureReason(t))throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${A.describeValue(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 ${A.describeValue(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,ct,{value:!0})}}const nr=e=>e instanceof Error&&Object.hasOwn(e,ct)&&w.isExplorerFailureReason(e.reason),sr=e=>typeof e=="object"&&e!==null&&e.name==="AbortError",Te=(e,t,r)=>{try{e.error(t,r)}catch(s){console.error("[markdown-explorer] the logger threw while reporting a failure",{operation:r.operation,error:s})}},j=(e,t)=>Te(e,`[markdown-explorer] ${t.operation} failed`,t),or=(e,t)=>Te(e,`[markdown-explorer] ${t.operation} left out an entry`,t),fe=(e,t)=>Te(e,`[markdown-explorer] ${t.operation} refused a path the deny rules match`,{...t,error:new RangeError("[markdown-explorer] the path matches a deny rule")}),ze=(e,t)=>{e===null||typeof e!="object"&&typeof e!="function"||Promise.resolve(e).then(void 0,t)},S=(e,t,r,s)=>nr(e)?w.failureOf(e.reason,e.code):(sr(e)||r.aborted||j(s,{...t,error:e}),{reason:"failed"}),Ve=2*1024*1024,Ue=256*1024*1024,ar=async(e,t)=>{const r=e.getReader(),s=new Uint8Array(t);let a=0;for(;a<t;){const{done:d,value:l}=await r.read();if(d)return s.subarray(0,a);const f=l.subarray(0,t-a);s.set(f,a),a+=f.byteLength}return r.cancel().catch(()=>{}),s},ir=async(e,t,r)=>{if(e.size===0)return{text:"",truncated:!1};const s=e.size!==null&&e.size>t,a=e.size===null?t+1:Math.min(e.size,t),d=await ar(await e.open(s?{offset:0,length:t}:null),a);if(e.size!==null&&d.byteLength<a)throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");const l=s||d.byteLength>t,f=l?d.subarray(0,t):d,h=C.decodeTextLeniently(f,!l,r);return h.includes("\0")?null:{text:h,truncated:l}},oe=e=>({result:e,json:JSON.stringify(e)}),pe=Object.freeze(oe(Object.freeze({status:"error",failure:Object.freeze({reason:"failed"})}))),cr=e=>e.status==="ok"&&e.entries.length>0,dr=({ttlMs:e,maxEntries:t,maxBytes:r,now:s})=>{const a=ge.createLruCache(t,{max:r,of:(y,E)=>2*E.tree.json.length}),d=new Map,l=new Map,f=(y,E)=>{const b=new AbortController,x={waiters:0,superseded:!1,started:!1,loadTree:E},D=l.get(y),V=(z,Q)=>{const W=oe(z);return!(x.superseded||b.signal.aborted)&&cr(z)&&a.set(y,{tree:W,loadedAt:Q}),W},F=(async()=>{if(D!==void 0&&await D,b.signal.aborted)return pe;const z=s();return x.started=!0,V(await x.loadTree(b.signal,z),z)})().finally(()=>{d.get(y)===M&&d.delete(y)}),M={promise:F,controller:b,state:x};d.set(y,M);const N=F.then(()=>{},()=>{});return l.set(y,N),N.then(()=>{l.get(y)===N&&l.delete(y)}),M},h=(y,E,b)=>{E.state.waiters+=1;const x=()=>{E.state.waiters-=1,!(E.state.waiters>0)&&(d.get(y)===E&&d.delete(y),E.controller.abort())};return b.addEventListener("abort",x,{once:!0}),E.promise.finally(()=>{b.removeEventListener("abort",x)})},R=y=>{a.delete(y);const E=d.get(y);E?.state.started&&(E.state.superseded=!0,d.delete(y))};return{load:(y,E,b)=>{if(E.aborted)return Promise.resolve(pe);const x=a.get(y);if(x!==void 0){if(s()-x.loadedAt<e)return Promise.resolve(x.tree);a.delete(y)}const D=d.get(y);return h(y,D===void 0?f(y,b):D,E)},refresh:(y,E,b)=>{if(E.aborted)return Promise.resolve(pe);R(y);const x=d.get(y);return x===void 0?h(y,f(y,b),E):(x.state.loadTree=b,h(y,x,E))},forget:R}},ur=e=>({load:(t,r,s)=>s(r,e()).then(oe),refresh:(t,r,s)=>s(r,e()).then(oe),forget:()=>{}}),g=e=>{throw new TypeError(`[markdown-explorer] ${e}`)},lr=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)"}},fr=(e,t,r,s)=>{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 ${A.describeValue(e)}`);const a=new Set;for(const d of e){if(typeof d!="string"||!w.isAcceptableDocumentPath(d))throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");if(r.deniesPath(d))throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");if(!s(d))throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");if(d===t)throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");if(a.has(d))throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");a.add(d)}return Object.freeze([...a])},pr=(e,t,r,s,a)=>{const d=new Set,l=h=>{if(!Array.isArray(h))return g("a source returned entries that are not an array");const R=[];for(const y of h){const E=f(y);E!==null&&R.push(E)}return R},f=h=>{const R=lr(h);if(R!==null)return s(R),null;const y=w.entryViolation(h);if(y!==null)return g(y);const E=h;if(d.has(E))return g("a source returned entries that contain themselves");const{name:b,path:x,type:D,mimeType:V,modifiedAt:B,children:F,lazy:M}=E;if(t.deniesName(b)||t.deniesPath(x))return null;if(!a(x))return s({path:x,reason:"a path outside the source's boundary"}),null;const N={name:b,path:x,...V===void 0?{}:{mimeType:V},...B===void 0?{}:{modifiedAt:B}};if(D==="file")return{...N,type:D};if(M===!0)return r?{...N,type:D,lazy:!0,children:[]}:g("a lazy directory came from a source without a children function");if(F===void 0)return{...N,type:D};d.add(E);const z=l(F);return d.delete(E),{...N,type:D,children:z}};return l(e)},hr=/^[\x21\x23-\x7E]{1,256}$/u,dt=e=>typeof e=="string"&&hr.test(e),wr=new Set(["text","image","media","spreadsheet","file"]),yr=e=>typeof e=="string"&&wr.has(e),mr=(e,t,r)=>{if(e!==null&&typeof e=="object"){const d=e,{kind:l}=d;if(yr(l)){if(Object.hasOwn(d,"url"))return g(`a ${l} document carries its version, not a url`);if(typeof d.name!="string")return g("a document needs a name string");if(!dt(d.version))return g(`a ${l} document needs a version of 1 to 256 visible ASCII characters other than '"'`);const f=t(d.version);switch(l){case"image":{const{imageType:h}=d;return w.isExplorerImageType(h)?{kind:l,name:d.name,url:f,imageType:h}:g(`unknown image type ${A.describeValue(h)}`)}case"file":return{kind:l,name:d.name,url:f};case"media":{const{mediaType:h}=d;return w.isExplorerMediaType(h)?{kind:l,name:d.name,url:f,mediaType:h}:g(`unknown media type ${A.describeValue(h)}`)}case"text":{const{text:h,truncated:R,lang:y}=d;return typeof h!="string"||typeof R!="boolean"?g("a text document needs text and truncated"):w.isExplorerDocumentLang(y)?{kind:l,name:d.name,text:h,truncated:R,lang:y,url:f}:g(w.documentLangRefusal(l,y))}case"spreadsheet":{const h=w.spreadsheetFieldsViolation(d);if(h!==null)return g(h);const{format:R,firstSheetText:y,edit:E}=d;return{kind:l,name:d.name,url:f,format:R,firstSheetText:y,edit:Er(E)}}}}}const s=w.documentViolation(e);if(s!==null)return g(s);const a=e;switch(a.kind){case"failure":{const{reason:d,code:l}=a.failure;return{kind:"failure",failure:w.failureOf(d,l)}}case"markdown":return a.headings.length>w.EXPLORER_MAX_HEADINGS?{kind:"failure",failure:w.failureOf("too-large")}:(a.edit?.kind==="inline"||a.edit?.kind==="draft")&&!r?g(`a markdown document offers ${a.edit.kind} editing, but the server has no edit ports`):{kind:"unsanitized-markdown",name:a.name,html:a.htmlContent,headings:a.headings.map(({text:d,depth:l,id:f})=>({text:d,depth:l,id:f})),lang:a.lang,edit:gr(a.edit)}}},gr=e=>{if(e===null)return null;switch(e.kind){case"inline":return{kind:"inline"};case"draft":return{kind:"draft"};case"external":return{kind:"external",href:e.href}}},Er=e=>e===null?null:{kind:"external",href:e.href},ae=(e,t,r)=>typeof e!="string"?g(`${r} needs a text string`):e.includes("\0")?g(`${r} holds NUL, which no text editor can keep`):new TextEncoder().encode(e).byteLength>t?g(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`):e,ut=e=>w.isRootRelativeUrl(e.href)?{kind:"grant",href:e.href}:g("a grant needs a root-relative href"),br=(e,t)=>{if(e===null||typeof e!="object")return g("an edit source must be an object");const r=e;return r.kind==="grant"?ut(r):r.kind==="draft"?{kind:"draft",text:ae(r.text,t,"a draft source")}:r.kind!=="edit"?g(`an edit source's kind must be "edit", "draft" or "grant"`):w.isExplorerEditToken(r.version)?typeof r.history!="boolean"?g("an edit source needs history"):{kind:"edit",text:ae(r.text,t,"an edit source"),version:r.version,history:r.history}:g("an edit source needs a version of 1 to 1024 characters")},Tr=(e,t)=>{if(e===null||typeof e!="object")return g("a save result must be an object");const r=e;switch(r.kind){case"grant":return ut(r);case"saved":return w.isExplorerEditToken(r.version)?{kind:"saved",version:r.version}:g("a saved result needs a version of 1 to 1024 characters");case"conflict":return w.isExplorerEditToken(r.version)?{kind:"conflict",version:r.version,text:ae(r.text,t,"a conflict's current text")}:g("a conflict needs the current version of 1 to 1024 characters");default:return g(`a save result's kind must be "saved", "conflict" or "grant"`)}},Rr=e=>{if(e===null||typeof e!="object")return g("a preview must be an object");const{htmlContent:t,headings:r}=e;if(typeof t!="string"||!Array.isArray(r))return g("a preview needs htmlContent and headings");if(r.length>w.EXPLORER_MAX_HEADINGS)return{kind:"failure",failure:w.failureOf("too-large")};for(const s of r){const a=w.headingViolation(s);if(a!==null)return g(a)}return{html:t,headings:r.map(({text:s,depth:a,id:d})=>({text:s,depth:a,id:d}))}},kr=e=>{if(!Array.isArray(e))return g("revisions must be an array");const t=new Set;return e.map(r=>{const s=w.revisionViolation(r);if(s!==null)return g(s);const{id:a,modifiedAt:d,size:l,author:f,kept:h,current:R}=r;return t.has(a)?g(`two revisions share the id ${A.describeValue(a)}`):(t.add(a),{id:a,modifiedAt:d,size:l,author:f,kept:h,current:R})})},Or=(e,t)=>ae(e,t,"a revision"),me=e=>{if(e===null||typeof e!="object")return g("an asset file must be an object");const{name:t,contentType:r,size:s,version:a,open:d,kind:l,bridge:f}=e;if(l!==void 0)return g(l==="redirect"?"an asset redirect answers only a request for the stored file (options.delivery file), never one that reads the bytes":'an asset file has no kind (the only kind is "redirect")');if(typeof t!="string"||t==="")return g("an asset file needs a non-empty name");if(typeof r!="string")return g("an asset file needs a contentType string ('' when unknown)");if(s!==null&&!(typeof s=="number"&&Number.isSafeInteger(s)&&s>=0))return g("an asset file's size must be null or a non-negative safe integer");if(!dt(a))return g(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`);if(typeof d!="function")return g("an asset file needs an open function");const h={name:t,contentType:r,size:s,version:a,open:d};return Object.freeze(f===void 0?h:{...h,bridge:xr(f)})},xr=e=>{if(e===null||typeof e!="object")return g("an asset file's bridge must be an object when present");const{uri:t,storageVersion:r,readFailure:s}=e;return typeof t!="string"||t===""?g("an asset file's bridge needs a non-empty uri"):r!==null&&(typeof r!="string"||r==="")?g("an asset file's bridge needs a storageVersion that is a non-empty string, or null when the storage keeps none"):typeof s!="function"?g("an asset file's bridge needs a readFailure function"):Object.freeze({uri:t,storageVersion:r,readFailure:s})},Ar=e=>{if(e===null||typeof e!="object"||e.kind!=="redirect")return me(e);const{url:t}=e;if(typeof t!="string"||!URL.canParse(t))return g("an asset redirect needs an absolute https URL");const r=new URL(t);return r.protocol!=="https:"||r.username!==""||r.password!==""?g("an asset redirect's URL must be https and carry no credentials"):Object.freeze({kind:"redirect",url:r.href})},vr=e=>Array.isArray(e)?e.map(t=>{if(t===null||typeof t!="object")return g("a notice must be an object");const{id:r,tone:s,title:a,body:d,action:l}=t;if(typeof r!="string"||r===""||typeof a!="string")return g("a notice needs an id and a title");if(!w.isExplorerNoticeTone(s))return g(`unknown notice tone ${A.describeValue(s)}`);if(d!==void 0&&typeof d!="string")return g("a notice body must be a string");const h={id:r,tone:s,title:a,...d===void 0?{}:{body:d}};if(l===void 0)return h;if(l===null||typeof l!="object")return g("a notice action must be an object");const{label:R,href:y}=l;return typeof R!="string"||!w.isAcceptableUrl(y,w.EXPLORER_LINK_PROTOCOLS)?g("a notice action needs a label and an http(s), mailto or relative href"):{...h,action:{label:R,href:y}}}):g("notices must be an array"),Sr=4e3,ee=Object.freeze({ttlMs:3e5,maxEntries:64,maxBytes:64*1024*1024}),lt="private, no-store",Pr=Object.freeze({"Content-Type":"application/json; charset=utf-8","Cache-Control":lt,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox","Cross-Origin-Resource-Policy":"same-origin"}),he=Object.freeze([]),_r=Object.freeze({status:"ok",source:null,ancestors:null}),Fe=Object.freeze(["contains","confirm"]),Xe=Object.freeze({readOnly:!1}),Dr=Object.freeze({readOnly:!0}),Ir=new Set(["file","text","workbook"]),Lr=new Set(["file","text"]),_=(e,t,r)=>{if(!(r&&t===void 0)&&typeof t!="function")throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${A.describeValue(t)}`)},X=(e,t,r)=>{if(typeof t!="number")throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${A.describeValue(t)}`);if(!Number.isSafeInteger(t)||t<=0||t>r)throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(r)}; got ${A.describeValue(t)}`);return t},$r=e=>{if(e===null||typeof e!="object"||!Object.isFrozen(e))throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");return C.revalidateExplorerConfig(e)},He=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)")}},Be=e=>e instanceof Response?new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`):e,Nr=(e,t)=>{if(!A.isPlainObject(t))throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);for(const r of Object.keys(t))if(!Fe.includes(r))throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${Fe.join(", ")}`);_(`${e}.boundary.contains`,t.contains,!1),_(`${e}.boundary.confirm`,t.confirm,!0)},jr=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[s,a]of t.entries()){if(a===null||typeof a!="object")throw new TypeError(`[markdown-explorer] sources[${String(s)}] must be an object`);const{id:d,label:l,boundary:f,tree:h,children:R,ancestors:y,cacheScope:E}=a;if(!C.isExplorerSourceId(d))throw new RangeError(`[markdown-explorer] sources[${String(s)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${A.describeValue(d)}`);const b=`source ${A.describeValue(d)}`;if(r.has(d))throw new RangeError(`[markdown-explorer] source ids must be unique; ${A.describeValue(d)} repeats at sources[${String(s)}]`);if(r.add(d),typeof l!="string"&&typeof l!="function")throw new TypeError(`[markdown-explorer] ${b}.label must be a string or a function`);if(typeof l=="string"&&l.trim()==="")throw new RangeError(`[markdown-explorer] ${b}.label must not be blank`);if(Nr(b,f),_(`${b}.tree`,h,!1),_(`${b}.children`,R,!0),_(`${b}.ancestors`,y,!0),E!==void 0&&E!=="principal"&&E!=="shared")throw new RangeError(`[markdown-explorer] ${b}.cacheScope must be "principal" or "shared"; got ${A.describeValue(E)}`)}return t},Mr=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:s}=e;return{ttlMs:t===void 0?ee.ttlMs:X("treeCache.ttlMs",t,Number.MAX_SAFE_INTEGER),maxEntries:r===void 0?ee.maxEntries:X("treeCache.maxEntries",r,Number.MAX_SAFE_INTEGER),maxBytes:s===void 0?ee.maxBytes:X("treeCache.maxBytes",s,Number.MAX_SAFE_INTEGER)}},Ye=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 ${A.describeValue(t)}`);return e},Ge=(e,t)=>{if(!(t instanceof Response))throw new TypeError(`[markdown-explorer] ${e} must return a Response`);return t},We=(e,t)=>{if(typeof t!="string"||t==="")throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");const r=e(t);if(!ge.isExplorerScope(r))throw new TypeError("[markdown-explorer] the platform's scope must be 22 base64url characters");return r},Cr=(e,t)=>{try{return e(t)}catch(r){return r}},zr=(e,t)=>{const r=e(t);if(r!==void 0&&typeof r!="string")throw new TypeError(`[markdown-explorer] readSettings must return a string or undefined; got ${r===null?"null":typeof r}`);return r},Vr=e=>e.view==="multi"?e.docs:e.doc===null?[]:[e.doc],U=(e,t)=>{const r=e.getAll(t),[s]=r;return r.length===1&&s!==void 0&&s!==""?s:null},L=(e,t,r,s={})=>{const a=new Headers(r);for(const[d,l]of Object.entries({...Pr,...s}))a.set(d,l);return new Response(t,{status:e,headers:a})},O=(e,t,r)=>L(w.EXPLORER_FAILURE_STATUS[e.reason],JSON.stringify({failure:e}),t,r),Ur=new Set(["refresh","save","preview"]),Fr=new Set(["edit","save","preview","revisions","revision"]),Ke=(e,t)=>{const r=Ur.has(t)?["POST"]:["GET","HEAD"];return r.includes(e.method.toUpperCase())?null:L(405,JSON.stringify({failure:{reason:"invalid"}}),void 0,{Allow:r.join(", ")})},Je=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_REFRESH_PROOF&&re.crossOriginRefusal(e,re.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Xr=e=>e.headers.get(w.EXPLORER_PROOF_HEADER)===w.EXPLORER_EDIT_PROOF&&re.crossOriginRefusal(e,re.NO_CROSS_ORIGIN_NAVIGATION)===void 0,Hr=async(e,t)=>{const[r,...s]=(e.headers.get("Content-Type")??"").split(";").map(b=>b.trim().toLowerCase()),a=s.find(b=>b.startsWith("charset="));if(r!==w.EXPLORER_DRAFT_MEDIA_TYPE||a!==void 0&&a!=="charset=utf-8")return{status:"error",failure:{reason:"invalid"}};const d=Number(e.headers.get("Content-Length")??"0");if(Number.isFinite(d)&&d>t)return{status:"error",failure:{reason:"too-large"}};if(e.body===null)return{status:"ok",text:""};const l=e.body.getReader(),f=[];let h=0;for(;;){const{done:b,value:x}=await l.read();if(b)break;if(h+=x.byteLength,h>t)return await l.cancel(),{status:"error",failure:{reason:"too-large"}};f.push(x)}const R=new Uint8Array(h);let y=0;for(const b of f)R.set(b,y),y+=b.byteLength;let E;try{E=new TextDecoder("utf-8",{fatal:!0}).decode(R)}catch{return{status:"error",failure:{reason:"invalid"}}}return E.includes("\0")?{status:"error",failure:{reason:"invalid"}}:{status:"ok",text:E}},Br=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"])_(`edit.${r}`,t[r],!1);return e},Yr=({parentHeaders:e,loaderHeaders:t,errorHeaders:r})=>{const s=new Headers,a=r===void 0?[e,t]:[e,t,r];for(const d of a)for(const[l,f]of d)l!=="set-cookie"&&s.set(l,f);return s},Gr=(e,t)=>{if(e===null||typeof e!="object")throw new TypeError("[markdown-explorer] the server configuration must be an object");const r=$r(e.config),s=t.prepareScope();_("authenticate",e.authenticate,!1),_("principalKey",e.principalKey,!1),_("document",e.document,!1),_("asset",e.asset,!1),_("signedOutPage",e.signedOutPage,!1),_("forbiddenPage",e.forbiddenPage,!0),_("notices",e.notices,!0),_("onTreeRefreshed",e.onTreeRefreshed,!0),_("readSettings",e.readSettings,!1);const a=jr(e.sources),d=C.withExplorerSources(r,a.map(n=>n.id)),l=e.logger;if(l!==void 0&&(l===null||typeof l!="object"||typeof l.error!="function"))throw new TypeError("[markdown-explorer] logger must be an object with an error function");const f=e.logger===void 0?tr:e.logger,h=w.resolvePathRules(e.deny),R=e.deferredTimeoutMs===void 0?Sr:X("deferredTimeoutMs",e.deferredTimeoutMs,ge.MAX_TIMER_MILLISECONDS),y=e.textMaxBytes===void 0?Ve:X("textMaxBytes",e.textMaxBytes,Ue),E=Br(e.edit);if(E===void 0&&e.editMaxBytes!==void 0)throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");const b=e.editMaxBytes===void 0?Ve:X("editMaxBytes",e.editMaxBytes,Ue),x=Mr(e.treeCache),D=()=>Date.now(),V=x===!1?ur(D):dr({...x,now:D}),B=t.createSanitizer({options:e.sanitizer,maxPanels:r.multiView.maxPanels,iframeHosts:r.iframeHosts,dataPath:r.dataPath,ownUrls:C.ownUrlsOf(r)}),F=e.readSettings,M=e.assetMaxRangeBytes===null?null:X("assetMaxRangeBytes",e.assetMaxRangeBytes,Number.MAX_SAFE_INTEGER),N=new Map(a.map(n=>[n.id,n])),z=C.documentStyleNames(r),{authenticate:Q,principalKey:W,signedOutPage:ft,forbiddenPage:Re,onTreeRefreshed:ke}=e,pt=(n,i)=>{if(typeof n.label=="string")return n.label;const o=n.label(i);if(typeof o!="string"||o.trim()==="")throw new TypeError(`[markdown-explorer] the label of source ${A.describeValue(n.id)} must be a non-blank string`);return o},ie=(n,i)=>n.cacheScope==="shared"?n.id:`${n.id}\0${i}`,Y=(n,i)=>{const o=u=>j(f,{operation:"boundary",sourceId:n.id,path:i,error:u});let c;try{c=n.boundary.contains(i)}catch(u){return o(u),!1}return typeof c=="boolean"?c:(ze(c,o),o(new TypeError(`[markdown-explorer] boundary.contains of source ${A.describeValue(n.id)} must return a boolean; got ${A.describeValue(c)}`)),!1)},ce=async(n,i,o)=>{const{confirm:c}=n.boundary;if(c===void 0)return{status:"inside",readPath:o};let u;try{u=await c(i,o)}catch(k){return{status:"error",failure:S(k,{operation:"boundary",sourceId:n.id,path:o},i.signal,f)}}const p=k=>(j(f,{operation:"boundary",sourceId:n.id,path:o,error:new TypeError(`[markdown-explorer] boundary.confirm of source ${A.describeValue(n.id)} ${k}`)}),{status:"outside"});if(u===null||typeof u!="object")return p(`must resolve to { inside, readPath? }; got ${u===null?"null":typeof u}`);const{inside:m,readPath:T}=u;return m===!1?{status:"outside"}:m!==!0||typeof T!="string"?p("must resolve to { inside: false } or { inside: true, readPath: string }"):!w.isAcceptableDocumentPath(T)||h.deniesPath(T)?(j(f,{operation:"boundary",sourceId:n.id,path:o,error:new RangeError(`[markdown-explorer] boundary.confirm of source ${A.describeValue(n.id)} answered a readPath the explorer does not serve (unacceptable or denied)`)}),{status:"error",failure:{reason:"failed"}}):{status:"inside",readPath:T}},Z=async(n,i)=>{const o=a.filter(u=>Y(u,i));if(o.length===0)return{status:"error",failure:{reason:"forbidden"}};if(o.some(u=>u.boundary.confirm===void 0))return{status:"inside",readPath:i};let c=null;for(const u of o){const p=await ce(u,n,i);if(p.status==="inside")return p;p.status==="error"&&c===null&&(c=p.failure)}return{status:"error",failure:c===null?{reason:"forbidden"}:c}},Oe=(n,i,o)=>{const c=({path:u,reason:p})=>or(f,{operation:o.operation,sourceId:o.sourceId,path:u,error:new TypeError(`[markdown-explorer] an entry with ${p} was left out`)});try{return{status:"ok",entries:pr(n,h,i.children!==void 0,c,u=>Y(i,u))}}catch(u){return j(f,{...o,error:u}),{status:"error",failure:{reason:"failed"}}}},ht=async(n,i,o)=>{let c;try{c=await n.tree(i)}catch(p){return{status:"error",failure:S(p,{operation:"tree",sourceId:n.id},i.signal,f)}}const u=Oe(c,n,{operation:"tree",sourceId:n.id});return u.status==="ok"?{status:"ok",entries:u.entries,loadedAt:o}:u},xe=(n,i,o,c)=>(u,p)=>ht(n,{principal:i,request:o,signal:u,refresh:c},p),Ae=(n,i,o,c,u)=>V.load(ie(n,o),u,xe(n,i,c,!1)),wt=(n,i,o,c)=>V.refresh(ie(n,o),c.signal,xe(n,i,c,!0)),yt=(n,i)=>{if(ke===void 0)return;const o=c=>j(f,{operation:"refresh",sourceId:n.id,error:c});try{ze(ke(i),o)}catch(c){o(c)}},mt=async(n,i,o,c)=>{if(h.deniesPath(c)||!Y(n,c))return{status:"error",failure:{reason:"forbidden"}};const u=await ce(n,o,c);if(u.status==="outside")return{status:"error",failure:{reason:"forbidden"}};if(u.status==="error")return{status:"error",failure:u.failure};let p;try{p=await i(o,c,u.readPath)}catch(m){return{status:"error",failure:S(m,{operation:"children",sourceId:n.id,path:c},o.signal,f)}}return Oe(p,n,{operation:"children",sourceId:n.id,path:c})},ve=async(n,i,o,c)=>{const u=await ce(n,o,c);if(u.status==="outside")return{status:"ok",ancestors:null};if(u.status==="error")return{status:"error",failure:u.failure};let p;try{p=await i(o,c,u.readPath,{maxDepth:r.revealDocument.maxDepth})}catch(m){return{status:"error",failure:S(m,{operation:"ancestors",sourceId:n.id,path:c},o.signal,f)}}if(Array.isArray(p)&&p.length>r.revealDocument.maxDepth)return{status:"ok",ancestors:null};try{return{status:"ok",ancestors:fr(p,c,h,m=>Y(n,m))}}catch(m){return j(f,{operation:"ancestors",sourceId:n.id,path:c,error:m}),{status:"error",failure:{reason:"failed"}}}},gt=async(n,i,o,c)=>h.deniesPath(c)?{status:"error",failure:{reason:"forbidden"}}:Y(n,c)?ve(n,i,o,c):{status:"ok",ancestors:null},Et=async(n,i,o)=>{if(h.deniesPath(o))return{status:"error",failure:{reason:"forbidden"}};for(const c of[n,...a.filter(u=>u!==n)]){if(i.signal.aborted)break;const u=c.ancestors;if(u===void 0||!Y(c,o))continue;const p=await ve(c,u,i,o);if(p.status==="ok"&&p.ancestors!==null)return{status:"ok",source:c.id,ancestors:p.ancestors}}return _r},Se=async(n,i,o)=>{if(h.deniesPath(o))return w.failureDocument("forbidden");const c=await Z(n,o);if(c.status==="error")return{kind:"failure",failure:c.failure};let u;try{u=await e.document(n,o,c.readPath)}catch(T){return{kind:"failure",failure:S(T,{operation:"document",path:o},n.signal,f)}}let p;try{p=mr(u,T=>w.explorerAssetHref(r.dataPath,o,T),E!==void 0)}catch(T){return j(f,{operation:"document",path:o,error:T}),w.failureDocument("failed")}if(p.kind!=="unsanitized-markdown")return p;const m=await B(p.html,{scope:i,signal:n.signal});return m.status==="sanitized"?{kind:"markdown",name:p.name,htmlContent:m.html,headings:p.headings,lang:p.lang,edit:p.edit}:(m.cause!==null&&j(f,{operation:"document",path:o,error:m.cause}),w.failureDocument(m.reason))},bt=async n=>{if(e.notices===void 0)return he;try{return vr(await e.notices(n))}catch(i){return S(i,{operation:"notices"},n.signal,f),he}},Pe=async(n,i,o,c)=>{const u=U(i,w.EXPLORER_DATA_QUERY.path);if(u===null||!w.isAcceptableDocumentPath(u))return{status:"answered",response:O({reason:"invalid"},o)};const p=w.readExplorerAssetDisplay(i);if(p===null||!c.has(p))return{status:"answered",response:O({reason:"invalid"},o)};if(h.deniesPath(u))return fe(f,{operation:"asset",path:u}),{status:"answered",response:O({reason:"forbidden"},o)};const m=await Z(n,u);if(m.status==="error")return{status:"answered",response:O(m.failure,o)};try{const T=await e.asset(n,u,m.readPath,{delivery:p}),k=p==="file"?Ar(T):me(T);return"kind"in k?{status:"answered",response:er(k.url,o)}:{status:"admitted",path:u,display:p,file:k}}catch(T){return{status:"answered",response:O(S(T,{operation:"asset",path:u},n.signal,f),o)}}},Tt=async(n,i,o)=>{const c=await Pe(n,i,o,Ir);if(c.status==="answered")return c.response;const{path:u,display:p,file:m}=c;try{return p==="text"?await Jt(n.request,m,o,r.legacyTextEncoding,M):p==="workbook"?await Zt(n.request,m,o):await Gt(n.request,m,o,M)}catch(T){return O(S(T,{operation:"asset",path:u},n.signal,f),o)}},Rt=async(n,i,o)=>{const c=it(n,i,o,r.legacyTextEncoding,M);return c.kind==="respond"?c:ye(c.selection,await at(i,r.legacyTextEncoding))},kt=async(n,i,o)=>{const c=await Pe(n,i,o,Lr);if(c.status==="answered")return{kind:"response",response:c.response};const{path:u,display:p,file:m}=c,T=P=>O(S(P,{operation:"asset",path:u},n.signal,f),o);let k;try{k=p==="text"?await Rt(n.request,m,o):st(n.request,m,o,M)}catch(P){return{kind:"response",response:T(P)}}if(k.kind==="respond")return{kind:"response",response:k.response};const{bridge:$}=m;return $===void 0?(j(f,{operation:"asset",path:u,error:new TypeError("[markdown-explorer] the asset port must attach a bridge to a file the host streams itself")}),{kind:"response",response:O({reason:"failed"},o)}):{kind:"file",status:k.status,headers:k.headers,bridge:{uri:$.uri,storageVersion:$.storageVersion},range:k.range,length:k.length,fail:P=>T(Cr($.readFailure,P))}},Ot=async(n,i)=>{if(h.deniesPath(i))return fe(f,{operation:"text",path:i}),w.failureDocument("forbidden");const o=await Z(n,i);if(o.status==="error")return{kind:"failure",failure:o.failure};try{const c=me(await e.asset(n,i,o.readPath,{delivery:"text"})),u=await ir(c,y,r.legacyTextEncoding);return u===null?w.failureDocument("unsupported"):{kind:"text",name:c.name,text:u.text,truncated:u.truncated,url:w.explorerAssetHref(r.dataPath,i,c.version)}}catch(c){return{kind:"failure",failure:S(c,{operation:"text",path:i},n.signal,f)}}},K=async(n,i,o)=>h.deniesPath(o)?(fe(f,{operation:i,path:o}),{status:"error",failure:{reason:"forbidden"}}):Z(n,o),xt=async(n,i,o)=>{const c=await K(i,"edit",o);if(c.status==="error")return{kind:"failure",failure:c.failure};try{return br(await n.source(i,o,c.readPath),b)}catch(u){return{kind:"failure",failure:S(u,{operation:"edit",path:o},i.signal,f)}}},At=async(n,i,o,c,u)=>{const p=await K(i,"save",o);if(p.status==="error")return{kind:"failure",failure:p.failure};try{return Tr(await n.save(i,o,p.readPath,{text:u,baseVersion:c}),b)}catch(m){return{kind:"failure",failure:S(m,{operation:"save",path:o},i.signal,f)}}},vt=async(n,i,o,c,u)=>{const p=await K(i,"preview",c);if(p.status==="error")return{kind:"failure",failure:p.failure};let m;try{m=Rr(await n.preview(i,c,p.readPath,u))}catch(k){return{kind:"failure",failure:S(k,{operation:"preview",path:c},i.signal,f)}}if("kind"in m)return m.kind==="failure"?m:w.failureDocument("failed");const T=await B(m.html,{scope:o,signal:i.signal});return T.status==="sanitized"?{kind:"preview",htmlContent:T.html,headings:m.headings}:(T.cause!==null&&j(f,{operation:"preview",path:c,error:T.cause}),w.failureDocument(T.reason))},St=async(n,i,o)=>{const c=await K(i,"revisions",o);if(c.status==="error")return{kind:"failure",failure:c.failure};try{return{kind:"revisions",revisions:kr(await n.revisions(i,o,c.readPath))}}catch(u){return{kind:"failure",failure:S(u,{operation:"revisions",path:o},i.signal,f)}}},Pt=async(n,i,o,c)=>{const u=await K(i,"revision",o);if(u.status==="error")return{kind:"failure",failure:u.failure};try{return{kind:"revision",id:c,text:Or(await n.revision(i,o,u.readPath,c),b)}}catch(p){return{kind:"failure",failure:S(p,{operation:"revision",path:o},i.signal,f)}}},_t=async(n,i,o,c,u,p)=>{const m=U(u,w.EXPLORER_DATA_QUERY.path);if(m===null||!w.isAcceptableDocumentPath(m))return O({reason:"invalid"},p);if(i==="edit")return L(200,JSON.stringify(await xt(n,o,m)),p);if(i==="revisions")return L(200,JSON.stringify(await St(n,o,m)),p);if(i==="revision"){const $=U(u,w.EXPLORER_DATA_QUERY.revision);return w.isExplorerEditToken($)?L(200,JSON.stringify(await Pt(n,o,m,$)),p):O({reason:"invalid"},p)}const T=U(u,w.EXPLORER_DATA_QUERY.base);if(i==="save"&&!w.isExplorerEditToken(T))return O({reason:"invalid"},p);const k=await Hr(o.request,b);return k.status==="error"?O(k.failure,p):i==="preview"?L(200,JSON.stringify(await vt(n,o,c,m,k.text)),p):L(200,JSON.stringify(await At(n,o,m,T,k.text)),p)},Dt=async({request:n,url:i,params:o})=>{const c=Ye(await Q(n,Xe)),u=He(c.headers);if(u.set("Cache-Control",lt),c.status==="signed-out")throw Ge("signedOutPage",ft(n,u));if(c.status==="forbidden")throw Re===void 0?ue.data(null,{status:403,headers:u}):Ge("forbiddenPage",Re(n,u));const p=C.resolveExplorerLocation(d,o["*"],i.searchParams);if(p.kind==="redirect")throw ue.redirect(p.href,{headers:u});const{location:m}=p,{principal:T}=c,k=We(s,W(T)),$=N.get(m.source);if($===void 0)throw new RangeError(`[markdown-explorer] no source for ${A.describeValue(m.source)}`);const P={signal:n.signal,timeoutMs:R,late:null,handOverMs:R},I={scope:k,sources:a.map(v=>({id:v.id,label:pt(v,T)})),settings:C.parseViewSettings(zr(F,n),z),tree:m.view==="single"?null:{sourceId:m.source,result:le(P,v=>Ae($,T,k,n,v).then(G=>G.result))},documents:Vr(m).map(v=>({path:v,document:le(P,G=>Se({principal:T,request:n,signal:G,refresh:!1},k,v))})),notices:le({signal:n.signal,timeoutMs:R,late:he,handOverMs:0},v=>bt({principal:T,request:n,signal:v,refresh:!1}))};return ue.data(I,{headers:u})},_e=async(n,i)=>{const o=Ye(await Q(n,i));return{authentication:o,headers:He(o.headers)}},De=async n=>{let i;try{i=await _e(n,Xe)}catch(u){return{status:"answered",response:O(S(Be(u),{operation:"authenticate"},n.signal,f))}}const{authentication:o,headers:c}=i;return o.status==="signed-out"?{status:"answered",response:O({reason:"unauthorized"},c)}:o.status==="forbidden"?{status:"answered",response:O({reason:"forbidden"},c)}:{status:"signed-in",principal:o.principal,headers:c}},It=async(n,i,o)=>{const c=await De(i);if(c.status==="answered")return c.response;const{principal:u,headers:p}=c;if(n==="asset")return Tt({principal:u,request:i,signal:i.signal,refresh:!1},o,p);const m=We(s,W(u));p.set(w.EXPLORER_SCOPE_HEADER,m);const T={principal:u,request:i,signal:i.signal,refresh:!1},k=()=>O({reason:"invalid"},p);if(n==="document"){const v=U(o,w.EXPLORER_DATA_QUERY.path);if(v===null||!w.isAcceptableDocumentPath(v))return k();const G=i.headers.has(w.EXPLORER_PROOF_HEADER);return G&&!Je(i)?O({reason:"forbidden"},p):L(200,JSON.stringify(await Se({...T,refresh:G},m,v)),p)}if(n==="text"){const v=U(o,w.EXPLORER_DATA_QUERY.path);return v===null||!w.isAcceptableDocumentPath(v)?k():L(200,JSON.stringify(await Ot(T,v)),p)}if(n==="edit"||n==="save"||n==="preview"||n==="revisions"||n==="revision")return E===void 0?O({reason:"not-found"},p):_t(E,n,T,m,o,p);const $=U(o,w.EXPLORER_DATA_QUERY.source),P=U(o,w.EXPLORER_DATA_QUERY.path);if($===null||(n==="children"||n==="ancestors"||n==="reveal")&&(P===null||!w.isAcceptableDocumentPath(P)))return k();const I=N.get($);if(I===void 0)return O({reason:"not-found"},p);if(n==="tree")return L(200,(await Ae(I,u,m,i,i.signal)).json,p);if(n==="refresh"){const v=await wt(I,u,m,i);return i.signal.aborted||yt(I,ie(I,m)),L(200,v.json,p)}return n==="ancestors"?I.ancestors===void 0||P===null?O({reason:"not-found"},p):L(200,JSON.stringify(await gt(I,I.ancestors,T,P)),p):n==="reveal"?P===null?k():L(200,JSON.stringify(await Et(I,T,P)),p):I.children===void 0||P===null?O({reason:"not-found"},p):L(200,JSON.stringify(await mt(I,I.children,T,P)),p)},Lt=async n=>{const{authentication:i,headers:o}=await _e(n,Dr);if(!o.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 i.status==="signed-in"},Ie=r.embeds.linkCardEndpoint===null?null:t.createLinkCardHandler({authorize:Lt}),$t=async(n,i)=>{try{return await n(i)}catch(o){return O(S(Be(o),{operation:"authenticate"},i.signal,f))}},de=async(n,i,o)=>{if(new URL(n.url).pathname.endsWith(".data"))return O({reason:"not-found"});if(!w.isExplorerDataOperation(o))return O({reason:"not-found"});if(o==="link-card"){if(Ie===null)return O({reason:"not-found"});const u=Ke(n,o);return u!==null?u:$t(Ie,n)}if(Fr.has(o)&&E===void 0)return O({reason:"not-found"});const c=Ke(n,o);if(c!==null)return c;if(o==="refresh"&&!Je(n))return O({reason:"forbidden"});if((o==="save"||o==="preview")&&!Xr(n))return O({reason:"forbidden"});try{return await It(o,n,i.searchParams)}catch(u){return O(S(u,{operation:o},n.signal,f))}},Nt=async(n,i,o)=>{if(o!=="asset"||n.method.toUpperCase()!=="GET"||new URL(n.url).pathname.endsWith(".data"))return{kind:"response",response:await de(n,i,o)};try{const c=await De(n);return c.status==="answered"?{kind:"response",response:c.response}:await kt({principal:c.principal,request:n,signal:n.signal,refresh:!1},i.searchParams,c.headers)}catch(c){return{kind:"response",response:O(S(c,{operation:"asset"},n.signal,f))}}};return Object.freeze({loader:Dt,headers:Yr,dataLoader:({request:n,url:i,params:o})=>de(n,i,o["*"]),dataAction:({request:n,url:i,params:o})=>de(n,i,o["*"]),planData:({request:n,url:i,params:o})=>Nt(n,i,o["*"]),forgetTree:n=>{if(typeof n!="string")throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${A.describeValue(n)}`);V.forget(n)}})};exports.ASSET_CONTENT_SECURITY_POLICIES=ne;exports.ExplorerError=rr;exports.createExplorerServer=Gr;