@aiquants/markdown-explorer 0.6.0 → 0.7.1

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