@aiquants/markdown-explorer 0.24.0 → 0.25.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 (35) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +25 -11
  3. package/dist/{EditSurface-CcWEczj3.js → EditSurface-Blymamic.js} +3 -3
  4. package/dist/{EditSurface-CRc4g0Qa.cjs → EditSurface-Co4Rvfa1.cjs} +1 -1
  5. package/dist/{ExplorerSplit-97SeIAOS.js → ExplorerSplit-BZ0PA3z3.js} +47 -47
  6. package/dist/{ExplorerSplit-ByxxXlgs.cjs → ExplorerSplit-WApgYMPb.cjs} +1 -1
  7. package/dist/{MultiLayout-CnbuAlxd.js → MultiLayout-B5-1N3JD.js} +3 -3
  8. package/dist/{MultiLayout-B_yMVDt_.cjs → MultiLayout-dAW_JCzg.cjs} +1 -1
  9. package/dist/{NativeScrollBar-BXdaM3EA.js → NativeScrollBar-BraWuZvN.js} +1 -1
  10. package/dist/{NativeScrollBar-D4a7fBOS.cjs → NativeScrollBar-ThVMbI0Y.cjs} +1 -1
  11. package/dist/{TreeLayout-C6QDpEBS.cjs → TreeLayout-C60lb9hP.cjs} +1 -1
  12. package/dist/{TreeLayout-BIQBKAkV.js → TreeLayout-CChoxh9W.js} +3 -3
  13. package/dist/core/labels.d.cts +3 -0
  14. package/dist/core/labels.d.ts +3 -0
  15. package/dist/core/textEncoding.d.cts +1 -0
  16. package/dist/core/textEncoding.d.ts +1 -0
  17. package/dist/index-B6FkGD-p.cjs +13 -0
  18. package/dist/{index-CeZDCyEl.js → index-Bd6hgisa.js} +546 -537
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +3 -3
  21. package/dist/location-D3DgoELB.cjs +1 -0
  22. package/dist/{location-gXXmC7CQ.js → location-DIxIjqs7.js} +147 -140
  23. package/dist/{merge-DqjUgcV_.js → merge-CgSp-0Dd.js} +1 -1
  24. package/dist/{merge-QLktbpZY.cjs → merge-DRWmjC24.cjs} +1 -1
  25. package/dist/server.cjs +1 -1
  26. package/dist/server.js +785 -725
  27. package/dist/{useSplitPersistence-Bmpb2prR.cjs → useSplitPersistence-D-T75Hlh.cjs} +1 -1
  28. package/dist/{useSplitPersistence-BPNjvuJi.js → useSplitPersistence-Df63lnQZ.js} +1 -1
  29. package/docs/behavior/layout.md +7 -4
  30. package/docs/behavior/localization.md +6 -3
  31. package/docs/behavior/security.md +7 -3
  32. package/docs/behavior/url-contract.md +3 -3
  33. package/package.json +3 -3
  34. package/dist/index-BwTVYkTR.cjs +0 -13
  35. package/dist/location-CasigkBk.cjs +0 -1
