@aiquants/markdown-explorer 0.35.0 → 0.36.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 (81) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +31 -2
  3. package/dist/{EditSurface-CLG70Vnn.cjs → EditSurface-B70iRFkG.cjs} +1 -1
  4. package/dist/{EditSurface-D2j1kCEE.js → EditSurface-BCFJRyIM.js} +5 -5
  5. package/dist/{ExplorerSplit-D_0VohOv.cjs → ExplorerSplit-BNrHrIus.cjs} +1 -1
  6. package/dist/{ExplorerSplit-CfP1smbT.js → ExplorerSplit-Bgccz2nm.js} +77 -77
  7. package/dist/{MultiLayout-CxV5SI7f.cjs → MultiLayout-Bo9LAXiY.cjs} +1 -1
  8. package/dist/{MultiLayout-BeJ5Lubb.js → MultiLayout-Dy5TIC2t.js} +4 -4
  9. package/dist/{NativeScrollBar-RWXpVhbI.cjs → NativeScrollBar-Bj-LKej0.cjs} +1 -1
  10. package/dist/{NativeScrollBar-BM5NULzg.js → NativeScrollBar-DpZMYhmf.js} +2 -2
  11. package/dist/TreeLayout-DsSKW_Qj.js +103 -0
  12. package/dist/TreeLayout-T8sc_wg7.cjs +1 -0
  13. package/dist/core/config.d.cts +6 -0
  14. package/dist/core/config.d.ts +6 -0
  15. package/dist/core/contracts.d.cts +21 -0
  16. package/dist/core/contracts.d.ts +21 -0
  17. package/dist/core/dataRoute.d.cts +5 -1
  18. package/dist/core/dataRoute.d.ts +5 -1
  19. package/dist/core/documentId.d.cts +6 -0
  20. package/dist/core/documentId.d.ts +6 -0
  21. package/dist/core/labels.d.cts +10 -0
  22. package/dist/core/labels.d.ts +10 -0
  23. package/dist/core/location.d.cts +21 -0
  24. package/dist/core/location.d.ts +21 -0
  25. package/dist/explorerCore-B3RGmMG6.js +1083 -0
  26. package/dist/explorerCore-CUkyKtm8.cjs +1 -0
  27. package/dist/{index-C1YMH-yI.js → index-D0l_BJqb.js} +2536 -2372
  28. package/dist/index-lpL7GltU.cjs +18 -0
  29. package/dist/index.cjs +1 -1
  30. package/dist/index.d.cts +2 -1
  31. package/dist/index.d.ts +2 -1
  32. package/dist/index.js +38 -33
  33. package/dist/location-Dh6K-y7w.js +761 -0
  34. package/dist/location-DrOP6t1F.cjs +1 -0
  35. package/dist/{merge-Bb_HpPhe.js → merge-BwcqBd4c.js} +1 -1
  36. package/dist/{merge-DQUYEGCx.cjs → merge-Dckw7r9T.cjs} +1 -1
  37. package/dist/ownUrls-BTPGNhBt.cjs +1 -0
  38. package/dist/ownUrls-DD0cSCsF.js +409 -0
  39. package/dist/{sanitizeJob-BYRk17nr.js → sanitizeJob-BYqzjFJC.js} +1 -1
  40. package/dist/{sanitizeJob-Cs9o3Vpl.cjs → sanitizeJob-CudE1RUP.cjs} +1 -1
  41. package/dist/{sanitizePolicy-CiQfnxyd.cjs → sanitizePolicy-C-ehd0J_.cjs} +1 -1
  42. package/dist/{sanitizePolicy-CEMdaLUB.js → sanitizePolicy-DAPnUUVm.js} +1 -1
  43. package/dist/sanitizeWorker.cjs +1 -1
  44. package/dist/sanitizeWorker.js +3 -3
  45. package/dist/{sanitizerService-KWXv7bPm.js → sanitizerService-B8v4ap9t.js} +1 -1
  46. package/dist/{sanitizerService-BY4CPCoA.cjs → sanitizerService-DomN7lwC.cjs} +1 -1
  47. package/dist/server/errors.d.cts +1 -1
  48. package/dist/server/errors.d.ts +1 -1
  49. package/dist/server/ports.d.cts +19 -0
  50. package/dist/server/ports.d.ts +19 -0
  51. package/dist/server.cjs +1 -1
  52. package/dist/server.d.cts +1 -1
  53. package/dist/server.d.ts +1 -1
  54. package/dist/server.js +6 -6
  55. package/dist/serverBrowser.cjs +1 -1
  56. package/dist/serverBrowser.js +3 -3
  57. package/dist/serverCore.cjs +1 -1
  58. package/dist/serverCore.d.cts +1 -1
  59. package/dist/serverCore.d.ts +1 -1
  60. package/dist/serverCore.js +4 -4
  61. package/dist/{tapScrollCircle-DdX0Wri0.cjs → tapScrollCircle-DyLInGck.cjs} +1 -1
  62. package/dist/{tapScrollCircle-BEydRn0y.js → tapScrollCircle-smKLgRa2.js} +1 -1
  63. package/dist/testing.cjs +1 -1
  64. package/dist/testing.d.cts +5 -0
  65. package/dist/testing.d.ts +5 -0
  66. package/dist/testing.js +80 -2
  67. package/dist/{useSplitPersistence-B2Fj508K.cjs → useSplitPersistence-BUa_KMsV.cjs} +1 -1
  68. package/dist/{useSplitPersistence-Fkqak8G8.js → useSplitPersistence-pnb21dsr.js} +1 -1
  69. package/docs/behavior/dom-hooks.md +3 -1
  70. package/docs/behavior/security.md +23 -2
  71. package/docs/behavior/url-contract.md +26 -0
  72. package/package.json +2 -2
  73. package/dist/TreeLayout-AxLw-36S.js +0 -103
  74. package/dist/TreeLayout-Bg2YH-EY.cjs +0 -1
  75. package/dist/explorerCore-DLpDuSev.js +0 -998
  76. package/dist/explorerCore-DYrxS9ez.cjs +0 -1
  77. package/dist/index-LQWQfpAf.cjs +0 -18
  78. package/dist/location--KvTA0Ri.js +0 -726
  79. package/dist/location-D8DyDkuA.cjs +0 -1
  80. package/dist/ownUrls-B259RGgd.cjs +0 -1
  81. package/dist/ownUrls-Dh5g6ZJi.js +0 -370
