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