package/dist/server.js CHANGED
@@ -1,22 +1,22 @@
1
- import { b as Ot, c as sr, f as xe, g as ir, h as ar, s as cr, j as ur, k as dr, l as lr, E as Rt, m as ge, r as fr, n as mr, i as re, o as pr, p as wr, q as hr, t as vt, u as yr, v as gr, w as Ce, x as Er, y as br, z as Tr, A as ce, B as ee, e as Ge, C as kr, D as Sr } from "./dataRoute-BEvesOvN.js";
2
- import { F as ms, M as ps, G as ws } from "./dataRoute-BEvesOvN.js";
3
- import { f as $e, w as xr, g as Or, r as Rr, i as vr, h as _r, p as Ar, j as Nr, k as Ir, l as Pr, N as Mr } from "./location-gXXmC7CQ.js";
4
- import { m as ys } from "./location-gXXmC7CQ.js";
5
- import { createHash as Lr, createHmac as $r } from "node:crypto";
6
- import { createLinkCardHandler as jr } from "@aiquants/markdown/server";
7
- import { crossOriginRefusal as _t, NO_CROSS_ORIGIN_NAVIGATION as At } from "@aiquants/request-isolation";
8
- import { data as Ye, redirect as zr } from "react-router";
9
- import { existsSync as Dr, statSync as Cr, realpathSync as Hr, constants as we } from "node:fs";
10
- import { extname as Br, isAbsolute as We, relative as Ke, sep as Ve, join as Ze, resolve as Fr } from "node:path";
11
- import { fileURLToPath as _e } from "node:url";
12
- import { Worker as Ur } from "node:worker_threads";
13
- import { open as Nt, lstat as It, realpath as Xr, readdir as Jr } from "node:fs/promises";
14
- import { Readable as Gr } from "node:stream";
15
- const Qe = Object.freeze({ kind: "anonymous" }), cs = Object.freeze({
16
- authenticate: async () => ({ status: "signed-in", principal: Qe }),
17
- principalKey: () => Qe.kind,
1
+ import { b as _t, c as pr, f as ve, g as wr, h as hr, s as yr, j as gr, k as Er, l as br, E as At, m as Ee, r as Tr, n as kr, i as re, o as xr, p as Sr, q as Or, t as Nt, u as Rr, v as vr, w as Be, x as _r, y as Ar, z as Nr, A as ce, B as ee, e as Ye, C as Ir, D as Pr } from "./dataRoute-BEvesOvN.js";
2
+ import { F as Ts, M as ks, G as xs } from "./dataRoute-BEvesOvN.js";
3
+ import { t as It, f as ze, w as Mr, g as $r, r as Lr, i as jr, h as zr, p as Cr, j as Dr, k as Hr, l as Br, N as Fr } from "./location-DIxIjqs7.js";
4
+ import { m as Os } from "./location-DIxIjqs7.js";
5
+ import { createHash as Ur, createHmac as Xr } from "node:crypto";
6
+ import { createLinkCardHandler as Jr } from "@aiquants/markdown/server";
7
+ import { crossOriginRefusal as Pt, NO_CROSS_ORIGIN_NAVIGATION as Mt } from "@aiquants/request-isolation";
8
+ import { data as Ke, redirect as Gr } from "react-router";
9
+ import { existsSync as Wr, statSync as Yr, realpathSync as Kr, constants as he } from "node:fs";
10
+ import { extname as Vr, isAbsolute as Ve, relative as Ze, sep as Qe, join as qe, resolve as Zr } from "node:path";
11
+ import { fileURLToPath as Ie } from "node:url";
12
+ import { Worker as Qr } from "node:worker_threads";
13
+ import { open as $t, lstat as Lt, realpath as qr, readdir as en } from "node:fs/promises";
14
+ import { Readable as tn } from "node:stream";
15
+ const et = Object.freeze({ kind: "anonymous" }), hs = Object.freeze({
16
+ authenticate: async () => ({ status: "signed-in", principal: et }),
17
+ principalKey: () => et.kind,
18
18
  signedOutPage: (e, t) => new Response(null, { status: 401, headers: t })
19
- }), Yr = "application/octet-stream", Pt = "application/pdf", Wr = /* @__PURE__ */ new Set([
19
+ }), rn = "application/octet-stream", jt = "application/pdf", nn = /* @__PURE__ */ new Set([
20
20
  "image/png",
21
21
  "image/apng",
22
22
  "image/jpeg",
@@ -42,8 +42,8 @@ const Qe = Object.freeze({ kind: "anonymous" }), cs = Object.freeze({
42
42
  "video/webm",
43
43
  "video/ogg",
44
44
  "video/quicktime",
45
- Pt
46
- ]), Mt = "default-src 'none'; media-src 'self'; style-src 'unsafe-inline'", Lt = `${Mt}; sandbox`, Kr = `${Mt}; sandbox allow-same-origin`, qe = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u, Vr = /^[\t\n\r ]+|[\t\n\r ]+$/gu, je = /^[\t ]+|[\t ]+$/gu, Zr = (e) => {
45
+ jt
46
+ ]), zt = "default-src 'none'; media-src 'self'; style-src 'unsafe-inline'", Ct = `${zt}; sandbox`, on = `${zt}; sandbox allow-same-origin`, tt = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u, sn = /^[\t\n\r ]+|[\t\n\r ]+$/gu, Ce = /^[\t ]+|[\t ]+$/gu, an = (e) => {
47
47
  const t = [];
48
48
  let r = "", n = 0;
49
49
  for (; ; ) {
@@ -55,192 +55,252 @@ const Qe = Object.freeze({ kind: "anonymous" }), cs = Object.freeze({
55
55
  n += e[n] === "\\" ? 2 : 1;
56
56
  if (n = Math.min(n + 1, e.length), r += e.slice(a, n), n < e.length) continue;
57
57
  }
58
- if (t.push(r.replace(je, "")), r = "", n >= e.length) return t;
58
+ if (t.push(r.replace(Ce, "")), r = "", n >= e.length) return t;
59
59
  n += 1;
60
60
  }
61
- }, Qr = (e) => {
62
- const t = e.replace(Vr, ""), r = t.indexOf("/");
61
+ }, cn = (e) => {
62
+ const t = e.replace(sn, ""), r = t.indexOf("/");
63
63
  if (r < 0) return null;
64
- const n = t.slice(0, r), a = t.indexOf(";", r + 1), s = t.slice(r + 1, a < 0 ? t.length : a).replace(/[\t\n\r ]+$/u, "");
65
- return qe.test(n) && qe.test(s) ? `${n}/${s}`.toLowerCase() : null;
66
- }, qr = (e) => {
64
+ const n = t.slice(0, r), a = t.indexOf(";", r + 1), o = t.slice(r + 1, a < 0 ? t.length : a).replace(/[\t\n\r ]+$/u, "");
65
+ return tt.test(n) && tt.test(o) ? `${n}/${o}`.toLowerCase() : null;
66
+ }, un = (e) => {
67
67
  let t = null;
68
- for (const r of Zr(e)) {
69
- const n = Qr(r);
68
+ for (const r of an(e)) {
69
+ const n = cn(r);
70
70
  n !== null && n !== "*/*" && (t = n);
71
71
  }
72
72
  return t;
73
- }, en = /['()*]/gu, $t = (e) => encodeURIComponent(e).replace(en, (t) => `%${t.charCodeAt(0).toString(16).toUpperCase()}`), tn = Object.freeze({
73
+ }, dn = /['()*]/gu, Dt = (e) => encodeURIComponent(e).replace(dn, (t) => `%${t.charCodeAt(0).toString(16).toUpperCase()}`), Ht = Object.freeze({
74
74
  "Cache-Control": "private, max-age=60, stale-while-revalidate=600, no-transform",
75
75
  Vary: "Cookie"
76
- }), rn = (e, t) => {
77
- const r = qr(e), n = r !== null && Wr.has(r), a = n && (r.startsWith("audio/") || r.startsWith("video/"));
76
+ }), ln = (e, t) => {
77
+ const r = un(e), n = r !== null && nn.has(r), a = n && (r.startsWith("audio/") || r.startsWith("video/"));
78
78
  return {
79
- contentType: r === null ? Yr : r,
79
+ contentType: r === null ? rn : r,
80
80
  inline: n,
81
81
  headers: {
82
82
  "X-Content-Type-Options": "nosniff",
83
- "Content-Disposition": `${n ? "inline" : "attachment"}; filename*=UTF-8''${$t(t)}`,
84
- ...r === Pt ? {} : { "Content-Security-Policy": a ? Kr : Lt },
83
+ "Content-Disposition": `${n ? "inline" : "attachment"}; filename*=UTF-8''${Dt(t)}`,
84
+ ...r === jt ? {} : { "Content-Security-Policy": a ? on : Ct },
85
85
  "Cross-Origin-Resource-Policy": "same-origin"
86
86
  }
87
87
  };
88
- }, nn = "text/plain; charset=utf-8", on = (e) => ({
89
- contentType: nn,
90
- inline: !0,
91
- headers: {
92
- "X-Content-Type-Options": "nosniff",
93
- "Content-Disposition": `inline; filename*=UTF-8''${$t(e)}`,
94
- "Content-Security-Policy": Lt,
95
- "Cross-Origin-Resource-Policy": "same-origin"
96
- }
97
- }), sn = /^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu, be = Object.freeze({ kind: "whole" }), et = Object.freeze({ kind: "unsatisfiable" }), an = (e, t, r) => {
88
+ }, Re = 64 * 1024, Te = (e) => `text/plain; charset=${e}`, fn = (e) => ({
89
+ "X-Content-Type-Options": "nosniff",
90
+ "Content-Disposition": `inline; filename*=UTF-8''${Dt(e)}`,
91
+ "Content-Security-Policy": Ct,
92
+ "Cross-Origin-Resource-Policy": "same-origin"
93
+ }), mn = (e, t) => `${t === null ? "" : t};${e}`, pn = /^bytes=(?:(\d+)-(\d*)|-(\d+))$/iu, ke = Object.freeze({ kind: "whole" }), rt = Object.freeze({ kind: "unsatisfiable" }), Bt = (e, t, r) => {
98
94
  const n = e.get("Range");
99
- if (n === null) return be;
95
+ if (n === null) return ke;
100
96
  const a = e.get("If-Range");
101
- if (a !== null && a !== r) return be;
102
- const s = sn.exec(n);
103
- if (s === null) return be;
104
- const [, c, m, f] = s;
97
+ if (a !== null && a !== r) return ke;
98
+ const o = pn.exec(n);
99
+ if (o === null) return ke;
100
+ const [, c, l, f] = o;
105
101
  if (f !== void 0) {
106
102
  const y = Number(f);
107
- if (y === 0) return et;
108
- const T = Math.max(0, t - y);
109
- return { kind: "partial", range: { offset: T, length: t - T } };
103
+ if (y === 0) return rt;
104
+ const E = Math.max(0, t - y);
105
+ return { kind: "partial", range: { offset: E, length: t - E } };
110
106
  }
111
- const S = Number(c), h = m === "" ? Number.POSITIVE_INFINITY : Number(m);
112
- return h < S ? be : S >= t ? et : { kind: "partial", range: { offset: S, length: Math.min(h, t - 1) - S + 1 } };
113
- }, tt = "W/", cn = (e) => {
107
+ const k = Number(c), h = l === "" ? Number.POSITIVE_INFINITY : Number(l);
108
+ return h < k ? ke : k >= t ? rt : { kind: "partial", range: { offset: k, length: Math.min(h, t - 1) - k + 1 } };
109
+ }, nt = "W/", wn = (e) => {
114
110
  const t = [];
115
111
  let r = 0, n = !1;
116
112
  for (let a = 0; a < e.length; a += 1)
117
- e[a] === '"' ? n = !n : e[a] === "," && !n && (t.push(e.slice(r, a).replace(je, "")), r = a + 1);
118
- return t.push(e.slice(r).replace(je, "")), t;
119
- }, rt = (e) => e.startsWith(tt) ? e.slice(tt.length) : e, un = (e, t) => {
113
+ e[a] === '"' ? n = !n : e[a] === "," && !n && (t.push(e.slice(r, a).replace(Ce, "")), r = a + 1);
114
+ return t.push(e.slice(r).replace(Ce, "")), t;
115
+ }, ot = (e) => e.startsWith(nt) ? e.slice(nt.length) : e, Ft = (e, t) => {
120
116
  if (e === null) return !1;
121
- const r = cn(e);
117
+ const r = wn(e);
122
118
  if (r.length === 1 && r[0] === "*") return !0;
123
- const n = rt(t);
124
- return r.some((a) => rt(a) === n);
125
- }, dn = (e, t) => {
119
+ const n = ot(t);
120
+ return r.some((a) => ot(a) === n);
121
+ }, hn = (e, t) => {
126
122
  let r = t;
127
123
  return e.pipeThrough(
128
124
  new TransformStream({
129
125
  transform: (n, a) => {
130
- const s = n.byteLength > r ? n.subarray(0, r) : n;
131
- r -= s.byteLength, a.enqueue(s), r === 0 && a.terminate();
126
+ const o = n.byteLength > r ? n.subarray(0, r) : n;
127
+ r -= o.byteLength, a.enqueue(o), r === 0 && a.terminate();
132
128
  },
133
129
  flush: (n) => {
134
130
  r > 0 && n.error(new RangeError("[markdown-explorer] the asset ended before its declared length"));
135
131
  }
136
132
  })
137
133
  );
138
- }, Ae = async (e, t, r, n, a) => {
134
+ }, pe = async (e, t, r, n, a) => {
139
135
  if (n !== null && r.set("Content-Length", String(n)), e.method.toUpperCase() === "HEAD") return new Response(null, { status: t, headers: r });
140
- const s = await a();
141
- return new Response(n === null ? s : dn(s, n), { status: t, headers: r });
142
- }, ln = (e, t) => {
136
+ const o = await a();
137
+ return new Response(n === null ? o : hn(o, n), { status: t, headers: r });
138
+ }, Ut = (e, t) => {
143
139
  const r = new Headers(e);
144
140
  for (const [n, a] of Object.entries({ "Accept-Ranges": "bytes", "Content-Range": `bytes */${t}`, "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff" })) r.set(n, a);
145
141
  return new Response(null, { status: 416, headers: r });
146
- }, fn = async (e, t, r, n) => {
147
- const a = `"${t.version}"`, s = n === "text" ? on(t.name) : rn(t.contentType, t.name), c = new Headers(r);
148
- for (const [S, h] of Object.entries({ ...s.headers, ...tn, ETag: a })) c.set(S, h);
149
- if (un(e.headers.get("If-None-Match"), a)) return new Response(null, { status: 304, headers: c });
150
- if (c.set("Content-Type", s.contentType), t.size === null) return Ae(e, 200, c, null, () => t.open(null));
142
+ }, yn = async (e, t, r) => {
143
+ const n = `"${t.version}"`, a = ln(t.contentType, t.name), o = new Headers(r);
144
+ for (const [f, k] of Object.entries({ ...a.headers, ...Ht, ETag: n })) o.set(f, k);
145
+ if (Ft(e.headers.get("If-None-Match"), n)) return new Response(null, { status: 304, headers: o });
146
+ if (o.set("Content-Type", a.contentType), t.size === null) return pe(e, 200, o, null, () => t.open(null));
147
+ if (t.size === 0)
148
+ return o.set("Content-Length", "0"), new Response(null, { status: 200, headers: o });
149
+ o.set("Accept-Ranges", "bytes");
150
+ const c = Bt(e.headers, t.size, n);
151
+ if (c.kind === "unsatisfiable") return Ut(r, t.size);
152
+ if (c.kind === "whole") return pe(e, 200, o, t.size, () => t.open(null));
153
+ const { range: l } = c;
154
+ return o.set("Content-Range", `bytes ${l.offset}-${l.offset + l.length - 1}/${t.size}`), pe(e, 206, o, l.length, () => t.open(l));
155
+ }, gn = (e, t) => {
156
+ const r = new Uint8Array(t);
157
+ let n = 0;
158
+ for (const a of e) {
159
+ if (n === t) break;
160
+ const o = a.subarray(0, t - n);
161
+ r.set(o, n), n += o.byteLength;
162
+ }
163
+ return r;
164
+ }, En = (e, t, r) => new ReadableStream(
165
+ {
166
+ start: (n) => {
167
+ for (const a of e) n.enqueue(a);
168
+ t && n.close();
169
+ },
170
+ pull: async (n) => {
171
+ const { done: a, value: o } = await r.read();
172
+ a ? n.close() : n.enqueue(o);
173
+ },
174
+ cancel: (n) => r.cancel(n)
175
+ },
176
+ { highWaterMark: 0 }
177
+ ), Xt = async (e, t, r) => {
178
+ const n = e.getReader(), a = t === null ? Re : Math.min(t, Re), o = t === null ? a + 1 : a, c = [];
179
+ let l = 0, f = !1;
180
+ try {
181
+ for (; l < o; ) {
182
+ const { done: y, value: E } = await n.read();
183
+ if (y) {
184
+ f = !0;
185
+ break;
186
+ }
187
+ c.push(E), l += E.byteLength;
188
+ }
189
+ if (f && t !== null && l < a) throw new RangeError("[markdown-explorer] the asset ended before its declared length");
190
+ const k = t === null ? f : t <= Re;
191
+ return { encoding: It(gn(c, Math.min(l, a)), k, r), body: En(c, f, n) };
192
+ } catch (k) {
193
+ throw n.cancel(k).catch(() => {
194
+ }), k;
195
+ }
196
+ }, st = async (e, t) => {
197
+ const r = await Xt(await e.open(e.size === null ? null : { offset: 0, length: Math.min(e.size, Re) }), e.size, t);
198
+ return r.body.cancel().catch(() => {
199
+ }), r.encoding;
200
+ }, bn = async (e, t, r, n) => {
201
+ const a = `"${mn(t.version, n)}"`, o = new Headers(r);
202
+ for (const [l, f] of Object.entries({ ...fn(t.name), ...Ht, ETag: a })) o.set(l, f);
203
+ if (Ft(e.headers.get("If-None-Match"), a)) return new Response(null, { status: 304, headers: o });
151
204
  if (t.size === 0)
152
- return c.set("Content-Length", "0"), new Response(null, { status: 200, headers: c });
153
- c.set("Accept-Ranges", "bytes");
154
- const m = an(e.headers, t.size, a);
155
- if (m.kind === "unsatisfiable") return ln(r, t.size);
156
- if (m.kind === "whole") return Ae(e, 200, c, t.size, () => t.open(null));
157
- const { range: f } = m;
158
- return c.set("Content-Range", `bytes ${f.offset}-${f.offset + f.length - 1}/${t.size}`), Ae(e, 206, c, f.length, () => t.open(f));
159
- }, mn = Object.freeze({
205
+ return o.set("Content-Type", Te(It(new Uint8Array(0), !0, n))), o.set("Content-Length", "0"), new Response(null, { status: 200, headers: o });
206
+ if (t.size !== null) {
207
+ o.set("Accept-Ranges", "bytes");
208
+ const l = Bt(e.headers, t.size, a);
209
+ if (l.kind === "unsatisfiable") return Ut(r, t.size);
210
+ if (l.kind === "partial") {
211
+ const { range: f } = l;
212
+ return o.set("Content-Type", Te(await st(t, n))), o.set("Content-Range", `bytes ${f.offset}-${f.offset + f.length - 1}/${t.size}`), pe(e, 206, o, f.length, () => t.open(f));
213
+ }
214
+ }
215
+ if (e.method.toUpperCase() === "HEAD")
216
+ return o.set("Content-Type", Te(await st(t, n))), pe(e, 200, o, t.size, () => t.open(null));
217
+ const c = await Xt(await t.open(null), t.size, n);
218
+ return o.set("Content-Type", Te(c.encoding)), pe(e, 200, o, t.size, async () => c.body);
219
+ }, Tn = Object.freeze({
160
220
  "Cache-Control": "private, no-store",
161
221
  "Referrer-Policy": "no-referrer"
162
- }), pn = (e, t) => {
222
+ }), kn = (e, t) => {
163
223
  const r = new Headers(t);
164
- for (const [n, a] of Object.entries(mn)) r.set(n, a);
224
+ for (const [n, a] of Object.entries(Tn)) r.set(n, a);
165
225
  return r.set("Location", e), new Response(null, { status: 302, headers: r });
166
- }, Ne = (e, t) => {
226
+ }, Pe = (e, t) => {
167
227
  const r = new AbortController(), n = t(AbortSignal.any([e.signal, r.signal]));
168
228
  return new Promise((a) => {
169
- let s;
229
+ let o;
170
230
  const c = setTimeout(() => {
171
- a(e.late), s = setTimeout(() => r.abort(), e.handOverMs);
172
- }, e.timeoutMs), m = () => {
173
- clearTimeout(c), clearTimeout(s);
231
+ a(e.late), o = setTimeout(() => r.abort(), e.handOverMs);
232
+ }, e.timeoutMs), l = () => {
233
+ clearTimeout(c), clearTimeout(o);
174
234
  };
175
235
  n.then(
176
236
  (f) => {
177
- m(), a(f);
237
+ l(), a(f);
178
238
  },
179
239
  () => {
180
- m(), a(e.late);
240
+ l(), a(e.late);
181
241
  }
182
242
  );
183
243
  });
184
- }, wn = Object.freeze({
244
+ }, xn = Object.freeze({
185
245
  error: (e, t) => {
186
246
  console.error(e, t);
187
247
  }
188
- }), jt = /* @__PURE__ */ Symbol.for("@aiquants/markdown-explorer:ExplorerError");
189
- class Oe extends Error {
248
+ }), Jt = /* @__PURE__ */ Symbol.for("@aiquants/markdown-explorer:ExplorerError");
249
+ class _e extends Error {
190
250
  reason;
191
251
  code;
192
252
  constructor(t, r = {}) {
193
- if (!Ot(t)) throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);
194
- if (r.code !== void 0 && !sr(r.code)) throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${JSON.stringify(r.code)}`);
195
- 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, jt, { value: !0 });
253
+ if (!_t(t)) throw new RangeError(`[markdown-explorer] ExplorerError needs a failure reason; got ${JSON.stringify(t)}`);
254
+ if (r.code !== void 0 && !pr(r.code)) throw new RangeError(`[markdown-explorer] an ExplorerError code must be 1 to 64 lowercase letters, digits or hyphens; got ${JSON.stringify(r.code)}`);
255
+ 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, Jt, { value: !0 });
196
256
  }
197
257
  }
198
- const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn = (e) => typeof e == "object" && e !== null && e.name === "AbortError", He = (e, t, r) => {
258
+ const Sn = (e) => e instanceof Error && Object.hasOwn(e, Jt) && _t(e.reason), On = (e) => typeof e == "object" && e !== null && e.name === "AbortError", Fe = (e, t, r) => {
199
259
  try {
200
260
  e.error(t, r);
201
261
  } catch (n) {
202
262
  console.error("[markdown-explorer] the logger threw while reporting a failure", { operation: r.operation, error: n });
203
263
  }
204
- }, ie = (e, t) => He(e, `[markdown-explorer] ${t.operation} failed`, t), gn = (e, t) => He(e, `[markdown-explorer] ${t.operation} left out an entry`, t), Ie = (e, t) => He(e, `[markdown-explorer] ${t.operation} refused a path the deny rules match`, { ...t, error: new RangeError("[markdown-explorer] the path matches a deny rule") }), nt = (e, t) => {
264
+ }, ae = (e, t) => Fe(e, `[markdown-explorer] ${t.operation} failed`, t), Rn = (e, t) => Fe(e, `[markdown-explorer] ${t.operation} left out an entry`, t), Me = (e, t) => Fe(e, `[markdown-explorer] ${t.operation} refused a path the deny rules match`, { ...t, error: new RangeError("[markdown-explorer] the path matches a deny rule") }), at = (e, t) => {
205
265
  e === null || typeof e != "object" && typeof e != "function" || Promise.resolve(e).then(void 0, t);
206
- }, Y = (e, t, r, n) => hn(e) ? xe(e.reason, e.code) : (yn(e) || r.aborted || ie(n, { ...t, error: e }), { reason: "failed" }), ot = 2 * 1024 * 1024, st = 256 * 1024 * 1024, En = async (e, t) => {
266
+ }, W = (e, t, r, n) => Sn(e) ? ve(e.reason, e.code) : (On(e) || r.aborted || ae(n, { ...t, error: e }), { reason: "failed" }), it = 2 * 1024 * 1024, ct = 256 * 1024 * 1024, vn = async (e, t) => {
207
267
  const r = e.getReader(), n = new Uint8Array(t);
208
268
  let a = 0;
209
269
  for (; a < t; ) {
210
- const { done: s, value: c } = await r.read();
211
- if (s) return n.subarray(0, a);
212
- const m = c.subarray(0, t - a);
213
- n.set(m, a), a += m.byteLength;
270
+ const { done: o, value: c } = await r.read();
271
+ if (o) return n.subarray(0, a);
272
+ const l = c.subarray(0, t - a);
273
+ n.set(l, a), a += l.byteLength;
214
274
  }
215
275
  return r.cancel().catch(() => {
216
276
  }), n;
217
- }, bn = async (e, t, r) => {
277
+ }, _n = async (e, t, r) => {
218
278
  if (e.size === 0) return { text: "", truncated: !1 };
219
- const n = e.size !== null && e.size > t, a = e.size === null ? t + 1 : Math.min(e.size, t), s = await En(await e.open(n ? { offset: 0, length: t } : null), a);
220
- if (e.size !== null && s.byteLength < a) throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");
221
- const c = n || s.byteLength > t, m = c ? s.subarray(0, t) : s, f = $e(m, !c, r);
279
+ const n = e.size !== null && e.size > t, a = e.size === null ? t + 1 : Math.min(e.size, t), o = await vn(await e.open(n ? { offset: 0, length: t } : null), a);
280
+ if (e.size !== null && o.byteLength < a) throw new RangeError("[markdown-explorer] the file ended before the length its asset port reported");
281
+ const c = n || o.byteLength > t, l = c ? o.subarray(0, t) : o, f = ze(l, !c, r);
222
282
  return f.includes("\0") ? null : { text: f, truncated: c };
223
- }, it = (e, t) => {
283
+ }, ut = (e, t) => {
224
284
  if (!Number.isSafeInteger(t) || t <= 0) throw new RangeError(`[markdown-explorer] a cache ${e} must be a positive integer; got ${String(t)}`);
225
- }, zt = (e, t) => {
226
- it("capacity", e), t !== void 0 && it("weight budget", t.max);
285
+ }, Gt = (e, t) => {
286
+ ut("capacity", e), t !== void 0 && ut("weight budget", t.max);
227
287
  const r = /* @__PURE__ */ new Map();
228
288
  let n = 0;
229
- const a = (s) => {
230
- const c = r.get(s);
231
- c !== void 0 && (r.delete(s), n -= c.weight);
289
+ const a = (o) => {
290
+ const c = r.get(o);
291
+ c !== void 0 && (r.delete(o), n -= c.weight);
232
292
  };
233
293
  return {
234
- get: (s) => {
235
- const c = r.get(s);
294
+ get: (o) => {
295
+ const c = r.get(o);
236
296
  if (c !== void 0)
237
- return r.delete(s), r.set(s, c), c.value;
297
+ return r.delete(o), r.set(o, c), c.value;
238
298
  },
239
- set: (s, c) => {
240
- a(s);
241
- const m = t === void 0 ? 0 : t.of(s, c);
242
- if (!(t !== void 0 && m > t.max)) {
243
- r.set(s, { value: c, weight: m }), n += m;
299
+ set: (o, c) => {
300
+ a(o);
301
+ const l = t === void 0 ? 0 : t.of(o, c);
302
+ if (!(t !== void 0 && l > t.max)) {
303
+ r.set(o, { value: c, weight: l }), n += l;
244
304
  for (const f of r.keys()) {
245
305
  if (r.size <= e && (t === void 0 || n <= t.max)) break;
246
306
  a(f);
@@ -251,53 +311,53 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
251
311
  size: () => r.size,
252
312
  weight: () => n
253
313
  };
254
- }, Dt = (e) => Math.max(1, e - 1), Tn = 2147483647, at = Object.freeze({ status: "aborted" }), le = (e, t, r) => {
314
+ }, Wt = (e) => Math.max(1, e - 1), An = 2147483647, dt = Object.freeze({ status: "aborted" }), le = (e, t, r) => {
255
315
  const n = (e.get(t) ?? 0) + r;
256
316
  n === 0 ? e.delete(t) : e.set(t, n);
257
317
  }, me = (e, t, r) => {
258
318
  if (!Number.isSafeInteger(t) || t <= 0 || t > r) throw new RangeError(`[markdown-explorer] a worker pool's ${e} must be an integer in 1..${String(r)}; got ${String(t)}`);
259
- }, kn = (e) => e !== null && typeof e == "object" && e.ready === !0 && !("id" in e), Sn = (e, t) => e !== null && typeof e == "object" && e.id === t && "output" in e, xn = ({ url: e, size: t, deadlineMs: r, jobsPerScope: n, maxQueuedJobs: a, heapLimits: s }) => {
260
- me("size", t, Number.MAX_SAFE_INTEGER), me("deadline", r, Tn), me("jobsPerScope", n, Number.MAX_SAFE_INTEGER), me("maxQueuedJobs", a, Number.MAX_SAFE_INTEGER), me("maxOldGenerationSizeMb", s.maxOldGenerationSizeMb, Number.MAX_SAFE_INTEGER), me("maxYoungGenerationSizeMb", s.maxYoungGenerationSizeMb, Number.MAX_SAFE_INTEGER);
261
- const c = Object.freeze({ maxOldGenerationSizeMb: s.maxOldGenerationSizeMb, maxYoungGenerationSizeMb: s.maxYoungGenerationSizeMb }), m = /* @__PURE__ */ new Set(), f = [], S = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map(), y = Dt(t);
262
- let T = 0;
319
+ }, Nn = (e) => e !== null && typeof e == "object" && e.ready === !0 && !("id" in e), In = (e, t) => e !== null && typeof e == "object" && e.id === t && "output" in e, Pn = ({ url: e, size: t, deadlineMs: r, jobsPerScope: n, maxQueuedJobs: a, heapLimits: o }) => {
320
+ me("size", t, Number.MAX_SAFE_INTEGER), me("deadline", r, An), me("jobsPerScope", n, Number.MAX_SAFE_INTEGER), me("maxQueuedJobs", a, Number.MAX_SAFE_INTEGER), me("maxOldGenerationSizeMb", o.maxOldGenerationSizeMb, Number.MAX_SAFE_INTEGER), me("maxYoungGenerationSizeMb", o.maxYoungGenerationSizeMb, Number.MAX_SAFE_INTEGER);
321
+ const c = Object.freeze({ maxOldGenerationSizeMb: o.maxOldGenerationSizeMb, maxYoungGenerationSizeMb: o.maxYoungGenerationSizeMb }), l = /* @__PURE__ */ new Set(), f = [], k = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map(), y = Wt(t);
322
+ let E = 0;
263
323
  const v = (w, g) => {
264
324
  const { job: M } = w;
265
- w.timer !== null && clearTimeout(w.timer), w.timer = null, w.job = null, w.sent = !1, M !== null && (le(S, M.scope, -1), le(h, M.scope, -1), M.settle(g));
325
+ w.timer !== null && clearTimeout(w.timer), w.timer = null, w.job = null, w.sent = !1, M !== null && (le(k, M.scope, -1), le(h, M.scope, -1), M.settle(g));
266
326
  }, z = (w) => {
267
327
  const [g] = f.splice(w, 1);
268
328
  g?.detach();
269
- }, x = () => {
329
+ }, S = () => {
270
330
  let w = -1, g = y, M = Number.POSITIVE_INFINITY;
271
- for (const [U, E] of f.entries()) {
272
- const _ = S.get(E.scope) ?? 0, N = h.get(E.scope) ?? 0;
331
+ for (const [U, b] of f.entries()) {
332
+ const _ = k.get(b.scope) ?? 0, N = h.get(b.scope) ?? 0;
273
333
  (_ < g || _ === g && w >= 0 && N < M) && (w = U, g = _, M = N);
274
334
  }
275
335
  return w;
276
336
  }, O = (w, g) => {
277
- m.has(w) && (m.delete(w), v(w, g), w.worker.terminate().catch(() => {
337
+ l.has(w) && (l.delete(w), v(w, g), w.worker.terminate().catch(() => {
278
338
  }), F());
279
- }, D = (w) => {
339
+ }, C = (w) => {
280
340
  w.timer = setTimeout(() => {
281
341
  O(w, { status: "timeout" });
282
342
  }, r);
283
343
  }, R = (w, g) => w.sent ? { status: "crashed", error: g } : { status: "unavailable", error: g }, I = (w, g) => {
284
- w.sent = !0, D(w);
344
+ w.sent = !0, C(w);
285
345
  try {
286
346
  w.worker.postMessage({ id: g.id, input: g.input });
287
347
  } catch (M) {
288
348
  v(w, { status: "crashed", error: M }), w.worker.unref();
289
349
  }
290
- }, C = () => {
291
- const w = { worker: new Ur(e, { resourceLimits: c }), job: null, sent: !1, timer: null, ready: !1 };
350
+ }, D = () => {
351
+ const w = { worker: new Qr(e, { resourceLimits: c }), job: null, sent: !1, timer: null, ready: !1 };
292
352
  return w.worker.unref(), w.timer = setTimeout(() => {
293
353
  O(w, { status: "unavailable", error: new Error(`[markdown-explorer] a worker did not start within ${String(r)} ms`) });
294
354
  }, r), w.worker.on("message", (g) => {
295
- if (!w.ready && kn(g)) {
355
+ if (!w.ready && Nn(g)) {
296
356
  w.ready = !0, w.timer !== null && clearTimeout(w.timer), w.timer = null, w.job === null ? w.worker.unref() : I(w, w.job), w.job === null && F();
297
357
  return;
298
358
  }
299
359
  const { job: M } = w;
300
- if (M === null || !Sn(g, M.id)) {
360
+ if (M === null || !In(g, M.id)) {
301
361
  O(w, R(w, new Error("[markdown-explorer] a worker sent a message that answers no job")));
302
362
  return;
303
363
  }
@@ -308,26 +368,26 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
308
368
  O(w, R(w, g));
309
369
  }), w.worker.on("exit", (g) => {
310
370
  O(w, R(w, new Error(`[markdown-explorer] a worker exited with code ${String(g)}`)));
311
- }), m.add(w), w;
371
+ }), l.add(w), w;
312
372
  }, F = () => {
313
373
  for (; ; ) {
314
- const w = x(), g = f[w];
374
+ const w = S(), g = f[w];
315
375
  if (g === void 0) return;
316
376
  let M;
317
- for (const E of m)
318
- if (E.job === null) {
319
- M = E;
377
+ for (const b of l)
378
+ if (b.job === null) {
379
+ M = b;
320
380
  break;
321
381
  }
322
- if (M === void 0 && m.size < t)
382
+ if (M === void 0 && l.size < t)
323
383
  try {
324
- M = C();
325
- } catch (E) {
326
- z(w), le(h, g.scope, -1), g.settle({ status: "unavailable", error: E });
384
+ M = D();
385
+ } catch (b) {
386
+ z(w), le(h, g.scope, -1), g.settle({ status: "unavailable", error: b });
327
387
  continue;
328
388
  }
329
389
  if (M === void 0) return;
330
- z(w), le(S, g.scope, 1);
390
+ z(w), le(k, g.scope, 1);
331
391
  const U = M;
332
392
  U.job = g, U.worker.ref(), U.ready && I(U, g);
333
393
  }
@@ -335,145 +395,145 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
335
395
  return {
336
396
  run: (w, { scope: g, signal: M }) => new Promise((U) => {
337
397
  if (M.aborted) {
338
- U(at);
398
+ U(dt);
339
399
  return;
340
400
  }
341
401
  if ((h.get(g) ?? 0) >= n) {
342
402
  U({ status: "refused", limit: "scope" });
343
403
  return;
344
404
  }
345
- T += 1;
346
- const E = { id: T, input: w, scope: g, settle: U, detach: () => {
405
+ E += 1;
406
+ const b = { id: E, input: w, scope: g, settle: U, detach: () => {
347
407
  } };
348
- f.push(E), le(h, g, 1), F();
349
- const _ = f.indexOf(E);
408
+ f.push(b), le(h, g, 1), F();
409
+ const _ = f.indexOf(b);
350
410
  if (_ < 0) return;
351
411
  if (f.length > a) {
352
412
  z(_), le(h, g, -1), U({ status: "refused", limit: "queue" });
353
413
  return;
354
414
  }
355
415
  const N = () => {
356
- const $ = f.indexOf(E);
357
- $ < 0 || (z($), le(h, g, -1), U(at));
416
+ const j = f.indexOf(b);
417
+ j < 0 || (z(j), le(h, g, -1), U(dt));
358
418
  };
359
- M.addEventListener("abort", N, { once: !0 }), E.detach = () => {
419
+ M.addEventListener("abort", N, { once: !0 }), b.detach = () => {
360
420
  M.removeEventListener("abort", N);
361
421
  };
362
422
  }),
363
- workers: () => m.size
423
+ workers: () => l.size
364
424
  };
365
- }, Be = 1024 * 1024, On = 3e4, Rn = 4 * Be, vn = 64 * Be, _n = 3, An = 2, Nn = (e, t) => e + Dt(t) + _n, In = 4, Pn = 32, Mn = 512, Ln = 64, $n = 4096, jn = 32, ct = 4096, zn = 4, Ct = ({ workerHeapMb: e, maxHtmlBytes: t }) => Math.floor(((e - Ln) * Be - t * jn) / $n), Dn = ({ maxHtmlBytes: e }) => e, Cn = ({ maxHtmlBytes: e }) => zn * e, Hn = 1024, Bn = 2147483647, Fn = 64, Un = 2 ** 29, Xn = 1024 * 1024, Jn = 64, ut = Object.freeze({ status: "rejected", reason: "too-large", cause: null }), Pe = Object.freeze({ status: "rejected", reason: "failed", cause: null }), fe = (e, t, r, n) => {
425
+ }, Ue = 1024 * 1024, Mn = 3e4, $n = 4 * Ue, Ln = 64 * Ue, jn = 3, zn = 2, Cn = (e, t) => e + Wt(t) + jn, Dn = 4, Hn = 32, Bn = 512, Fn = 64, Un = 4096, Xn = 32, lt = 4096, Jn = 4, Yt = ({ workerHeapMb: e, maxHtmlBytes: t }) => Math.floor(((e - Fn) * Ue - t * Xn) / Un), Gn = ({ maxHtmlBytes: e }) => e, Wn = ({ maxHtmlBytes: e }) => Jn * e, Yn = 1024, Kn = 2147483647, Vn = 64, Zn = 2 ** 29, Qn = 1024 * 1024, qn = 64, ft = Object.freeze({ status: "rejected", reason: "too-large", cause: null }), $e = Object.freeze({ status: "rejected", reason: "failed", cause: null }), fe = (e, t, r, n) => {
366
426
  if (t === void 0) return r;
367
427
  if (typeof t != "number") throw new TypeError(`[markdown-explorer] sanitizer.${e} must be a number; got ${typeof t}`);
368
428
  if (!Number.isSafeInteger(t) || t <= 0 || t > n) throw new RangeError(`[markdown-explorer] sanitizer.${e} must be an integer in 1..${String(n)}; got ${String(t)}`);
369
429
  return t;
370
- }, Gn = (e, t) => {
430
+ }, eo = (e, t) => {
371
431
  if (e !== void 0 && (e === null || typeof e != "object")) throw new TypeError("[markdown-explorer] sanitizer must be an object of { workers, deadlineMs, maxHtmlBytes, cacheBytes, workerHeapMb, jobsPerScope, maxQueuedJobs }");
372
- const { workers: r, deadlineMs: n, maxHtmlBytes: a, cacheBytes: s, workerHeapMb: c, jobsPerScope: m, maxQueuedJobs: f } = e ?? {}, S = fe("workers", r, An, Fn), h = fe("jobsPerScope", m, Nn(t, S), Number.MAX_SAFE_INTEGER), y = Object.freeze({
373
- workers: S,
374
- deadlineMs: fe("deadlineMs", n, On, Bn),
375
- maxHtmlBytes: fe("maxHtmlBytes", a, Rn, Un),
376
- cacheBytes: fe("cacheBytes", s, vn, Number.MAX_SAFE_INTEGER),
377
- workerHeapMb: fe("workerHeapMb", c, Mn, Xn),
432
+ const { workers: r, deadlineMs: n, maxHtmlBytes: a, cacheBytes: o, workerHeapMb: c, jobsPerScope: l, maxQueuedJobs: f } = e ?? {}, k = fe("workers", r, zn, Vn), h = fe("jobsPerScope", l, Cn(t, k), Number.MAX_SAFE_INTEGER), y = Object.freeze({
433
+ workers: k,
434
+ deadlineMs: fe("deadlineMs", n, Mn, Kn),
435
+ maxHtmlBytes: fe("maxHtmlBytes", a, $n, Zn),
436
+ cacheBytes: fe("cacheBytes", o, Ln, Number.MAX_SAFE_INTEGER),
437
+ workerHeapMb: fe("workerHeapMb", c, Bn, Qn),
378
438
  jobsPerScope: h,
379
- maxQueuedJobs: fe("maxQueuedJobs", f, In * h, Number.MAX_SAFE_INTEGER)
439
+ maxQueuedJobs: fe("maxQueuedJobs", f, Dn * h, Number.MAX_SAFE_INTEGER)
380
440
  });
381
441
  if (y.jobsPerScope < t)
382
442
  throw new RangeError(`[markdown-explorer] sanitizer.jobsPerScope must be at least multiView.maxPanels (${String(t)}), because a page sends the document of every panel to the sanitizer at once for one reader; got ${String(y.jobsPerScope)}`);
383
443
  if (y.maxQueuedJobs < t)
384
444
  throw new RangeError(`[markdown-explorer] sanitizer.maxQueuedJobs must be at least multiView.maxPanels (${String(t)}), because a reader whose page finds every worker busy waits with the document of every panel; got ${String(y.maxQueuedJobs)}`);
385
- if (Ct(y) < ct)
445
+ if (Yt(y) < lt)
386
446
  throw new RangeError(
387
- `[markdown-explorer] sanitizer.workerHeapMb (${String(y.workerHeapMb)} MiB) must leave room for ${String(ct)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(y.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`
447
+ `[markdown-explorer] sanitizer.workerHeapMb (${String(y.workerHeapMb)} MiB) must leave room for ${String(lt)} parsed nodes beside HTML of sanitizer.maxHtmlBytes (${String(y.maxHtmlBytes)} bytes); raise workerHeapMb or lower maxHtmlBytes`
388
448
  );
389
449
  return y;
390
- }, Yn = () => {
391
- const e = import.meta.url, t = new URL(`./sanitizeWorker${Br(_e(e))}`, e);
392
- if (!Dr(_e(t))) throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${_e(t)}`);
450
+ }, to = () => {
451
+ const e = import.meta.url, t = new URL(`./sanitizeWorker${Vr(Ie(e))}`, e);
452
+ if (!Wr(Ie(t))) throw new Error(`[markdown-explorer] the HTML sanitizer worker is missing: ${Ie(t)}`);
393
453
  return t;
394
- }, dt = /* @__PURE__ */ new Map(), Wn = (e, t) => {
454
+ }, mt = /* @__PURE__ */ new Map(), ro = (e, t) => {
395
455
  const r = [e.href, t.workers, t.deadlineMs, t.workerHeapMb, t.jobsPerScope, t.maxQueuedJobs].map(String).join("\0");
396
- let n = dt.get(r);
397
- return n === void 0 && (n = xn({
456
+ let n = mt.get(r);
457
+ return n === void 0 && (n = Pn({
398
458
  url: e,
399
459
  size: t.workers,
400
460
  deadlineMs: t.deadlineMs,
401
461
  jobsPerScope: t.jobsPerScope,
402
462
  maxQueuedJobs: t.maxQueuedJobs,
403
- heapLimits: { maxOldGenerationSizeMb: t.workerHeapMb, maxYoungGenerationSizeMb: Pn }
404
- }), dt.set(r, n)), n;
405
- }, Kn = (e) => {
463
+ heapLimits: { maxOldGenerationSizeMb: t.workerHeapMb, maxYoungGenerationSizeMb: Hn }
464
+ }), mt.set(r, n)), n;
465
+ }, no = (e) => {
406
466
  if (e === null || typeof e != "object") return !1;
407
467
  const { status: t, html: r, message: n } = e;
408
468
  return t === "sanitized" && typeof r == "string" || t === "too-large" || t === "error" && typeof n == "string";
409
- }, Vn = (e) => e instanceof Error && e.code === "ERR_WORKER_OUT_OF_MEMORY", Zn = ({ iframeHosts: e, dataPath: t, options: r, pool: n }) => {
410
- const a = Object.freeze([...e]), s = Ct(r), c = Dn(r), m = Cn(r), f = zt(Hn, {
469
+ }, oo = (e) => e instanceof Error && e.code === "ERR_WORKER_OUT_OF_MEMORY", so = ({ iframeHosts: e, dataPath: t, options: r, pool: n }) => {
470
+ const a = Object.freeze([...e]), o = Yt(r), c = Gn(r), l = Wn(r), f = Gt(Yn, {
411
471
  max: r.cacheBytes,
412
- of: (x, O) => 2 * x.length + (O.status === "sanitized" ? 2 * O.html.length : Jn)
413
- }), S = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map(), y = (x) => {
414
- S.get(x.key) === x && S.delete(x.key);
415
- const O = h.get(x.hash);
416
- O?.delete(x), O?.size === 0 && h.delete(x.hash);
417
- }, T = async (x, O, D) => {
418
- const R = await n.run({ html: x, iframeHosts: a, dataPath: t, maxNodes: s, maxAttributeChars: c, maxSanitizedChars: m }, { scope: O, signal: D });
472
+ of: (S, O) => 2 * S.length + (O.status === "sanitized" ? 2 * O.html.length : qn)
473
+ }), k = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map(), y = (S) => {
474
+ k.get(S.key) === S && k.delete(S.key);
475
+ const O = h.get(S.hash);
476
+ O?.delete(S), O?.size === 0 && h.delete(S.hash);
477
+ }, E = async (S, O, C) => {
478
+ const R = await n.run({ html: S, iframeHosts: a, dataPath: t, maxNodes: o, maxAttributeChars: c, maxSanitizedChars: l }, { scope: O, signal: C });
419
479
  if (R.status === "refused") {
420
- const C = R.limit === "scope" ? `its reader already has ${String(r.jobsPerScope)} documents being sanitized or waiting` : `${String(r.maxQueuedJobs)} documents are already waiting`;
421
- return { outcome: { status: "rejected", reason: "failed", cause: new Error(`[markdown-explorer] the HTML sanitizer refused a document: ${C}`) }, lasting: !1 };
480
+ const D = R.limit === "scope" ? `its reader already has ${String(r.jobsPerScope)} documents being sanitized or waiting` : `${String(r.maxQueuedJobs)} documents are already waiting`;
481
+ return { outcome: { status: "rejected", reason: "failed", cause: new Error(`[markdown-explorer] the HTML sanitizer refused a document: ${D}`) }, lasting: !1 };
422
482
  }
423
- if (R.status === "aborted") return { outcome: Pe, lasting: !1 };
483
+ if (R.status === "aborted") return { outcome: $e, lasting: !1 };
424
484
  if (R.status === "timeout") return { outcome: { status: "rejected", reason: "too-large", cause: new Error(`[markdown-explorer] the HTML sanitizer did not finish within ${String(r.deadlineMs)} ms`) }, lasting: !0 };
425
485
  if (R.status === "unavailable") return { outcome: { status: "rejected", reason: "failed", cause: new Error("[markdown-explorer] the HTML sanitizer worker could not start", { cause: R.error }) }, lasting: !1 };
426
- if (R.status === "crashed" && Vn(R.error))
486
+ if (R.status === "crashed" && oo(R.error))
427
487
  return { outcome: { status: "rejected", reason: "too-large", cause: new Error(`[markdown-explorer] the HTML sanitizer ran out of its ${String(r.workerHeapMb)} MiB worker heap`, { cause: R.error }) }, lasting: !0 };
428
488
  if (R.status === "crashed") return { outcome: { status: "rejected", reason: "failed", cause: new Error("[markdown-explorer] the HTML sanitizer worker failed", { cause: R.error }) }, lasting: !0 };
429
489
  const { output: I } = R;
430
- return Kn(I) ? I.status === "too-large" ? { outcome: ut, lasting: !0 } : I.status === "error" ? { outcome: { status: "rejected", reason: "failed", cause: new Error(`[markdown-explorer] the HTML sanitizer failed: ${I.message}`) }, lasting: !0 } : I.html.length > m ? { outcome: { status: "rejected", reason: "too-large", cause: new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(I.html.length)} characters exceeds its limit of ${String(m)}`) }, lasting: !0 } : { outcome: { status: "sanitized", html: I.html }, lasting: !0 } : { outcome: { status: "rejected", reason: "failed", cause: new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome") }, lasting: !0 };
431
- }, v = (x, O, D, R) => {
490
+ return no(I) ? I.status === "too-large" ? { outcome: ft, lasting: !0 } : I.status === "error" ? { outcome: { status: "rejected", reason: "failed", cause: new Error(`[markdown-explorer] the HTML sanitizer failed: ${I.message}`) }, lasting: !0 } : I.html.length > l ? { outcome: { status: "rejected", reason: "too-large", cause: new Error(`[markdown-explorer] the HTML sanitizer's output of ${String(I.html.length)} characters exceeds its limit of ${String(l)}`) }, lasting: !0 } : { outcome: { status: "sanitized", html: I.html }, lasting: !0 } : { outcome: { status: "rejected", reason: "failed", cause: new Error("[markdown-explorer] the HTML sanitizer worker answered something that is not an outcome") }, lasting: !0 };
491
+ }, v = (S, O, C, R) => {
432
492
  let I = () => {
433
493
  };
434
- const C = new Promise((g) => {
494
+ const D = new Promise((g) => {
435
495
  I = g;
436
- }), F = { hash: O, key: D, outcome: C, answer: I, controller: new AbortController(), waiters: 0 };
437
- S.set(D, F);
496
+ }), F = { hash: O, key: C, outcome: D, answer: I, controller: new AbortController(), waiters: 0 };
497
+ k.set(C, F);
438
498
  const w = h.get(O);
439
- return w === void 0 ? h.set(O, /* @__PURE__ */ new Set([F])) : w.add(F), T(x, R, F.controller.signal).catch((g) => ({ outcome: { status: "rejected", reason: "failed", cause: g instanceof Error ? g : new Error(String(g)) }, lasting: !0 })).then(({ outcome: g, lasting: M }) => {
499
+ return w === void 0 ? h.set(O, /* @__PURE__ */ new Set([F])) : w.add(F), E(S, R, F.controller.signal).catch((g) => ({ outcome: { status: "rejected", reason: "failed", cause: g instanceof Error ? g : new Error(String(g)) }, lasting: !0 })).then(({ outcome: g, lasting: M }) => {
440
500
  if (y(F), F.answer(g), !M) return;
441
- const U = f.get(O), E = U ?? (g.status === "rejected" ? { ...g, cause: null } : g);
442
- U === void 0 && f.set(O, E);
501
+ const U = f.get(O), b = U ?? (g.status === "rejected" ? { ...g, cause: null } : g);
502
+ U === void 0 && f.set(O, b);
443
503
  for (const _ of h.get(O) ?? [])
444
- y(_), _.answer(E), _.controller.abort();
504
+ y(_), _.answer(b), _.controller.abort();
445
505
  }), F;
446
- }, z = (x, O) => new Promise((D) => {
447
- x.waiters += 1;
506
+ }, z = (S, O) => new Promise((C) => {
507
+ S.waiters += 1;
448
508
  const R = () => {
449
- x.waiters -= 1, D(Pe), !(x.waiters > 0) && (y(x), x.controller.abort());
509
+ S.waiters -= 1, C($e), !(S.waiters > 0) && (y(S), S.controller.abort());
450
510
  };
451
- O.addEventListener("abort", R, { once: !0 }), x.outcome.then((I) => {
452
- O.removeEventListener("abort", R), D(I);
511
+ O.addEventListener("abort", R, { once: !0 }), S.outcome.then((I) => {
512
+ O.removeEventListener("abort", R), C(I);
453
513
  });
454
514
  });
455
- return (x, { scope: O, signal: D }) => {
456
- if (x.length > r.maxHtmlBytes || Buffer.byteLength(x, "utf8") > r.maxHtmlBytes) return Promise.resolve(ut);
457
- const R = Lr("sha256").update(x, "utf8").digest("base64"), I = f.get(R);
515
+ return (S, { scope: O, signal: C }) => {
516
+ if (S.length > r.maxHtmlBytes || Buffer.byteLength(S, "utf8") > r.maxHtmlBytes) return Promise.resolve(ft);
517
+ const R = Ur("sha256").update(S, "utf8").digest("base64"), I = f.get(R);
458
518
  if (I !== void 0) return Promise.resolve(I);
459
- if (D.aborted) return Promise.resolve(Pe);
460
- const C = `${R}\0${O}`, F = S.get(C);
461
- return z(F === void 0 ? v(x, R, C, O) : F, D);
519
+ if (C.aborted) return Promise.resolve($e);
520
+ const D = `${R}\0${O}`, F = k.get(D);
521
+ return z(F === void 0 ? v(S, R, D, O) : F, C);
462
522
  };
463
- }, Re = (e) => ({ result: e, json: JSON.stringify(e) }), Me = Object.freeze(Re(Object.freeze({ status: "error", failure: Object.freeze({ reason: "failed" }) }))), Qn = (e) => e.status === "ok" && e.entries.length > 0, qn = ({ ttlMs: e, maxEntries: t, maxBytes: r, now: n }) => {
464
- const a = zt(t, { max: r, of: (h, y) => 2 * y.tree.json.length }), s = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), m = (h, y) => {
465
- const T = new AbortController(), v = { waiters: 0, superseded: !1, started: !1, loadTree: y }, z = c.get(h), x = (C, F) => {
466
- const w = Re(C);
467
- return !(v.superseded || T.signal.aborted) && Qn(C) && a.set(h, { tree: w, loadedAt: F }), w;
468
- }, D = (async () => {
469
- if (z !== void 0 && await z, T.signal.aborted) return Me;
470
- const C = n();
471
- return v.started = !0, x(await v.loadTree(T.signal, C), C);
523
+ }, Ae = (e) => ({ result: e, json: JSON.stringify(e) }), Le = Object.freeze(Ae(Object.freeze({ status: "error", failure: Object.freeze({ reason: "failed" }) }))), ao = (e) => e.status === "ok" && e.entries.length > 0, io = ({ ttlMs: e, maxEntries: t, maxBytes: r, now: n }) => {
524
+ const a = Gt(t, { max: r, of: (h, y) => 2 * y.tree.json.length }), o = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), l = (h, y) => {
525
+ const E = new AbortController(), v = { waiters: 0, superseded: !1, started: !1, loadTree: y }, z = c.get(h), S = (D, F) => {
526
+ const w = Ae(D);
527
+ return !(v.superseded || E.signal.aborted) && ao(D) && a.set(h, { tree: w, loadedAt: F }), w;
528
+ }, C = (async () => {
529
+ if (z !== void 0 && await z, E.signal.aborted) return Le;
530
+ const D = n();
531
+ return v.started = !0, S(await v.loadTree(E.signal, D), D);
472
532
  })().finally(() => {
473
- s.get(h) === R && s.delete(h);
474
- }), R = { promise: D, controller: T, state: v };
475
- s.set(h, R);
476
- const I = D.then(
533
+ o.get(h) === R && o.delete(h);
534
+ }), R = { promise: C, controller: E, state: v };
535
+ o.set(h, R);
536
+ const I = C.then(
477
537
  () => {
478
538
  },
479
539
  () => {
@@ -482,135 +542,135 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
482
542
  return c.set(h, I), I.then(() => {
483
543
  c.get(h) === I && c.delete(h);
484
544
  }), R;
485
- }, f = (h, y, T) => {
545
+ }, f = (h, y, E) => {
486
546
  y.state.waiters += 1;
487
547
  const v = () => {
488
- y.state.waiters -= 1, !(y.state.waiters > 0) && (s.get(h) === y && s.delete(h), y.controller.abort());
548
+ y.state.waiters -= 1, !(y.state.waiters > 0) && (o.get(h) === y && o.delete(h), y.controller.abort());
489
549
  };
490
- return T.addEventListener("abort", v, { once: !0 }), y.promise.finally(() => {
491
- T.removeEventListener("abort", v);
550
+ return E.addEventListener("abort", v, { once: !0 }), y.promise.finally(() => {
551
+ E.removeEventListener("abort", v);
492
552
  });
493
- }, S = (h) => {
553
+ }, k = (h) => {
494
554
  a.delete(h);
495
- const y = s.get(h);
496
- y?.state.started && (y.state.superseded = !0, s.delete(h));
555
+ const y = o.get(h);
556
+ y?.state.started && (y.state.superseded = !0, o.delete(h));
497
557
  };
498
558
  return {
499
- load: (h, y, T) => {
500
- if (y.aborted) return Promise.resolve(Me);
559
+ load: (h, y, E) => {
560
+ if (y.aborted) return Promise.resolve(Le);
501
561
  const v = a.get(h);
502
562
  if (v !== void 0) {
503
563
  if (n() - v.loadedAt < e) return Promise.resolve(v.tree);
504
564
  a.delete(h);
505
565
  }
506
- const z = s.get(h);
507
- return f(h, z === void 0 ? m(h, T) : z, y);
566
+ const z = o.get(h);
567
+ return f(h, z === void 0 ? l(h, E) : z, y);
508
568
  },
509
- refresh: (h, y, T) => {
510
- if (y.aborted) return Promise.resolve(Me);
511
- S(h);
512
- const v = s.get(h);
513
- return v === void 0 ? f(h, m(h, T), y) : (v.state.loadTree = T, f(h, v, y));
569
+ refresh: (h, y, E) => {
570
+ if (y.aborted) return Promise.resolve(Le);
571
+ k(h);
572
+ const v = o.get(h);
573
+ return v === void 0 ? f(h, l(h, E), y) : (v.state.loadTree = E, f(h, v, y));
514
574
  },
515
- forget: S
575
+ forget: k
516
576
  };
517
- }, eo = (e) => ({
518
- load: (t, r, n) => n(r, e()).then(Re),
519
- refresh: (t, r, n) => n(r, e()).then(Re),
577
+ }, co = (e) => ({
578
+ load: (t, r, n) => n(r, e()).then(Ae),
579
+ refresh: (t, r, n) => n(r, e()).then(Ae),
520
580
  forget: () => {
521
581
  }
522
- }), k = (e) => {
582
+ }), x = (e) => {
523
583
  throw new TypeError(`[markdown-explorer] ${e}`);
524
- }, to = (e) => {
584
+ }, uo = (e) => {
525
585
  if (e === null || typeof e != "object") return null;
526
586
  const { name: t, path: r } = e;
527
587
  return typeof t != "string" || typeof r != "string" ? null : t === "" ? { path: r, reason: "an empty name" } : re(r) ? null : { path: r, reason: "a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash)" };
528
- }, ro = (e, t, r, n) => {
588
+ }, lo = (e, t, r, n) => {
529
589
  if (e === null) return null;
530
590
  if (!Array.isArray(e)) throw new TypeError(`[markdown-explorer] a source's ancestors must be null or an array of folder paths; got ${typeof e}`);
531
591
  const a = /* @__PURE__ */ new Set();
532
- for (const s of e) {
533
- if (typeof s != "string" || !re(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");
534
- if (r.deniesPath(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");
535
- if (!n(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");
536
- if (s === t) throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");
537
- if (a.has(s)) throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");
538
- a.add(s);
592
+ for (const o of e) {
593
+ if (typeof o != "string" || !re(o)) throw new TypeError("[markdown-explorer] a source's ancestors held a path the explorer does not accept");
594
+ if (r.deniesPath(o)) throw new TypeError("[markdown-explorer] a source's ancestors held a denied path");
595
+ if (!n(o)) throw new TypeError("[markdown-explorer] a source's ancestors held a path outside the source's boundary");
596
+ if (o === t) throw new TypeError("[markdown-explorer] a source's ancestors held the document itself");
597
+ if (a.has(o)) throw new TypeError("[markdown-explorer] a source's ancestors held a path twice");
598
+ a.add(o);
539
599
  }
540
600
  return Object.freeze([...a]);
541
- }, no = (e, t, r, n, a) => {
542
- const s = /* @__PURE__ */ new Set(), c = (f) => {
543
- if (!Array.isArray(f)) return k("a source returned entries that are not an array");
544
- const S = [];
601
+ }, fo = (e, t, r, n, a) => {
602
+ const o = /* @__PURE__ */ new Set(), c = (f) => {
603
+ if (!Array.isArray(f)) return x("a source returned entries that are not an array");
604
+ const k = [];
545
605
  for (const h of f) {
546
- const y = m(h);
547
- y !== null && S.push(y);
606
+ const y = l(h);
607
+ y !== null && k.push(y);
548
608
  }
549
- return S;
550
- }, m = (f) => {
551
- const S = to(f);
552
- if (S !== null)
553
- return n(S), null;
554
- const h = wr(f);
555
- if (h !== null) return k(h);
609
+ return k;
610
+ }, l = (f) => {
611
+ const k = uo(f);
612
+ if (k !== null)
613
+ return n(k), null;
614
+ const h = Sr(f);
615
+ if (h !== null) return x(h);
556
616
  const y = f;
557
- if (s.has(y)) return k("a source returned entries that contain themselves");
558
- const { name: T, path: v, type: z, mimeType: x, modifiedAt: O, children: D, lazy: R } = y;
559
- if (t.deniesName(T) || t.deniesPath(v)) return null;
617
+ if (o.has(y)) return x("a source returned entries that contain themselves");
618
+ const { name: E, path: v, type: z, mimeType: S, modifiedAt: O, children: C, lazy: R } = y;
619
+ if (t.deniesName(E) || t.deniesPath(v)) return null;
560
620
  if (!a(v))
561
621
  return n({ path: v, reason: "a path outside the source's boundary" }), null;
562
- const I = { name: T, path: v, ...x === void 0 ? {} : { mimeType: x }, ...O === void 0 ? {} : { modifiedAt: O } };
622
+ const I = { name: E, path: v, ...S === void 0 ? {} : { mimeType: S }, ...O === void 0 ? {} : { modifiedAt: O } };
563
623
  if (z === "file") return { ...I, type: z };
564
624
  if (R === !0)
565
- return r ? { ...I, type: z, lazy: !0, children: [] } : k("a lazy directory came from a source without a children function");
566
- if (D === void 0) return { ...I, type: z };
567
- s.add(y);
568
- const C = c(D);
569
- return s.delete(y), { ...I, type: z, children: C };
625
+ return r ? { ...I, type: z, lazy: !0, children: [] } : x("a lazy directory came from a source without a children function");
626
+ if (C === void 0) return { ...I, type: z };
627
+ o.add(y);
628
+ const D = c(C);
629
+ return o.delete(y), { ...I, type: z, children: D };
570
630
  };
571
631
  return c(e);
572
- }, oo = /^[\x21\x23-\x7E]{1,256}$/u, Ht = (e) => typeof e == "string" && oo.test(e), so = /* @__PURE__ */ new Set(["text", "image", "media", "spreadsheet", "file"]), io = (e) => typeof e == "string" && so.has(e), ao = (e, t, r) => {
632
+ }, mo = /^[\x21\x23-\x7E]{1,256}$/u, Kt = (e) => typeof e == "string" && mo.test(e), po = /* @__PURE__ */ new Set(["text", "image", "media", "spreadsheet", "file"]), wo = (e) => typeof e == "string" && po.has(e), ho = (e, t, r) => {
573
633
  if (e !== null && typeof e == "object") {
574
- const s = e, { kind: c } = s;
575
- if (io(c)) {
576
- if (Object.hasOwn(s, "url")) return k(`a ${c} document carries its version, not a url`);
577
- if (typeof s.name != "string") return k("a document needs a name string");
578
- if (!Ht(s.version)) return k(`a ${c} document needs a version of 1 to 256 visible ASCII characters other than '"'`);
579
- const m = t(s.version);
634
+ const o = e, { kind: c } = o;
635
+ if (wo(c)) {
636
+ if (Object.hasOwn(o, "url")) return x(`a ${c} document carries its version, not a url`);
637
+ if (typeof o.name != "string") return x("a document needs a name string");
638
+ if (!Kt(o.version)) return x(`a ${c} document needs a version of 1 to 256 visible ASCII characters other than '"'`);
639
+ const l = t(o.version);
580
640
  switch (c) {
581
641
  case "image": {
582
- const { imageType: f } = s;
583
- return dr(f) ? { kind: c, name: s.name, url: m, imageType: f } : k(`unknown image type ${typeof f == "string" ? JSON.stringify(f.slice(0, 64)) : typeof f}`);
642
+ const { imageType: f } = o;
643
+ return Er(f) ? { kind: c, name: o.name, url: l, imageType: f } : x(`unknown image type ${typeof f == "string" ? JSON.stringify(f.slice(0, 64)) : typeof f}`);
584
644
  }
585
645
  case "file":
586
- return { kind: c, name: s.name, url: m };
646
+ return { kind: c, name: o.name, url: l };
587
647
  case "media": {
588
- const { mediaType: f } = s;
589
- return ur(f) ? { kind: c, name: s.name, url: m, mediaType: f } : k(`unknown media type ${typeof f == "string" ? JSON.stringify(f.slice(0, 64)) : typeof f}`);
648
+ const { mediaType: f } = o;
649
+ return gr(f) ? { kind: c, name: o.name, url: l, mediaType: f } : x(`unknown media type ${typeof f == "string" ? JSON.stringify(f.slice(0, 64)) : typeof f}`);
590
650
  }
591
651
  case "text":
592
- return typeof s.text != "string" || typeof s.truncated != "boolean" ? k("a text document needs text and truncated") : { kind: c, name: s.name, text: s.text, truncated: s.truncated, url: m };
652
+ return typeof o.text != "string" || typeof o.truncated != "boolean" ? x("a text document needs text and truncated") : { kind: c, name: o.name, text: o.text, truncated: o.truncated, url: l };
593
653
  case "spreadsheet": {
594
- const f = cr(s);
595
- if (f !== null) return k(f);
596
- const { format: S, firstSheetOnly: h, edit: y } = s;
597
- return { kind: c, name: s.name, url: m, format: S, firstSheetOnly: h, edit: uo(y) };
654
+ const f = yr(o);
655
+ if (f !== null) return x(f);
656
+ const { format: k, firstSheetOnly: h, edit: y } = o;
657
+ return { kind: c, name: o.name, url: l, format: k, firstSheetOnly: h, edit: go(y) };
598
658
  }
599
659
  }
600
660
  }
601
661
  }
602
- const n = lr(e);
603
- if (n !== null) return k(n);
662
+ const n = br(e);
663
+ if (n !== null) return x(n);
604
664
  const a = e;
605
665
  switch (a.kind) {
606
666
  case "failure": {
607
- const { reason: s, code: c } = a.failure;
608
- return { kind: "failure", failure: xe(s, c) };
667
+ const { reason: o, code: c } = a.failure;
668
+ return { kind: "failure", failure: ve(o, c) };
609
669
  }
610
670
  case "markdown":
611
- return a.headings.length > Rt ? { kind: "failure", failure: xe("too-large") } : (a.edit?.kind === "inline" || a.edit?.kind === "draft") && !r ? k(`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: s, depth: c, id: m }) => ({ text: s, depth: c, id: m })), edit: co(a.edit) };
671
+ return a.headings.length > At ? { kind: "failure", failure: ve("too-large") } : (a.edit?.kind === "inline" || a.edit?.kind === "draft") && !r ? x(`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: o, depth: c, id: l }) => ({ text: o, depth: c, id: l })), edit: yo(a.edit) };
612
672
  }
613
- }, co = (e) => {
673
+ }, yo = (e) => {
614
674
  if (e === null) return null;
615
675
  switch (e.kind) {
616
676
  case "inline":
@@ -620,514 +680,514 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
620
680
  case "external":
621
681
  return { kind: "external", href: e.href };
622
682
  }
623
- }, uo = (e) => e === null ? null : { kind: "external", href: e.href }, ve = (e, t, r) => typeof e != "string" ? k(`${r} needs a text string`) : e.includes("\0") ? k(`${r} holds NUL, which no text editor can keep`) : new TextEncoder().encode(e).byteLength > t ? k(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`) : e, Bt = (e) => pr(e.href) ? { kind: "grant", href: e.href } : k("a grant needs a root-relative href"), lo = (e, t) => {
624
- if (e === null || typeof e != "object") return k("an edit source must be an object");
683
+ }, go = (e) => e === null ? null : { kind: "external", href: e.href }, Ne = (e, t, r) => typeof e != "string" ? x(`${r} needs a text string`) : e.includes("\0") ? x(`${r} holds NUL, which no text editor can keep`) : new TextEncoder().encode(e).byteLength > t ? x(`${r} is over editMaxBytes (${t} bytes); refuse a longer source with ExplorerError "too-large"`) : e, Vt = (e) => xr(e.href) ? { kind: "grant", href: e.href } : x("a grant needs a root-relative href"), Eo = (e, t) => {
684
+ if (e === null || typeof e != "object") return x("an edit source must be an object");
625
685
  const r = e;
626
- return r.kind === "grant" ? Bt(r) : r.kind === "draft" ? { kind: "draft", text: ve(r.text, t, "a draft source") } : r.kind !== "edit" ? k(`an edit source's kind must be "edit", "draft" or "grant"`) : ge(r.version) ? typeof r.history != "boolean" ? k("an edit source needs history") : { kind: "edit", text: ve(r.text, t, "an edit source"), version: r.version, history: r.history } : k("an edit source needs a version of 1 to 1024 characters");
627
- }, fo = (e, t) => {
628
- if (e === null || typeof e != "object") return k("a save result must be an object");
686
+ return r.kind === "grant" ? Vt(r) : r.kind === "draft" ? { kind: "draft", text: Ne(r.text, t, "a draft source") } : r.kind !== "edit" ? x(`an edit source's kind must be "edit", "draft" or "grant"`) : Ee(r.version) ? typeof r.history != "boolean" ? x("an edit source needs history") : { kind: "edit", text: Ne(r.text, t, "an edit source"), version: r.version, history: r.history } : x("an edit source needs a version of 1 to 1024 characters");
687
+ }, bo = (e, t) => {
688
+ if (e === null || typeof e != "object") return x("a save result must be an object");
629
689
  const r = e;
630
690
  switch (r.kind) {
631
691
  case "grant":
632
- return Bt(r);
692
+ return Vt(r);
633
693
  case "saved":
634
- return ge(r.version) ? { kind: "saved", version: r.version } : k("a saved result needs a version of 1 to 1024 characters");
694
+ return Ee(r.version) ? { kind: "saved", version: r.version } : x("a saved result needs a version of 1 to 1024 characters");
635
695
  case "conflict":
636
- return ge(r.version) ? { kind: "conflict", version: r.version, text: ve(r.text, t, "a conflict's current text") } : k("a conflict needs the current version of 1 to 1024 characters");
696
+ return Ee(r.version) ? { kind: "conflict", version: r.version, text: Ne(r.text, t, "a conflict's current text") } : x("a conflict needs the current version of 1 to 1024 characters");
637
697
  default:
638
- return k(`a save result's kind must be "saved", "conflict" or "grant"`);
698
+ return x(`a save result's kind must be "saved", "conflict" or "grant"`);
639
699
  }
640
- }, mo = (e) => {
641
- if (e === null || typeof e != "object") return k("a preview must be an object");
700
+ }, To = (e) => {
701
+ if (e === null || typeof e != "object") return x("a preview must be an object");
642
702
  const { htmlContent: t, headings: r } = e;
643
- if (typeof t != "string" || !Array.isArray(r)) return k("a preview needs htmlContent and headings");
644
- if (r.length > Rt) return { kind: "failure", failure: xe("too-large") };
703
+ if (typeof t != "string" || !Array.isArray(r)) return x("a preview needs htmlContent and headings");
704
+ if (r.length > At) return { kind: "failure", failure: ve("too-large") };
645
705
  for (const n of r) {
646
- const a = mr(n);
647
- if (a !== null) return k(a);
706
+ const a = kr(n);
707
+ if (a !== null) return x(a);
648
708
  }
649
- return { html: t, headings: r.map(({ text: n, depth: a, id: s }) => ({ text: n, depth: a, id: s })) };
650
- }, po = (e) => {
651
- if (!Array.isArray(e)) return k("revisions must be an array");
709
+ return { html: t, headings: r.map(({ text: n, depth: a, id: o }) => ({ text: n, depth: a, id: o })) };
710
+ }, ko = (e) => {
711
+ if (!Array.isArray(e)) return x("revisions must be an array");
652
712
  const t = /* @__PURE__ */ new Set();
653
713
  return e.map((r) => {
654
- const n = fr(r);
655
- if (n !== null) return k(n);
656
- const { id: a, modifiedAt: s, size: c, author: m, kept: f, current: S } = r;
657
- return t.has(a) ? k(`two revisions share the id ${JSON.stringify(a.slice(0, 64))}`) : (t.add(a), { id: a, modifiedAt: s, size: c, author: m, kept: f, current: S });
714
+ const n = Tr(r);
715
+ if (n !== null) return x(n);
716
+ const { id: a, modifiedAt: o, size: c, author: l, kept: f, current: k } = r;
717
+ return t.has(a) ? x(`two revisions share the id ${JSON.stringify(a.slice(0, 64))}`) : (t.add(a), { id: a, modifiedAt: o, size: c, author: l, kept: f, current: k });
658
718
  });
659
- }, wo = (e, t) => ve(e, t, "a revision"), ze = (e) => {
660
- if (e === null || typeof e != "object") return k("an asset file must be an object");
661
- const { name: t, contentType: r, size: n, version: a, open: s, kind: c } = e;
662
- return c !== void 0 ? k(c === "redirect" ? "an asset redirect answers only a request for the stored file (options.redirect), never one that reads the bytes" : 'an asset file has no kind (the only kind is "redirect")') : typeof t != "string" || t === "" ? k("an asset file needs a non-empty name") : typeof r != "string" ? k("an asset file needs a contentType string ('' when unknown)") : n !== null && !(typeof n == "number" && Number.isSafeInteger(n) && n >= 0) ? k("an asset file's size must be null or a non-negative safe integer") : Ht(a) ? typeof s != "function" ? k("an asset file needs an open function") : Object.freeze({ name: t, contentType: r, size: n, version: a, open: s }) : k(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`);
663
- }, ho = (e) => {
664
- if (e === null || typeof e != "object" || e.kind !== "redirect") return ze(e);
719
+ }, xo = (e, t) => Ne(e, t, "a revision"), De = (e) => {
720
+ if (e === null || typeof e != "object") return x("an asset file must be an object");
721
+ const { name: t, contentType: r, size: n, version: a, open: o, kind: c } = e;
722
+ return c !== void 0 ? x(c === "redirect" ? "an asset redirect answers only a request for the stored file (options.redirect), never one that reads the bytes" : 'an asset file has no kind (the only kind is "redirect")') : typeof t != "string" || t === "" ? x("an asset file needs a non-empty name") : typeof r != "string" ? x("an asset file needs a contentType string ('' when unknown)") : n !== null && !(typeof n == "number" && Number.isSafeInteger(n) && n >= 0) ? x("an asset file's size must be null or a non-negative safe integer") : Kt(a) ? typeof o != "function" ? x("an asset file needs an open function") : Object.freeze({ name: t, contentType: r, size: n, version: a, open: o }) : x(`an asset file needs a version of 1 to 256 visible ASCII characters other than '"'`);
723
+ }, So = (e) => {
724
+ if (e === null || typeof e != "object" || e.kind !== "redirect") return De(e);
665
725
  const { url: t } = e;
666
- if (typeof t != "string" || !URL.canParse(t)) return k("an asset redirect needs an absolute https URL");
726
+ if (typeof t != "string" || !URL.canParse(t)) return x("an asset redirect needs an absolute https URL");
667
727
  const r = new URL(t);
668
- return r.protocol !== "https:" || r.username !== "" || r.password !== "" ? k("an asset redirect's URL must be https and carry no credentials") : Object.freeze({ kind: "redirect", url: r.href });
669
- }, yo = (e) => Array.isArray(e) ? e.map((t) => {
670
- if (t === null || typeof t != "object") return k("a notice must be an object");
671
- const { id: r, tone: n, title: a, body: s, action: c } = t;
672
- if (typeof r != "string" || r === "" || typeof a != "string") return k("a notice needs an id and a title");
673
- if (!ir(n)) return k(`unknown notice tone ${typeof n == "string" ? JSON.stringify(n.slice(0, 64)) : typeof n}`);
674
- if (s !== void 0 && typeof s != "string") return k("a notice body must be a string");
675
- const f = { id: r, tone: n, title: a, ...s === void 0 ? {} : { body: s } };
728
+ return r.protocol !== "https:" || r.username !== "" || r.password !== "" ? x("an asset redirect's URL must be https and carry no credentials") : Object.freeze({ kind: "redirect", url: r.href });
729
+ }, Oo = (e) => Array.isArray(e) ? e.map((t) => {
730
+ if (t === null || typeof t != "object") return x("a notice must be an object");
731
+ const { id: r, tone: n, title: a, body: o, action: c } = t;
732
+ if (typeof r != "string" || r === "" || typeof a != "string") return x("a notice needs an id and a title");
733
+ if (!wr(n)) return x(`unknown notice tone ${typeof n == "string" ? JSON.stringify(n.slice(0, 64)) : typeof n}`);
734
+ if (o !== void 0 && typeof o != "string") return x("a notice body must be a string");
735
+ const f = { id: r, tone: n, title: a, ...o === void 0 ? {} : { body: o } };
676
736
  if (c === void 0) return f;
677
- if (c === null || typeof c != "object") return k("a notice action must be an object");
678
- const { label: S, href: h } = c;
679
- return typeof S != "string" || !ar(h, hr) ? k("a notice action needs a label and an http(s), mailto or relative href") : { ...f, action: { label: S, href: h } };
680
- }) : k("notices must be an array"), go = 4e3, Te = Object.freeze({ ttlMs: 3e5, maxEntries: 64, maxBytes: 64 * 1024 * 1024 }), lt = 32, Ft = "private, no-store", Eo = Object.freeze({
737
+ if (c === null || typeof c != "object") return x("a notice action must be an object");
738
+ const { label: k, href: h } = c;
739
+ return typeof k != "string" || !hr(h, Or) ? x("a notice action needs a label and an http(s), mailto or relative href") : { ...f, action: { label: k, href: h } };
740
+ }) : x("notices must be an array"), Ro = 4e3, xe = Object.freeze({ ttlMs: 3e5, maxEntries: 64, maxBytes: 64 * 1024 * 1024 }), pt = 32, Zt = "private, no-store", vo = Object.freeze({
681
741
  "Content-Type": "application/json; charset=utf-8",
682
- "Cache-Control": Ft,
742
+ "Cache-Control": Zt,
683
743
  "X-Content-Type-Options": "nosniff",
684
744
  "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'; sandbox",
685
745
  "Cross-Origin-Resource-Policy": "same-origin"
686
- }), bo = 22, To = 2147483647, Le = Object.freeze([]), ko = Object.freeze({ status: "ok", source: null, ancestors: null }), ft = Object.freeze(["contains", "confirm"]), mt = Object.freeze({ readOnly: !1 }), So = Object.freeze({ readOnly: !0 }), Q = (e, t, r) => {
746
+ }), _o = 22, Ao = 2147483647, je = Object.freeze([]), No = Object.freeze({ status: "ok", source: null, ancestors: null }), wt = Object.freeze(["contains", "confirm"]), ht = Object.freeze({ readOnly: !1 }), Io = Object.freeze({ readOnly: !0 }), Q = (e, t, r) => {
687
747
  if (!(r && t === void 0) && typeof t != "function")
688
748
  throw new TypeError(`[markdown-explorer] ${e} must be a function; got ${typeof t}`);
689
- }, pe = (e, t, r) => {
749
+ }, we = (e, t, r) => {
690
750
  if (typeof t != "number") throw new TypeError(`[markdown-explorer] ${e} must be a number; got ${typeof t}`);
691
751
  if (!Number.isSafeInteger(t) || t <= 0 || t > r) throw new RangeError(`[markdown-explorer] ${e} must be an integer in 1..${String(r)}; got ${String(t)}`);
692
752
  return t;
693
- }, xo = (e) => {
753
+ }, Po = (e) => {
694
754
  if (e === null || typeof e != "object" || !Object.isFrozen(e)) throw new TypeError("[markdown-explorer] config must be the value returned by defineExplorerConfig");
695
- return Rr(e);
696
- }, pt = (e) => {
755
+ return Lr(e);
756
+ }, yt = (e) => {
697
757
  try {
698
758
  return new Headers(e);
699
759
  } catch {
700
760
  throw new TypeError("[markdown-explorer] authenticate returned headers that are not a valid headers init (their values are not logged)");
701
761
  }
702
- }, wt = (e) => e instanceof Response ? new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`) : e, Oo = (e) => {
762
+ }, gt = (e) => e instanceof Response ? new TypeError(`[markdown-explorer] authenticate threw a Response (status ${String(e.status)}), which a data request does not follow`) : e, Mo = (e) => {
703
763
  if (typeof e != "string") throw new TypeError(`[markdown-explorer] scopeSecret must be a string; got ${typeof e}`);
704
- if (e.length < lt) throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(lt)} characters; got ${String(e.length)}`);
764
+ if (e.length < pt) throw new RangeError(`[markdown-explorer] scopeSecret must have at least ${String(pt)} characters; got ${String(e.length)}`);
705
765
  return e;
706
- }, Ro = (e, t) => {
707
- if (!Ir(t)) throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);
766
+ }, $o = (e, t) => {
767
+ if (!Hr(t)) throw new TypeError(`[markdown-explorer] ${e}.boundary must be a plain object { contains, confirm? }`);
708
768
  for (const r of Object.keys(t))
709
- if (!ft.includes(r)) throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${ft.join(", ")}`);
769
+ if (!wt.includes(r)) throw new RangeError(`[markdown-explorer] ${e}.boundary.${r} is not an option; expected ${wt.join(", ")}`);
710
770
  Q(`${e}.boundary.contains`, t.contains, !1), Q(`${e}.boundary.confirm`, t.confirm, !0);
711
- }, vo = (e) => {
771
+ }, Lo = (e) => {
712
772
  if (!Array.isArray(e)) throw new TypeError("[markdown-explorer] sources must be an array");
713
773
  const t = e;
714
774
  if (t.length === 0) throw new RangeError("[markdown-explorer] sources must hold at least one source");
715
775
  const r = /* @__PURE__ */ new Set();
716
776
  for (const [n, a] of t.entries()) {
717
777
  if (a === null || typeof a != "object") throw new TypeError(`[markdown-explorer] sources[${String(n)}] must be an object`);
718
- const { id: s, label: c, boundary: m, tree: f, children: S, ancestors: h, cacheScope: y } = a;
719
- if (!vr(s))
720
- throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof s == "string" ? JSON.stringify(s) : typeof s}`);
721
- const T = `source ${JSON.stringify(s)}`;
722
- if (r.has(s)) throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(s)} repeats at sources[${String(n)}]`);
723
- if (r.add(s), typeof c != "string" && typeof c != "function") throw new TypeError(`[markdown-explorer] ${T}.label must be a string or a function`);
724
- if (typeof c == "string" && c.trim() === "") throw new RangeError(`[markdown-explorer] ${T}.label must not be blank`);
725
- if (Ro(T, m), Q(`${T}.tree`, f, !1), Q(`${T}.children`, S, !0), Q(`${T}.ancestors`, h, !0), y !== void 0 && y !== "principal" && y !== "shared") throw new RangeError(`[markdown-explorer] ${T}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(y)}`);
778
+ const { id: o, label: c, boundary: l, tree: f, children: k, ancestors: h, cacheScope: y } = a;
779
+ if (!jr(o))
780
+ throw new RangeError(`[markdown-explorer] sources[${String(n)}].id must use lowercase letters, digits and "-" and start with a letter or digit; got ${typeof o == "string" ? JSON.stringify(o) : typeof o}`);
781
+ const E = `source ${JSON.stringify(o)}`;
782
+ if (r.has(o)) throw new RangeError(`[markdown-explorer] source ids must be unique; ${JSON.stringify(o)} repeats at sources[${String(n)}]`);
783
+ if (r.add(o), typeof c != "string" && typeof c != "function") throw new TypeError(`[markdown-explorer] ${E}.label must be a string or a function`);
784
+ if (typeof c == "string" && c.trim() === "") throw new RangeError(`[markdown-explorer] ${E}.label must not be blank`);
785
+ if ($o(E, l), Q(`${E}.tree`, f, !1), Q(`${E}.children`, k, !0), Q(`${E}.ancestors`, h, !0), y !== void 0 && y !== "principal" && y !== "shared") throw new RangeError(`[markdown-explorer] ${E}.cacheScope must be "principal" or "shared"; got ${JSON.stringify(y)}`);
726
786
  }
727
787
  return t;
728
- }, _o = (e) => {
788
+ }, jo = (e) => {
729
789
  if (e === !1) return !1;
730
- if (e === void 0) return Te;
790
+ if (e === void 0) return xe;
731
791
  if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] treeCache must be { ttlMs, maxEntries, maxBytes } or false");
732
792
  const { ttlMs: t, maxEntries: r, maxBytes: n } = e;
733
793
  return {
734
- ttlMs: t === void 0 ? Te.ttlMs : pe("treeCache.ttlMs", t, Number.MAX_SAFE_INTEGER),
735
- maxEntries: r === void 0 ? Te.maxEntries : pe("treeCache.maxEntries", r, Number.MAX_SAFE_INTEGER),
736
- maxBytes: n === void 0 ? Te.maxBytes : pe("treeCache.maxBytes", n, Number.MAX_SAFE_INTEGER)
794
+ ttlMs: t === void 0 ? xe.ttlMs : we("treeCache.ttlMs", t, Number.MAX_SAFE_INTEGER),
795
+ maxEntries: r === void 0 ? xe.maxEntries : we("treeCache.maxEntries", r, Number.MAX_SAFE_INTEGER),
796
+ maxBytes: n === void 0 ? xe.maxBytes : we("treeCache.maxBytes", n, Number.MAX_SAFE_INTEGER)
737
797
  };
738
- }, ht = (e) => {
798
+ }, Et = (e) => {
739
799
  if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] authenticate must resolve to { status, ... }");
740
800
  const { status: t } = e;
741
801
  if (t !== "signed-in" && t !== "signed-out" && t !== "forbidden") throw new TypeError(`[markdown-explorer] authenticate resolved to an unknown status ${JSON.stringify(t)}`);
742
802
  return e;
743
- }, yt = (e, t) => {
803
+ }, bt = (e, t) => {
744
804
  if (!(t instanceof Response)) throw new TypeError(`[markdown-explorer] ${e} must return a Response`);
745
805
  return t;
746
- }, gt = (e, t) => {
806
+ }, Tt = (e, t) => {
747
807
  if (typeof t != "string" || t === "") throw new TypeError("[markdown-explorer] principalKey must return a non-empty string");
748
- return $r("sha256", e).update(t, "utf8").digest("base64url").slice(0, bo);
749
- }, Ao = (e) => e.view === "multi" ? e.docs : e.doc === null ? [] : [e.doc], ue = (e, t) => {
808
+ return Xr("sha256", e).update(t, "utf8").digest("base64url").slice(0, _o);
809
+ }, zo = (e) => e.view === "multi" ? e.docs : e.doc === null ? [] : [e.doc], ue = (e, t) => {
750
810
  const r = e.getAll(t), [n] = r;
751
811
  return r.length === 1 && n !== void 0 && n !== "" ? n : null;
752
812
  }, Z = (e, t, r, n = {}) => {
753
813
  const a = new Headers(r);
754
- for (const [s, c] of Object.entries({ ...Eo, ...n })) a.set(s, c);
814
+ for (const [o, c] of Object.entries({ ...vo, ...n })) a.set(o, c);
755
815
  return new Response(t, { status: e, headers: a });
756
- }, L = (e, t, r) => Z(gr[e.reason], JSON.stringify({ failure: e }), t, r), No = /* @__PURE__ */ new Set(["refresh", "save", "preview"]), Io = /* @__PURE__ */ new Set(["edit", "save", "preview", "revisions", "revision"]), Et = (e, t) => {
757
- const r = No.has(t) ? ["POST"] : ["GET", "HEAD"];
816
+ }, L = (e, t, r) => Z(vr[e.reason], JSON.stringify({ failure: e }), t, r), Co = /* @__PURE__ */ new Set(["refresh", "save", "preview"]), Do = /* @__PURE__ */ new Set(["edit", "save", "preview", "revisions", "revision"]), kt = (e, t) => {
817
+ const r = Co.has(t) ? ["POST"] : ["GET", "HEAD"];
758
818
  return r.includes(e.method.toUpperCase()) ? null : Z(405, JSON.stringify({ failure: { reason: "invalid" } }), void 0, { Allow: r.join(", ") });
759
- }, bt = (e) => e.headers.get(Ce) === Er && _t(e, At) === void 0, Po = (e) => e.headers.get(Ce) === br && _t(e, At) === void 0, Mo = async (e, t) => {
760
- const [r, ...n] = (e.headers.get("Content-Type") ?? "").split(";").map((T) => T.trim().toLowerCase()), a = n.find((T) => T.startsWith("charset="));
761
- if (r !== Sr || a !== void 0 && a !== "charset=utf-8") return { status: "error", failure: { reason: "invalid" } };
762
- const s = Number(e.headers.get("Content-Length") ?? "0");
763
- if (Number.isFinite(s) && s > t) return { status: "error", failure: { reason: "too-large" } };
819
+ }, xt = (e) => e.headers.get(Be) === _r && Pt(e, Mt) === void 0, Ho = (e) => e.headers.get(Be) === Ar && Pt(e, Mt) === void 0, Bo = async (e, t) => {
820
+ const [r, ...n] = (e.headers.get("Content-Type") ?? "").split(";").map((E) => E.trim().toLowerCase()), a = n.find((E) => E.startsWith("charset="));
821
+ if (r !== Pr || a !== void 0 && a !== "charset=utf-8") return { status: "error", failure: { reason: "invalid" } };
822
+ const o = Number(e.headers.get("Content-Length") ?? "0");
823
+ if (Number.isFinite(o) && o > t) return { status: "error", failure: { reason: "too-large" } };
764
824
  if (e.body === null) return { status: "ok", text: "" };
765
- const c = e.body.getReader(), m = [];
825
+ const c = e.body.getReader(), l = [];
766
826
  let f = 0;
767
827
  for (; ; ) {
768
- const { done: T, value: v } = await c.read();
769
- if (T) break;
828
+ const { done: E, value: v } = await c.read();
829
+ if (E) break;
770
830
  if (f += v.byteLength, f > t)
771
831
  return await c.cancel(), { status: "error", failure: { reason: "too-large" } };
772
- m.push(v);
832
+ l.push(v);
773
833
  }
774
- const S = new Uint8Array(f);
834
+ const k = new Uint8Array(f);
775
835
  let h = 0;
776
- for (const T of m)
777
- S.set(T, h), h += T.byteLength;
836
+ for (const E of l)
837
+ k.set(E, h), h += E.byteLength;
778
838
  let y;
779
839
  try {
780
- y = new TextDecoder("utf-8", { fatal: !0 }).decode(S);
840
+ y = new TextDecoder("utf-8", { fatal: !0 }).decode(k);
781
841
  } catch {
782
842
  return { status: "error", failure: { reason: "invalid" } };
783
843
  }
784
844
  return y.includes("\0") ? { status: "error", failure: { reason: "invalid" } } : { status: "ok", text: y };
785
- }, Lo = (e) => {
845
+ }, Fo = (e) => {
786
846
  if (e === void 0) return;
787
847
  if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] edit must be an object of the editor's ports");
788
848
  const t = e;
789
849
  for (const r of ["source", "save", "preview", "revisions", "revision"]) Q(`edit.${r}`, t[r], !1);
790
850
  return e;
791
- }, $o = ({ parentHeaders: e, loaderHeaders: t, errorHeaders: r }) => {
851
+ }, Uo = ({ parentHeaders: e, loaderHeaders: t, errorHeaders: r }) => {
792
852
  const n = new Headers(), a = r === void 0 ? [e, t] : [e, t, r];
793
- for (const s of a)
794
- for (const [c, m] of s)
795
- c !== "set-cookie" && n.set(c, m);
853
+ for (const o of a)
854
+ for (const [c, l] of o)
855
+ c !== "set-cookie" && n.set(c, l);
796
856
  return n;
797
- }, us = (e) => {
857
+ }, ys = (e) => {
798
858
  if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] the server configuration must be an object");
799
- const t = xo(e.config), r = Oo(e.scopeSecret);
859
+ const t = Po(e.config), r = Mo(e.scopeSecret);
800
860
  Q("authenticate", e.authenticate, !1), Q("principalKey", e.principalKey, !1), Q("document", e.document, !1), Q("asset", e.asset, !1), Q("signedOutPage", e.signedOutPage, !1), Q("forbiddenPage", e.forbiddenPage, !0), Q("notices", e.notices, !0), Q("onTreeRefreshed", e.onTreeRefreshed, !0);
801
- const n = vo(e.sources), a = xr(
861
+ const n = Lo(e.sources), a = Mr(
802
862
  t,
803
- n.map((o) => o.id)
804
- ), s = e.logger;
805
- if (s !== void 0 && (s === null || typeof s != "object" || typeof s.error != "function"))
863
+ n.map((s) => s.id)
864
+ ), o = e.logger;
865
+ if (o !== void 0 && (o === null || typeof o != "object" || typeof o.error != "function"))
806
866
  throw new TypeError("[markdown-explorer] logger must be an object with an error function");
807
- const c = e.logger === void 0 ? wn : e.logger, m = vt(e.deny), f = e.deferredTimeoutMs === void 0 ? go : pe("deferredTimeoutMs", e.deferredTimeoutMs, To), S = e.textMaxBytes === void 0 ? ot : pe("textMaxBytes", e.textMaxBytes, st), h = Lo(e.edit);
867
+ const c = e.logger === void 0 ? xn : e.logger, l = Nt(e.deny), f = e.deferredTimeoutMs === void 0 ? Ro : we("deferredTimeoutMs", e.deferredTimeoutMs, Ao), k = e.textMaxBytes === void 0 ? it : we("textMaxBytes", e.textMaxBytes, ct), h = Fo(e.edit);
808
868
  if (h === void 0 && e.editMaxBytes !== void 0) throw new TypeError("[markdown-explorer] editMaxBytes needs the edit ports");
809
- const y = e.editMaxBytes === void 0 ? ot : pe("editMaxBytes", e.editMaxBytes, st), T = _o(e.treeCache), v = () => Date.now(), z = T === !1 ? eo(v) : qn({ ...T, now: v }), x = Gn(e.sanitizer, t.multiView.maxPanels), O = Zn({ iframeHosts: t.iframeHosts, dataPath: t.dataPath, options: x, pool: Wn(Yn(), x) }), D = new Map(n.map((o) => [o.id, o])), R = Or(t), { authenticate: I, principalKey: C, signedOutPage: F, forbiddenPage: w, onTreeRefreshed: g } = e, M = (o, u) => {
810
- if (typeof o.label == "string") return o.label;
811
- const i = o.label(u);
812
- if (typeof i != "string" || i.trim() === "") throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(o.id)} must be a non-blank string`);
869
+ const y = e.editMaxBytes === void 0 ? it : we("editMaxBytes", e.editMaxBytes, ct), E = jo(e.treeCache), v = () => Date.now(), z = E === !1 ? co(v) : io({ ...E, now: v }), S = eo(e.sanitizer, t.multiView.maxPanels), O = so({ iframeHosts: t.iframeHosts, dataPath: t.dataPath, options: S, pool: ro(to(), S) }), C = new Map(n.map((s) => [s.id, s])), R = $r(t), { authenticate: I, principalKey: D, signedOutPage: F, forbiddenPage: w, onTreeRefreshed: g } = e, M = (s, u) => {
870
+ if (typeof s.label == "string") return s.label;
871
+ const i = s.label(u);
872
+ if (typeof i != "string" || i.trim() === "") throw new TypeError(`[markdown-explorer] the label of source ${JSON.stringify(s.id)} must be a non-blank string`);
813
873
  return i;
814
- }, U = (o, u) => o.cacheScope === "shared" ? o.id : `${o.id}\0${u}`, E = (o, u) => {
815
- const i = (l) => ie(c, { operation: "boundary", sourceId: o.id, path: u, error: l });
874
+ }, U = (s, u) => s.cacheScope === "shared" ? s.id : `${s.id}\0${u}`, b = (s, u) => {
875
+ const i = (m) => ae(c, { operation: "boundary", sourceId: s.id, path: u, error: m });
816
876
  let d;
817
877
  try {
818
- d = o.boundary.contains(u);
819
- } catch (l) {
820
- return i(l), !1;
878
+ d = s.boundary.contains(u);
879
+ } catch (m) {
880
+ return i(m), !1;
821
881
  }
822
- return typeof d == "boolean" ? d : (nt(d, i), i(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(o.id)} must return a boolean; got ${typeof d}`)), !1);
823
- }, _ = async (o, u, i) => {
824
- const { confirm: d } = o.boundary;
882
+ return typeof d == "boolean" ? d : (at(d, i), i(new TypeError(`[markdown-explorer] boundary.contains of source ${JSON.stringify(s.id)} must return a boolean; got ${typeof d}`)), !1);
883
+ }, _ = async (s, u, i) => {
884
+ const { confirm: d } = s.boundary;
825
885
  if (d === void 0) return { status: "inside", readPath: i };
826
- let l;
886
+ let m;
827
887
  try {
828
- l = await d(u, i);
829
- } catch (j) {
830
- return { status: "error", failure: Y(j, { operation: "boundary", sourceId: o.id, path: i }, u.signal, c) };
888
+ m = await d(u, i);
889
+ } catch ($) {
890
+ return { status: "error", failure: W($, { operation: "boundary", sourceId: s.id, path: i }, u.signal, c) };
831
891
  }
832
- const p = (j) => (ie(c, { operation: "boundary", sourceId: o.id, path: i, error: new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} ${j}`) }), { status: "outside" });
833
- if (l === null || typeof l != "object") return p(`must resolve to { inside, readPath? }; got ${l === null ? "null" : typeof l}`);
834
- const { inside: b, readPath: A } = l;
835
- return b === !1 ? { status: "outside" } : b !== !0 || typeof A != "string" ? p("must resolve to { inside: false } or { inside: true, readPath: string }") : !re(A) || m.deniesPath(A) ? (ie(c, { operation: "boundary", sourceId: o.id, path: i, error: new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(o.id)} answered a readPath the explorer does not serve (unacceptable or denied)`) }), { status: "error", failure: { reason: "failed" } }) : { status: "inside", readPath: A };
836
- }, N = async (o, u) => {
837
- const i = n.filter((l) => E(l, u));
892
+ const p = ($) => (ae(c, { operation: "boundary", sourceId: s.id, path: i, error: new TypeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} ${$}`) }), { status: "outside" });
893
+ if (m === null || typeof m != "object") return p(`must resolve to { inside, readPath? }; got ${m === null ? "null" : typeof m}`);
894
+ const { inside: T, readPath: A } = m;
895
+ return T === !1 ? { status: "outside" } : T !== !0 || typeof A != "string" ? p("must resolve to { inside: false } or { inside: true, readPath: string }") : !re(A) || l.deniesPath(A) ? (ae(c, { operation: "boundary", sourceId: s.id, path: i, error: new RangeError(`[markdown-explorer] boundary.confirm of source ${JSON.stringify(s.id)} answered a readPath the explorer does not serve (unacceptable or denied)`) }), { status: "error", failure: { reason: "failed" } }) : { status: "inside", readPath: A };
896
+ }, N = async (s, u) => {
897
+ const i = n.filter((m) => b(m, u));
838
898
  if (i.length === 0) return { status: "error", failure: { reason: "forbidden" } };
839
- if (i.some((l) => l.boundary.confirm === void 0)) return { status: "inside", readPath: u };
899
+ if (i.some((m) => m.boundary.confirm === void 0)) return { status: "inside", readPath: u };
840
900
  let d = null;
841
- for (const l of i) {
842
- const p = await _(l, o, u);
901
+ for (const m of i) {
902
+ const p = await _(m, s, u);
843
903
  if (p.status === "inside") return p;
844
904
  p.status === "error" && d === null && (d = p.failure);
845
905
  }
846
906
  return { status: "error", failure: d === null ? { reason: "forbidden" } : d };
847
- }, $ = (o, u, i) => {
848
- const d = ({ path: l, reason: p }) => gn(c, { operation: i.operation, sourceId: i.sourceId, path: l, error: new TypeError(`[markdown-explorer] an entry with ${p} was left out`) });
907
+ }, j = (s, u, i) => {
908
+ const d = ({ path: m, reason: p }) => Rn(c, { operation: i.operation, sourceId: i.sourceId, path: m, error: new TypeError(`[markdown-explorer] an entry with ${p} was left out`) });
849
909
  try {
850
- return { status: "ok", entries: no(o, m, u.children !== void 0, d, (l) => E(u, l)) };
851
- } catch (l) {
852
- return ie(c, { ...i, error: l }), { status: "error", failure: { reason: "failed" } };
910
+ return { status: "ok", entries: fo(s, l, u.children !== void 0, d, (m) => b(u, m)) };
911
+ } catch (m) {
912
+ return ae(c, { ...i, error: m }), { status: "error", failure: { reason: "failed" } };
853
913
  }
854
- }, X = async (o, u, i) => {
914
+ }, X = async (s, u, i) => {
855
915
  let d;
856
916
  try {
857
- d = await o.tree(u);
917
+ d = await s.tree(u);
858
918
  } catch (p) {
859
- return { status: "error", failure: Y(p, { operation: "tree", sourceId: o.id }, u.signal, c) };
919
+ return { status: "error", failure: W(p, { operation: "tree", sourceId: s.id }, u.signal, c) };
860
920
  }
861
- const l = $(d, o, { operation: "tree", sourceId: o.id });
862
- return l.status === "ok" ? { status: "ok", entries: l.entries, loadedAt: i } : l;
863
- }, G = (o, u, i, d) => (l, p) => X(o, { principal: u, request: i, signal: l, refresh: d }, p), P = (o, u, i, d, l) => z.load(U(o, i), l, G(o, u, d, !1)), W = (o, u, i, d) => z.refresh(U(o, i), d.signal, G(o, u, d, !0)), K = (o, u) => {
921
+ const m = j(d, s, { operation: "tree", sourceId: s.id });
922
+ return m.status === "ok" ? { status: "ok", entries: m.entries, loadedAt: i } : m;
923
+ }, G = (s, u, i, d) => (m, p) => X(s, { principal: u, request: i, signal: m, refresh: d }, p), P = (s, u, i, d, m) => z.load(U(s, i), m, G(s, u, d, !1)), Y = (s, u, i, d) => z.refresh(U(s, i), d.signal, G(s, u, d, !0)), K = (s, u) => {
864
924
  if (g === void 0) return;
865
- const i = (d) => ie(c, { operation: "refresh", sourceId: o.id, error: d });
925
+ const i = (d) => ae(c, { operation: "refresh", sourceId: s.id, error: d });
866
926
  try {
867
- nt(g(u), i);
927
+ at(g(u), i);
868
928
  } catch (d) {
869
929
  i(d);
870
930
  }
871
- }, J = async (o, u, i, d) => {
872
- if (m.deniesPath(d) || !E(o, d)) return { status: "error", failure: { reason: "forbidden" } };
873
- const l = await _(o, i, d);
874
- if (l.status === "outside") return { status: "error", failure: { reason: "forbidden" } };
875
- if (l.status === "error") return { status: "error", failure: l.failure };
931
+ }, J = async (s, u, i, d) => {
932
+ if (l.deniesPath(d) || !b(s, d)) return { status: "error", failure: { reason: "forbidden" } };
933
+ const m = await _(s, i, d);
934
+ if (m.status === "outside") return { status: "error", failure: { reason: "forbidden" } };
935
+ if (m.status === "error") return { status: "error", failure: m.failure };
876
936
  let p;
877
937
  try {
878
- p = await u(i, d, l.readPath);
879
- } catch (b) {
880
- return { status: "error", failure: Y(b, { operation: "children", sourceId: o.id, path: d }, i.signal, c) };
938
+ p = await u(i, d, m.readPath);
939
+ } catch (T) {
940
+ return { status: "error", failure: W(T, { operation: "children", sourceId: s.id, path: d }, i.signal, c) };
881
941
  }
882
- return $(p, o, { operation: "children", sourceId: o.id, path: d });
883
- }, ae = async (o, u, i, d) => {
884
- const l = await _(o, i, d);
885
- if (l.status === "outside") return { status: "ok", ancestors: null };
886
- if (l.status === "error") return { status: "error", failure: l.failure };
942
+ return j(p, s, { operation: "children", sourceId: s.id, path: d });
943
+ }, ie = async (s, u, i, d) => {
944
+ const m = await _(s, i, d);
945
+ if (m.status === "outside") return { status: "ok", ancestors: null };
946
+ if (m.status === "error") return { status: "error", failure: m.failure };
887
947
  let p;
888
948
  try {
889
- p = await u(i, d, l.readPath, { maxDepth: t.revealDocument.maxDepth });
890
- } catch (b) {
891
- return { status: "error", failure: Y(b, { operation: "ancestors", sourceId: o.id, path: d }, i.signal, c) };
949
+ p = await u(i, d, m.readPath, { maxDepth: t.revealDocument.maxDepth });
950
+ } catch (T) {
951
+ return { status: "error", failure: W(T, { operation: "ancestors", sourceId: s.id, path: d }, i.signal, c) };
892
952
  }
893
953
  if (Array.isArray(p) && p.length > t.revealDocument.maxDepth) return { status: "ok", ancestors: null };
894
954
  try {
895
- return { status: "ok", ancestors: ro(p, d, m, (b) => E(o, b)) };
896
- } catch (b) {
897
- return ie(c, { operation: "ancestors", sourceId: o.id, path: d, error: b }), { status: "error", failure: { reason: "failed" } };
955
+ return { status: "ok", ancestors: lo(p, d, l, (T) => b(s, T)) };
956
+ } catch (T) {
957
+ return ae(c, { operation: "ancestors", sourceId: s.id, path: d, error: T }), { status: "error", failure: { reason: "failed" } };
898
958
  }
899
- }, H = async (o, u, i, d) => m.deniesPath(d) ? { status: "error", failure: { reason: "forbidden" } } : E(o, d) ? ae(o, u, i, d) : { status: "ok", ancestors: null }, te = async (o, u, i) => {
900
- if (m.deniesPath(i)) return { status: "error", failure: { reason: "forbidden" } };
901
- for (const d of [o, ...n.filter((l) => l !== o)]) {
959
+ }, H = async (s, u, i, d) => l.deniesPath(d) ? { status: "error", failure: { reason: "forbidden" } } : b(s, d) ? ie(s, u, i, d) : { status: "ok", ancestors: null }, te = async (s, u, i) => {
960
+ if (l.deniesPath(i)) return { status: "error", failure: { reason: "forbidden" } };
961
+ for (const d of [s, ...n.filter((m) => m !== s)]) {
902
962
  if (u.signal.aborted) break;
903
- const l = d.ancestors;
904
- if (l === void 0 || !E(d, i)) continue;
905
- const p = await ae(d, l, u, i);
963
+ const m = d.ancestors;
964
+ if (m === void 0 || !b(d, i)) continue;
965
+ const p = await ie(d, m, u, i);
906
966
  if (p.status === "ok" && p.ancestors !== null) return { status: "ok", source: d.id, ancestors: p.ancestors };
907
967
  }
908
- return ko;
909
- }, q = async (o, u, i) => {
910
- if (m.deniesPath(i)) return ee("forbidden");
911
- const d = await N(o, i);
968
+ return No;
969
+ }, q = async (s, u, i) => {
970
+ if (l.deniesPath(i)) return ee("forbidden");
971
+ const d = await N(s, i);
912
972
  if (d.status === "error") return { kind: "failure", failure: d.failure };
913
- let l;
973
+ let m;
914
974
  try {
915
- l = await e.document(o, i, d.readPath);
975
+ m = await e.document(s, i, d.readPath);
916
976
  } catch (A) {
917
- return { kind: "failure", failure: Y(A, { operation: "document", path: i }, o.signal, c) };
977
+ return { kind: "failure", failure: W(A, { operation: "document", path: i }, s.signal, c) };
918
978
  }
919
979
  let p;
920
980
  try {
921
- p = ao(l, (A) => Ge(t.dataPath, i, A), h !== void 0);
981
+ p = ho(m, (A) => Ye(t.dataPath, i, A), h !== void 0);
922
982
  } catch (A) {
923
- return ie(c, { operation: "document", path: i, error: A }), ee("failed");
983
+ return ae(c, { operation: "document", path: i, error: A }), ee("failed");
924
984
  }
925
985
  if (p.kind !== "unsanitized-markdown") return p;
926
- const b = await O(p.html, { scope: u, signal: o.signal });
927
- return b.status === "sanitized" ? { kind: "markdown", name: p.name, htmlContent: b.html, headings: p.headings, edit: p.edit } : (b.cause !== null && ie(c, { operation: "document", path: i, error: b.cause }), ee(b.reason));
928
- }, ne = async (o) => {
929
- if (e.notices === void 0) return Le;
986
+ const T = await O(p.html, { scope: u, signal: s.signal });
987
+ return T.status === "sanitized" ? { kind: "markdown", name: p.name, htmlContent: T.html, headings: p.headings, edit: p.edit } : (T.cause !== null && ae(c, { operation: "document", path: i, error: T.cause }), ee(T.reason));
988
+ }, ne = async (s) => {
989
+ if (e.notices === void 0) return je;
930
990
  try {
931
- return yo(await e.notices(o));
991
+ return Oo(await e.notices(s));
932
992
  } catch (u) {
933
- return Y(u, { operation: "notices" }, o.signal, c), Le;
993
+ return W(u, { operation: "notices" }, s.signal, c), je;
934
994
  }
935
- }, de = async (o, u, i) => {
995
+ }, de = async (s, u, i) => {
936
996
  const d = ue(u, ce.path);
937
997
  if (d === null || !re(d)) return L({ reason: "invalid" }, i);
938
- const l = kr(u);
939
- if (l === null) return L({ reason: "invalid" }, i);
940
- if (m.deniesPath(d))
941
- return Ie(c, { operation: "asset", path: d }), L({ reason: "forbidden" }, i);
942
- const p = await N(o, d);
998
+ const m = Ir(u);
999
+ if (m === null) return L({ reason: "invalid" }, i);
1000
+ if (l.deniesPath(d))
1001
+ return Me(c, { operation: "asset", path: d }), L({ reason: "forbidden" }, i);
1002
+ const p = await N(s, d);
943
1003
  if (p.status === "error") return L(p.failure, i);
944
1004
  try {
945
- const b = l === "file", A = await e.asset(o, d, p.readPath, { redirect: b }), j = b ? ho(A) : ze(A);
946
- return "kind" in j ? pn(j.url, i) : await fn(o.request, j, i, l);
947
- } catch (b) {
948
- return L(Y(b, { operation: "asset", path: d }, o.signal, c), i);
1005
+ const T = m === "file", A = await e.asset(s, d, p.readPath, { redirect: T }), $ = T ? So(A) : De(A);
1006
+ return "kind" in $ ? kn($.url, i) : m === "text" ? await bn(s.request, $, i, t.legacyTextEncoding) : await yn(s.request, $, i);
1007
+ } catch (T) {
1008
+ return L(W(T, { operation: "asset", path: d }, s.signal, c), i);
949
1009
  }
950
- }, Ee = async (o, u) => {
951
- if (m.deniesPath(u))
952
- return Ie(c, { operation: "text", path: u }), ee("forbidden");
953
- const i = await N(o, u);
1010
+ }, be = async (s, u) => {
1011
+ if (l.deniesPath(u))
1012
+ return Me(c, { operation: "text", path: u }), ee("forbidden");
1013
+ const i = await N(s, u);
954
1014
  if (i.status === "error") return { kind: "failure", failure: i.failure };
955
1015
  try {
956
- const d = ze(await e.asset(o, u, i.readPath, { redirect: !1 })), l = await bn(d, S, t.legacyTextEncoding);
957
- return l === null ? ee("unsupported") : { kind: "text", name: d.name, text: l.text, truncated: l.truncated, url: Ge(t.dataPath, u, d.version) };
1016
+ const d = De(await e.asset(s, u, i.readPath, { redirect: !1 })), m = await _n(d, k, t.legacyTextEncoding);
1017
+ return m === null ? ee("unsupported") : { kind: "text", name: d.name, text: m.text, truncated: m.truncated, url: Ye(t.dataPath, u, d.version) };
958
1018
  } catch (d) {
959
- return { kind: "failure", failure: Y(d, { operation: "text", path: u }, o.signal, c) };
1019
+ return { kind: "failure", failure: W(d, { operation: "text", path: u }, s.signal, c) };
960
1020
  }
961
- }, he = async (o, u, i) => m.deniesPath(i) ? (Ie(c, { operation: u, path: i }), { status: "error", failure: { reason: "forbidden" } }) : N(o, i), Kt = async (o, u, i) => {
962
- const d = await he(u, "edit", i);
1021
+ }, ye = async (s, u, i) => l.deniesPath(i) ? (Me(c, { operation: u, path: i }), { status: "error", failure: { reason: "forbidden" } }) : N(s, i), or = async (s, u, i) => {
1022
+ const d = await ye(u, "edit", i);
963
1023
  if (d.status === "error") return { kind: "failure", failure: d.failure };
964
1024
  try {
965
- return lo(await o.source(u, i, d.readPath), y);
966
- } catch (l) {
967
- return { kind: "failure", failure: Y(l, { operation: "edit", path: i }, u.signal, c) };
1025
+ return Eo(await s.source(u, i, d.readPath), y);
1026
+ } catch (m) {
1027
+ return { kind: "failure", failure: W(m, { operation: "edit", path: i }, u.signal, c) };
968
1028
  }
969
- }, Vt = async (o, u, i, d, l) => {
970
- const p = await he(u, "save", i);
1029
+ }, sr = async (s, u, i, d, m) => {
1030
+ const p = await ye(u, "save", i);
971
1031
  if (p.status === "error") return { kind: "failure", failure: p.failure };
972
1032
  try {
973
- return fo(await o.save(u, i, p.readPath, { text: l, baseVersion: d }), y);
974
- } catch (b) {
975
- return { kind: "failure", failure: Y(b, { operation: "save", path: i }, u.signal, c) };
1033
+ return bo(await s.save(u, i, p.readPath, { text: m, baseVersion: d }), y);
1034
+ } catch (T) {
1035
+ return { kind: "failure", failure: W(T, { operation: "save", path: i }, u.signal, c) };
976
1036
  }
977
- }, Zt = async (o, u, i, d, l) => {
978
- const p = await he(u, "preview", d);
1037
+ }, ar = async (s, u, i, d, m) => {
1038
+ const p = await ye(u, "preview", d);
979
1039
  if (p.status === "error") return { kind: "failure", failure: p.failure };
980
- let b;
1040
+ let T;
981
1041
  try {
982
- b = mo(await o.preview(u, d, p.readPath, l));
983
- } catch (j) {
984
- return { kind: "failure", failure: Y(j, { operation: "preview", path: d }, u.signal, c) };
1042
+ T = To(await s.preview(u, d, p.readPath, m));
1043
+ } catch ($) {
1044
+ return { kind: "failure", failure: W($, { operation: "preview", path: d }, u.signal, c) };
985
1045
  }
986
- if ("kind" in b) return b.kind === "failure" ? b : ee("failed");
987
- const A = await O(b.html, { scope: i, signal: u.signal });
988
- return A.status === "sanitized" ? { kind: "preview", htmlContent: A.html, headings: b.headings } : (A.cause !== null && ie(c, { operation: "preview", path: d, error: A.cause }), ee(A.reason));
989
- }, Qt = async (o, u, i) => {
990
- const d = await he(u, "revisions", i);
1046
+ if ("kind" in T) return T.kind === "failure" ? T : ee("failed");
1047
+ const A = await O(T.html, { scope: i, signal: u.signal });
1048
+ return A.status === "sanitized" ? { kind: "preview", htmlContent: A.html, headings: T.headings } : (A.cause !== null && ae(c, { operation: "preview", path: d, error: A.cause }), ee(A.reason));
1049
+ }, ir = async (s, u, i) => {
1050
+ const d = await ye(u, "revisions", i);
991
1051
  if (d.status === "error") return { kind: "failure", failure: d.failure };
992
1052
  try {
993
- return { kind: "revisions", revisions: po(await o.revisions(u, i, d.readPath)) };
994
- } catch (l) {
995
- return { kind: "failure", failure: Y(l, { operation: "revisions", path: i }, u.signal, c) };
1053
+ return { kind: "revisions", revisions: ko(await s.revisions(u, i, d.readPath)) };
1054
+ } catch (m) {
1055
+ return { kind: "failure", failure: W(m, { operation: "revisions", path: i }, u.signal, c) };
996
1056
  }
997
- }, qt = async (o, u, i, d) => {
998
- const l = await he(u, "revision", i);
999
- if (l.status === "error") return { kind: "failure", failure: l.failure };
1057
+ }, cr = async (s, u, i, d) => {
1058
+ const m = await ye(u, "revision", i);
1059
+ if (m.status === "error") return { kind: "failure", failure: m.failure };
1000
1060
  try {
1001
- return { kind: "revision", id: d, text: wo(await o.revision(u, i, l.readPath, d), y) };
1061
+ return { kind: "revision", id: d, text: xo(await s.revision(u, i, m.readPath, d), y) };
1002
1062
  } catch (p) {
1003
- return { kind: "failure", failure: Y(p, { operation: "revision", path: i }, u.signal, c) };
1063
+ return { kind: "failure", failure: W(p, { operation: "revision", path: i }, u.signal, c) };
1004
1064
  }
1005
- }, er = async (o, u, i, d, l, p) => {
1006
- const b = ue(l, ce.path);
1007
- if (b === null || !re(b)) return L({ reason: "invalid" }, p);
1008
- if (u === "edit") return Z(200, JSON.stringify(await Kt(o, i, b)), p);
1009
- if (u === "revisions") return Z(200, JSON.stringify(await Qt(o, i, b)), p);
1065
+ }, ur = async (s, u, i, d, m, p) => {
1066
+ const T = ue(m, ce.path);
1067
+ if (T === null || !re(T)) return L({ reason: "invalid" }, p);
1068
+ if (u === "edit") return Z(200, JSON.stringify(await or(s, i, T)), p);
1069
+ if (u === "revisions") return Z(200, JSON.stringify(await ir(s, i, T)), p);
1010
1070
  if (u === "revision") {
1011
- const oe = ue(l, ce.revision);
1012
- return ge(oe) ? Z(200, JSON.stringify(await qt(o, i, b, oe)), p) : L({ reason: "invalid" }, p);
1071
+ const oe = ue(m, ce.revision);
1072
+ return Ee(oe) ? Z(200, JSON.stringify(await cr(s, i, T, oe)), p) : L({ reason: "invalid" }, p);
1013
1073
  }
1014
- const A = ue(l, ce.base);
1015
- if (u === "save" && !ge(A)) return L({ reason: "invalid" }, p);
1016
- const j = await Mo(i.request, y);
1017
- return j.status === "error" ? L(j.failure, p) : u === "preview" ? Z(200, JSON.stringify(await Zt(o, i, d, b, j.text)), p) : Z(200, JSON.stringify(await Vt(o, i, b, A, j.text)), p);
1018
- }, tr = async ({ request: o, url: u, params: i }) => {
1019
- const d = ht(await I(o, mt)), l = pt(d.headers);
1020
- if (l.set("Cache-Control", Ft), d.status === "signed-out") throw yt("signedOutPage", F(o, l));
1021
- if (d.status === "forbidden") throw w === void 0 ? Ye(null, { status: 403, headers: l }) : yt("forbiddenPage", w(o, l));
1022
- const p = _r(a, i["*"], u.searchParams);
1023
- if (p.kind === "redirect") throw zr(p.href, { headers: l });
1024
- const { location: b } = p, { principal: A } = d, j = gt(r, C(A)), oe = D.get(b.source);
1025
- if (oe === void 0) throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(b.source)}`);
1026
- const ye = { signal: o.signal, timeoutMs: f, late: null, handOverMs: f }, se = {
1027
- scope: j,
1074
+ const A = ue(m, ce.base);
1075
+ if (u === "save" && !Ee(A)) return L({ reason: "invalid" }, p);
1076
+ const $ = await Bo(i.request, y);
1077
+ return $.status === "error" ? L($.failure, p) : u === "preview" ? Z(200, JSON.stringify(await ar(s, i, d, T, $.text)), p) : Z(200, JSON.stringify(await sr(s, i, T, A, $.text)), p);
1078
+ }, dr = async ({ request: s, url: u, params: i }) => {
1079
+ const d = Et(await I(s, ht)), m = yt(d.headers);
1080
+ if (m.set("Cache-Control", Zt), d.status === "signed-out") throw bt("signedOutPage", F(s, m));
1081
+ if (d.status === "forbidden") throw w === void 0 ? Ke(null, { status: 403, headers: m }) : bt("forbiddenPage", w(s, m));
1082
+ const p = zr(a, i["*"], u.searchParams);
1083
+ if (p.kind === "redirect") throw Gr(p.href, { headers: m });
1084
+ const { location: T } = p, { principal: A } = d, $ = Tt(r, D(A)), oe = C.get(T.source);
1085
+ if (oe === void 0) throw new RangeError(`[markdown-explorer] no source for ${JSON.stringify(T.source)}`);
1086
+ const ge = { signal: s.signal, timeoutMs: f, late: null, handOverMs: f }, se = {
1087
+ scope: $,
1028
1088
  sources: n.map((B) => ({ id: B.id, label: M(B, A) })),
1029
- settings: Ar(Nr(o.headers.get("Cookie"), t.settingsCookie), R),
1030
- tree: b.view === "single" ? null : {
1031
- sourceId: b.source,
1032
- result: Ne(ye, (B) => P(oe, A, j, o, B).then((V) => V.result))
1089
+ settings: Cr(Dr(s.headers.get("Cookie"), t.settingsCookie), R),
1090
+ tree: T.view === "single" ? null : {
1091
+ sourceId: T.source,
1092
+ result: Pe(ge, (B) => P(oe, A, $, s, B).then((V) => V.result))
1033
1093
  },
1034
- documents: Ao(b).map((B) => ({ path: B, document: Ne(ye, (V) => q({ principal: A, request: o, signal: V, refresh: !1 }, j, B)) })),
1035
- notices: Ne({ signal: o.signal, timeoutMs: f, late: Le, handOverMs: 0 }, (B) => ne({ principal: A, request: o, signal: B, refresh: !1 }))
1094
+ documents: zo(T).map((B) => ({ path: B, document: Pe(ge, (V) => q({ principal: A, request: s, signal: V, refresh: !1 }, $, B)) })),
1095
+ notices: Pe({ signal: s.signal, timeoutMs: f, late: je, handOverMs: 0 }, (B) => ne({ principal: A, request: s, signal: B, refresh: !1 }))
1036
1096
  };
1037
- return Ye(se, { headers: l });
1038
- }, Fe = async (o, u) => {
1039
- const i = ht(await I(o, u));
1040
- return { authentication: i, headers: pt(i.headers) };
1041
- }, rr = async (o, u, i) => {
1097
+ return Ke(se, { headers: m });
1098
+ }, Xe = async (s, u) => {
1099
+ const i = Et(await I(s, u));
1100
+ return { authentication: i, headers: yt(i.headers) };
1101
+ }, lr = async (s, u, i) => {
1042
1102
  let d;
1043
1103
  try {
1044
- d = await Fe(u, mt);
1104
+ d = await Xe(u, ht);
1045
1105
  } catch (V) {
1046
- return L(Y(wt(V), { operation: "authenticate" }, u.signal, c));
1106
+ return L(W(gt(V), { operation: "authenticate" }, u.signal, c));
1047
1107
  }
1048
- const { authentication: l, headers: p } = d;
1049
- if (l.status === "signed-out") return L({ reason: "unauthorized" }, p);
1050
- if (l.status === "forbidden") return L({ reason: "forbidden" }, p);
1051
- const { principal: b } = l;
1052
- if (o === "asset") return de({ principal: b, request: u, signal: u.signal, refresh: !1 }, i, p);
1053
- const A = gt(r, C(b));
1054
- p.set(Tr, A);
1055
- const j = { principal: b, request: u, signal: u.signal, refresh: !1 }, oe = () => L({ reason: "invalid" }, p);
1056
- if (o === "document") {
1108
+ const { authentication: m, headers: p } = d;
1109
+ if (m.status === "signed-out") return L({ reason: "unauthorized" }, p);
1110
+ if (m.status === "forbidden") return L({ reason: "forbidden" }, p);
1111
+ const { principal: T } = m;
1112
+ if (s === "asset") return de({ principal: T, request: u, signal: u.signal, refresh: !1 }, i, p);
1113
+ const A = Tt(r, D(T));
1114
+ p.set(Nr, A);
1115
+ const $ = { principal: T, request: u, signal: u.signal, refresh: !1 }, oe = () => L({ reason: "invalid" }, p);
1116
+ if (s === "document") {
1057
1117
  const V = ue(i, ce.path);
1058
1118
  if (V === null || !re(V)) return oe();
1059
- const Je = u.headers.has(Ce);
1060
- return Je && !bt(u) ? L({ reason: "forbidden" }, p) : Z(200, JSON.stringify(await q({ ...j, refresh: Je }, A, V)), p);
1119
+ const We = u.headers.has(Be);
1120
+ return We && !xt(u) ? L({ reason: "forbidden" }, p) : Z(200, JSON.stringify(await q({ ...$, refresh: We }, A, V)), p);
1061
1121
  }
1062
- if (o === "text") {
1122
+ if (s === "text") {
1063
1123
  const V = ue(i, ce.path);
1064
- return V === null || !re(V) ? oe() : Z(200, JSON.stringify(await Ee(j, V)), p);
1124
+ return V === null || !re(V) ? oe() : Z(200, JSON.stringify(await be($, V)), p);
1065
1125
  }
1066
- if (o === "edit" || o === "save" || o === "preview" || o === "revisions" || o === "revision")
1067
- return h === void 0 ? L({ reason: "not-found" }, p) : er(h, o, j, A, i, p);
1068
- const ye = ue(i, ce.source), se = ue(i, ce.path);
1069
- if (ye === null || (o === "children" || o === "ancestors" || o === "reveal") && (se === null || !re(se))) return oe();
1070
- const B = D.get(ye);
1126
+ if (s === "edit" || s === "save" || s === "preview" || s === "revisions" || s === "revision")
1127
+ return h === void 0 ? L({ reason: "not-found" }, p) : ur(h, s, $, A, i, p);
1128
+ const ge = ue(i, ce.source), se = ue(i, ce.path);
1129
+ if (ge === null || (s === "children" || s === "ancestors" || s === "reveal") && (se === null || !re(se))) return oe();
1130
+ const B = C.get(ge);
1071
1131
  if (B === void 0) return L({ reason: "not-found" }, p);
1072
- if (o === "tree") return Z(200, (await P(B, b, A, u, u.signal)).json, p);
1073
- if (o === "refresh") {
1074
- const V = await W(B, b, A, u);
1132
+ if (s === "tree") return Z(200, (await P(B, T, A, u, u.signal)).json, p);
1133
+ if (s === "refresh") {
1134
+ const V = await Y(B, T, A, u);
1075
1135
  return u.signal.aborted || K(B, U(B, A)), Z(200, V.json, p);
1076
1136
  }
1077
- return o === "ancestors" ? B.ancestors === void 0 || se === null ? L({ reason: "not-found" }, p) : Z(200, JSON.stringify(await H(B, B.ancestors, j, se)), p) : o === "reveal" ? se === null ? oe() : Z(200, JSON.stringify(await te(B, j, se)), p) : B.children === void 0 || se === null ? L({ reason: "not-found" }, p) : Z(200, JSON.stringify(await J(B, B.children, j, se)), p);
1078
- }, nr = async (o) => {
1079
- const { authentication: u, headers: i } = await Fe(o, So);
1137
+ return s === "ancestors" ? B.ancestors === void 0 || se === null ? L({ reason: "not-found" }, p) : Z(200, JSON.stringify(await H(B, B.ancestors, $, se)), p) : s === "reveal" ? se === null ? oe() : Z(200, JSON.stringify(await te(B, $, se)), p) : B.children === void 0 || se === null ? L({ reason: "not-found" }, p) : Z(200, JSON.stringify(await J(B, B.children, $, se)), p);
1138
+ }, fr = async (s) => {
1139
+ const { authentication: u, headers: i } = await Xe(s, Io);
1080
1140
  if (!i.keys().next().done) throw new TypeError("[markdown-explorer] authenticate returned headers in read-only mode; a read-only authentication must only read the session (none was forwarded)");
1081
1141
  return u.status === "signed-in";
1082
- }, Ue = t.embeds.linkCardEndpoint === null ? null : jr({ authorize: nr }), or = async (o, u) => {
1142
+ }, Je = t.embeds.linkCardEndpoint === null ? null : Jr({ authorize: fr }), mr = async (s, u) => {
1083
1143
  try {
1084
- return await o(u);
1144
+ return await s(u);
1085
1145
  } catch (i) {
1086
- return L(Y(wt(i), { operation: "authenticate" }, u.signal, c));
1146
+ return L(W(gt(i), { operation: "authenticate" }, u.signal, c));
1087
1147
  }
1088
- }, Xe = async (o, u, i) => {
1089
- if (new URL(o.url).pathname.endsWith(".data")) return L({ reason: "not-found" });
1090
- if (!yr(i)) return L({ reason: "not-found" });
1148
+ }, Ge = async (s, u, i) => {
1149
+ if (new URL(s.url).pathname.endsWith(".data")) return L({ reason: "not-found" });
1150
+ if (!Rr(i)) return L({ reason: "not-found" });
1091
1151
  if (i === "link-card") {
1092
- if (Ue === null) return L({ reason: "not-found" });
1093
- const l = Et(o, i);
1094
- return l !== null ? l : or(Ue, o);
1152
+ if (Je === null) return L({ reason: "not-found" });
1153
+ const m = kt(s, i);
1154
+ return m !== null ? m : mr(Je, s);
1095
1155
  }
1096
- if (Io.has(i) && h === void 0) return L({ reason: "not-found" });
1097
- const d = Et(o, i);
1156
+ if (Do.has(i) && h === void 0) return L({ reason: "not-found" });
1157
+ const d = kt(s, i);
1098
1158
  if (d !== null) return d;
1099
- if (i === "refresh" && !bt(o)) return L({ reason: "forbidden" });
1100
- if ((i === "save" || i === "preview") && !Po(o)) return L({ reason: "forbidden" });
1159
+ if (i === "refresh" && !xt(s)) return L({ reason: "forbidden" });
1160
+ if ((i === "save" || i === "preview") && !Ho(s)) return L({ reason: "forbidden" });
1101
1161
  try {
1102
- return await rr(i, o, u.searchParams);
1103
- } catch (l) {
1104
- return L(Y(l, { operation: i }, o.signal, c));
1162
+ return await lr(i, s, u.searchParams);
1163
+ } catch (m) {
1164
+ return L(W(m, { operation: i }, s.signal, c));
1105
1165
  }
1106
1166
  };
1107
1167
  return Object.freeze({
1108
- loader: tr,
1109
- headers: $o,
1110
- dataLoader: ({ request: o, url: u, params: i }) => Xe(o, u, i["*"]),
1111
- dataAction: ({ request: o, url: u, params: i }) => Xe(o, u, i["*"]),
1112
- forgetTree: (o) => {
1113
- if (typeof o != "string") throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof o}`);
1114
- z.forget(o);
1168
+ loader: dr,
1169
+ headers: Uo,
1170
+ dataLoader: ({ request: s, url: u, params: i }) => Ge(s, u, i["*"]),
1171
+ dataAction: ({ request: s, url: u, params: i }) => Ge(s, u, i["*"]),
1172
+ forgetTree: (s) => {
1173
+ if (typeof s != "string") throw new TypeError(`[markdown-explorer] forgetTree needs the string key onTreeRefreshed received; got ${typeof s}`);
1174
+ z.forget(s);
1115
1175
  }
1116
1176
  });
1117
- }, ke = Object.freeze({ maxEntries: 2e4, maxDocumentBytes: 2 * 1024 * 1024, textPreviewBytes: 8 * 1024, walkConcurrency: 8 }), jo = /* @__PURE__ */ new Set(["md", "markdown", "mdx"]), Tt = "image/svg+xml", Ut = new Map([
1177
+ }, Se = Object.freeze({ maxEntries: 2e4, maxDocumentBytes: 2 * 1024 * 1024, textPreviewBytes: 8 * 1024, walkConcurrency: 8 }), Xo = /* @__PURE__ */ new Set(["md", "markdown", "mdx"]), St = "image/svg+xml", Qt = new Map([
1118
1178
  ...[
1119
1179
  ["png", "image/png"],
1120
1180
  ["jpg", "image/jpeg"],
1121
1181
  ["jpeg", "image/jpeg"],
1122
1182
  ["gif", "image/gif"],
1123
- ["svg", Tt],
1183
+ ["svg", St],
1124
1184
  ["webp", "image/webp"],
1125
1185
  ["ico", "image/x-icon"],
1126
1186
  ["bmp", "image/bmp"],
1127
1187
  ["tif", "image/tiff"],
1128
1188
  ["tiff", "image/tiff"],
1129
1189
  ["avif", "image/avif"]
1130
- ].map(([e, t]) => [e, { kind: "image", imageType: t === Tt ? "svg" : "raster", contentType: t }]),
1190
+ ].map(([e, t]) => [e, { kind: "image", imageType: t === St ? "svg" : "raster", contentType: t }]),
1131
1191
  ...[
1132
1192
  ["mp4", "video/mp4"],
1133
1193
  ["m4v", "video/mp4"],
@@ -1149,11 +1209,11 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
1149
1209
  ["wma", "audio/x-ms-wma"]
1150
1210
  ].map(([e, t]) => [e, { kind: "media", mediaType: "audio", contentType: t }]),
1151
1211
  ["pdf", { kind: "media", mediaType: "pdf", contentType: "application/pdf" }]
1152
- ]), zo = /* @__PURE__ */ new Map([
1212
+ ]), Jo = /* @__PURE__ */ new Map([
1153
1213
  ["csv", "csv"],
1154
1214
  ["tsv", "tsv"],
1155
1215
  ["tab", "tsv"]
1156
- ]), Do = /* @__PURE__ */ new Set([
1216
+ ]), Go = /* @__PURE__ */ new Set([
1157
1217
  "txt",
1158
1218
  "text",
1159
1219
  "log",
@@ -1276,7 +1336,7 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
1276
1336
  "eslintrc",
1277
1337
  "babelrc",
1278
1338
  "mailmap"
1279
- ]), Co = /* @__PURE__ */ new Set([
1339
+ ]), Wo = /* @__PURE__ */ new Set([
1280
1340
  "readme",
1281
1341
  "license",
1282
1342
  "licence",
@@ -1297,19 +1357,19 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
1297
1357
  "jenkinsfile",
1298
1358
  "brewfile",
1299
1359
  "codeowners"
1300
- ]), Xt = typeof we.O_NOFOLLOW == "number" ? we.O_NOFOLLOW : 0, Jt = typeof we.O_NONBLOCK == "number" ? we.O_NONBLOCK : 0, kt = (e) => `${e.size}-${e.mtimeNs}`, Ho = (e) => e !== "" && e !== "." && e !== ".." && !e.includes(":") && !e.endsWith(".") && !e.endsWith(" "), St = (e) => re(e) && e === e.normalize("NFC") && e.split("/").every(Ho), Gt = (e) => {
1360
+ ]), qt = typeof he.O_NOFOLLOW == "number" ? he.O_NOFOLLOW : 0, er = typeof he.O_NONBLOCK == "number" ? he.O_NONBLOCK : 0, Ot = (e) => `${e.size}-${e.mtimeNs}`, Yo = (e) => e !== "" && e !== "." && e !== ".." && !e.includes(":") && !e.endsWith(".") && !e.endsWith(" "), Rt = (e) => re(e) && e === e.normalize("NFC") && e.split("/").every(Yo), tr = (e) => {
1301
1361
  const t = e.toLowerCase(), r = t.lastIndexOf(".");
1302
1362
  return r < 0 ? "" : t.slice(r + 1);
1303
- }, Bo = (e) => {
1304
- const t = Gt(e);
1305
- if (jo.has(t)) return { kind: "markdown" };
1306
- const r = Ut.get(t);
1363
+ }, Ko = (e) => {
1364
+ const t = tr(e);
1365
+ if (Xo.has(t)) return { kind: "markdown" };
1366
+ const r = Qt.get(t);
1307
1367
  if (r !== void 0) return r.kind === "image" ? { kind: "image", imageType: r.imageType } : { kind: "media", mediaType: r.mediaType };
1308
- const n = zo.get(t);
1368
+ const n = Jo.get(t);
1309
1369
  if (n !== void 0) return { kind: "spreadsheet", format: n };
1310
1370
  const a = e.toLowerCase();
1311
- return Do.has(t) || !a.includes(".") && Co.has(a) ? { kind: "text" } : { kind: "file" };
1312
- }, De = (e) => {
1371
+ return Go.has(t) || !a.includes(".") && Wo.has(a) ? { kind: "text" } : { kind: "file" };
1372
+ }, He = (e) => {
1313
1373
  switch (typeof e == "object" && e !== null ? e.code : void 0) {
1314
1374
  case "ENOENT":
1315
1375
  case "ENOTDIR":
@@ -1325,41 +1385,41 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
1325
1385
  default:
1326
1386
  return null;
1327
1387
  }
1328
- }, Yt = (e) => {
1329
- const t = De(e);
1330
- return t === null ? e : new Oe(t);
1331
- }, Wt = (e) => {
1388
+ }, rr = (e) => {
1389
+ const t = He(e);
1390
+ return t === null ? e : new _e(t);
1391
+ }, nr = (e) => {
1332
1392
  const t = typeof e == "object" && e !== null ? e.code : void 0;
1333
1393
  return t === "EACCES" || t === "EPERM" || t === "ENOENT" || t === "ENOTDIR";
1334
- }, Fo = async (e) => {
1394
+ }, Vo = async (e) => {
1335
1395
  try {
1336
- return Math.trunc((await It(e)).mtimeMs);
1396
+ return Math.trunc((await Lt(e)).mtimeMs);
1337
1397
  } catch (t) {
1338
- if (Wt(t)) return;
1398
+ if (nr(t)) return;
1339
1399
  throw t;
1340
1400
  }
1341
- }, xt = async (e, t) => {
1401
+ }, vt = async (e, t) => {
1342
1402
  const r = [];
1343
1403
  for await (const n of e.createReadStream({ start: 0, end: t - 1, autoClose: !1 }))
1344
1404
  r.push(n);
1345
1405
  return Buffer.concat(r);
1346
- }, Uo = (e, t) => e !== null ? { start: e.offset, end: e.offset + e.length - 1 } : t === 0n ? {} : { start: 0, end: Number(t) - 1 }, Xo = async (e, t, r, n) => {
1406
+ }, Zo = (e, t) => e !== null ? { start: e.offset, end: e.offset + e.length - 1 } : t === 0n ? {} : { start: 0, end: Number(t) - 1 }, Qo = async (e, t, r, n) => {
1347
1407
  let a;
1348
1408
  try {
1349
- a = await Nt(e, we.O_RDONLY | Xt | Jt);
1409
+ a = await $t(e, he.O_RDONLY | qt | er);
1350
1410
  const f = await a.stat({ bigint: !0 });
1351
- if (!f.isFile() || f.ino !== t.ino || f.dev !== t.dev || f.size !== t.size || f.mtimeNs !== t.mtimeNs) throw new Oe("not-found");
1411
+ if (!f.isFile() || f.ino !== t.ino || f.dev !== t.dev || f.size !== t.size || f.mtimeNs !== t.mtimeNs) throw new _e("not-found");
1352
1412
  } catch (f) {
1353
- throw await a?.close(), Yt(f);
1413
+ throw await a?.close(), rr(f);
1354
1414
  }
1355
- const s = a.createReadStream(Uo(r, t.size)), c = Gr.toWeb(s), m = () => {
1356
- s.destroy(n.reason);
1415
+ const o = a.createReadStream(Zo(r, t.size)), c = tn.toWeb(o), l = () => {
1416
+ o.destroy(n.reason);
1357
1417
  };
1358
- return n.aborted ? m() : n.addEventListener("abort", m, { once: !0 }), c;
1359
- }, Jo = (e, t) => {
1360
- const r = Mr.compare(e, t);
1418
+ return n.aborted ? l() : n.addEventListener("abort", l, { once: !0 }), c;
1419
+ }, qo = (e, t) => {
1420
+ const r = Fr.compare(e, t);
1361
1421
  return r !== 0 ? r : e === t ? 0 : e < t ? -1 : 1;
1362
- }, Go = (e) => {
1422
+ }, es = (e) => {
1363
1423
  let t = 0;
1364
1424
  const r = [];
1365
1425
  return async (n) => {
@@ -1371,86 +1431,86 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
1371
1431
  a === void 0 ? t -= 1 : a();
1372
1432
  }
1373
1433
  };
1374
- }, Yo = (e, t) => {
1434
+ }, ts = (e, t) => {
1375
1435
  if (e.isSymbolicLink()) return "symbolic-link";
1376
1436
  if (!(e.isDirectory() || e.isFile())) return "special-file";
1377
1437
  const { name: r } = e;
1378
1438
  return r !== r.normalize("NFC") ? "not-nfc" : r.includes(":") ? "colon" : r.endsWith(".") || r.endsWith(" ") ? "trailing-dot-or-space" : re(r) ? re(t) ? null : "path-too-long" : "control-character-or-backslash";
1379
- }, Wo = /* @__PURE__ */ new Set(["id", "label", "root", "pathPrefix", "parse", "deny", "maxEntries", "maxDocumentBytes", "textPreviewBytes", "legacyTextEncoding", "walkConcurrency", "cacheScope", "reportSkipped"]), Se = (e, t, r) => {
1439
+ }, rs = /* @__PURE__ */ new Set(["id", "label", "root", "pathPrefix", "parse", "deny", "maxEntries", "maxDocumentBytes", "textPreviewBytes", "legacyTextEncoding", "walkConcurrency", "cacheScope", "reportSkipped"]), Oe = (e, t, r) => {
1380
1440
  if (t === void 0) return r;
1381
1441
  if (typeof t != "number" || !Number.isSafeInteger(t) || t <= 0) throw new RangeError(`[markdown-explorer] ${e} must be a positive integer; got ${String(t)}`);
1382
1442
  return t;
1383
- }, ds = (e) => {
1443
+ }, gs = (e) => {
1384
1444
  if (e === null || typeof e != "object") throw new TypeError("[markdown-explorer] createFileSystemSource needs an options object");
1385
- for (const E of Object.keys(e))
1386
- if (!Wo.has(E)) throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(E)}`);
1445
+ for (const b of Object.keys(e))
1446
+ if (!rs.has(b)) throw new TypeError(`[markdown-explorer] createFileSystemSource does not know the option ${JSON.stringify(b)}`);
1387
1447
  const { id: t, label: r, root: n, parse: a } = e;
1388
1448
  if (typeof t != "string" || t === "") throw new TypeError("[markdown-explorer] a file-system source needs a non-empty id");
1389
1449
  if (typeof r != "string" || r.trim() === "") throw new TypeError("[markdown-explorer] a file-system source needs a non-blank label");
1390
1450
  if (typeof a != "function") throw new TypeError("[markdown-explorer] a file-system source needs a parse function");
1391
- if (typeof n != "string" || !We(n)) throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);
1392
- let s;
1451
+ if (typeof n != "string" || !Ve(n)) throw new RangeError(`[markdown-explorer] root must be an absolute path; got ${JSON.stringify(n)}`);
1452
+ let o;
1393
1453
  try {
1394
- s = Cr(n).isDirectory();
1395
- } catch (E) {
1396
- throw new RangeError(`[markdown-explorer] root does not exist: ${n}`, { cause: E });
1454
+ o = Yr(n).isDirectory();
1455
+ } catch (b) {
1456
+ throw new RangeError(`[markdown-explorer] root does not exist: ${n}`, { cause: b });
1397
1457
  }
1398
- if (!s) throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);
1399
- const c = Hr(n), m = e.pathPrefix;
1400
- if (typeof m != "string") throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');
1401
- if (m !== "" && !(m.endsWith("/") && St(m.slice(0, -1))))
1402
- throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(m)}`);
1403
- const f = vt(e.deny), S = Se("maxEntries", e.maxEntries, ke.maxEntries), h = Se("maxDocumentBytes", e.maxDocumentBytes, ke.maxDocumentBytes), y = Se("textPreviewBytes", e.textPreviewBytes, ke.textPreviewBytes), T = e.legacyTextEncoding;
1404
- if (T != null && typeof T != "string") throw new TypeError("[markdown-explorer] legacyTextEncoding must be a string or null");
1405
- const v = typeof T == "string" ? Pr(T) : null, z = Se("walkConcurrency", e.walkConcurrency, ke.walkConcurrency), x = e.cacheScope === void 0 ? "principal" : e.cacheScope;
1406
- if (x !== "principal" && x !== "shared") throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(x)}`);
1458
+ if (!o) throw new RangeError(`[markdown-explorer] root is not a directory: ${n}`);
1459
+ const c = Kr(n), l = e.pathPrefix;
1460
+ if (typeof l != "string") throw new TypeError('[markdown-explorer] pathPrefix is required: "" for a source over the whole root, or relative segments ending with "/"');
1461
+ if (l !== "" && !(l.endsWith("/") && Rt(l.slice(0, -1))))
1462
+ throw new RangeError(`[markdown-explorer] pathPrefix must be empty or relative segments ending with "/"; got ${JSON.stringify(l)}`);
1463
+ const f = Nt(e.deny), k = Oe("maxEntries", e.maxEntries, Se.maxEntries), h = Oe("maxDocumentBytes", e.maxDocumentBytes, Se.maxDocumentBytes), y = Oe("textPreviewBytes", e.textPreviewBytes, Se.textPreviewBytes), E = e.legacyTextEncoding;
1464
+ if (E != null && typeof E != "string") throw new TypeError("[markdown-explorer] legacyTextEncoding must be a string or null");
1465
+ const v = typeof E == "string" ? Br(E) : null, z = Oe("walkConcurrency", e.walkConcurrency, Se.walkConcurrency), S = e.cacheScope === void 0 ? "principal" : e.cacheScope;
1466
+ if (S !== "principal" && S !== "shared") throw new RangeError(`[markdown-explorer] cacheScope must be "principal" or "shared"; got ${JSON.stringify(S)}`);
1407
1467
  const O = e.reportSkipped;
1408
1468
  if (O !== void 0 && typeof O != "function") throw new TypeError("[markdown-explorer] reportSkipped must be a function");
1409
- const D = O === void 0 ? (E) => {
1410
- console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(E.sourceId)} does not list ${JSON.stringify(E.path)}: ${E.reason}`);
1411
- } : O, R = /* @__PURE__ */ new Set(), I = (E) => {
1412
- const _ = Fr(c, ...E.split("/")), N = Ke(c, _);
1413
- return N === "" || N === ".." || N.startsWith(`..${Ve}`) || We(N) ? null : _;
1414
- }, C = (E, _) => {
1415
- const N = `${_}\0${E}`;
1416
- R.has(N) || R.size >= S || (R.add(N), D({ sourceId: t, path: E, reason: _ }));
1417
- }, F = async ({ signal: E }) => {
1418
- E.throwIfAborted();
1469
+ const C = O === void 0 ? (b) => {
1470
+ console.warn(`[markdown-explorer] the file-system source ${JSON.stringify(b.sourceId)} does not list ${JSON.stringify(b.path)}: ${b.reason}`);
1471
+ } : O, R = /* @__PURE__ */ new Set(), I = (b) => {
1472
+ const _ = Zr(c, ...b.split("/")), N = Ze(c, _);
1473
+ return N === "" || N === ".." || N.startsWith(`..${Qe}`) || Ve(N) ? null : _;
1474
+ }, D = (b, _) => {
1475
+ const N = `${_}\0${b}`;
1476
+ R.has(N) || R.size >= k || (R.add(N), C({ sourceId: t, path: b, reason: _ }));
1477
+ }, F = async ({ signal: b }) => {
1478
+ b.throwIfAborted();
1419
1479
  const _ = new AbortController(), N = () => {
1420
- _.abort(E.reason);
1480
+ _.abort(b.reason);
1421
1481
  };
1422
- E.addEventListener("abort", N, { once: !0 });
1423
- const $ = Go(z);
1482
+ b.addEventListener("abort", N, { once: !0 });
1483
+ const j = es(z);
1424
1484
  let X = 0;
1425
- const G = async (P, W) => {
1426
- const K = await $(async () => {
1485
+ const G = async (P, Y) => {
1486
+ const K = await j(async () => {
1427
1487
  _.signal.throwIfAborted();
1428
1488
  try {
1429
- return await Jr(P, { withFileTypes: !0 });
1489
+ return await en(P, { withFileTypes: !0 });
1430
1490
  } catch (H) {
1431
- if (W === "" || !Wt(H)) throw H;
1491
+ if (Y === "" || !nr(H)) throw H;
1432
1492
  return null;
1433
1493
  }
1434
1494
  });
1435
1495
  if (_.signal.throwIfAborted(), K === null)
1436
- return C(`${m}${W}`, "unreadable-directory"), null;
1496
+ return D(`${l}${Y}`, "unreadable-directory"), null;
1437
1497
  const J = [];
1438
1498
  for (const H of K) {
1439
1499
  if (f.deniesName(H.name)) continue;
1440
- const te = W === "" ? H.name : `${W}/${H.name}`, q = `${m}${te}`, ne = Yo(H, q);
1500
+ const te = Y === "" ? H.name : `${Y}/${H.name}`, q = `${l}${te}`, ne = ts(H, q);
1441
1501
  if (ne !== null) {
1442
- C(q, ne);
1502
+ D(q, ne);
1443
1503
  continue;
1444
1504
  }
1445
1505
  J.push({ dirent: H, relativePath: te, path: q });
1446
1506
  }
1447
- if (X += J.length, X > S) throw new Oe("too-large");
1448
- return J.sort((H, te) => Jo(H.dirent.name, te.dirent.name)), (await Promise.all(
1507
+ if (X += J.length, X > k) throw new _e("too-large");
1508
+ return J.sort((H, te) => qo(H.dirent.name, te.dirent.name)), (await Promise.all(
1449
1509
  J.map(async ({ dirent: H, relativePath: te, path: q }) => {
1450
- const ne = await Fo(Ze(P, H.name)), de = ne === void 0 ? {} : { modifiedAt: ne };
1510
+ const ne = await Vo(qe(P, H.name)), de = ne === void 0 ? {} : { modifiedAt: ne };
1451
1511
  if (!H.isDirectory()) return { name: H.name, path: q, type: "file", ...de };
1452
- const Ee = await G(Ze(P, H.name), te);
1453
- return Ee === null ? null : { name: H.name, path: q, type: "directory", ...de, children: Ee };
1512
+ const be = await G(qe(P, H.name), te);
1513
+ return be === null ? null : { name: H.name, path: q, type: "directory", ...de, children: be };
1454
1514
  })
1455
1515
  )).filter((H) => H !== null);
1456
1516
  };
@@ -1461,78 +1521,78 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
1461
1521
  } catch (P) {
1462
1522
  throw _.abort(), P;
1463
1523
  } finally {
1464
- E.removeEventListener("abort", N);
1524
+ b.removeEventListener("abort", N);
1465
1525
  }
1466
- }, w = async (E) => {
1467
- if (!E.startsWith(m)) return { status: "refused", reason: "not-found" };
1468
- const _ = E.slice(m.length);
1469
- if (!St(_)) return { status: "refused", reason: "invalid" };
1526
+ }, w = async (b) => {
1527
+ if (!b.startsWith(l)) return { status: "refused", reason: "not-found" };
1528
+ const _ = b.slice(l.length);
1529
+ if (!Rt(_)) return { status: "refused", reason: "invalid" };
1470
1530
  if (f.deniesPath(_)) return { status: "refused", reason: "forbidden" };
1471
1531
  const N = I(_);
1472
1532
  if (N === null) return { status: "refused", reason: "forbidden" };
1473
- const $ = await It(N, { bigint: !0 });
1474
- if ($.isSymbolicLink()) return { status: "refused", reason: "forbidden" };
1475
- if (!$.isFile()) return { status: "refused", reason: "unsupported" };
1476
- const X = await Xr(N);
1477
- return X !== N || f.deniesPath(Ke(c, X).split(Ve).join("/")) ? { status: "refused", reason: "forbidden" } : { status: "file", target: N, name: _.slice(_.lastIndexOf("/") + 1), stats: $ };
1478
- }, g = async (E, _, N) => {
1479
- let $;
1533
+ const j = await Lt(N, { bigint: !0 });
1534
+ if (j.isSymbolicLink()) return { status: "refused", reason: "forbidden" };
1535
+ if (!j.isFile()) return { status: "refused", reason: "unsupported" };
1536
+ const X = await qr(N);
1537
+ return X !== N || f.deniesPath(Ze(c, X).split(Qe).join("/")) ? { status: "refused", reason: "forbidden" } : { status: "file", target: N, name: _.slice(_.lastIndexOf("/") + 1), stats: j };
1538
+ }, g = async (b, _, N) => {
1539
+ let j;
1480
1540
  try {
1481
1541
  const X = await w(N);
1482
1542
  if (X.status === "refused") return ee(X.reason);
1483
- const { target: G, name: P, stats: W } = X, K = Bo(P), J = kt(W);
1543
+ const { target: G, name: P, stats: Y } = X, K = Ko(P), J = Ot(Y);
1484
1544
  if (K.kind === "image") return { kind: "image", name: P, imageType: K.imageType, version: J };
1485
1545
  if (K.kind === "media") return { kind: "media", name: P, mediaType: K.mediaType, version: J };
1486
1546
  if (K.kind === "spreadsheet") return { kind: "spreadsheet", name: P, format: K.format, firstSheetOnly: !1, edit: null, version: J };
1487
1547
  if (K.kind === "file") return { kind: "file", name: P, version: J };
1488
- $ = await Nt(G, we.O_RDONLY | Xt | Jt);
1489
- const ae = await $.stat({ bigint: !0 });
1490
- if (!ae.isFile() || ae.ino !== W.ino || ae.dev !== W.dev) return ee("forbidden");
1548
+ j = await $t(G, he.O_RDONLY | qt | er);
1549
+ const ie = await j.stat({ bigint: !0 });
1550
+ if (!ie.isFile() || ie.ino !== Y.ino || ie.dev !== Y.dev) return ee("forbidden");
1491
1551
  if (K.kind === "markdown") {
1492
- if (ae.size > BigInt(h)) return ee("too-large");
1493
- const ne = await xt($, h + 1);
1552
+ if (ie.size > BigInt(h)) return ee("too-large");
1553
+ const ne = await vt(j, h + 1);
1494
1554
  if (ne.length > h) return ee("too-large");
1495
- const de = await a($e(ne, !0, v), _);
1555
+ const de = await a(ze(ne, !0, v), _);
1496
1556
  return { kind: "markdown", name: P, htmlContent: de.htmlContent, headings: de.headings, edit: null };
1497
1557
  }
1498
- const H = await xt($, y), te = ae.size > BigInt(y), q = $e(H, !te, v);
1558
+ const H = await vt(j, y), te = ie.size > BigInt(y), q = ze(H, !te, v);
1499
1559
  return q.includes("\0") ? { kind: "file", name: P, version: J } : { kind: "text", name: P, text: q, truncated: te, version: J };
1500
1560
  } catch (X) {
1501
- const G = De(X);
1561
+ const G = He(X);
1502
1562
  if (G === null) throw X;
1503
1563
  return ee(G);
1504
1564
  } finally {
1505
- await $?.close();
1565
+ await j?.close();
1506
1566
  }
1507
- }, M = async (E, _, N) => {
1508
- let $;
1567
+ }, M = async (b, _, N) => {
1568
+ let j;
1509
1569
  try {
1510
- $ = await w(N);
1570
+ j = await w(N);
1511
1571
  } catch (J) {
1512
- throw Yt(J);
1572
+ throw rr(J);
1513
1573
  }
1514
- if ($.status === "refused") throw new Oe($.reason);
1515
- const { target: X, name: G, stats: P } = $, W = Ut.get(Gt(G)), K = W === void 0 ? "" : W.contentType;
1516
- return { name: G, contentType: K, size: Number(P.size), version: kt(P), open: (J) => Xo(X, P, J, E.signal) };
1517
- }, U = async (E, _, N) => {
1518
- let $;
1574
+ if (j.status === "refused") throw new _e(j.reason);
1575
+ const { target: X, name: G, stats: P } = j, Y = Qt.get(tr(G)), K = Y === void 0 ? "" : Y.contentType;
1576
+ return { name: G, contentType: K, size: Number(P.size), version: Ot(P), open: (J) => Qo(X, P, J, b.signal) };
1577
+ }, U = async (b, _, N) => {
1578
+ let j;
1519
1579
  try {
1520
- $ = await w(N);
1580
+ j = await w(N);
1521
1581
  } catch (P) {
1522
- if (De(P) !== null) return null;
1582
+ if (He(P) !== null) return null;
1523
1583
  throw P;
1524
1584
  }
1525
- if ($.status === "refused") return null;
1526
- const X = N.slice(m.length).split("/");
1585
+ if (j.status === "refused") return null;
1586
+ const X = N.slice(l.length).split("/");
1527
1587
  if (X.some((P) => f.deniesName(P))) return null;
1528
1588
  const G = X.slice(0, -1);
1529
- return G.map((P, W) => `${m}${G.slice(0, W + 1).join("/")}`);
1589
+ return G.map((P, Y) => `${l}${G.slice(0, Y + 1).join("/")}`);
1530
1590
  };
1531
1591
  return Object.freeze({
1532
1592
  id: t,
1533
1593
  label: r,
1534
- cacheScope: x,
1535
- boundary: Object.freeze({ contains: (E) => E.startsWith(m) }),
1594
+ cacheScope: S,
1595
+ boundary: Object.freeze({ contains: (b) => b.startsWith(l) }),
1536
1596
  tree: F,
1537
1597
  ancestors: U,
1538
1598
  document: g,
@@ -1540,15 +1600,15 @@ const hn = (e) => e instanceof Error && Object.hasOwn(e, jt) && Ot(e.reason), yn
1540
1600
  });
1541
1601
  };
1542
1602
  export {
1543
- ms as DEFAULT_DENIED_PATH_SEGMENTS,
1544
- Oe as ExplorerError,
1545
- ps as MAX_DOCUMENT_PATH_LENGTH,
1546
- cs as anonymousAccess,
1547
- ds as createFileSystemSource,
1548
- us as createMarkdownExplorer,
1549
- ys as decodeText,
1550
- $e as decodeTextLeniently,
1603
+ Ts as DEFAULT_DENIED_PATH_SEGMENTS,
1604
+ _e as ExplorerError,
1605
+ ks as MAX_DOCUMENT_PATH_LENGTH,
1606
+ hs as anonymousAccess,
1607
+ gs as createFileSystemSource,
1608
+ ys as createMarkdownExplorer,
1609
+ Os as decodeText,
1610
+ ze as decodeTextLeniently,
1551
1611
  re as isAcceptableDocumentPath,
1552
- ws as isDeniedPath,
1553
- Pr as legacyTextEncodingOf
1612
+ xs as isDeniedPath,
1613
+ Br as legacyTextEncodingOf
1554
1614
  };