@@ -0,0 +1,1083 @@
1
+ import { crossOriginRefusal as ke, NO_CROSS_ORIGIN_NAVIGATION as Te } from "@aiquants/request-isolation";
2
+ import { data as pe, redirect as Fe } from "react-router";
3
+ import { t as ur, b as nt, w as st, o as ot, f as at, g as it, i as ct, h as dt, e as ut, j as lt, p as ft, k as lr } from "./location-Dh6K-y7w.js";
4
+ import { h as fr, j as pt, k as se, s as ht, b as wt, m as mt, n as yt, o as gt, p as bt, E as pr, q as ee, t as Et, u as kt, i as U, v as Tt, w as Ot, x as Rt, y as vt, z as xt, f as At, A as hr, B as St, C as ce, F as Pt, G as It, H as _t, I as Dt, J as M, K as wr, L as $t, g as V, e as He, N as Nt, O as Lt } from "./ownUrls-DD0cSCsF.js";
5
+ import { d as x, i as jt } from "./describeValue-CLlVRO8d.js";
6
+ import { c as Mt, i as Ct, M as zt } from "./lru-DC8GBmkX.js";
7
+ const mr = "application/octet-stream", yr = "application/pdf", Ut = /* @__PURE__ */ new Set([
8
+ "image/png",
9
+ "image/apng",
10
+ "image/jpeg",
11
+ "image/gif",
12
+ "image/webp",
13
+ "image/avif",
14
+ "image/bmp",
15
+ "image/x-icon",
16
+ "image/vnd.microsoft.icon",
17
+ "audio/mpeg",
18
+ "audio/mp4",
19
+ "audio/aac",
20
+ "audio/ogg",
21
+ "audio/opus",
22
+ "audio/wav",
23
+ "audio/wave",
24
+ "audio/x-wav",
25
+ "audio/webm",
26
+ "audio/flac",
27
+ "audio/x-flac",
28
+ "audio/x-m4a",
29
+ "video/mp4",
30
+ "video/webm",
31
+ "video/ogg",
32
+ "video/quicktime",
33
+ yr
34
+ ]), Xe = "default-src 'none'; media-src 'self'; style-src 'unsafe-inline'", ye = Object.freeze({
35
+ sandboxed: `${Xe}; sandbox`,
36
+ mediaDocument: `${Xe}; sandbox allow-same-origin`
37
+ }), Be = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u, Ft = /^[\t\n\r ]+|[\t\n\r ]+$/gu, ge = /^[\t ]+|[\t ]+$/gu, Ht = (e) => {
38
+ const r = [];
39
+ let t = "", o = 0;
40
+ for (; ; ) {
41
+ for (; o < e.length && e[o] !== '"' && e[o] !== ","; )
42
+ t += e[o], o += 1;
43
+ if (o < e.length && e[o] === '"') {
44
+ const c = o;
45
+ for (o += 1; o < e.length && e[o] !== '"'; )
46
+ o += e[o] === "\\" ? 2 : 1;
47
+ if (o = Math.min(o + 1, e.length), t += e.slice(c, o), o < e.length) continue;
48
+ }
49
+ if (r.push(t.replace(ge, "")), t = "", o >= e.length) return r;
50
+ o += 1;
51
+ }
52
+ }, Xt = (e) => {
53
+ const r = e.replace(Ft, ""), t = r.indexOf("/");
54
+ if (t < 0) return null;
55
+ const o = r.slice(0, t), c = r.indexOf(";", t + 1), u = r.slice(t + 1, c < 0 ? r.length : c).replace(/[\t\n\r ]+$/u, "");
56
+ return Be.test(o) && Be.test(u) ? `${o}/${u}`.toLowerCase() : null;
57
+ }, Bt = (e) => {
58
+ let r = null;
59
+ for (const t of Ht(e)) {
60
+ const o = Xt(t);
61
+ o !== null && o !== "*/*" && (r = o);
62
+ }
63
+ return r;
64
+ }, Vt = /['()*]/gu, gr = (e) => encodeURIComponent(e).replace(Vt, (r) => `%${r.charCodeAt(0).toString(16).toUpperCase()}`), Oe = Object.freeze({
65
+ "Cache-Control": "private, max-age=60, stale-while-revalidate=600, no-transform",
66
+ Vary: "Cookie"
67
+ }), br = (e, r) => {
68
+ const t = Bt(e), o = t !== null && Ut.has(t), c = o && (t.startsWith("audio/") || t.startsWith("video/"));
69
+ return {
70
+ contentType: t === null ? mr : t,
71
+ inline: o,
72
+ headers: {
73
+ "X-Content-Type-Options": "nosniff",
74
+ "Content-Disposition": `${o ? "inline" : "attachment"}; filename*=UTF-8''${gr(r)}`,
75
+ ...t === yr ? {} : { "Content-Security-Policy": c ? ye.mediaDocument : ye.sandboxed },
76
+ "Cross-Origin-Resource-Policy": "same-origin"
77
+ }
78
+ };
79
+ }, ne = 64 * 1024, Er = (e) => `text/plain; charset=${e}`, Gt = (e) => ({
80
+ "X-Content-Type-Options": "nosniff",
81
+ "Content-Disposition": `inline; filename*=UTF-8''${gr(e)}`,
82
+ "Content-Security-Policy": ye.sandboxed,
83
+ "Cross-Origin-Resource-Policy": "same-origin"
84
+ }), Wt = (e, r) => `${r === null ? "" : r};${e}`, Yt = /^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu, re = Object.freeze({ kind: "whole" }), Ve = Object.freeze({ kind: "unsatisfiable" }), kr = (e, r, t, o) => {
85
+ const c = e.get("Range");
86
+ if (c === null) return re;
87
+ const u = e.get("If-Range");
88
+ if (u !== null && u !== t) return re;
89
+ const f = Yt.exec(c);
90
+ if (f === null) return re;
91
+ const [, p, h, T] = f;
92
+ if (T !== void 0) {
93
+ const E = Number(T);
94
+ if (E === 0) return Ve;
95
+ const R = Math.max(0, r - E);
96
+ return Ge(R, r - R, o);
97
+ }
98
+ const m = Number(p), b = h === "" ? Number.POSITIVE_INFINITY : Number(h);
99
+ return b < m ? re : m >= r ? Ve : Ge(m, Math.min(b, r - 1) - m + 1, o);
100
+ }, Ge = (e, r, t) => ({ kind: "partial", range: { offset: e, length: t === null ? r : Math.min(r, t) } }), We = "W/", Jt = (e) => {
101
+ const r = [];
102
+ let t = 0, o = !1;
103
+ for (let c = 0; c < e.length; c += 1)
104
+ e[c] === '"' ? o = !o : e[c] === "," && !o && (r.push(e.slice(t, c).replace(ge, "")), t = c + 1);
105
+ return r.push(e.slice(t).replace(ge, "")), r;
106
+ }, Ye = (e) => e.startsWith(We) ? e.slice(We.length) : e, Re = (e, r) => {
107
+ if (e === null) return !1;
108
+ const t = Jt(e);
109
+ if (t.length === 1 && t[0] === "*") return !0;
110
+ const o = Ye(r);
111
+ return t.some((c) => Ye(c) === o);
112
+ }, Kt = (e, r) => {
113
+ let t = r;
114
+ return e.pipeThrough(
115
+ new TransformStream({
116
+ transform: (o, c) => {
117
+ const u = o.byteLength > t ? o.subarray(0, t) : o;
118
+ t -= u.byteLength, c.enqueue(u), t === 0 && c.terminate();
119
+ },
120
+ flush: (o) => {
121
+ t > 0 && o.error(new RangeError("[markdown-explorer] the asset ended before its declared length"));
122
+ }
123
+ })
124
+ );
125
+ }, W = (e, r, t, o, c) => (c !== null && t.set("Content-Length", String(c)), { head: e.method.toUpperCase() === "HEAD", status: r, headers: t, range: o, length: c }), q = ({ head: e, status: r, headers: t, range: o, length: c }) => e ? { kind: "respond", response: new Response(null, { status: r, headers: t }) } : { kind: "stream", status: r, headers: t, range: o, length: c }, oe = async (e, r) => {
126
+ if (e.kind === "respond") return e.response;
127
+ const t = await r(e.range);
128
+ return new Response(e.length === null ? t : Kt(t, e.length), { status: e.status, headers: e.headers });
129
+ }, Tr = (e, r) => {
130
+ const t = new Headers(e);
131
+ for (const [o, c] of Object.entries({ "Accept-Ranges": "bytes", "Content-Range": `bytes */${r}`, "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff" })) t.set(o, c);
132
+ return new Response(null, { status: 416, headers: t });
133
+ }, Or = (e, r, t, o) => {
134
+ const c = `"${r.version}"`, u = br(r.contentType, r.name), f = new Headers(t);
135
+ for (const [T, m] of Object.entries({ ...u.headers, ...Oe, ETag: c })) f.set(T, m);
136
+ if (Re(e.headers.get("If-None-Match"), c)) return { kind: "respond", response: new Response(null, { status: 304, headers: f }) };
137
+ if (f.set("Content-Type", u.contentType), r.size === null) return q(W(e, 200, f, null, null));
138
+ if (r.size === 0)
139
+ return f.set("Content-Length", "0"), { kind: "respond", response: new Response(null, { status: 200, headers: f }) };
140
+ f.set("Accept-Ranges", "bytes");
141
+ const p = kr(e.headers, r.size, c, o);
142
+ if (p.kind === "unsatisfiable") return { kind: "respond", response: Tr(t, r.size) };
143
+ if (p.kind === "whole") return q(W(e, 200, f, null, r.size));
144
+ const { range: h } = p;
145
+ return f.set("Content-Range", `bytes ${h.offset}-${h.offset + h.length - 1}/${r.size}`), q(W(e, 206, f, h, h.length));
146
+ }, Qt = async (e, r, t, o) => oe(Or(e, r, t, o), (c) => r.open(c)), Zt = (e, r) => {
147
+ const t = new Uint8Array(r);
148
+ let o = 0;
149
+ for (const c of e) {
150
+ if (o === r) break;
151
+ const u = c.subarray(0, r - o);
152
+ t.set(u, o), o += u.byteLength;
153
+ }
154
+ return t;
155
+ }, qt = (e, r, t) => new ReadableStream(
156
+ {
157
+ start: (o) => {
158
+ for (const c of e) o.enqueue(c);
159
+ r && o.close();
160
+ },
161
+ pull: async (o) => {
162
+ const { done: c, value: u } = await t.read();
163
+ c ? o.close() : o.enqueue(u);
164
+ },
165
+ cancel: (o) => t.cancel(o)
166
+ },
167
+ { highWaterMark: 0 }
168
+ ), Rr = async (e, r, t) => {
169
+ const o = e.getReader(), c = r === null ? ne : Math.min(r, ne), u = r === null ? c + 1 : c, f = [];
170
+ let p = 0, h = !1;
171
+ try {
172
+ for (; p < u; ) {
173
+ const { done: b, value: E } = await o.read();
174
+ if (b) {
175
+ h = !0;
176
+ break;
177
+ }
178
+ f.push(E), p += E.byteLength;
179
+ }
180
+ if (h && r !== null && p < c) throw new RangeError("[markdown-explorer] the asset ended before its declared length");
181
+ const T = r === null ? h : r <= ne;
182
+ return { encoding: ur(Zt(f, Math.min(p, c)), T, t), body: qt(f, h, o) };
183
+ } catch (T) {
184
+ throw o.cancel(T).catch(() => {
185
+ }), T;
186
+ }
187
+ }, vr = async (e, r) => {
188
+ const t = await Rr(await e.open(e.size === null ? null : { offset: 0, length: Math.min(e.size, ne) }), e.size, r);
189
+ return t.body.cancel().catch(() => {
190
+ }), t.encoding;
191
+ }, xr = (e, r, t, o, c) => {
192
+ const u = `"${Wt(r.version, o)}"`, f = new Headers(t);
193
+ for (const [T, m] of Object.entries({ ...Gt(r.name), ...Oe, ETag: u })) f.set(T, m);
194
+ if (Re(e.headers.get("If-None-Match"), u)) return { kind: "respond", response: new Response(null, { status: 304, headers: f }) };
195
+ if (r.size === 0)
196
+ return f.set("Content-Type", Er(ur(new Uint8Array(0), !0, o))), f.set("Content-Length", "0"), { kind: "respond", response: new Response(null, { status: 200, headers: f }) };
197
+ if (r.size === null) return { kind: "needs-encoding", selection: W(e, 200, f, null, null) };
198
+ f.set("Accept-Ranges", "bytes");
199
+ const p = kr(e.headers, r.size, u, c);
200
+ if (p.kind === "unsatisfiable") return { kind: "respond", response: Tr(t, r.size) };
201
+ if (p.kind === "whole") return { kind: "needs-encoding", selection: W(e, 200, f, null, r.size) };
202
+ const { range: h } = p;
203
+ return f.set("Content-Range", `bytes ${h.offset}-${h.offset + h.length - 1}/${r.size}`), { kind: "needs-encoding", selection: W(e, 206, f, h, h.length) };
204
+ }, be = (e, r) => {
205
+ const t = new Headers(e.headers);
206
+ return t.set("Content-Type", Er(r)), q({ ...e, headers: t });
207
+ }, en = async (e, r, t, o, c) => {
208
+ const u = xr(e, r, t, o, c);
209
+ if (u.kind === "respond") return u.response;
210
+ const { selection: f } = u;
211
+ if (f.head || f.range !== null) return oe(be(f, await vr(r, o)), (h) => r.open(h));
212
+ const p = await Rr(await r.open(null), r.size, o);
213
+ return oe(be(f, p.encoding), async () => p.body);
214
+ }, rn = (e) => `workbook;${e}`, tn = async (e, r, t) => {
215
+ const o = `"${rn(r.version)}"`, c = br(mr, r.name), u = new Headers(t);
216
+ for (const [f, p] of Object.entries({ ...c.headers, ...Oe, ETag: o })) u.set(f, p);
217
+ return Re(e.headers.get("If-None-Match"), o) ? new Response(null, { status: 304, headers: u }) : (u.set("Content-Type", c.contentType), oe(q(W(e, 200, u, null, r.size)), (f) => r.open(f)));
218
+ }, nn = Object.freeze({
219
+ "Cache-Control": "private, no-store",
220
+ "Referrer-Policy": "no-referrer"
221
+ }), sn = (e, r) => {
222
+ const t = new Headers(r);
223
+ for (const [o, c] of Object.entries(nn)) t.set(o, c);
224
+ return t.set("Location", e), new Response(null, { status: 302, headers: t });
225
+ }, he = (e, r) => {
226
+ const t = new AbortController(), o = r(AbortSignal.any([e.signal, t.signal]));
227
+ return new Promise((c) => {
228
+ let u;
229
+ const f = setTimeout(() => {
230
+ c(e.late), u = setTimeout(() => t.abort(), e.handOverMs);
231
+ }, e.timeoutMs), p = () => {
232
+ clearTimeout(f), clearTimeout(u);
233
+ };
234
+ o.then(
235
+ (h) => {
236
+ p(), c(h);
237
+ },
238
+ () => {
239
+ p(), c(e.late);
240
+ }
241
+ );
242
+ });
243
+ }, on = Object.freeze({
244
+ error: (e, r) => {
245
+ console.error(e, r);
246
+ }
247
+ }), Ar = /* @__PURE__ */ Symbol.for("@aiquants/markdown-explorer:ExplorerError");
248
+ class ds extends Error {
249
+ reason;
250
+ code;
251
+ constructor(r, t = {}) {
252
+ if (!fr(r)) throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${x(r)}`);
253
+ if (t.code !== void 0 && !pt(t.code)) throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${x(t.code)}`);
254
+ super(`[markdown-explorer] ${r}`, t.cause === void 0 ? void 0 : { cause: t.cause }), this.name = "ExplorerError", this.reason = r, this.code = t.code, Object.defineProperty(this, Ar, { value: !0 });
255
+ }
256
+ }
257
+ const an = (e) => e instanceof Error && Object.hasOwn(e, Ar) && fr(e.reason), cn = (e) => typeof e == "object" && e !== null && e.name === "AbortError", ve = (e, r, t) => {
258
+ try {
259
+ e.error(r, t);
260
+ } catch (o) {
261
+ console.error("[markdown-explorer] the logger threw while reporting a failure", { operation: t.operation, error: o });
262
+ }
263
+ }, $ = (e, r) => ve(e, `[markdown-explorer] ${r.operation} failed`, r), dn = (e, r) => ve(e, `[markdown-explorer] ${r.operation} left out an entry`, r), Z = (e, r) => ve(e, `[markdown-explorer] ${r.operation} refused a path the deny rules match`, { ...r, error: new RangeError("[markdown-explorer] the path matches a deny rule") }), Je = (e, r) => {
264
+ e === null || typeof e != "object" && typeof e != "function" || Promise.resolve(e).then(void 0, r);
265
+ }, v = (e, r, t, o) => an(e) ? se(e.reason, e.code) : (cn(e) || t.aborted || $(o, { ...r, error: e }), { reason: "failed" }), Ke = 2 * 1024 * 1024, Qe = 256 * 1024 * 1024, un = async (e, r) => {
266
+ const t = e.getReader(), o = new Uint8Array(r);
267
+ let c = 0;
268
+ for (; c < r; ) {
269
+ const { done: u, value: f } = await t.read();
270
+ if (u) return o.subarray(0, c);
271
+ const p = f.subarray(0, r - c);
272
+ o.set(p, c), c += p.byteLength;
273
+ }
274
+ return t.cancel().catch(() => {
275
+ }), o;
276
+ }, ln = async (e, r, t) => {
277
+ if (e.size === 0) return { text: "", truncated: !1 };
278
+ const o = e.size !== null && e.size > r, c = e.size === null ? r + 1 : Math.min(e.size, r), u = await un(await e.open(o ? { offset: 0, length: r } : null), c);
279
+ if (e.size !== null && u.byteLength < c) throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");
280
+ const f = o || u.byteLength > r, p = f ? u.subarray(0, r) : u, h = nt(p, !f, t);
281
+ return h.includes("\0") ? null : { text: h, truncated: f };
282
+ }, ae = (e) => ({ result: e, json: JSON.stringify(e) }), we = Object.freeze(ae(Object.freeze({ status: "error", failure: Object.freeze({ reason: "failed" }) }))), fn = (e) => e.status === "ok" && e.entries.length > 0, pn = ({ ttlMs: e, maxEntries: r, maxBytes: t, now: o }) => {
283
+ const c = Mt(r, { max: t, of: (m, b) => 2 * b.tree.json.length }), u = /* @__PURE__ */ new Map(), f = /* @__PURE__ */ new Map(), p = (m, b) => {
284
+ const E = new AbortController(), R = { waiters: 0, superseded: !1, started: !1, loadTree: b }, I = f.get(m), F = (j, de) => {
285
+ const K = ae(j);
286
+ return !(R.superseded || E.signal.aborted) && fn(j) && c.set(m, { tree: K, loadedAt: de }), K;
287
+ }, z = (async () => {
288
+ if (I !== void 0 && await I, E.signal.aborted) return we;
289
+ const j = o();
290
+ return R.started = !0, F(await R.loadTree(E.signal, j), j);
291
+ })().finally(() => {
292
+ u.get(m) === X && u.delete(m);
293
+ }), X = { promise: z, controller: E, state: R };
294
+ u.set(m, X);
295
+ const N = z.then(
296
+ () => {
297
+ },
298
+ () => {
299
+ }
300
+ );
301
+ return f.set(m, N), N.then(() => {
302
+ f.get(m) === N && f.delete(m);
303
+ }), X;
304
+ }, h = (m, b, E) => {
305
+ b.state.waiters += 1;
306
+ const R = () => {
307
+ b.state.waiters -= 1, !(b.state.waiters > 0) && (u.get(m) === b && u.delete(m), b.controller.abort());
308
+ };
309
+ return E.addEventListener("abort", R, { once: !0 }), b.promise.finally(() => {
310
+ E.removeEventListener("abort", R);
311
+ });
312
+ }, T = (m) => {
313
+ c.delete(m);
314
+ const b = u.get(m);
315
+ b?.state.started && (b.state.superseded = !0, u.delete(m));
316
+ };
317
+ return {
318
+ load: (m, b, E) => {
319
+ if (b.aborted) return Promise.resolve(we);
320
+ const R = c.get(m);
321
+ if (R !== void 0) {
322
+ if (o() - R.loadedAt < e) return Promise.resolve(R.tree);
323
+ c.delete(m);
324
+ }
325
+ const I = u.get(m);
326
+ return h(m, I === void 0 ? p(m, E) : I, b);
327
+ },
328
+ refresh: (m, b, E) => {
329
+ if (b.aborted) return Promise.resolve(we);
330
+ T(m);
331
+ const R = u.get(m);
332
+ return R === void 0 ? h(m, p(m, E), b) : (R.state.loadTree = E, h(m, R, b));
333
+ },
334
+ forget: T
335
+ };
336
+ }, hn = (e) => ({
337
+ load: (r, t, o) => o(t, e()).then(ae),
338
+ refresh: (r, t, o) => o(t, e()).then(ae),
339
+ forget: () => {
340
+ }
341
+ }), g = (e) => {
342
+ throw new TypeError(`[markdown-explorer] ${e}`);
343
+ }, wn = (e) => {
344
+ if (e === null || typeof e != "object") return null;
345
+ const { name: r, path: t } = e;
346
+ return typeof r != "string" || typeof t != "string" ? null : r === "" ? { path: t, reason: "an empty name" } : U(t) ? null : { path: t, reason: "a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)" };
347
+ }, mn = (e, r, t, o) => {
348
+ if (e === null) return null;
349
+ if (!Array.isArray(e)) throw new TypeError(`[markdown-explorer] a source's ancestors must be null or an array of folder paths; got ${x(e)}`);
350
+ const c = /* @__PURE__ */ new Set();
351
+ for (const u of e) {
352
+ if (typeof u != "string" || !U(u)) throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");
353
+ if (t.deniesPath(u)) throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");
354
+ if (!o(u)) throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");
355
+ if (u === r) throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");
356
+ if (c.has(u)) throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");
357
+ c.add(u);
358
+ }
359
+ return Object.freeze([...c]);
360
+ }, yn = (e, r, t, o, c) => {
361
+ const u = /* @__PURE__ */ new Set(), f = (h) => {
362
+ if (!Array.isArray(h)) return g("a source returned entries that are not an array");
363
+ const T = [];
364
+ for (const m of h) {
365
+ const b = p(m);
366
+ b !== null && T.push(b);
367
+ }
368
+ return T;
369
+ }, p = (h) => {
370
+ const T = wn(h);
371
+ if (T !== null)
372
+ return o(T), null;
373
+ const m = Ot(h);
374
+ if (m !== null) return g(m);
375
+ const b = h;
376
+ if (u.has(b)) return g("a source returned entries that contain themselves");
377
+ const { name: E, path: R, type: I, mimeType: F, modifiedAt: H, children: z, lazy: X } = b;
378
+ if (r.deniesName(E) || r.deniesPath(R)) return null;
379
+ if (!c(R))
380
+ return o({ path: R, reason: "a path outside the source's boundary" }), null;
381
+ const N = { name: E, path: R, ...F === void 0 ? {} : { mimeType: F }, ...H === void 0 ? {} : { modifiedAt: H } };
382
+ if (I === "file") return { ...N, type: I };
383
+ if (X === !0)
384
+ return t ? { ...N, type: I, lazy: !0, children: [] } : g("a lazy directory came from a source without a children function");
385
+ if (z === void 0) return { ...N, type: I };
386
+ u.add(b);
387
+ const j = f(z);
388
+ return u.delete(b), { ...N, type: I, children: j };
389
+ };
390
+ return f(e);
391
+ }, gn = /^[\x21\x23-\x7E]{1,256}$/u, Sr = (e) => typeof e == "string" && gn.test(e), bn = /* @__PURE__ */ new Set(["text", "image", "media", "spreadsheet", "file"]), En = (e) => typeof e == "string" && bn.has(e), kn = (e, r, t) => {
392
+ if (e !== null && typeof e == "object") {
393
+ const u = e, { kind: f } = u;
394
+ if (En(f)) {
395
+ if (Object.hasOwn(u, "url")) return g(`a ${f} document carries its version, not a url`);
396
+ if (typeof u.name != "string") return g("a document needs a name string");
397
+ if (!Sr(u.version)) return g(`a ${f} document needs a version of 1 to 256 visible ASCII characters other than '"'`);
398
+ const p = r(u.version);
399
+ switch (f) {
400
+ case "image": {
401
+ const { imageType: h } = u;
402
+ return gt(h) ? { kind: f, name: u.name, url: p, imageType: h } : g(`unknown image type ${x(h)}`);
403
+ }
404
+ case "file":
405
+ return { kind: f, name: u.name, url: p };
406
+ case "media": {
407
+ const { mediaType: h } = u;
408
+ return yt(h) ? { kind: f, name: u.name, url: p, mediaType: h } : g(`unknown media type ${x(h)}`);
409
+ }
410
+ case "text": {
411
+ const { text: h, truncated: T, lang: m } = u;
412
+ return typeof h != "string" || typeof T != "boolean" ? g("a text document needs text and truncated") : wt(m) ? { kind: f, name: u.name, text: h, truncated: T, lang: m, url: p } : g(mt(f, m));
413
+ }
414
+ case "spreadsheet": {
415
+ const h = ht(u);
416
+ if (h !== null) return g(h);
417
+ const { format: T, firstSheetText: m, edit: b } = u;
418
+ return { kind: f, name: u.name, url: p, format: T, firstSheetText: m, edit: On(b) };
419
+ }
420
+ }
421
+ }
422
+ }
423
+ const o = bt(e);
424
+ if (o !== null) return g(o);
425
+ const c = e;
426
+ switch (c.kind) {
427
+ case "failure": {
428
+ const { reason: u, code: f } = c.failure;
429
+ return { kind: "failure", failure: se(u, f) };
430
+ }
431
+ case "markdown":
432
+ return c.headings.length > pr ? { kind: "failure", failure: se("too-large") } : (c.edit?.kind === "inline" || c.edit?.kind === "draft") && !t ? g(`a markdown document offers ${c.edit.kind} editing, but the server has no edit ports`) : { kind: "unsanitized-markdown", name: c.name, html: c.htmlContent, headings: c.headings.map(({ text: u, depth: f, id: p }) => ({ text: u, depth: f, id: p })), lang: c.lang, edit: Tn(c.edit) };
433
+ }
434
+ }, Tn = (e) => {
435
+ if (e === null) return null;
436
+ switch (e.kind) {
437
+ case "inline":
438
+ return { kind: "inline" };
439
+ case "draft":
440
+ return { kind: "draft" };
441
+ case "external":
442
+ return { kind: "external", href: e.href };
443
+ }
444
+ }, On = (e) => e === null ? null : { kind: "external", href: e.href }, ie = (e, r, t) => typeof e != "string" ? g(`${t} needs a text string`) : e.includes("\0") ? g(`${t} holds NUL, which no text editor can keep`) : new TextEncoder().encode(e).byteLength > r ? g(`${t} is over editMaxBytes (${r} bytes); refuse a longer source with ExplorerError "too-large"`) : e, Pr = (e) => Tt(e.href) ? { kind: "grant", href: e.href } : g("a grant needs a root-relative href"), Rn = (e, r) => {
445
+ if (e === null || typeof e != "object") return g("an edit source must be an object");
446
+ const t = e;
447
+ return t.kind === "grant" ? Pr(t) : t.kind === "draft" ? { kind: "draft", text: ie(t.text, r, "a draft source") } : t.kind !== "edit" ? g(`an edit source's kind must be "edit", "draft" or "grant"`) : ee(t.version) ? typeof t.history != "boolean" ? g("an edit source needs history") : { kind: "edit", text: ie(t.text, r, "an edit source"), version: t.version, history: t.history } : g("an edit source needs a version of 1 to 1024 characters");
448
+ }, vn = (e, r) => {
449
+ if (e === null || typeof e != "object") return g("a save result must be an object");
450
+ const t = e;
451
+ switch (t.kind) {
452
+ case "grant":
453
+ return Pr(t);
454
+ case "saved":
455
+ return ee(t.version) ? { kind: "saved", version: t.version } : g("a saved result needs a version of 1 to 1024 characters");
456
+ case "conflict":
457
+ return ee(t.version) ? { kind: "conflict", version: t.version, text: ie(t.text, r, "a conflict's current text") } : g("a conflict needs the current version of 1 to 1024 characters");
458
+ default:
459
+ return g(`a save result's kind must be "saved", "conflict" or "grant"`);
460
+ }
461
+ }, xn = (e) => {
462
+ if (e === null || typeof e != "object") return g("a preview must be an object");
463
+ const { htmlContent: r, headings: t } = e;
464
+ if (typeof r != "string" || !Array.isArray(t)) return g("a preview needs htmlContent and headings");
465
+ if (t.length > pr) return { kind: "failure", failure: se("too-large") };
466
+ for (const o of t) {
467
+ const c = kt(o);
468
+ if (c !== null) return g(c);
469
+ }
470
+ return { html: r, headings: t.map(({ text: o, depth: c, id: u }) => ({ text: o, depth: c, id: u })) };
471
+ }, An = (e) => {
472
+ if (!Array.isArray(e)) return g("revisions must be an array");
473
+ const r = /* @__PURE__ */ new Set();
474
+ return e.map((t) => {
475
+ const o = Et(t);
476
+ if (o !== null) return g(o);
477
+ const { id: c, modifiedAt: u, size: f, author: p, kept: h, current: T } = t;
478
+ return r.has(c) ? g(`two revisions share the id ${x(c)}`) : (r.add(c), { id: c, modifiedAt: u, size: f, author: p, kept: h, current: T });
479
+ });
480
+ }, Sn = (e, r) => ie(e, r, "a revision"), Ee = (e) => {
481
+ if (e === null || typeof e != "object") return g("an asset file must be an object");
482
+ const { name: r, contentType: t, size: o, version: c, open: u, kind: f, bridge: p } = e;
483
+ if (f !== void 0) return g(f === "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")');
484
+ if (typeof r != "string" || r === "") return g("an asset file needs a non-empty name");
485
+ if (typeof t != "string") return g("an asset file needs a contentType string ('' when unknown)");
486
+ if (o !== null && !(typeof o == "number" && Number.isSafeInteger(o) && o >= 0)) return g("an asset file's size must be null or a non-negative safe integer");
487
+ if (!Sr(c)) return g(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`);
488
+ if (typeof u != "function") return g("an asset file needs an open function");
489
+ const h = { name: r, contentType: t, size: o, version: c, open: u };
490
+ return Object.freeze(p === void 0 ? h : { ...h, bridge: Pn(p) });
491
+ }, Pn = (e) => {
492
+ if (e === null || typeof e != "object") return g("an asset file's bridge must be an object when present");
493
+ const { uri: r, storageVersion: t, readFailure: o } = e;
494
+ return typeof r != "string" || r === "" ? g("an asset file's bridge needs a non-empty uri") : t !== null && (typeof t != "string" || t === "") ? g("an asset file's bridge needs a storageVersion that is a non-empty string, or null when the storage keeps none") : typeof o != "function" ? g("an asset file's bridge needs a readFailure function") : Object.freeze({ uri: r, storageVersion: t, readFailure: o });
495
+ }, Ze = (e) => {
496
+ if (e === null || typeof e != "object" || e.kind !== "redirect") return Ee(e);
497
+ const { url: r } = e;
498
+ if (typeof r != "string" || !URL.canParse(r)) return g("an asset redirect needs an absolute https URL");
499
+ const t = new URL(r);
500
+ return t.protocol !== "https:" || t.username !== "" || t.password !== "" ? g("an asset redirect's URL must be https and carry no credentials") : Object.freeze({ kind: "redirect", url: t.href });
501
+ }, In = (e) => Array.isArray(e) ? e.map((r) => {
502
+ if (r === null || typeof r != "object") return g("a notice must be an object");
503
+ const { id: t, tone: o, title: c, body: u, action: f } = r;
504
+ if (typeof t != "string" || t === "" || typeof c != "string") return g("a notice needs an id and a title");
505
+ if (!Rt(o)) return g(`unknown notice tone ${x(o)}`);
506
+ if (u !== void 0 && typeof u != "string") return g("a notice body must be a string");
507
+ const h = { id: t, tone: o, title: c, ...u === void 0 ? {} : { body: u } };
508
+ if (f === void 0) return h;
509
+ if (f === null || typeof f != "object") return g("a notice action must be an object");
510
+ const { label: T, href: m } = f;
511
+ return typeof T != "string" || !vt(m, xt) ? g("a notice action needs a label and an http(s), mailto or relative href") : { ...h, action: { label: T, href: m } };
512
+ }) : g("notices must be an array"), _n = 4e3, te = Object.freeze({ ttlMs: 3e5, maxEntries: 64, maxBytes: 64 * 1024 * 1024 }), Ir = "private, no-store", Dn = Object.freeze({
513
+ "Content-Type": "application/json; charset=utf-8",
514
+ "Cache-Control": Ir,
515
+ "X-Content-Type-Options": "nosniff",
516
+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'; sandbox",
517
+ "Cross-Origin-Resource-Policy": "same-origin"
518
+ }), me = Object.freeze([]), $n = Object.freeze({ status: "ok", source: null, ancestors: null }), qe = Object.freeze(["contains", "confirm"]), er = Object.freeze({ readOnly: !1 }), Nn = Object.freeze({ readOnly: !0 }), Ln = /* @__PURE__ */ new Set(["file", "text", "workbook"]), jn = /* @__PURE__ */ new Set(["file", "text"]), Mn = Object.freeze({ status: "error", failure: Object.freeze({ reason: "invalid" }) }), S = (e, r, t) => {
519
+ if (!(t && r === void 0) && typeof r != "function")
520
+ throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${x(r)}`);
521
+ }, G = (e, r, t) => {
522
+ if (typeof r != "number") throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${x(r)}`);
523
+ if (!Number.isSafeInteger(r) || r <= 0 || r > t) throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(t)}; got ${x(r)}`);
524
+ return r;
525
+ }, Cn = (e) => {
526
+ if (e === null || typeof e != "object" || !Object.isFrozen(e)) throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");
527
+ return it(e);
528
+ }, rr = (e) => {
529
+ try {
530
+ return new Headers(e);
531
+ } catch {
532
+ throw new TypeError("[markdown-explorer] authenticate returned headers that are not a valid headers init (their values are not logged)");
533
+ }
534
+ }, tr = (e) => e instanceof Response ? new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`) : e, zn = (e, r) => {
535
+ if (!jt(r)) throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);
536
+ for (const t of Object.keys(r))
537
+ if (!qe.includes(t)) throw new RangeError(`[markdown-explorer] ${e}.boundary.${t} is not an option; expected ${qe.join(", ")}`);
538
+ S(`${e}.boundary.contains`, r.contains, !1), S(`${e}.boundary.confirm`, r.confirm, !0);
539
+ }, Un = (e) => {
540
+ if (!Array.isArray(e)) throw new TypeError("[markdown-explorer] sources must be an array");
541
+ const r = e;
542
+ if (r.length === 0) throw new RangeError("[markdown-explorer] sources must hold at least one source");
543
+ const t = /* @__PURE__ */ new Set();
544
+ for (const [o, c] of r.entries()) {
545
+ if (c === null || typeof c != "object") throw new TypeError(`[markdown-explorer] sources[${String(o)}] must be an object`);
546
+ const { id: u, label: f, boundary: p, tree: h, children: T, ancestors: m, cacheScope: b } = c;
547
+ if (!ct(u))
548
+ throw new RangeError(`[markdown-explorer] sources[${String(o)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${x(u)}`);
549
+ const E = `source ${x(u)}`;
550
+ if (t.has(u)) throw new RangeError(`[markdown-explorer] source ids must be unique; ${x(u)} repeats at sources[${String(o)}]`);
551
+ if (t.add(u), typeof f != "string" && typeof f != "function") throw new TypeError(`[markdown-explorer] ${E}.label must be a string or a function`);
552
+ if (typeof f == "string" && f.trim() === "") throw new RangeError(`[markdown-explorer] ${E}.label must not be blank`);
553
+ if (zn(E, p), S(`${E}.tree`, h, !1), S(`${E}.children`, T, !0), S(`${E}.ancestors`, m, !0), b !== void 0 && b !== "principal" && b !== "shared") throw new RangeError(`[markdown-explorer] ${E}.cacheScope must be "principal" or "shared"; got ${x(b)}`);
554
+ }
555
+ return r;
556
+ }, Fn = (e) => {
557
+ if (e === !1) return !1;
558
+ if (e === void 0) return te;
559
+ if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] treeCache must be { ttlMs, maxEntries, maxBytes } or false");
560
+ const { ttlMs: r, maxEntries: t, maxBytes: o } = e;
561
+ return {
562
+ ttlMs: r === void 0 ? te.ttlMs : G("treeCache.ttlMs", r, Number.MAX_SAFE_INTEGER),
563
+ maxEntries: t === void 0 ? te.maxEntries : G("treeCache.maxEntries", t, Number.MAX_SAFE_INTEGER),
564
+ maxBytes: o === void 0 ? te.maxBytes : G("treeCache.maxBytes", o, Number.MAX_SAFE_INTEGER)
565
+ };
566
+ }, nr = (e) => {
567
+ if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] authenticate must resolve to { status, ... }");
568
+ const { status: r } = e;
569
+ if (r !== "signed-in" && r !== "signed-out" && r !== "forbidden") throw new TypeError(`[markdown-explorer] authenticate resolved to an unknown status ${x(r)}`);
570
+ return e;
571
+ }, sr = (e, r) => {
572
+ if (!(r instanceof Response)) throw new TypeError(`[markdown-explorer] ${e} must return a Response`);
573
+ return r;
574
+ }, or = (e, r) => {
575
+ if (typeof r != "string" || r === "") throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");
576
+ const t = e(r);
577
+ if (!Ct(t)) throw new TypeError("[markdown-explorer] the platform's scope must be 22 base64url characters");
578
+ return t;
579
+ }, Hn = (e, r) => {
580
+ try {
581
+ return e(r);
582
+ } catch (t) {
583
+ return t;
584
+ }
585
+ }, Xn = (e, r) => {
586
+ const t = e(r);
587
+ if (t !== void 0 && typeof t != "string") throw new TypeError(`[markdown-explorer] readSettings must return a string or undefined; got ${t === null ? "null" : typeof t}`);
588
+ return t;
589
+ }, Bn = (e) => e.view === "multi" ? e.docs : e.doc === null ? [] : [e.doc], C = (e, r) => {
590
+ const t = e.getAll(r), [o] = t;
591
+ return t.length === 1 && o !== void 0 && o !== "" ? o : null;
592
+ }, P = (e, r, t, o = {}) => {
593
+ const c = new Headers(t);
594
+ for (const [u, f] of Object.entries({ ...Dn, ...o })) c.set(u, f);
595
+ return new Response(r, { status: e, headers: c });
596
+ }, O = (e, r, t) => P(hr[e.reason], JSON.stringify({ failure: e }), r, t), Vn = /* @__PURE__ */ new Set(["refresh", "save", "preview", "issue-id"]), Gn = /* @__PURE__ */ new Set(["issue-id", "resolve-id"]), ar = 4, Wn = /* @__PURE__ */ new Set(["edit", "save", "preview", "revisions", "revision"]), ir = (e, r) => {
597
+ const t = Vn.has(r) ? ["POST"] : ["GET", "HEAD"];
598
+ return t.includes(e.method.toUpperCase()) ? null : P(405, JSON.stringify({ failure: { reason: "invalid" } }), void 0, { Allow: t.join(", ") });
599
+ }, cr = (e) => e.headers.get(ce) === Pt && ke(e, Te) === void 0, Yn = (e) => e.headers.get(ce) === It && ke(e, Te) === void 0, Jn = (e) => e.headers.get(ce) === _t && ke(e, Te) === void 0, Kn = async (e, r) => {
600
+ const [t, ...o] = (e.headers.get("Content-Type") ?? "").split(";").map((E) => E.trim().toLowerCase()), c = o.find((E) => E.startsWith("charset="));
601
+ if (t !== Lt || c !== void 0 && c !== "charset=utf-8") return { status: "error", failure: { reason: "invalid" } };
602
+ const u = Number(e.headers.get("Content-Length") ?? "0");
603
+ if (Number.isFinite(u) && u > r) return { status: "error", failure: { reason: "too-large" } };
604
+ if (e.body === null) return { status: "ok", text: "" };
605
+ const f = e.body.getReader(), p = [];
606
+ let h = 0;
607
+ for (; ; ) {
608
+ const { done: E, value: R } = await f.read();
609
+ if (E) break;
610
+ if (h += R.byteLength, h > r)
611
+ return await f.cancel(), { status: "error", failure: { reason: "too-large" } };
612
+ p.push(R);
613
+ }
614
+ const T = new Uint8Array(h);
615
+ let m = 0;
616
+ for (const E of p)
617
+ T.set(E, m), m += E.byteLength;
618
+ let b;
619
+ try {
620
+ b = new TextDecoder("utf-8", { fatal: !0 }).decode(T);
621
+ } catch {
622
+ return { status: "error", failure: { reason: "invalid" } };
623
+ }
624
+ return b.includes("\0") ? { status: "error", failure: { reason: "invalid" } } : { status: "ok", text: b };
625
+ }, Qn = (e) => {
626
+ if (e === void 0) return;
627
+ if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] edit must be an object of the editor's ports");
628
+ const r = e;
629
+ for (const t of ["source", "save", "preview", "revisions", "revision"]) S(`edit.${t}`, r[t], !1);
630
+ return e;
631
+ }, Zn = (e, r) => {
632
+ if (e.documentIds === null != (r === void 0)) throw new TypeError("[markdown-explorer] documentIds in defineExplorerConfig and the server's documentIds ports go together; give both or neither");
633
+ if (r === void 0) return;
634
+ if (r === null || typeof r != "object") throw new TypeError("[markdown-explorer] documentIds must be an object of the registry's ports");
635
+ const t = r;
636
+ for (const o of ["issue", "resolve"]) S(`documentIds.${o}`, t[o], !1);
637
+ return r;
638
+ }, qn = (e) => {
639
+ if (e === null || typeof e != "object") return null;
640
+ const { kind: r, id: t } = e;
641
+ return r === "issued" || r === "taken" ? { kind: r } : r === "existing" && wr(t) ? { kind: r, id: t } : null;
642
+ }, es = (e) => {
643
+ if (e === null || typeof e != "object") return;
644
+ const { kind: r, path: t } = e;
645
+ return r === "unbound" ? null : r === "bound" && typeof t == "string" && lr(t) ? t : void 0;
646
+ }, dr = (e, r) => e.status === "ok" ? P(200, JSON.stringify(e), r) : O(e.failure, r), rs = ({ parentHeaders: e, loaderHeaders: r, errorHeaders: t }) => {
647
+ const o = new Headers(), c = t === void 0 ? [e, r] : [e, r, t];
648
+ for (const u of c)
649
+ for (const [f, p] of u)
650
+ f !== "set-cookie" && o.set(f, p);
651
+ return o;
652
+ }, us = (e, r) => {
653
+ if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] the server configuration must be an object");
654
+ const t = Cn(e.config), o = r.prepareScope();
655
+ S("authenticate", e.authenticate, !1), S("principalKey", e.principalKey, !1), S("document", e.document, !1), S("asset", e.asset, !1), S("signedOutPage", e.signedOutPage, !1), S("forbiddenPage", e.forbiddenPage, !0), S("notices", e.notices, !0), S("onTreeRefreshed", e.onTreeRefreshed, !0), S("readSettings", e.readSettings, !1);
656
+ const c = Un(e.sources), u = st(
657
+ t,
658
+ c.map((n) => n.id)
659
+ ), f = e.logger;
660
+ if (f !== void 0 && (f === null || typeof f != "object" || typeof f.error != "function"))
661
+ throw new TypeError("[markdown-explorer] logger must be an object with an error function");
662
+ const p = e.logger === void 0 ? on : e.logger, h = At(e.deny), T = e.deferredTimeoutMs === void 0 ? _n : G("deferredTimeoutMs", e.deferredTimeoutMs, zt), m = e.textMaxBytes === void 0 ? Ke : G("textMaxBytes", e.textMaxBytes, Qe), b = Qn(e.edit);
663
+ if (b === void 0 && e.editMaxBytes !== void 0) throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");
664
+ const E = e.editMaxBytes === void 0 ? Ke : G("editMaxBytes", e.editMaxBytes, Qe), R = Zn(t, e.documentIds), I = Fn(e.treeCache), F = () => Date.now(), H = I === !1 ? hn(F) : pn({ ...I, now: F }), z = r.createSanitizer({ options: e.sanitizer, maxPanels: t.multiView.maxPanels, iframeHosts: t.iframeHosts, dataPath: t.dataPath, ownUrls: ot(t) }), X = e.readSettings, N = e.assetMaxRangeBytes === null ? null : G("assetMaxRangeBytes", e.assetMaxRangeBytes, Number.MAX_SAFE_INTEGER), j = new Map(c.map((n) => [n.id, n])), de = at(t), { authenticate: K, principalKey: xe, signedOutPage: _r, forbiddenPage: Ae, onTreeRefreshed: Se } = e, Dr = (n, a) => {
665
+ if (typeof n.label == "string") return n.label;
666
+ const s = n.label(a);
667
+ if (typeof s != "string" || s.trim() === "") throw new TypeError(`[markdown-explorer] the label of source ${x(n.id)} must be a non-blank string`);
668
+ return s;
669
+ }, ue = (n, a) => n.cacheScope === "shared" ? n.id : `${n.id}\0${a}`, Y = (n, a) => {
670
+ const s = (d) => $(p, { operation: "boundary", sourceId: n.id, path: a, error: d });
671
+ let i;
672
+ try {
673
+ i = n.boundary.contains(a);
674
+ } catch (d) {
675
+ return s(d), !1;
676
+ }
677
+ return typeof i == "boolean" ? i : (Je(i, s), s(new TypeError(`[markdown-explorer] boundary.contains of source ${x(n.id)} must return a boolean; got ${x(i)}`)), !1);
678
+ }, le = async (n, a, s) => {
679
+ const { confirm: i } = n.boundary;
680
+ if (i === void 0) return { status: "inside", readPath: s };
681
+ let d;
682
+ try {
683
+ d = await i(a, s);
684
+ } catch (k) {
685
+ return { status: "error", failure: v(k, { operation: "boundary", sourceId: n.id, path: s }, a.signal, p) };
686
+ }
687
+ const l = (k) => ($(p, { operation: "boundary", sourceId: n.id, path: s, error: new TypeError(`[markdown-explorer] boundary.confirm of source ${x(n.id)} ${k}`) }), { status: "outside" });
688
+ if (d === null || typeof d != "object") return l(`must resolve to { inside, readPath? }; got ${d === null ? "null" : typeof d}`);
689
+ const { inside: w, readPath: y } = d;
690
+ return w === !1 ? { status: "outside" } : w !== !0 || typeof y != "string" ? l("must resolve to { inside: false } or { inside: true, readPath: string }") : !U(y) || h.deniesPath(y) ? ($(p, { operation: "boundary", sourceId: n.id, path: s, error: new RangeError(`[markdown-explorer] boundary.confirm of source ${x(n.id)} answered a readPath the explorer does not serve (unacceptable or denied)`) }), { status: "error", failure: { reason: "failed" } }) : { status: "inside", readPath: y };
691
+ }, J = async (n, a) => {
692
+ const s = c.filter((l) => Y(l, a));
693
+ if (s.length === 0) return { status: "error", failure: { reason: "forbidden" } };
694
+ const i = s.find((l) => l.boundary.confirm === void 0);
695
+ if (i !== void 0) return { status: "inside", readPath: a, sourceId: i.id };
696
+ let d = null;
697
+ for (const l of s) {
698
+ const w = await le(l, n, a);
699
+ if (w.status === "inside") return { status: "inside", readPath: w.readPath, sourceId: l.id };
700
+ w.status === "error" && d === null && (d = w.failure);
701
+ }
702
+ return { status: "error", failure: d === null ? { reason: "forbidden" } : d };
703
+ }, Pe = async (n, a, s) => {
704
+ try {
705
+ return Ze(await e.asset(n, a, s, { delivery: "file" })), null;
706
+ } catch (i) {
707
+ return v(i, { operation: "asset", path: a }, n.signal, p);
708
+ }
709
+ }, Ie = async (n, a, s) => {
710
+ let i;
711
+ try {
712
+ i = await n.resolve(a, s);
713
+ } catch (y) {
714
+ return { status: "error", failure: v(y, { operation: "resolve-id" }, a.signal, p) };
715
+ }
716
+ const d = es(i);
717
+ if (d === void 0)
718
+ return $(p, { operation: "resolve-id", error: new TypeError('[markdown-explorer] documentIds.resolve must resolve to { kind: "unbound" } or { kind: "bound", path } with a document path that has a URL') }), { status: "error", failure: { reason: "failed" } };
719
+ if (d === null) return { status: "error", failure: { reason: "not-found" } };
720
+ if (h.deniesPath(d))
721
+ return Z(p, { operation: "resolve-id", path: d }), { status: "error", failure: { reason: "forbidden" } };
722
+ const l = await J(a, d);
723
+ if (l.status === "error") return l;
724
+ const w = await Pe(a, d, l.readPath);
725
+ return w !== null ? { status: "error", failure: w } : { status: "resolved", path: d, sourceId: l.sourceId };
726
+ }, $r = async (n, a, s) => {
727
+ if (h.deniesPath(s))
728
+ return Z(p, { operation: "issue-id", path: s }), { status: "error", failure: { reason: "forbidden" } };
729
+ const i = await J(a, s);
730
+ if (i.status === "error") return i;
731
+ const d = await Pe(a, s, i.readPath);
732
+ if (d !== null) return { status: "error", failure: d };
733
+ for (let l = 0; l < ar; l += 1) {
734
+ const w = Nt((_) => crypto.getRandomValues(_));
735
+ let y;
736
+ try {
737
+ y = await n.issue(a, s, w);
738
+ } catch (_) {
739
+ return { status: "error", failure: v(_, { operation: "issue-id", path: s }, a.signal, p) };
740
+ }
741
+ const k = qn(y);
742
+ if (k === null)
743
+ return $(p, { operation: "issue-id", path: s, error: new TypeError('[markdown-explorer] documentIds.issue must resolve to { kind: "issued" }, { kind: "existing", id } with an ID in its canonical form, or { kind: "taken" }') }), { status: "error", failure: { reason: "failed" } };
744
+ if (k.kind === "issued") return { status: "ok", id: w };
745
+ if (k.kind === "existing") return { status: "ok", id: k.id };
746
+ }
747
+ return $(p, { operation: "issue-id", path: s, error: new Error(`[markdown-explorer] documentIds.issue answered taken for ${String(ar)} candidates in a row`) }), { status: "error", failure: { reason: "failed" } };
748
+ }, _e = (n, a, s) => {
749
+ const i = ({ path: d, reason: l }) => dn(p, { operation: s.operation, sourceId: s.sourceId, path: d, error: new TypeError(`[markdown-explorer] an entry with ${l} was left out`) });
750
+ try {
751
+ return { status: "ok", entries: yn(n, h, a.children !== void 0, i, (d) => Y(a, d)) };
752
+ } catch (d) {
753
+ return $(p, { ...s, error: d }), { status: "error", failure: { reason: "failed" } };
754
+ }
755
+ }, Nr = async (n, a, s) => {
756
+ let i;
757
+ try {
758
+ i = await n.tree(a);
759
+ } catch (l) {
760
+ return { status: "error", failure: v(l, { operation: "tree", sourceId: n.id }, a.signal, p) };
761
+ }
762
+ const d = _e(i, n, { operation: "tree", sourceId: n.id });
763
+ return d.status === "ok" ? { status: "ok", entries: d.entries, loadedAt: s } : d;
764
+ }, De = (n, a, s, i) => (d, l) => Nr(n, { principal: a, request: s, signal: d, refresh: i }, l), $e = (n, a, s, i, d) => H.load(ue(n, s), d, De(n, a, i, !1)), Lr = (n, a, s, i) => H.refresh(ue(n, s), i.signal, De(n, a, i, !0)), jr = (n, a) => {
765
+ if (Se === void 0) return;
766
+ const s = (i) => $(p, { operation: "refresh", sourceId: n.id, error: i });
767
+ try {
768
+ Je(Se(a), s);
769
+ } catch (i) {
770
+ s(i);
771
+ }
772
+ }, Mr = async (n, a, s, i) => {
773
+ if (h.deniesPath(i) || !Y(n, i)) return { status: "error", failure: { reason: "forbidden" } };
774
+ const d = await le(n, s, i);
775
+ if (d.status === "outside") return { status: "error", failure: { reason: "forbidden" } };
776
+ if (d.status === "error") return { status: "error", failure: d.failure };
777
+ let l;
778
+ try {
779
+ l = await a(s, i, d.readPath);
780
+ } catch (w) {
781
+ return { status: "error", failure: v(w, { operation: "children", sourceId: n.id, path: i }, s.signal, p) };
782
+ }
783
+ return _e(l, n, { operation: "children", sourceId: n.id, path: i });
784
+ }, Ne = async (n, a, s, i) => {
785
+ const d = await le(n, s, i);
786
+ if (d.status === "outside") return { status: "ok", ancestors: null };
787
+ if (d.status === "error") return { status: "error", failure: d.failure };
788
+ let l;
789
+ try {
790
+ l = await a(s, i, d.readPath, { maxDepth: t.revealDocument.maxDepth });
791
+ } catch (w) {
792
+ return { status: "error", failure: v(w, { operation: "ancestors", sourceId: n.id, path: i }, s.signal, p) };
793
+ }
794
+ if (Array.isArray(l) && l.length > t.revealDocument.maxDepth) return { status: "ok", ancestors: null };
795
+ try {
796
+ return { status: "ok", ancestors: mn(l, i, h, (w) => Y(n, w)) };
797
+ } catch (w) {
798
+ return $(p, { operation: "ancestors", sourceId: n.id, path: i, error: w }), { status: "error", failure: { reason: "failed" } };
799
+ }
800
+ }, Cr = async (n, a, s, i) => h.deniesPath(i) ? { status: "error", failure: { reason: "forbidden" } } : Y(n, i) ? Ne(n, a, s, i) : { status: "ok", ancestors: null }, zr = async (n, a, s) => {
801
+ if (h.deniesPath(s)) return { status: "error", failure: { reason: "forbidden" } };
802
+ for (const i of [n, ...c.filter((d) => d !== n)]) {
803
+ if (a.signal.aborted) break;
804
+ const d = i.ancestors;
805
+ if (d === void 0 || !Y(i, s)) continue;
806
+ const l = await Ne(i, d, a, s);
807
+ if (l.status === "ok" && l.ancestors !== null) return { status: "ok", source: i.id, ancestors: l.ancestors };
808
+ }
809
+ return $n;
810
+ }, Le = async (n, a, s) => {
811
+ if (h.deniesPath(s)) return V("forbidden");
812
+ const i = await J(n, s);
813
+ if (i.status === "error") return { kind: "failure", failure: i.failure };
814
+ let d;
815
+ try {
816
+ d = await e.document(n, s, i.readPath);
817
+ } catch (y) {
818
+ return { kind: "failure", failure: v(y, { operation: "document", path: s }, n.signal, p) };
819
+ }
820
+ let l;
821
+ try {
822
+ l = kn(d, (y) => He(t.dataPath, s, y), b !== void 0);
823
+ } catch (y) {
824
+ return $(p, { operation: "document", path: s, error: y }), V("failed");
825
+ }
826
+ if (l.kind !== "unsanitized-markdown") return l;
827
+ const w = await z(l.html, { scope: a, signal: n.signal });
828
+ return w.status === "sanitized" ? { kind: "markdown", name: l.name, htmlContent: w.html, headings: l.headings, lang: l.lang, edit: l.edit } : (w.cause !== null && $(p, { operation: "document", path: s, error: w.cause }), V(w.reason));
829
+ }, Ur = async (n) => {
830
+ if (e.notices === void 0) return me;
831
+ try {
832
+ return In(await e.notices(n));
833
+ } catch (a) {
834
+ return v(a, { operation: "notices" }, n.signal, p), me;
835
+ }
836
+ }, je = async (n, a, s, i) => {
837
+ const d = C(a, M.path);
838
+ if (d === null || !U(d)) return { status: "answered", response: O({ reason: "invalid" }, s) };
839
+ const l = $t(a);
840
+ if (l === null || !i.has(l)) return { status: "answered", response: O({ reason: "invalid" }, s) };
841
+ if (h.deniesPath(d))
842
+ return Z(p, { operation: "asset", path: d }), { status: "answered", response: O({ reason: "forbidden" }, s) };
843
+ const w = await J(n, d);
844
+ if (w.status === "error") return { status: "answered", response: O(w.failure, s) };
845
+ try {
846
+ const y = await e.asset(n, d, w.readPath, { delivery: l }), k = l === "file" ? Ze(y) : Ee(y);
847
+ return "kind" in k ? { status: "answered", response: sn(k.url, s) } : { status: "admitted", path: d, display: l, file: k };
848
+ } catch (y) {
849
+ return { status: "answered", response: O(v(y, { operation: "asset", path: d }, n.signal, p), s) };
850
+ }
851
+ }, Fr = async (n, a, s) => {
852
+ const i = await je(n, a, s, Ln);
853
+ if (i.status === "answered") return i.response;
854
+ const { path: d, display: l, file: w } = i;
855
+ try {
856
+ return l === "text" ? await en(n.request, w, s, t.legacyTextEncoding, N) : l === "workbook" ? await tn(n.request, w, s) : await Qt(n.request, w, s, N);
857
+ } catch (y) {
858
+ return O(v(y, { operation: "asset", path: d }, n.signal, p), s);
859
+ }
860
+ }, Hr = async (n, a, s) => {
861
+ const i = xr(n, a, s, t.legacyTextEncoding, N);
862
+ return i.kind === "respond" ? i : be(i.selection, await vr(a, t.legacyTextEncoding));
863
+ }, Xr = async (n, a, s) => {
864
+ const i = await je(n, a, s, jn);
865
+ if (i.status === "answered") return { kind: "response", response: i.response };
866
+ const { path: d, display: l, file: w } = i, y = (D) => O(v(D, { operation: "asset", path: d }, n.signal, p), s);
867
+ let k;
868
+ try {
869
+ k = l === "text" ? await Hr(n.request, w, s) : Or(n.request, w, s, N);
870
+ } catch (D) {
871
+ return { kind: "response", response: y(D) };
872
+ }
873
+ if (k.kind === "respond") return { kind: "response", response: k.response };
874
+ const { bridge: _ } = w;
875
+ return _ === void 0 ? ($(p, { operation: "asset", path: d, 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" }, s) }) : { kind: "file", status: k.status, headers: k.headers, bridge: { uri: _.uri, storageVersion: _.storageVersion }, range: k.range, length: k.length, fail: (D) => y(Hn(_.readFailure, D)) };
876
+ }, Br = async (n, a) => {
877
+ if (h.deniesPath(a))
878
+ return Z(p, { operation: "text", path: a }), V("forbidden");
879
+ const s = await J(n, a);
880
+ if (s.status === "error") return { kind: "failure", failure: s.failure };
881
+ try {
882
+ const i = Ee(await e.asset(n, a, s.readPath, { delivery: "text" })), d = await ln(i, m, t.legacyTextEncoding);
883
+ return d === null ? V("unsupported") : { kind: "text", name: i.name, text: d.text, truncated: d.truncated, url: He(t.dataPath, a, i.version) };
884
+ } catch (i) {
885
+ return { kind: "failure", failure: v(i, { operation: "text", path: a }, n.signal, p) };
886
+ }
887
+ }, Q = async (n, a, s) => h.deniesPath(s) ? (Z(p, { operation: a, path: s }), { status: "error", failure: { reason: "forbidden" } }) : J(n, s), Vr = async (n, a, s) => {
888
+ const i = await Q(a, "edit", s);
889
+ if (i.status === "error") return { kind: "failure", failure: i.failure };
890
+ try {
891
+ return Rn(await n.source(a, s, i.readPath), E);
892
+ } catch (d) {
893
+ return { kind: "failure", failure: v(d, { operation: "edit", path: s }, a.signal, p) };
894
+ }
895
+ }, Gr = async (n, a, s, i, d) => {
896
+ const l = await Q(a, "save", s);
897
+ if (l.status === "error") return { kind: "failure", failure: l.failure };
898
+ try {
899
+ return vn(await n.save(a, s, l.readPath, { text: d, baseVersion: i }), E);
900
+ } catch (w) {
901
+ return { kind: "failure", failure: v(w, { operation: "save", path: s }, a.signal, p) };
902
+ }
903
+ }, Wr = async (n, a, s, i, d) => {
904
+ const l = await Q(a, "preview", i);
905
+ if (l.status === "error") return { kind: "failure", failure: l.failure };
906
+ let w;
907
+ try {
908
+ w = xn(await n.preview(a, i, l.readPath, d));
909
+ } catch (k) {
910
+ return { kind: "failure", failure: v(k, { operation: "preview", path: i }, a.signal, p) };
911
+ }
912
+ if ("kind" in w) return w.kind === "failure" ? w : V("failed");
913
+ const y = await z(w.html, { scope: s, signal: a.signal });
914
+ return y.status === "sanitized" ? { kind: "preview", htmlContent: y.html, headings: w.headings } : (y.cause !== null && $(p, { operation: "preview", path: i, error: y.cause }), V(y.reason));
915
+ }, Yr = async (n, a, s) => {
916
+ const i = await Q(a, "revisions", s);
917
+ if (i.status === "error") return { kind: "failure", failure: i.failure };
918
+ try {
919
+ return { kind: "revisions", revisions: An(await n.revisions(a, s, i.readPath)) };
920
+ } catch (d) {
921
+ return { kind: "failure", failure: v(d, { operation: "revisions", path: s }, a.signal, p) };
922
+ }
923
+ }, Jr = async (n, a, s, i) => {
924
+ const d = await Q(a, "revision", s);
925
+ if (d.status === "error") return { kind: "failure", failure: d.failure };
926
+ try {
927
+ return { kind: "revision", id: i, text: Sn(await n.revision(a, s, d.readPath, i), E) };
928
+ } catch (l) {
929
+ return { kind: "failure", failure: v(l, { operation: "revision", path: s }, a.signal, p) };
930
+ }
931
+ }, Kr = async (n, a, s, i, d, l) => {
932
+ const w = C(d, M.path);
933
+ if (w === null || !U(w)) return O({ reason: "invalid" }, l);
934
+ if (a === "edit") return P(200, JSON.stringify(await Vr(n, s, w)), l);
935
+ if (a === "revisions") return P(200, JSON.stringify(await Yr(n, s, w)), l);
936
+ if (a === "revision") {
937
+ const _ = C(d, M.revision);
938
+ return ee(_) ? P(200, JSON.stringify(await Jr(n, s, w, _)), l) : O({ reason: "invalid" }, l);
939
+ }
940
+ const y = C(d, M.base);
941
+ if (a === "save" && !ee(y)) return O({ reason: "invalid" }, l);
942
+ const k = await Kn(s.request, E);
943
+ return k.status === "error" ? O(k.failure, l) : a === "preview" ? P(200, JSON.stringify(await Wr(n, s, i, w, k.text)), l) : P(200, JSON.stringify(await Gr(n, s, w, y, k.text)), l);
944
+ }, Qr = async ({ request: n, url: a, params: s }) => {
945
+ const i = nr(await K(n, er)), d = rr(i.headers);
946
+ if (d.set("Cache-Control", Ir), i.status === "signed-out") throw sr("signedOutPage", _r(n, d));
947
+ if (i.status === "forbidden") throw Ae === void 0 ? pe(null, { status: 403, headers: d }) : sr("forbiddenPage", Ae(n, d));
948
+ const l = dt(u, s["*"], a.searchParams);
949
+ if (l.kind === "redirect") throw Fe(l.href, { headers: d });
950
+ const { principal: w } = i, y = or(o, xe(w));
951
+ if (l.kind === "document-id") {
952
+ if (R === void 0) throw new TypeError("[markdown-explorer] an ID URL was resolved without the documentIds ports");
953
+ const k = l.id === null ? Mn : await Ie(R, { principal: w, request: n, signal: n.signal, refresh: !1 }, l.id);
954
+ if (k.status === "resolved") throw Fe(Zr(l.opens, k), { headers: d });
955
+ return pe(Me(w, y, n, l.location, { id: l.id, failure: k.failure }), { status: hr[k.failure.reason], headers: d });
956
+ }
957
+ return pe(Me(w, y, n, l.location, null), { headers: d });
958
+ }, Zr = (n, a) => ut(u, lt(n, a.path, a.sourceId)), Me = (n, a, s, i, d) => {
959
+ const l = j.get(i.source);
960
+ if (l === void 0) throw new RangeError(`[markdown-explorer] no source for ${x(i.source)}`);
961
+ const w = { signal: s.signal, timeoutMs: T, late: null, handOverMs: T };
962
+ return {
963
+ scope: a,
964
+ sources: c.map((y) => ({ id: y.id, label: Dr(y, n) })),
965
+ settings: ft(Xn(X, s), de),
966
+ tree: i.view === "single" ? null : {
967
+ sourceId: i.source,
968
+ result: he(w, (y) => $e(l, n, a, s, y).then((k) => k.result))
969
+ },
970
+ documents: Bn(i).map((y) => ({ path: y, document: he(w, (k) => Le({ principal: n, request: s, signal: k, refresh: !1 }, a, y)) })),
971
+ notices: he({ signal: s.signal, timeoutMs: T, late: me, handOverMs: 0 }, (y) => Ur({ principal: n, request: s, signal: y, refresh: !1 })),
972
+ documentId: d
973
+ };
974
+ }, Ce = async (n, a) => {
975
+ const s = nr(await K(n, a));
976
+ return { authentication: s, headers: rr(s.headers) };
977
+ }, ze = async (n) => {
978
+ let a;
979
+ try {
980
+ a = await Ce(n, er);
981
+ } catch (d) {
982
+ return { status: "answered", response: O(v(tr(d), { operation: "authenticate" }, n.signal, p)) };
983
+ }
984
+ const { authentication: s, headers: i } = a;
985
+ return s.status === "signed-out" ? { status: "answered", response: O({ reason: "unauthorized" }, i) } : s.status === "forbidden" ? { status: "answered", response: O({ reason: "forbidden" }, i) } : { status: "signed-in", principal: s.principal, headers: i };
986
+ }, qr = async (n, a, s) => {
987
+ const i = await ze(a);
988
+ if (i.status === "answered") return i.response;
989
+ const { principal: d, headers: l } = i;
990
+ if (n === "asset") return Fr({ principal: d, request: a, signal: a.signal, refresh: !1 }, s, l);
991
+ const w = or(o, xe(d));
992
+ l.set(Dt, w);
993
+ const y = { principal: d, request: a, signal: a.signal, refresh: !1 }, k = () => O({ reason: "invalid" }, l);
994
+ if (n === "document") {
995
+ const A = C(s, M.path);
996
+ if (A === null || !U(A)) return k();
997
+ const B = a.headers.has(ce);
998
+ return B && !cr(a) ? O({ reason: "forbidden" }, l) : P(200, JSON.stringify(await Le({ ...y, refresh: B }, w, A)), l);
999
+ }
1000
+ if (n === "text") {
1001
+ const A = C(s, M.path);
1002
+ return A === null || !U(A) ? k() : P(200, JSON.stringify(await Br(y, A)), l);
1003
+ }
1004
+ if (n === "edit" || n === "save" || n === "preview" || n === "revisions" || n === "revision")
1005
+ return b === void 0 ? O({ reason: "not-found" }, l) : Kr(b, n, y, w, s, l);
1006
+ if (n === "issue-id") {
1007
+ if (R === void 0) return O({ reason: "not-found" }, l);
1008
+ const A = C(s, M.path);
1009
+ return A === null || !lr(A) ? k() : dr(await $r(R, y, A), l);
1010
+ }
1011
+ if (n === "resolve-id") {
1012
+ if (R === void 0) return O({ reason: "not-found" }, l);
1013
+ const A = C(s, M.id);
1014
+ if (A === null || !wr(A)) return k();
1015
+ const B = await Ie(R, y, A);
1016
+ return dr(B.status === "resolved" ? { status: "ok", path: B.path, source: B.sourceId } : B, l);
1017
+ }
1018
+ const _ = C(s, M.source), D = C(s, M.path);
1019
+ if (_ === null || (n === "children" || n === "ancestors" || n === "reveal") && (D === null || !U(D))) return k();
1020
+ const L = j.get(_);
1021
+ if (L === void 0) return O({ reason: "not-found" }, l);
1022
+ if (n === "tree") return P(200, (await $e(L, d, w, a, a.signal)).json, l);
1023
+ if (n === "refresh") {
1024
+ const A = await Lr(L, d, w, a);
1025
+ return a.signal.aborted || jr(L, ue(L, w)), P(200, A.json, l);
1026
+ }
1027
+ return n === "ancestors" ? L.ancestors === void 0 || D === null ? O({ reason: "not-found" }, l) : P(200, JSON.stringify(await Cr(L, L.ancestors, y, D)), l) : n === "reveal" ? D === null ? k() : P(200, JSON.stringify(await zr(L, y, D)), l) : L.children === void 0 || D === null ? O({ reason: "not-found" }, l) : P(200, JSON.stringify(await Mr(L, L.children, y, D)), l);
1028
+ }, et = async (n) => {
1029
+ const { authentication: a, headers: s } = await Ce(n, Nn);
1030
+ 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)");
1031
+ return a.status === "signed-in";
1032
+ }, Ue = t.embeds.linkCardEndpoint === null ? null : r.createLinkCardHandler({ authorize: et }), rt = async (n, a) => {
1033
+ try {
1034
+ return await n(a);
1035
+ } catch (s) {
1036
+ return O(v(tr(s), { operation: "authenticate" }, a.signal, p));
1037
+ }
1038
+ }, fe = async (n, a, s) => {
1039
+ if (new URL(n.url).pathname.endsWith(".data")) return O({ reason: "not-found" });
1040
+ if (!St(s)) return O({ reason: "not-found" });
1041
+ if (s === "link-card") {
1042
+ if (Ue === null) return O({ reason: "not-found" });
1043
+ const d = ir(n, s);
1044
+ return d !== null ? d : rt(Ue, n);
1045
+ }
1046
+ if (Wn.has(s) && b === void 0) return O({ reason: "not-found" });
1047
+ if (Gn.has(s) && R === void 0) return O({ reason: "not-found" });
1048
+ const i = ir(n, s);
1049
+ if (i !== null) return i;
1050
+ if (s === "refresh" && !cr(n)) return O({ reason: "forbidden" });
1051
+ if ((s === "save" || s === "preview") && !Yn(n)) return O({ reason: "forbidden" });
1052
+ if (s === "issue-id" && !Jn(n)) return O({ reason: "forbidden" });
1053
+ try {
1054
+ return await qr(s, n, a.searchParams);
1055
+ } catch (d) {
1056
+ return O(v(d, { operation: s }, n.signal, p));
1057
+ }
1058
+ }, tt = async (n, a, s) => {
1059
+ if (s !== "asset" || n.method.toUpperCase() !== "GET" || new URL(n.url).pathname.endsWith(".data")) return { kind: "response", response: await fe(n, a, s) };
1060
+ try {
1061
+ const i = await ze(n);
1062
+ return i.status === "answered" ? { kind: "response", response: i.response } : await Xr({ principal: i.principal, request: n, signal: n.signal, refresh: !1 }, a.searchParams, i.headers);
1063
+ } catch (i) {
1064
+ return { kind: "response", response: O(v(i, { operation: "asset" }, n.signal, p)) };
1065
+ }
1066
+ };
1067
+ return Object.freeze({
1068
+ loader: Qr,
1069
+ headers: rs,
1070
+ dataLoader: ({ request: n, url: a, params: s }) => fe(n, a, s["*"]),
1071
+ dataAction: ({ request: n, url: a, params: s }) => fe(n, a, s["*"]),
1072
+ planData: ({ request: n, url: a, params: s }) => tt(n, a, s["*"]),
1073
+ forgetTree: (n) => {
1074
+ if (typeof n != "string") throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${x(n)}`);
1075
+ H.forget(n);
1076
+ }
1077
+ });
1078
+ };
1079
+ export {
1080
+ ye as A,
1081
+ ds as E,
1082
+ us as c
1083
+ };