@tdacorp/hyle-sdk 0.9.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +111 -2
  2. package/bin/hyle-sdk-engage-keygen.mjs +3 -0
  3. package/dist/check-routes-bin.js +5 -1
  4. package/dist/{chunk-54JF4E53.js → chunk-N7ZQUAGM.js} +45 -2
  5. package/dist/chunk-R5EMI4HQ.js +61 -0
  6. package/dist/{chunk-XKR74Y5G.js → chunk-S7PCCEHP.js} +1 -1
  7. package/dist/{chunk-6LW33475.js → chunk-ZQFYH4FX.js} +538 -50
  8. package/dist/comments.cjs +1048 -0
  9. package/dist/comments.d.cts +152 -0
  10. package/dist/comments.d.ts +152 -0
  11. package/dist/comments.js +1025 -0
  12. package/dist/{types-BPPZrYOZ.d.cts → embed-DL5QIZRJ.d.ts} +44 -3
  13. package/dist/{types-C1eCQ2As.d.ts → embed-jCaSI31t.d.cts} +44 -3
  14. package/dist/engage-keygen-bin.js +67 -0
  15. package/dist/index.cjs +26 -1
  16. package/dist/index.d.cts +11 -3
  17. package/dist/index.d.ts +11 -3
  18. package/dist/index.js +5 -1
  19. package/dist/mermaid-diagram.js +9 -54
  20. package/dist/next.cjs +1010 -78
  21. package/dist/next.d.cts +163 -6
  22. package/dist/next.d.ts +163 -6
  23. package/dist/next.js +442 -14
  24. package/dist/react.cjs +340 -49
  25. package/dist/react.d.cts +112 -7
  26. package/dist/react.d.ts +112 -7
  27. package/dist/react.js +7 -1
  28. package/dist/{resolve-Dpb6Orsj.d.ts → resolve-DvmuBlpO.d.ts} +1 -1
  29. package/dist/{resolve-D2rnnho9.d.cts → resolve-f6IJ6SL9.d.cts} +1 -1
  30. package/dist/styles.css +117 -0
  31. package/dist/{types-CHxH5E0S.d.cts → types-5D6ZD0Wi.d.cts} +59 -1
  32. package/dist/{types-CHxH5E0S.d.ts → types-5D6ZD0Wi.d.ts} +59 -1
  33. package/dist/use-cache.cjs +5 -1
  34. package/dist/use-cache.d.cts +2 -2
  35. package/dist/use-cache.d.ts +2 -2
  36. package/dist/use-cache.js +2 -2
  37. package/package.json +4 -3
@@ -0,0 +1,1025 @@
1
+ "use client";
2
+ import "./chunk-R5EMI4HQ.js";
3
+
4
+ // src/react/comments.tsx
5
+ import { useCallback, useEffect as useEffect2, useId, useRef as useRef2, useState as useState2 } from "react";
6
+
7
+ // src/react/comments-api.ts
8
+ var CSRF_HEADER = "x-hyle-engage";
9
+ var TIMEOUT_MS = 15e3;
10
+ async function call(endpoint, method, path, body) {
11
+ try {
12
+ const res = await fetch(`${endpoint}${path}`, {
13
+ method,
14
+ credentials: "same-origin",
15
+ cache: "no-store",
16
+ headers: { accept: "application/json", [CSRF_HEADER]: "1", ...body ? { "content-type": "application/json" } : {} },
17
+ ...body ? { body: JSON.stringify(body) } : {},
18
+ signal: AbortSignal.timeout(TIMEOUT_MS)
19
+ });
20
+ let data;
21
+ try {
22
+ data = (await res.json()).data;
23
+ } catch {
24
+ }
25
+ const retry = Number(res.headers.get("retry-after"));
26
+ return { status: res.status, data, retryAfter: Number.isFinite(retry) && retry > 0 ? retry : void 0 };
27
+ } catch {
28
+ return { status: 0, data: void 0, retryAfter: void 0 };
29
+ }
30
+ }
31
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
32
+ var count = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.trunc(v) : 0;
33
+ function toComment(raw) {
34
+ if (!isObject(raw) || typeof raw.id !== "string" || typeof raw.created_at !== "string") return void 0;
35
+ const depth = typeof raw.depth === "number" ? Math.min(4, Math.max(1, Math.trunc(raw.depth))) : 1;
36
+ const author = isObject(raw.author) && typeof raw.author.name === "string" ? raw.author.name : void 0;
37
+ const name = typeof raw.author_name === "string" ? raw.author_name : author;
38
+ const body = isObject(raw.body) && raw.body.format === "hast" ? { format: "hast", tree: raw.body.tree } : null;
39
+ const removed = raw.removed === true || body === null;
40
+ return {
41
+ id: raw.id,
42
+ parent_id: typeof raw.parent_id === "string" ? raw.parent_id : null,
43
+ depth,
44
+ author_name: name ?? null,
45
+ created_at: raw.created_at,
46
+ edited_at: typeof raw.edited_at === "string" ? raw.edited_at : null,
47
+ like_count: count(raw.like_count),
48
+ removed,
49
+ ...removed && (raw.removed_by === "moderator" || raw.removed_by === "author") ? { removed_by: raw.removed_by } : {},
50
+ body,
51
+ // Viewer members exist only on a live comment of a viewer-aware listing; a tombstone never carries them.
52
+ ...!removed && typeof raw.mine === "boolean" ? { mine: raw.mine, liked_by_me: raw.liked_by_me === true, can_edit_until: typeof raw.can_edit_until === "string" ? raw.can_edit_until : null } : {}
53
+ };
54
+ }
55
+ function toHeld(raw) {
56
+ if (!isObject(raw) || typeof raw.id !== "string" || typeof raw.created_at !== "string" || !isObject(raw.body) || raw.body.format !== "hast") return void 0;
57
+ const author = isObject(raw.author) && typeof raw.author.name === "string" ? raw.author.name : null;
58
+ return {
59
+ id: raw.id,
60
+ parent_id: typeof raw.parent_id === "string" ? raw.parent_id : null,
61
+ depth: typeof raw.depth === "number" ? Math.min(4, Math.max(1, Math.trunc(raw.depth))) : 1,
62
+ author_name: author,
63
+ created_at: raw.created_at,
64
+ edited_at: typeof raw.edited_at === "string" ? raw.edited_at : null,
65
+ can_edit_until: typeof raw.can_edit_until === "string" ? raw.can_edit_until : null,
66
+ body: { format: "hast", tree: raw.body.tree }
67
+ };
68
+ }
69
+ function parseListing(data) {
70
+ if (!isObject(data) || data.kind !== "comments" || !Array.isArray(data.comments)) return void 0;
71
+ const comments = data.comments.map(toComment).filter((c) => c !== void 0);
72
+ const viewer = Array.isArray(data.mine_held) ? { liked_by_me: data.liked_by_me === true, mine_held: data.mine_held.slice(0, 5).map(toHeld).filter((h) => h !== void 0) } : {};
73
+ return { cp: 1, kind: "comments", publication_id: String(data.publication_id ?? ""), comment_count: count(data.comment_count), like_count: count(data.like_count), truncated: data.truncated === true, comments, ...viewer };
74
+ }
75
+ var untilMs = (iso) => {
76
+ const t = iso ? Date.parse(iso) : NaN;
77
+ return Number.isFinite(t) ? t : void 0;
78
+ };
79
+ function buildThread(listing, localHeld) {
80
+ const byId = /* @__PURE__ */ new Map();
81
+ const roots = [];
82
+ const place = (node, parentId) => {
83
+ const parent = parentId ? byId.get(parentId) : void 0;
84
+ (parent ? parent.kids : roots).push(node);
85
+ };
86
+ for (const c of listing.comments) {
87
+ if (byId.has(c.id)) continue;
88
+ const removed = c.removed;
89
+ const node = {
90
+ id: c.id,
91
+ depth: c.depth,
92
+ status: removed ? "removed" : "visible",
93
+ removedBy: removed ? c.removed_by : void 0,
94
+ mine: !removed && c.mine === true,
95
+ canEditUntil: untilMs(c.can_edit_until),
96
+ likedByMe: !removed && c.liked_by_me === true,
97
+ name: removed ? null : c.author_name ?? null,
98
+ createdAt: c.created_at,
99
+ editedAt: c.edited_at,
100
+ likes: c.like_count,
101
+ tree: c.body?.tree,
102
+ text: void 0,
103
+ kids: []
104
+ };
105
+ place(node, c.parent_id === c.id ? null : c.parent_id);
106
+ byId.set(c.id, node);
107
+ }
108
+ const mine = [];
109
+ const addHeld = (node, parentId, oldestFirst) => {
110
+ const parent = parentId ? byId.get(parentId) : void 0;
111
+ if (parent) parent.kids.push(node);
112
+ else if (oldestFirst) mine.unshift(node);
113
+ else mine.push(node);
114
+ };
115
+ const heldIds = /* @__PURE__ */ new Set();
116
+ for (const h of listing.mine_held ?? []) {
117
+ heldIds.add(h.id);
118
+ const parent = h.parent_id ? byId.get(h.parent_id) : void 0;
119
+ addHeld({ id: h.id, depth: Math.min(4, (parent?.depth ?? h.depth - 1) + 1), status: "held", removedBy: void 0, mine: true, canEditUntil: untilMs(h.can_edit_until), likedByMe: false, name: h.author_name, createdAt: h.created_at, editedAt: h.edited_at, likes: 0, tree: h.body?.tree, text: void 0, kids: [] }, h.parent_id, true);
120
+ }
121
+ if (listing.mine_held === void 0) {
122
+ for (const h of localHeld) {
123
+ if (byId.has(h.id) || heldIds.has(h.id)) continue;
124
+ const parent = h.parentId ? byId.get(h.parentId) : void 0;
125
+ addHeld({ id: h.id, depth: Math.min(4, (parent?.depth ?? 0) + 1), status: "held", removedBy: void 0, mine: true, canEditUntil: void 0, likedByMe: false, name: h.name, createdAt: h.createdAt, editedAt: null, likes: 0, tree: void 0, text: h.text, kids: [] }, h.parentId, false);
126
+ }
127
+ }
128
+ return [...mine, ...roots];
129
+ }
130
+
131
+ // src/react/comments-parts.tsx
132
+ import { useEffect, useRef, useState } from "react";
133
+
134
+ // src/react/comments-body.tsx
135
+ import { toJsxRuntime } from "hast-util-to-jsx-runtime";
136
+ import { Fragment } from "react";
137
+ import { jsx, jsxs } from "react/jsx-runtime";
138
+
139
+ // src/asset-path.ts
140
+ var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
141
+ var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
142
+ var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg";
143
+ var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
144
+ var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
145
+ function hostAssetSrc(src) {
146
+ const file = HYLE_ASSET_URL.exec(src)?.[1];
147
+ return file ? `${ASSET_ROUTE_PREFIX}/${file.toLowerCase()}` : src;
148
+ }
149
+
150
+ // src/react/sanitize.ts
151
+ var HastLimitError = class extends Error {
152
+ constructor(message) {
153
+ super(message);
154
+ this.name = "HastLimitError";
155
+ }
156
+ };
157
+ var MAX_NODES = 2e4;
158
+ var MAX_TEXT = 512 * 1024;
159
+ var MAX_DEPTH = 128;
160
+ var MAX_SRCDOC = 64 * 1024;
161
+ var DROP = /* @__PURE__ */ new Set(["script", "style", "template", "noscript"]);
162
+ var VOID = /* @__PURE__ */ new Set(["br", "hr", "img", "input", "path"]);
163
+ var isString = (v) => typeof v === "string";
164
+ var isScalar = (v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean";
165
+ var matches = (re) => (v) => typeof v === "string" && re.test(v);
166
+ var ID_PREFIX = "user-content-";
167
+ var scopeId = (id) => id.startsWith(ID_PREFIX) ? id : ID_PREFIX + id;
168
+ var ID_BODY = /^[\p{L}\p{N}_:.-]{1,180}$/u;
169
+ var isIdValue = (v) => typeof v === "string" && ID_BODY.test(v.startsWith(ID_PREFIX) ? v.slice(ID_PREFIX.length) : v);
170
+ var CLASS_TOKEN = /^[A-Za-z_][\w:-]*$/;
171
+ var classTokens = (v) => {
172
+ const tokens = Array.isArray(v) ? v : typeof v === "string" ? v.split(/\s+/) : [];
173
+ return tokens.length > 0 && tokens.every((t) => typeof t === "string" && CLASS_TOKEN.test(t)) ? tokens : void 0;
174
+ };
175
+ var isClass = (v) => classTokens(v) !== void 0;
176
+ var isAlign = matches(/^(left|right|center)$/);
177
+ var isLength = matches(/^[\d.]+(em|px|%)?$/);
178
+ var STYLE_PROPS = /* @__PURE__ */ new Set(["height", "vertical-align", "margin-left", "margin-right", "margin-top", "margin-bottom", "top", "width", "min-width", "border-bottom-width", "padding-left"]);
179
+ var STYLE_LENGTH = /^(-?\d+(?:\.\d+)?)(em|px|%)?$/;
180
+ var MAX_STYLE_MAGNITUDE = 100;
181
+ function isKatexStyle(v, ctx) {
182
+ if (typeof v !== "string" || !ctx.katex) return false;
183
+ return v.split(";").filter((d) => d !== "").every((decl) => {
184
+ const [prop, value, ...extra] = decl.split(":");
185
+ if (extra.length > 0 || prop === void 0 || value === void 0) return false;
186
+ if (prop === "position") return value === "relative";
187
+ const m = STYLE_LENGTH.exec(value);
188
+ return STYLE_PROPS.has(prop) && m !== null && Math.abs(Number(m[1])) <= MAX_STYLE_MAGNITUDE;
189
+ });
190
+ }
191
+ function isSafeUrl(value, kind) {
192
+ if (typeof value !== "string") return false;
193
+ const url = value.trim();
194
+ if (url.length === 0 || /[\u0000-\u001f\u007f\\]/.test(url)) return false;
195
+ if (url.startsWith("#")) return kind === "href";
196
+ if (url.startsWith("/")) return !url.startsWith("//");
197
+ try {
198
+ const { protocol } = new URL(url);
199
+ return protocol === "https:" || protocol === "http:" || kind === "href" && protocol === "mailto:";
200
+ } catch {
201
+ return false;
202
+ }
203
+ }
204
+ var isHref = (v) => isSafeUrl(v, "href") && (typeof v !== "string" || !v.trim().startsWith("#") || isIdValue(v.trim().slice(1)));
205
+ var isSrc = (v) => isSafeUrl(v, "src");
206
+ var MERMAID_SCRIPT_URL = "https://cdnjs.cloudflare.com/ajax/libs/mermaid/11.9.0/mermaid.min.js";
207
+ var MERMAID_SRCDOC = new RegExp(
208
+ `^<!doctype html><html><head><meta charset="utf-8"></head><body><div class="mermaid">([^<]*)</div><script src="${MERMAID_SCRIPT_URL.replace(/[.]/g, "\\.")}"></script><script>mermaid\\.initialize\\(\\{ startOnLoad: true, securityLevel: "strict" \\}\\);</script></body></html>$`
209
+ );
210
+ var isMermaidSrcdoc = (v) => typeof v === "string" && v.length <= MAX_SRCDOC && MERMAID_SRCDOC.test(v);
211
+ var MERMAID_FRAME_CSP = `default-src 'none'; script-src ${MERMAID_SCRIPT_URL} 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:`;
212
+ var heading = { id: isIdValue, className: isClass };
213
+ var ATTRS = new Map(
214
+ Object.entries({
215
+ p: {},
216
+ em: {},
217
+ strong: {},
218
+ del: {},
219
+ hr: {},
220
+ br: {},
221
+ sup: {},
222
+ blockquote: {},
223
+ thead: {},
224
+ tbody: {},
225
+ tr: {},
226
+ ol: {},
227
+ ul: { className: isClass },
228
+ li: { id: isIdValue, className: isClass },
229
+ h1: heading,
230
+ h2: heading,
231
+ h3: heading,
232
+ h4: heading,
233
+ h5: heading,
234
+ h6: heading,
235
+ a: { href: isHref, id: isIdValue, ariaDescribedBy: isIdValue, ariaLabel: isString, dataFootnoteRef: isScalar, dataFootnoteBackref: isScalar, className: isClass },
236
+ img: { src: isSrc, alt: isString },
237
+ table: {},
238
+ th: { scope: matches(/^(row|col|rowgroup|colgroup)$/), align: isAlign },
239
+ td: { align: isAlign },
240
+ pre: { className: isClass },
241
+ code: { className: isClass },
242
+ section: { dataFootnotes: isScalar, className: isClass },
243
+ input: { type: matches(/^checkbox$/), disabled: isScalar, checked: isScalar },
244
+ span: { className: isClass, style: isKatexStyle, ariaHidden: matches(/^(true|false)$/) },
245
+ svg: { xmlns: matches(/^http:\/\/www\.w3\.org\/2000\/svg$/), width: isLength, height: isLength, viewBox: matches(/^-?[\d.]+ -?[\d.]+ -?[\d.]+ -?[\d.]+$/), preserveAspectRatio: matches(/^[\w ]+$/) },
246
+ path: { d: matches(/^[MLCSQTAHVZmlcsqtahvz0-9.,\-\s]+$/) },
247
+ video: { src: isSrc, controls: isScalar },
248
+ audio: { src: isSrc, controls: isScalar },
249
+ // hyle's sandboxed Mermaid frame (ADR 0001). The renderer emits `sandbox` as ["allow-scripts"]; it is normalized below.
250
+ iframe: { sandbox: (v) => v === "allow-scripts" || Array.isArray(v) && v.length === 1 && v[0] === "allow-scripts", srcdoc: isMermaidSrcdoc }
251
+ })
252
+ );
253
+ var isObject2 = (v) => typeof v === "object" && v !== null;
254
+ function textOf(node, depth = 0) {
255
+ if (!isObject2(node) || depth > MAX_DEPTH) return "";
256
+ if (node.type === "text") return typeof node.value === "string" ? node.value : "";
257
+ return Array.isArray(node.children) ? node.children.map((c) => textOf(c, depth + 1)).join("") : "";
258
+ }
259
+ var CALLOUT_MARKER = /^\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*/i;
260
+ var CALLOUT_KIND = { note: "note", tip: "tip", important: "warning", warning: "warning", caution: "caution" };
261
+ function toCallout(children) {
262
+ const first = children.find((c) => c.type === "element");
263
+ const lead = first?.tagName === "p" ? first.children[0] : void 0;
264
+ const marker = lead?.type === "text" ? CALLOUT_MARKER.exec(lead.value) : null;
265
+ if (!first || lead?.type !== "text" || !marker) return void 0;
266
+ const rest = lead.value.slice(marker[0].length);
267
+ const firstChildren = rest ? [{ type: "text", value: rest }, ...first.children.slice(1)] : first.children.slice(1);
268
+ const body = firstChildren.length > 0 ? [{ ...first, children: firstChildren }] : [];
269
+ const kind = CALLOUT_KIND[(marker[1] ?? "note").toLowerCase()] ?? "note";
270
+ return { type: "element", tagName: "callout", properties: { kind }, children: [...body, ...children.slice(children.indexOf(first) + 1)] };
271
+ }
272
+ function clean(node, depth, ctx, budget) {
273
+ if (!isObject2(node) || depth > MAX_DEPTH) return [];
274
+ if (++budget.nodes > MAX_NODES) throw new HastLimitError("content has too many nodes");
275
+ if (node.type === "text") {
276
+ if (typeof node.value !== "string") return [];
277
+ budget.text += node.value.length;
278
+ if (budget.text > MAX_TEXT) throw new HastLimitError("content is too large");
279
+ return [{ type: "text", value: node.value }];
280
+ }
281
+ if (node.type !== "element" || typeof node.tagName !== "string" || DROP.has(node.tagName)) return [];
282
+ const tag = node.tagName;
283
+ const rules = ATTRS.get(tag);
284
+ const own = isObject2(node.properties) ? classTokens(node.properties.className) : void 0;
285
+ const inner = tag === "span" && own?.some((t) => t === "katex" || t.startsWith("katex-")) ? { katex: true } : ctx;
286
+ const children = Array.isArray(node.children) ? node.children.flatMap((c) => clean(c, depth + 1, inner, budget)) : [];
287
+ if (!rules) return children;
288
+ const properties = {};
289
+ if (isObject2(node.properties)) {
290
+ for (const [key, value] of Object.entries(node.properties)) {
291
+ if (Object.hasOwn(rules, key) && rules[key](value, inner)) properties[key] = value;
292
+ }
293
+ }
294
+ if ((tag === "img" || tag === "video" || tag === "audio") && typeof properties.src === "string") properties.src = hostAssetSrc(properties.src);
295
+ if (tag === "iframe") {
296
+ if (properties.sandbox === void 0 || properties.srcdoc === void 0) return [];
297
+ properties.sandbox = "allow-scripts";
298
+ }
299
+ if (tag === "input") {
300
+ if (properties.type !== "checkbox") return [];
301
+ properties.disabled = true;
302
+ }
303
+ for (const key of ["id", "ariaDescribedBy"]) if (typeof properties[key] === "string") properties[key] = scopeId(properties[key]);
304
+ if (tag === "a" && typeof properties.href === "string" && properties.href.trim().startsWith("#")) properties.href = `#${scopeId(properties.href.trim().slice(1))}`;
305
+ if (tag === "blockquote") {
306
+ const callout = toCallout(children);
307
+ if (callout) return [callout];
308
+ }
309
+ const tagName = tag === "h1" ? "h2" : tag;
310
+ return [{ type: "element", tagName, properties, children: VOID.has(tag) ? [] : children }];
311
+ }
312
+ function sanitizeHast(tree, title, description) {
313
+ const raw = isObject2(tree) && tree.type === "root" && Array.isArray(tree.children) ? tree.children : [];
314
+ const elements = raw.filter((n) => isObject2(n) && n.type === "element");
315
+ const [first] = elements;
316
+ const skip = title !== void 0 && isObject2(first) && first.tagName === "h1" && textOf(first).trim() === title.trim() ? first : void 0;
317
+ const lead = elements[skip ? 1 : 0];
318
+ const repeat = description && isObject2(lead) && lead.tagName === "p" && textOf(lead).trim().startsWith(description.trim()) ? lead : void 0;
319
+ const budget = { nodes: 0, text: 0 };
320
+ return { type: "root", children: raw.filter((n) => n !== skip && n !== repeat).flatMap((n) => clean(n, 0, { katex: false }, budget)) };
321
+ }
322
+
323
+ // src/react/comments-body.tsx
324
+ import { jsx as jsx2 } from "react/jsx-runtime";
325
+ var ALLOWED = /* @__PURE__ */ new Set(["p", "a", "em", "strong", "del", "code", "pre", "blockquote", "ul", "ol", "li", "br"]);
326
+ var LINK_REL = "nofollow ugc noopener noreferrer";
327
+ function narrow(node) {
328
+ if (node.type === "text") return [node];
329
+ if (node.type !== "element") return [];
330
+ const children = node.children.flatMap(narrow);
331
+ if (!ALLOWED.has(node.tagName)) return children;
332
+ if (node.tagName === "a") {
333
+ const href = node.properties.href;
334
+ if (!isSafeUrl(href, "href")) return children;
335
+ return [{ type: "element", tagName: "a", properties: { href: String(href), rel: LINK_REL.split(" ") }, children }];
336
+ }
337
+ return [{ type: "element", tagName: node.tagName, properties: {}, children: node.tagName === "br" ? [] : children }];
338
+ }
339
+ function CommentBody({ tree }) {
340
+ let children;
341
+ try {
342
+ children = sanitizeHast(tree).children.flatMap((n) => narrow(n));
343
+ } catch (error) {
344
+ if (error instanceof HastLimitError) return null;
345
+ throw error;
346
+ }
347
+ return /* @__PURE__ */ jsx2("div", { className: "hyle-cm-body", children: toJsxRuntime({ type: "root", children }, { Fragment, jsx, jsxs, elementAttributeNameCase: "react", stylePropertyNameCase: "dom" }) });
348
+ }
349
+
350
+ // src/react/comments-markdown.ts
351
+ function inline(nodes) {
352
+ return nodes.map((node) => {
353
+ if (node.type === "text") return node.value;
354
+ if (node.type !== "element") return "";
355
+ const inner = inline(node.children);
356
+ switch (node.tagName) {
357
+ case "strong":
358
+ return `**${inner}**`;
359
+ case "em":
360
+ return `*${inner}*`;
361
+ case "del":
362
+ return `~~${inner}~~`;
363
+ case "code":
364
+ return `\`${inner}\``;
365
+ case "br":
366
+ return "\n";
367
+ case "a":
368
+ return typeof node.properties.href === "string" ? `[${inner}](${node.properties.href})` : inner;
369
+ default:
370
+ return inner;
371
+ }
372
+ }).join("");
373
+ }
374
+ function block(node, indent = "") {
375
+ if (node.type === "text") return node.value.trim() ? node.value.trim() : "";
376
+ if (node.type !== "element") return "";
377
+ const el = node;
378
+ switch (el.tagName) {
379
+ case "blockquote":
380
+ return el.children.map((c) => block(c)).filter(Boolean).join("\n\n").split("\n").map((l) => `> ${l}`.trimEnd()).join("\n");
381
+ case "pre":
382
+ return `\`\`\`
383
+ ${inline(el.children).replace(/\n$/, "")}
384
+ \`\`\``;
385
+ case "ul":
386
+ case "ol": {
387
+ let n = 0;
388
+ return el.children.filter((c) => c.type === "element" && c.tagName === "li").map((li) => `${indent}${el.tagName === "ol" ? `${++n}.` : "-"} ${li.children.map((c) => c.type === "element" && (c.tagName === "ul" || c.tagName === "ol") ? `
389
+ ${block(c, `${indent} `)}` : inline([c])).join("").trim()}`).join("\n");
390
+ }
391
+ default:
392
+ return inline(el.children).trim();
393
+ }
394
+ }
395
+ function hastToMarkdown(tree) {
396
+ try {
397
+ return sanitizeHast(tree).children.map((n) => block(n)).filter(Boolean).join("\n\n");
398
+ } catch {
399
+ return "";
400
+ }
401
+ }
402
+
403
+ // src/react/icons.tsx
404
+ import { Fragment as Fragment2, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
405
+ var SHAPES = {
406
+ info: /* @__PURE__ */ jsxs2(Fragment2, { children: [
407
+ /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
408
+ /* @__PURE__ */ jsx3("path", { d: "M8 7.3V11M8 5v.1" })
409
+ ] }),
410
+ "check-circle": /* @__PURE__ */ jsxs2(Fragment2, { children: [
411
+ /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
412
+ /* @__PURE__ */ jsx3("path", { d: "m5.3 8.3 1.9 1.9 3.5-3.9" })
413
+ ] }),
414
+ alert: /* @__PURE__ */ jsx3("path", { d: "M8 2 1.8 13h12.4zM8 6.5v3M8 11.3v.1" }),
415
+ "x-circle": /* @__PURE__ */ jsxs2(Fragment2, { children: [
416
+ /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
417
+ /* @__PURE__ */ jsx3("path", { d: "m5.8 5.8 4.4 4.4M10.2 5.8l-4.4 4.4" })
418
+ ] }),
419
+ calendar: /* @__PURE__ */ jsxs2(Fragment2, { children: [
420
+ /* @__PURE__ */ jsx3("rect", { x: "2", y: "3", width: "12", height: "11", rx: "1.3" }),
421
+ /* @__PURE__ */ jsx3("path", { d: "M2 6.5h12M5.5 1.7v2.6M10.5 1.7v2.6" })
422
+ ] }),
423
+ globe: /* @__PURE__ */ jsxs2(Fragment2, { children: [
424
+ /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
425
+ /* @__PURE__ */ jsx3("path", { d: "M2 8h12M8 2c2 1.7 2.8 3.7 2.8 6S10 12.3 8 14M8 2C6 3.7 5.2 5.7 5.2 8S6 12.3 8 14" })
426
+ ] }),
427
+ file: /* @__PURE__ */ jsxs2(Fragment2, { children: [
428
+ /* @__PURE__ */ jsx3("path", { d: "M4 1.8h5l3 3v8.4a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2.8a1 1 0 0 1 1-1z" }),
429
+ /* @__PURE__ */ jsx3("path", { d: "M9 1.8v3h3" })
430
+ ] }),
431
+ chev: /* @__PURE__ */ jsx3("path", { d: "m6 3.5 4.5 4.5L6 12.5" }),
432
+ "chev-down": /* @__PURE__ */ jsx3("path", { d: "m3.5 6 4.5 4.5L12.5 6" }),
433
+ "chev-left": /* @__PURE__ */ jsx3("path", { d: "M10 3.5 5.5 8 10 12.5" }),
434
+ x: /* @__PURE__ */ jsx3("path", { d: "m4 4 8 8M12 4l-8 8" }),
435
+ heart: /* @__PURE__ */ jsx3("path", { d: "M8 13.5S2.2 10 2.2 6.1A3 3 0 0 1 8 5a3 3 0 0 1 5.8 1.1C13.8 10 8 13.5 8 13.5z" }),
436
+ reply: /* @__PURE__ */ jsx3("path", { d: "M6.5 3.5 2.5 7.5l4 4M2.5 7.5h6a5 5 0 0 1 5 5" }),
437
+ clock: /* @__PURE__ */ jsxs2(Fragment2, { children: [
438
+ /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
439
+ /* @__PURE__ */ jsx3("path", { d: "M8 4.5V8l2.3 1.5" })
440
+ ] }),
441
+ ban: /* @__PURE__ */ jsxs2(Fragment2, { children: [
442
+ /* @__PURE__ */ jsx3("circle", { cx: "8", cy: "8", r: "6" }),
443
+ /* @__PURE__ */ jsx3("path", { d: "m3.8 12.2 8.4-8.4" })
444
+ ] }),
445
+ refresh: /* @__PURE__ */ jsx3("path", { d: "M13 8a5 5 0 1 1-1.6-3.7M13 2.5v2.8h-2.8" })
446
+ };
447
+ function Icon({ name, className }) {
448
+ return /* @__PURE__ */ jsx3("svg", { className: className ? `hyle-ic ${className}` : "hyle-ic", viewBox: "0 0 16 16", "aria-hidden": "true", children: SHAPES[name] });
449
+ }
450
+
451
+ // src/react/comments-parts.tsx
452
+ import { Fragment as Fragment3, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
453
+ var MAX_CHARS = 4e3;
454
+ var EDIT_WINDOW_MS = 10 * 60 * 1e3;
455
+ var MAX_DEPTH2 = 4;
456
+ var fill = (template, values) => template.replace(/\{(\w+)\}/g, (_, k) => String(values[k] ?? ""));
457
+ var initials = (name) => name.trim().split(/\s+/).slice(0, 2).map((w) => [...w][0] ?? "").join("").toUpperCase() || "?";
458
+ var replyButtonId = (ui, id) => `${ui.idp}-reply-${id}`;
459
+ var nameId = (ui, id) => `${ui.idp}-${id}-n`;
460
+ function relative(iso, now, locale, s) {
461
+ const seconds = Math.round((now - Date.parse(iso)) / 1e3);
462
+ if (!Number.isFinite(seconds)) return iso;
463
+ if (seconds < 45) return s.justNow;
464
+ try {
465
+ const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto", style: "short" });
466
+ if (seconds < 3600) return rtf.format(-Math.round(seconds / 60), "minute");
467
+ if (seconds < 86400) return rtf.format(-Math.round(seconds / 3600), "hour");
468
+ if (seconds < 30 * 86400) return rtf.format(-Math.round(seconds / 86400), "day");
469
+ return new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(new Date(iso));
470
+ } catch {
471
+ return iso.slice(0, 10);
472
+ }
473
+ }
474
+ var absolute = (iso, locale) => {
475
+ try {
476
+ return new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" }).format(new Date(iso));
477
+ } catch {
478
+ return iso;
479
+ }
480
+ };
481
+ function Avatar({ name }) {
482
+ return /* @__PURE__ */ jsx4("span", { className: "hyle-avatar", "aria-hidden": "true", children: name ? initials(name) : /* @__PURE__ */ jsx4(Icon, { name: "ban" }) });
483
+ }
484
+ function SignInLink({ ui, className, children }) {
485
+ return /* @__PURE__ */ jsx4("a", { className, href: `#${ui.signInId}`, children });
486
+ }
487
+ function LikeButton({ ui, itemKey, serverCount, serverOn, scope }) {
488
+ const { s } = ui;
489
+ const state = ui.likes[itemKey];
490
+ const count2 = state?.count ?? serverCount;
491
+ const on = state?.on ?? serverOn;
492
+ const cls = scope === "article" ? "hyle-btn" : "hyle-cm-btn cnt";
493
+ const lead = scope === "article" ? on ? s.likedArticle : s.likeArticle : null;
494
+ const sr = scope === "article" ? ", " : s.likeComment;
495
+ const icon = /* @__PURE__ */ jsx4(Icon, { name: "heart" });
496
+ if (ui.ready && !ui.me) {
497
+ return /* @__PURE__ */ jsxs3(SignInLink, { ui, className: cls, children: [
498
+ icon,
499
+ lead ?? null,
500
+ scope === "article" ? /* @__PURE__ */ jsxs3(Fragment3, { children: [
501
+ " ",
502
+ /* @__PURE__ */ jsx4("span", { className: "hyle-sr", children: s.likeArticleSignIn })
503
+ ] }) : /* @__PURE__ */ jsx4("span", { className: "hyle-sr", children: s.likeCommentSignIn }),
504
+ /* @__PURE__ */ jsx4("span", { children: count2 })
505
+ ] });
506
+ }
507
+ if (ui.banned || !ui.ready) {
508
+ return /* @__PURE__ */ jsxs3("button", { className: cls, type: "button", "aria-disabled": "true", children: [
509
+ icon,
510
+ lead,
511
+ scope === "article" ? " " : null,
512
+ /* @__PURE__ */ jsx4("span", { className: "hyle-sr", children: sr }),
513
+ /* @__PURE__ */ jsx4("span", { children: count2 })
514
+ ] });
515
+ }
516
+ return /* @__PURE__ */ jsxs3("button", { className: cls, type: "button", "aria-pressed": on, onClick: () => ui.actions.like(itemKey, serverCount, serverOn), children: [
517
+ icon,
518
+ lead,
519
+ scope === "article" ? " " : null,
520
+ /* @__PURE__ */ jsx4("span", { className: "hyle-sr", children: sr }),
521
+ /* @__PURE__ */ jsx4("span", { children: count2 })
522
+ ] });
523
+ }
524
+ function Composer({ ui, id, parentId, name, autoFocus, onCancel }) {
525
+ const { s } = ui;
526
+ const [text, setText] = useState("");
527
+ const [busy, setBusy] = useState(false);
528
+ const [error, setError] = useState(null);
529
+ const area = useRef(null);
530
+ const limited = ui.rateLeft > 0;
531
+ useEffect(() => {
532
+ if (autoFocus) area.current?.focus();
533
+ }, [autoFocus]);
534
+ async function submit() {
535
+ if (busy || limited) return;
536
+ const length = [...text].length;
537
+ if (text.trim() === "" || length > MAX_CHARS) {
538
+ setError(s.tooLong);
539
+ area.current?.focus();
540
+ return;
541
+ }
542
+ setBusy(true);
543
+ setError(null);
544
+ const result = await ui.actions.post(text, parentId);
545
+ setBusy(false);
546
+ if (result.ok) {
547
+ setText("");
548
+ onCancel?.();
549
+ return;
550
+ }
551
+ if (result.reason !== "rate") setError(result.reason === "tooLong" ? s.tooLong : result.reason === "expired" ? s.expired : s.postError);
552
+ area.current?.focus();
553
+ }
554
+ const onKey = (e) => {
555
+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
556
+ e.preventDefault();
557
+ void submit();
558
+ } else if (e.key === "Escape" && onCancel) {
559
+ e.preventDefault();
560
+ onCancel();
561
+ }
562
+ };
563
+ const helpId = `${id}-help`;
564
+ const errId = `${id}-err`;
565
+ return /* @__PURE__ */ jsxs3("form", { className: "hyle-cm-compose", onSubmit: (e) => {
566
+ e.preventDefault();
567
+ void submit();
568
+ }, children: [
569
+ /* @__PURE__ */ jsx4(Avatar, { name }),
570
+ /* @__PURE__ */ jsxs3("div", { children: [
571
+ /* @__PURE__ */ jsxs3("p", { className: "hyle-cm-as", children: [
572
+ s.commentingAs.split("{name}")[0],
573
+ /* @__PURE__ */ jsx4("b", { children: name }),
574
+ s.commentingAs.split("{name}")[1]
575
+ ] }),
576
+ /* @__PURE__ */ jsx4("label", { className: "hyle-sr", htmlFor: id, children: parentId ? s.replyPlaceholder : s.write }),
577
+ /* @__PURE__ */ jsx4(
578
+ "textarea",
579
+ {
580
+ ref: area,
581
+ className: "hyle-cm-input",
582
+ id,
583
+ rows: 3,
584
+ maxLength: MAX_CHARS,
585
+ placeholder: parentId ? s.replyPlaceholder : s.placeholder,
586
+ value: text,
587
+ disabled: limited,
588
+ "aria-invalid": error ? true : void 0,
589
+ "aria-describedby": error ? errId : helpId,
590
+ onChange: (e) => setText(e.target.value),
591
+ onKeyDown: onKey
592
+ }
593
+ ),
594
+ error ? /* @__PURE__ */ jsxs3("p", { className: "hyle-cm-err", id: errId, role: "alert", children: [
595
+ /* @__PURE__ */ jsx4(Icon, { name: "alert" }),
596
+ /* @__PURE__ */ jsx4("span", { children: error })
597
+ ] }) : null,
598
+ /* @__PURE__ */ jsxs3("div", { className: "hyle-cm-foot", children: [
599
+ /* @__PURE__ */ jsx4("span", { className: "grow", id: helpId, children: limited ? fill(s.rateWait, { n: ui.rateLeft }) : s.help }),
600
+ /* @__PURE__ */ jsx4("span", { className: "cnt", children: fill(s.chars, { n: [...text].length, max: MAX_CHARS }) }),
601
+ onCancel ? /* @__PURE__ */ jsx4("button", { className: "hyle-btn sm", type: "button", onClick: onCancel, children: s.cancel }) : null,
602
+ /* @__PURE__ */ jsx4("button", { className: "hyle-btn primary", type: "submit", "aria-disabled": busy || limited ? true : void 0, "aria-busy": busy || void 0, children: busy ? s.posting : parentId ? s.reply : s.post })
603
+ ] })
604
+ ] })
605
+ ] });
606
+ }
607
+ function EditForm({ ui, node, initial }) {
608
+ const { s } = ui;
609
+ const [text, setText] = useState(initial);
610
+ const [busy, setBusy] = useState(false);
611
+ const [error, setError] = useState(null);
612
+ const area = useRef(null);
613
+ useEffect(() => area.current?.focus(), []);
614
+ const id = `${ui.idp}-edit-${node.id}`;
615
+ async function save() {
616
+ if (busy) return;
617
+ setBusy(true);
618
+ setError(null);
619
+ const r = await ui.actions.save(node.id, text);
620
+ setBusy(false);
621
+ if (r.ok) return;
622
+ setError(r.reason === "tooLong" ? s.tooLong : r.reason === "closed" ? s.editClosed : r.reason === "expired" ? s.expired : r.reason === "rate" ? s.rateTitle : s.postError);
623
+ area.current?.focus();
624
+ }
625
+ return /* @__PURE__ */ jsxs3("form", { onSubmit: (e) => {
626
+ e.preventDefault();
627
+ void save();
628
+ }, children: [
629
+ /* @__PURE__ */ jsx4("label", { className: "hyle-sr", htmlFor: id, children: s.edit }),
630
+ /* @__PURE__ */ jsx4(
631
+ "textarea",
632
+ {
633
+ ref: area,
634
+ className: "hyle-cm-input",
635
+ id,
636
+ rows: 3,
637
+ maxLength: MAX_CHARS,
638
+ value: text,
639
+ "aria-invalid": error ? true : void 0,
640
+ "aria-describedby": error ? `${id}-err` : void 0,
641
+ onChange: (e) => setText(e.target.value),
642
+ onKeyDown: (e) => {
643
+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
644
+ e.preventDefault();
645
+ void save();
646
+ } else if (e.key === "Escape") {
647
+ e.preventDefault();
648
+ ui.actions.edit(null);
649
+ }
650
+ }
651
+ }
652
+ ),
653
+ error ? /* @__PURE__ */ jsxs3("p", { className: "hyle-cm-err", id: `${id}-err`, role: "alert", children: [
654
+ /* @__PURE__ */ jsx4(Icon, { name: "alert" }),
655
+ /* @__PURE__ */ jsx4("span", { children: error })
656
+ ] }) : null,
657
+ /* @__PURE__ */ jsxs3("div", { className: "hyle-cm-foot", children: [
658
+ /* @__PURE__ */ jsx4("span", { className: "grow" }),
659
+ /* @__PURE__ */ jsx4("button", { className: "hyle-btn sm", type: "button", onClick: () => ui.actions.edit(null), children: s.cancel }),
660
+ /* @__PURE__ */ jsx4("button", { className: "hyle-btn sm primary", type: "submit", "aria-disabled": busy ? true : void 0, children: s.save })
661
+ ] })
662
+ ] });
663
+ }
664
+ function Actions({ ui, node }) {
665
+ const { s } = ui;
666
+ const local = ui.own[node.id];
667
+ const mine = node.mine || !!local;
668
+ const until = node.canEditUntil ?? (local ? local.at + EDIT_WINDOW_MS : void 0);
669
+ const minutes = until === void 0 ? 0 : Math.min(10, Math.ceil((until - Math.max(ui.now, local?.at ?? 0)) / 6e4));
670
+ const canReply = node.depth < MAX_DEPTH2 && node.status === "visible";
671
+ if (ui.confirming === node.id) {
672
+ return /* @__PURE__ */ jsxs3("div", { className: "hyle-cm-acts", role: "group", "aria-label": s.deleteConfirm, children: [
673
+ /* @__PURE__ */ jsx4("span", { className: "hyle-cm-depth", children: s.deleteConfirm }),
674
+ /* @__PURE__ */ jsx4("button", { className: "hyle-cm-btn danger", type: "button", onClick: () => ui.actions.remove(node.id), children: s.delete }),
675
+ /* @__PURE__ */ jsx4("button", { className: "hyle-cm-btn", type: "button", autoFocus: true, onClick: () => ui.actions.confirm(null), children: s.keep })
676
+ ] });
677
+ }
678
+ return /* @__PURE__ */ jsxs3("div", { className: "hyle-cm-acts", children: [
679
+ node.status === "visible" ? /* @__PURE__ */ jsx4(LikeButton, { ui, itemKey: node.id, serverCount: node.likes, serverOn: node.likedByMe, scope: "comment" }) : null,
680
+ canReply && ui.me && !ui.banned ? /* @__PURE__ */ jsxs3("button", { className: "hyle-cm-btn", type: "button", id: replyButtonId(ui, node.id), "aria-label": fill(s.replyTo, { name: node.name ?? "" }), "aria-expanded": ui.replyOpen === node.id, onClick: () => ui.actions.reply(ui.replyOpen === node.id ? null : node.id), children: [
681
+ /* @__PURE__ */ jsx4(Icon, { name: "reply" }),
682
+ s.reply
683
+ ] }) : null,
684
+ canReply && !ui.me ? /* @__PURE__ */ jsxs3(SignInLink, { ui, className: "hyle-cm-btn", children: [
685
+ /* @__PURE__ */ jsx4(Icon, { name: "reply" }),
686
+ /* @__PURE__ */ jsx4("span", { className: "hyle-sr", children: fill(s.replyTo, { name: node.name ?? "" }) }),
687
+ /* @__PURE__ */ jsx4("span", { "aria-hidden": "true", children: s.reply })
688
+ ] }) : null,
689
+ node.status === "visible" && node.depth >= MAX_DEPTH2 ? /* @__PURE__ */ jsx4("span", { className: "hyle-cm-depth", children: s.depthEnd }) : null,
690
+ mine && !ui.banned && minutes > 0 ? /* @__PURE__ */ jsxs3("button", { className: "hyle-cm-btn", type: "button", onClick: () => ui.actions.edit(node.id), children: [
691
+ s.edit,
692
+ " ",
693
+ /* @__PURE__ */ jsx4("small", { children: fill(s.editLeft, { n: minutes }) })
694
+ ] }) : null,
695
+ mine && !ui.banned ? /* @__PURE__ */ jsx4("button", { className: "hyle-cm-btn danger", type: "button", onClick: () => ui.actions.confirm(node.id), children: s.delete }) : null
696
+ ] });
697
+ }
698
+ function Thread({ ui, nodes }) {
699
+ return /* @__PURE__ */ jsx4("ol", { className: "hyle-cm-list", role: "list", children: nodes.map((node) => /* @__PURE__ */ jsx4(CommentItem, { ui, node }, node.id)) });
700
+ }
701
+ function CommentItem({ ui, node }) {
702
+ const { s } = ui;
703
+ const li = `${ui.idp}-c-${node.id}`;
704
+ const kids = node.kids.length > 0 ? /* @__PURE__ */ jsx4(Thread, { ui, nodes: node.kids }) : null;
705
+ if (node.status === "removed") {
706
+ const why = node.removedBy === "moderator" ? s.removedByModerator : node.removedBy === "author" ? s.removedByAuthor : s.removed;
707
+ return /* @__PURE__ */ jsxs3("li", { className: "hyle-cm", id: li, "data-depth": node.depth, "data-status": "removed", "data-removed-by": node.removedBy, children: [
708
+ /* @__PURE__ */ jsxs3("article", { "aria-label": why, children: [
709
+ /* @__PURE__ */ jsx4(Avatar, { name: null }),
710
+ /* @__PURE__ */ jsx4("div", { className: "hyle-cm-main", children: /* @__PURE__ */ jsx4("div", { className: "hyle-cm-body", children: /* @__PURE__ */ jsx4("p", { children: why }) }) })
711
+ ] }),
712
+ kids
713
+ ] });
714
+ }
715
+ const local = ui.own[node.id];
716
+ const mine = node.mine || !!local;
717
+ const editing = ui.editing === node.id && mine;
718
+ return /* @__PURE__ */ jsxs3("li", { className: "hyle-cm", id: li, "data-depth": node.depth, "data-status": node.status, children: [
719
+ /* @__PURE__ */ jsxs3("article", { "aria-labelledby": nameId(ui, node.id), children: [
720
+ /* @__PURE__ */ jsx4(Avatar, { name: node.name }),
721
+ /* @__PURE__ */ jsxs3("div", { className: "hyle-cm-main", children: [
722
+ /* @__PURE__ */ jsxs3("div", { className: "hyle-cm-by", children: [
723
+ /* @__PURE__ */ jsx4("b", { id: nameId(ui, node.id), tabIndex: -1, children: node.name }),
724
+ mine ? /* @__PURE__ */ jsx4("span", { className: "hyle-cm-tag", children: s.you }) : null,
725
+ /* @__PURE__ */ jsxs3("span", { children: [
726
+ /* @__PURE__ */ jsx4("time", { dateTime: node.createdAt, title: absolute(node.createdAt, ui.locale), children: relative(node.createdAt, ui.now, ui.locale, s) }),
727
+ node.editedAt ? /* @__PURE__ */ jsxs3(Fragment3, { children: [
728
+ " ",
729
+ /* @__PURE__ */ jsx4("span", { "aria-hidden": "true", children: "\xB7" }),
730
+ " ",
731
+ /* @__PURE__ */ jsx4("a", { href: `#${li}`, title: absolute(node.editedAt, ui.locale), children: s.edited })
732
+ ] }) : null
733
+ ] })
734
+ ] }),
735
+ editing ? /* @__PURE__ */ jsx4(EditForm, { ui, node, initial: local?.text ?? node.text ?? hastToMarkdown(node.tree) }) : node.text !== void 0 ? /* @__PURE__ */ jsx4("div", { className: "hyle-cm-body", children: /* @__PURE__ */ jsx4("p", { style: { whiteSpace: "pre-wrap" }, children: node.text }) }) : /* @__PURE__ */ jsx4(CommentBody, { tree: node.tree }),
736
+ node.status === "held" ? /* @__PURE__ */ jsxs3("p", { className: "hyle-cm-held", role: "status", children: [
737
+ /* @__PURE__ */ jsx4(Icon, { name: "clock" }),
738
+ /* @__PURE__ */ jsxs3("span", { children: [
739
+ /* @__PURE__ */ jsx4("b", { children: s.held }),
740
+ " ",
741
+ s.heldNote
742
+ ] })
743
+ ] }) : null,
744
+ editing ? null : /* @__PURE__ */ jsx4(Actions, { ui, node }),
745
+ ui.replyOpen === node.id && ui.me ? /* @__PURE__ */ jsx4(Composer, { ui, id: `${ui.idp}-rc-${node.id}`, parentId: node.id, name: ui.me, autoFocus: true, onCancel: () => ui.actions.reply(null) }) : null
746
+ ] })
747
+ ] }),
748
+ kids
749
+ ] });
750
+ }
751
+
752
+ // src/react/comments.tsx
753
+ import { Fragment as Fragment4, jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
754
+ var PAGE = 20;
755
+ var TICK_MS = 1e4;
756
+ var isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
757
+ var fill2 = (t, n) => t.replace("{n}", String(n));
758
+ function Comments({ path, endpoint, signInHref, locale, labels: s, initial, initialAt }) {
759
+ const idp = `hc${useId().replace(/[^A-Za-z0-9]/g, "")}`;
760
+ const [session, setSession] = useState2("loading");
761
+ const [listing, setListing] = useState2(initial ?? "loading");
762
+ const [own, setOwn] = useState2({});
763
+ const [held, setHeld] = useState2([]);
764
+ const [likes, setLikes] = useState2({});
765
+ const [replyOpen, setReplyOpen] = useState2(null);
766
+ const [editing, setEditing] = useState2(null);
767
+ const [confirming, setConfirming] = useState2(null);
768
+ const [banned, setBanned] = useState2(false);
769
+ const [expired, setExpired] = useState2(false);
770
+ const [rateUntil, setRateUntil] = useState2(0);
771
+ const [now, setNow] = useState2(() => initialAt ?? Date.now());
772
+ const [live, setLive] = useState2("");
773
+ const [actionError, setActionError] = useState2(null);
774
+ const [shown, setShown] = useState2(PAGE);
775
+ const [focusId, setFocusId] = useState2(null);
776
+ const pending = useRef2(/* @__PURE__ */ new Set());
777
+ const alive = useRef2(true);
778
+ const write404 = useRef2(0);
779
+ useEffect2(() => {
780
+ alive.current = true;
781
+ return () => void (alive.current = false);
782
+ }, []);
783
+ useEffect2(() => {
784
+ if (initialAt !== void 0) setNow(Date.now());
785
+ const t = setInterval(() => setNow(Date.now()), TICK_MS);
786
+ return () => clearInterval(t);
787
+ }, [initialAt]);
788
+ useEffect2(() => {
789
+ if (rateUntil <= Date.now()) return;
790
+ const t = setTimeout(() => setNow(Date.now()), rateUntil - Date.now() + 50);
791
+ return () => clearTimeout(t);
792
+ }, [rateUntil]);
793
+ const load = useCallback(async (silent) => {
794
+ const r = await call(endpoint, "GET", `/comments?path=${encodeURIComponent(path)}`);
795
+ if (!alive.current) return void 0;
796
+ const parsed = r.status === 200 ? parseListing(r.data) : void 0;
797
+ if (r.status === 404) setListing("off");
798
+ else if (parsed) {
799
+ setListing(parsed);
800
+ setLikes((l) => Object.fromEntries(Object.entries(l).filter(([k]) => pending.current.has(k))));
801
+ } else if (!silent) setListing("error");
802
+ return parsed;
803
+ }, [endpoint, path]);
804
+ useEffect2(() => {
805
+ setListing(initial ?? "loading");
806
+ void load(initial !== void 0);
807
+ void call(endpoint, "GET", "/session").then((r) => {
808
+ if (!alive.current) return;
809
+ const reader = isObject3(r.data) && isObject3(r.data.reader) ? r.data.reader : void 0;
810
+ setSession(r.status === 404 ? "off" : r.status === 200 && typeof reader?.name === "string" ? { name: reader.name } : null);
811
+ });
812
+ }, [endpoint, load, initial]);
813
+ useEffect2(() => {
814
+ if (!focusId) return;
815
+ const el = document.getElementById(`${idp}-${focusId}-n`);
816
+ if (el) {
817
+ el.focus();
818
+ setFocusId(null);
819
+ }
820
+ }, [focusId, listing, held, idp]);
821
+ const me = typeof session === "object" && session ? session.name : null;
822
+ const rateLeft = Math.max(0, Math.ceil((rateUntil - now) / 1e3));
823
+ const signInId = `${idp}-signin`;
824
+ function failed(status) {
825
+ if (status === 401) setExpired(true);
826
+ setActionError(status === 401 ? s.expired : s.actionError);
827
+ }
828
+ async function like(key, serverCount, serverOn) {
829
+ if (!me || banned || pending.current.has(key)) return;
830
+ const prev = likes[key] ?? { on: serverOn, count: serverCount };
831
+ const count2 = prev.count ?? serverCount;
832
+ pending.current.add(key);
833
+ setActionError(null);
834
+ setLikes((l) => ({ ...l, [key]: { on: !prev.on, count: Math.max(0, count2 + (prev.on ? -1 : 1)) } }));
835
+ const r = await call(endpoint, prev.on ? "DELETE" : "PUT", "/reactions", key === "article" ? { subject_type: "article", path } : { subject_type: "comment", comment_id: key });
836
+ pending.current.delete(key);
837
+ if (!alive.current) return;
838
+ const reaction = r.status === 200 && isObject3(r.data) && isObject3(r.data.reaction) ? r.data.reaction : void 0;
839
+ if (reaction && typeof reaction.like_count === "number") {
840
+ setLikes((l) => ({ ...l, [key]: { on: reaction.active === true, count: reaction.like_count } }));
841
+ return;
842
+ }
843
+ setLikes((l) => ({ ...l, [key]: { on: prev.on, count: count2 } }));
844
+ failed(r.status);
845
+ }
846
+ async function post(text, parentId) {
847
+ const r = await call(endpoint, "POST", "/comments", { path, body: text, ...parentId ? { parent_id: parentId } : {} });
848
+ const created = r.status === 201 && isObject3(r.data) && isObject3(r.data.comment) ? r.data.comment : void 0;
849
+ if (typeof created?.id === "string" && alive.current) {
850
+ const id = created.id;
851
+ write404.current = 0;
852
+ setOwn((o) => ({ ...o, [id]: { text, at: Date.now(), parentId } }));
853
+ setExpired(false);
854
+ if (created.status === "held") {
855
+ setHeld((h) => [{ id, parentId, text, name: me ?? "", createdAt: (/* @__PURE__ */ new Date()).toISOString() }, ...h]);
856
+ setLive(s.heldLive);
857
+ } else setLive(s.postedLive);
858
+ setShown(Number.MAX_SAFE_INTEGER);
859
+ setFocusId(id);
860
+ await load(true);
861
+ return { ok: true };
862
+ }
863
+ if (r.status === 429) {
864
+ setRateUntil(Date.now() + (r.retryAfter ?? 60) * 1e3);
865
+ setNow(Date.now());
866
+ return { ok: false, reason: "rate" };
867
+ }
868
+ if (r.status === 404) {
869
+ const [again, who] = await Promise.all([load(true), call(endpoint, "GET", "/session")]);
870
+ write404.current += 1;
871
+ const valid = who.status === 200 && isObject3(who.data) && isObject3(who.data.reader) && typeof who.data.reader.name === "string";
872
+ if (alive.current && valid && again && write404.current >= 2) setBanned(true);
873
+ return { ok: false, reason: "error" };
874
+ }
875
+ if (r.status === 401) setExpired(true);
876
+ return { ok: false, reason: r.status === 400 ? "tooLong" : r.status === 401 ? "expired" : "error" };
877
+ }
878
+ async function save(id, text) {
879
+ const r = await call(endpoint, "PATCH", `/comments/${id}`, { body: text });
880
+ if (r.status === 200 && alive.current) {
881
+ const meta = own[id];
882
+ setOwn((o) => ({ ...o, [id]: { text, at: o[id]?.at ?? Date.now(), parentId: o[id]?.parentId ?? null } }));
883
+ setHeld((h) => h.map((c) => c.id === id ? { ...c, text } : c));
884
+ setEditing(null);
885
+ setLive(s.savedLive);
886
+ setFocusId(id);
887
+ const fresh = await load(true);
888
+ if (fresh && !fresh.comments.some((c) => c.id === id)) setHeld((h) => h.some((c) => c.id === id) ? h : [{ id, parentId: meta?.parentId ?? null, text, name: me ?? "", createdAt: (/* @__PURE__ */ new Date()).toISOString() }, ...h]);
889
+ return { ok: true };
890
+ }
891
+ if (r.status === 429) {
892
+ setRateUntil(Date.now() + (r.retryAfter ?? 60) * 1e3);
893
+ setNow(Date.now());
894
+ return { ok: false, reason: "rate" };
895
+ }
896
+ if (r.status === 401) setExpired(true);
897
+ return r.status === 409 ? { ok: false, reason: "closed" } : { ok: false, reason: r.status === 400 ? "tooLong" : r.status === 401 ? "expired" : "error" };
898
+ }
899
+ async function remove(id) {
900
+ setActionError(null);
901
+ const r = await call(endpoint, "DELETE", `/comments/${id}`);
902
+ if (!alive.current) return;
903
+ setConfirming(null);
904
+ if (r.status !== 200) return failed(r.status);
905
+ setHeld((h) => h.filter((c) => c.id !== id));
906
+ setOwn(({ [id]: _gone, ...rest }) => rest);
907
+ setLive(s.deletedLive);
908
+ await load(true);
909
+ }
910
+ if (session === "off" || listing === "off") return null;
911
+ const loaded = typeof listing === "object" ? listing : void 0;
912
+ const ui = {
913
+ s,
914
+ locale,
915
+ now,
916
+ ready: session !== "loading",
917
+ me,
918
+ banned,
919
+ signInHref,
920
+ signInId,
921
+ idp,
922
+ rateLeft,
923
+ own,
924
+ likes,
925
+ replyOpen,
926
+ editing,
927
+ confirming,
928
+ actions: {
929
+ like: (k, c, on) => void like(k, c, on),
930
+ reply: (id) => {
931
+ const previous = replyOpen;
932
+ setReplyOpen(id);
933
+ if (id === null && previous) requestAnimationFrame(() => document.getElementById(replyButtonId(ui, previous))?.focus());
934
+ },
935
+ edit: setEditing,
936
+ confirm: setConfirming,
937
+ post,
938
+ save,
939
+ remove: (id) => void remove(id)
940
+ }
941
+ };
942
+ const thread = loaded ? buildThread(loaded, held) : [];
943
+ const hid = `${idp}-h`;
944
+ const canWrite = !!me && !banned;
945
+ return /* @__PURE__ */ jsxs4("section", { className: "hyle-comments", "aria-labelledby": hid, "data-slot-component": "Comments", children: [
946
+ /* @__PURE__ */ jsx5("div", { className: "hyle-cm-head", children: /* @__PURE__ */ jsxs4("h2", { id: hid, children: [
947
+ s.heading,
948
+ loaded ? /* @__PURE__ */ jsxs4(Fragment4, { children: [
949
+ " ",
950
+ /* @__PURE__ */ jsx5("span", { className: "hyle-cm-count", "aria-label": fill2(s.countLabel, loaded.comment_count), children: loaded.comment_count })
951
+ ] }) : null
952
+ ] }) }),
953
+ /* @__PURE__ */ jsx5("p", { className: "hyle-sr", role: "status", "aria-live": "polite", children: live }),
954
+ actionError ? /* @__PURE__ */ jsxs4("p", { className: "hyle-cm-err", role: "alert", children: [
955
+ /* @__PURE__ */ jsx5(Icon, { name: "alert" }),
956
+ /* @__PURE__ */ jsx5("span", { children: actionError })
957
+ ] }) : null,
958
+ listing === "error" ? /* @__PURE__ */ jsxs4("div", { className: "hyle-banner", "data-kind": "bad", role: "alert", children: [
959
+ /* @__PURE__ */ jsx5(Icon, { name: "alert" }),
960
+ /* @__PURE__ */ jsxs4("div", { className: "hyle-bt", children: [
961
+ /* @__PURE__ */ jsx5("b", { children: s.loadError }),
962
+ /* @__PURE__ */ jsx5("p", { children: s.loadErrorBody })
963
+ ] }),
964
+ /* @__PURE__ */ jsxs4("button", { className: "hyle-btn sm", type: "button", onClick: () => {
965
+ setListing("loading");
966
+ void load(false);
967
+ }, children: [
968
+ /* @__PURE__ */ jsx5(Icon, { name: "refresh" }),
969
+ s.retry
970
+ ] })
971
+ ] }) : /* @__PURE__ */ jsxs4(Fragment4, { children: [
972
+ loaded ? /* @__PURE__ */ jsx5("div", { className: "hyle-react", children: /* @__PURE__ */ jsx5(LikeButton, { ui, itemKey: "article", serverCount: loaded.like_count, serverOn: loaded.liked_by_me === true, scope: "article" }) }) : null,
973
+ held.length > 0 || (loaded?.mine_held?.length ?? 0) > 0 ? /* @__PURE__ */ jsxs4("div", { className: "hyle-banner", "data-kind": "warn", role: "status", children: [
974
+ /* @__PURE__ */ jsx5(Icon, { name: "clock" }),
975
+ /* @__PURE__ */ jsxs4("div", { className: "hyle-bt", children: [
976
+ /* @__PURE__ */ jsx5("b", { children: s.heldBanner }),
977
+ /* @__PURE__ */ jsx5("p", { children: s.heldBannerBody })
978
+ ] })
979
+ ] }) : null,
980
+ rateLeft > 0 ? /* @__PURE__ */ jsxs4("div", { className: "hyle-banner", "data-kind": "warn", children: [
981
+ /* @__PURE__ */ jsx5(Icon, { name: "clock" }),
982
+ /* @__PURE__ */ jsxs4("div", { className: "hyle-bt", children: [
983
+ /* @__PURE__ */ jsx5("b", { children: s.rateTitle }),
984
+ /* @__PURE__ */ jsx5("p", { children: s.rateBody })
985
+ ] })
986
+ ] }) : null,
987
+ banned ? /* @__PURE__ */ jsxs4("div", { className: "hyle-banner", children: [
988
+ /* @__PURE__ */ jsx5(Icon, { name: "ban" }),
989
+ /* @__PURE__ */ jsxs4("div", { className: "hyle-bt", children: [
990
+ /* @__PURE__ */ jsx5("b", { children: s.bannedTitle }),
991
+ /* @__PURE__ */ jsx5("p", { children: s.bannedBody })
992
+ ] })
993
+ ] }) : null,
994
+ session !== "loading" && (!me || expired) ? /* @__PURE__ */ jsxs4("div", { className: "hyle-cm-signin", id: signInId, children: [
995
+ /* @__PURE__ */ jsxs4("p", { children: [
996
+ /* @__PURE__ */ jsx5("b", { children: s.signInTitle }),
997
+ s.signInBody
998
+ ] }),
999
+ signInHref ? /* @__PURE__ */ jsx5("a", { className: "hyle-btn primary", href: signInHref, children: s.signIn }) : null
1000
+ ] }) : null,
1001
+ canWrite ? /* @__PURE__ */ jsx5(Composer, { ui, id: `${idp}-new`, parentId: null, name: me }) : null,
1002
+ !loaded ? /* @__PURE__ */ jsxs4("div", { role: "status", "aria-live": "polite", "aria-busy": "true", children: [
1003
+ /* @__PURE__ */ jsx5("span", { className: "hyle-sr", children: s.loading }),
1004
+ /* @__PURE__ */ jsx5("div", { "aria-hidden": "true", children: [0, 1, 2].map((i) => /* @__PURE__ */ jsxs4("div", { className: "hyle-cm-sk", children: [
1005
+ /* @__PURE__ */ jsx5("span", { className: "hyle-sk c" }),
1006
+ /* @__PURE__ */ jsxs4("div", { children: [
1007
+ /* @__PURE__ */ jsx5("span", { className: "hyle-sk l", style: { width: 120 } }),
1008
+ /* @__PURE__ */ jsx5("span", { className: "hyle-sk l", style: { width: "100%" } }),
1009
+ /* @__PURE__ */ jsx5("span", { className: "hyle-sk l", style: { width: "72%" } })
1010
+ ] })
1011
+ ] }, i)) })
1012
+ ] }) : thread.length === 0 ? /* @__PURE__ */ jsxs4("div", { className: "hyle-cm-empty", children: [
1013
+ /* @__PURE__ */ jsx5("b", { children: s.empty }),
1014
+ /* @__PURE__ */ jsx5("span", { children: s.emptyBody })
1015
+ ] }) : /* @__PURE__ */ jsxs4(Fragment4, { children: [
1016
+ /* @__PURE__ */ jsx5(Thread, { ui, nodes: thread.slice(0, shown) }),
1017
+ thread.length > shown ? /* @__PURE__ */ jsx5("div", { className: "hyle-cm-more", children: /* @__PURE__ */ jsx5("button", { className: "hyle-btn", type: "button", onClick: () => setShown((n) => n + PAGE), children: s.more }) }) : null,
1018
+ loaded.truncated ? /* @__PURE__ */ jsx5("p", { className: "hyle-cm-note", children: s.truncated }) : null
1019
+ ] })
1020
+ ] })
1021
+ ] });
1022
+ }
1023
+ export {
1024
+ Comments
1025
+ };