@tdacorp/hyle-sdk 0.17.0 → 0.22.2

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 (92) hide show
  1. package/README.md +261 -42
  2. package/dist/check-routes-bin.js +190 -53
  3. package/dist/{chunk-6VOHFFA5.js → chunk-7T5EEJHK.js} +2 -2
  4. package/dist/chunk-DUPT6XLB.js +57 -0
  5. package/dist/chunk-IW3TUD4G.js +841 -0
  6. package/dist/{chunk-MGSUQBDW.js → chunk-KU7LWK4E.js} +249 -24
  7. package/dist/{chunk-BUJFMR3M.js → chunk-QVYQM5R2.js} +15 -6
  8. package/dist/chunk-SFFBZFEN.js +178 -0
  9. package/dist/chunk-U74B7AUG.js +398 -0
  10. package/dist/chunk-ZIW6FDU2.js +1126 -0
  11. package/dist/client-BGjmEWhN.d.cts +207 -0
  12. package/dist/client-D0LTpr3Y.d.ts +207 -0
  13. package/dist/code-copy.cjs +74 -0
  14. package/dist/code-copy.d.cts +18 -0
  15. package/dist/code-copy.d.ts +18 -0
  16. package/dist/code-copy.js +50 -0
  17. package/dist/comments.cjs +738 -280
  18. package/dist/comments.d.cts +66 -3
  19. package/dist/comments.d.ts +66 -3
  20. package/dist/comments.js +419 -331
  21. package/dist/{diagram-viewer-FJPED4SN.js → diagram-viewer-XY3CG75U.js} +62 -21
  22. package/dist/docs-enhance.cjs +7 -4
  23. package/dist/docs-enhance.d.cts +5 -3
  24. package/dist/docs-enhance.d.ts +5 -3
  25. package/dist/docs-enhance.js +8 -5
  26. package/dist/{embed-DNTZ2UXv.d.ts → embed-CbtsbZs3.d.cts} +5 -3
  27. package/dist/{embed-BmdwA2G9.d.cts → embed-Cf_2ZR5x.d.ts} +5 -3
  28. package/dist/fragment-alias.cjs +51 -0
  29. package/dist/fragment-alias.d.cts +7 -0
  30. package/dist/fragment-alias.d.ts +7 -0
  31. package/dist/fragment-alias.js +27 -0
  32. package/dist/html.cjs +886 -0
  33. package/dist/html.d.cts +20 -0
  34. package/dist/html.d.ts +20 -0
  35. package/dist/html.js +45 -0
  36. package/dist/index.cjs +244 -24
  37. package/dist/index.d.cts +22 -68
  38. package/dist/index.d.ts +22 -68
  39. package/dist/index.js +12 -2
  40. package/dist/{labels-nmukKYgL.d.cts → labels-CrA-iqTN.d.cts} +9 -0
  41. package/dist/{labels-nmukKYgL.d.ts → labels-CrA-iqTN.d.ts} +9 -0
  42. package/dist/mermaid-diagram.cjs +441 -125
  43. package/dist/mermaid-diagram.d.cts +23 -7
  44. package/dist/mermaid-diagram.d.ts +23 -7
  45. package/dist/mermaid-diagram.js +213 -51
  46. package/dist/mermaid-image.cjs +137 -60
  47. package/dist/mermaid-image.d.cts +4 -3
  48. package/dist/mermaid-image.d.ts +4 -3
  49. package/dist/mermaid-image.js +27 -28
  50. package/dist/next.cjs +836 -304
  51. package/dist/next.d.cts +45 -20
  52. package/dist/next.d.ts +45 -20
  53. package/dist/next.js +151 -40
  54. package/dist/print-coordinator.cjs +157 -0
  55. package/dist/print-coordinator.d.cts +27 -0
  56. package/dist/print-coordinator.d.ts +27 -0
  57. package/dist/print-coordinator.js +83 -0
  58. package/dist/react.cjs +603 -240
  59. package/dist/react.d.cts +148 -30
  60. package/dist/react.d.ts +148 -30
  61. package/dist/react.js +26 -4
  62. package/dist/reactions.cjs +653 -0
  63. package/dist/reactions.d.cts +27 -0
  64. package/dist/reactions.d.ts +27 -0
  65. package/dist/reactions.js +364 -0
  66. package/dist/{resolve-euZ4-aC9.d.cts → resolve-BnIv7aB7.d.cts} +2 -2
  67. package/dist/{resolve-Ae7UFjsQ.d.ts → resolve-BysHtZ_i.d.ts} +2 -2
  68. package/dist/revalidation-callback-BQl77tQR.d.cts +75 -0
  69. package/dist/revalidation-callback-BQl77tQR.d.ts +75 -0
  70. package/dist/sanitize-BpY_AdZh.d.cts +23 -0
  71. package/dist/sanitize-BpY_AdZh.d.ts +23 -0
  72. package/dist/styles.css +100 -29
  73. package/dist/toc-spy.cjs +60 -0
  74. package/dist/toc-spy.d.cts +15 -0
  75. package/dist/toc-spy.d.ts +15 -0
  76. package/dist/toc-spy.js +36 -0
  77. package/dist/{types-Czt887Iv.d.cts → types-D09Z072G.d.cts} +57 -2
  78. package/dist/{types-Czt887Iv.d.ts → types-D09Z072G.d.ts} +57 -2
  79. package/dist/use-cache.cjs +89 -13
  80. package/dist/use-cache.d.cts +12 -5
  81. package/dist/use-cache.d.ts +12 -5
  82. package/dist/use-cache.js +8 -8
  83. package/dist/youtube-facade.cjs +50 -0
  84. package/dist/youtube-facade.d.cts +17 -0
  85. package/dist/youtube-facade.d.ts +17 -0
  86. package/dist/youtube-facade.js +26 -0
  87. package/package.json +16 -3
  88. package/dist/chunk-67IOIAVW.js +0 -35
  89. package/dist/chunk-DMK4XQLU.js +0 -1556
  90. package/dist/chunk-PJMJMP66.js +0 -63
  91. package/dist/revalidation-callback-D7Ms_Puz.d.cts +0 -42
  92. package/dist/revalidation-callback-D7Ms_Puz.d.ts +0 -42
@@ -1,8 +1,11 @@
1
1
  import {
2
2
  ASSET_FILE,
3
3
  ASSET_RESERVED_PATH,
4
- ASSET_ROUTE_PREFIX
5
- } from "./chunk-67IOIAVW.js";
4
+ ASSET_ROUTE_PREFIX,
5
+ PREVIEW_HEADER,
6
+ PREVIEW_PARAM,
7
+ PREVIEW_TOKEN
8
+ } from "./chunk-DUPT6XLB.js";
6
9
 
7
10
  // src/errors.ts
8
11
  var Cp1ClientError = class extends Error {
@@ -20,7 +23,43 @@ var Cp1ClientError = class extends Error {
20
23
  }
21
24
  };
22
25
 
26
+ // src/preview.ts
27
+ var ASSET_PATH = /^\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?:\.[a-z0-9]+)?(?= |$)/i;
28
+ var ASSET_PROPERTIES = ["src", "dataLight", "dataDark"];
29
+ var MAX_DEPTH = 200;
30
+ function mapNode(node, mark, depth) {
31
+ if (typeof node !== "object" || node === null || depth > MAX_DEPTH) return node;
32
+ const { properties, children } = node;
33
+ const marked = properties && Object.fromEntries(ASSET_PROPERTIES.filter((name) => name in properties).map((name) => [name, mark(properties[name])]));
34
+ return {
35
+ ...node,
36
+ ...properties ? { properties: { ...properties, ...marked } } : {},
37
+ ...Array.isArray(children) ? { children: children.map((child) => mapNode(child, mark, depth + 1)) } : {}
38
+ };
39
+ }
40
+ function withPreviewAssets(article, token) {
41
+ const mark = (value) => typeof value === "string" ? value.replace(ASSET_PATH, (path) => `${path}?${PREVIEW_PARAM}=${token}`) : value;
42
+ const { publication, content } = article;
43
+ return {
44
+ ...article,
45
+ publication: publication.cover ? { ...publication, cover: { path: String(mark(publication.cover.path)) } } : publication,
46
+ content: content.format === "hast" ? { ...content, tree: mapNode(content.tree, mark, 0) } : content
47
+ };
48
+ }
49
+
23
50
  // src/client.ts
51
+ var RENDERER_VERSION = "4";
52
+ function applyCredential(headers, credential, method, url) {
53
+ if (!credential.auth) {
54
+ headers.set("authorization", `Bearer ${credential.token}`);
55
+ return void 0;
56
+ }
57
+ const { workspaceId } = credential;
58
+ return credential.auth({ method, url }).then((extra) => {
59
+ for (const [name, value] of Object.entries(extra)) headers.set(name, value);
60
+ headers.set("cp-workspace", workspaceId);
61
+ });
62
+ }
24
63
  var DEFAULT_TIMEOUT_MS = 1e4;
25
64
  var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
26
65
  var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -43,6 +82,17 @@ async function readCapped(res, max) {
43
82
  }
44
83
  return Buffer.concat(chunks).toString("utf8");
45
84
  }
85
+ function isNotFoundBody(status, body) {
86
+ if (status !== 404) return false;
87
+ try {
88
+ return JSON.parse(body)?.error?.code === "NOT_FOUND";
89
+ } catch {
90
+ return false;
91
+ }
92
+ }
93
+ async function isNotFoundResponse(res) {
94
+ return isNotFoundBody(res.status, await readCapped(res, 64 * 1024).catch(() => ""));
95
+ }
46
96
  var KINDS = /* @__PURE__ */ new Set(["article", "list", "redirect", "notfound", "disabled"]);
47
97
  var isStrings = (value) => Array.isArray(value) && value.every((v) => typeof v === "string");
48
98
  function isMounts(data) {
@@ -62,14 +112,16 @@ function checkBaseUrl(baseUrl, allowInsecureHttp) {
62
112
  }
63
113
  function createHyleClient(options) {
64
114
  checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
65
- if (!options.token) throw new TypeError("token is required");
115
+ if (!options.auth && !options.token) throw new TypeError("token is required");
66
116
  const base = options.baseUrl.replace(/\/+$/, "");
67
117
  const fetchImpl = options.fetch ?? fetch;
68
118
  async function get(pathname, query, init) {
69
119
  const url = new URL(`${base}${pathname}`);
70
120
  url.search = query.toString();
71
121
  const headers = new Headers(init?.headers);
72
- headers.set("authorization", `Bearer ${options.token}`);
122
+ headers.set("cp-renderer-version", RENDERER_VERSION);
123
+ const applied = applyCredential(headers, options, "GET", url.toString());
124
+ if (applied) await applied;
73
125
  const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
74
126
  const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
75
127
  const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
@@ -109,41 +161,71 @@ function createHyleClient(options) {
109
161
  if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
110
162
  throw failure(reply);
111
163
  }
164
+ async function pushPosts(opts) {
165
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(opts.section)) throw new TypeError("section must be a section slug");
166
+ const query = new URLSearchParams();
167
+ if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
168
+ const reply = await get(`/cp1/read/sections/${opts.section}/posts`, query, opts.init);
169
+ const data = reply.parsed?.data;
170
+ if (data?.cp === 1 && data.kind === "push_posts" && Array.isArray(data.posts) && typeof data.complete === "boolean") return data;
171
+ throw failure(reply);
172
+ }
173
+ async function preview(token) {
174
+ if (typeof token !== "string" || !PREVIEW_TOKEN.test(token)) return { kind: "notfound" };
175
+ const reply = await get("/cp1/read/_preview", new URLSearchParams(), { headers: { [PREVIEW_HEADER]: token }, cache: "no-store" });
176
+ if (reply.status === 404 && reply.parsed?.error?.code === "NOT_FOUND") return { kind: "notfound" };
177
+ const data = reply.parsed?.data;
178
+ if (data?.cp === 1 && data.kind === "disabled") return { kind: "disabled" };
179
+ const article = data?.article;
180
+ if (data?.cp !== 1 || data.kind !== "preview" || typeof data.expires_at !== "string" || article?.kind !== "article" || article.content?.format !== "hast" || !article.publication) throw failure(reply);
181
+ return { kind: "preview", expires_at: data.expires_at, article: withPreviewAssets(article, token) };
182
+ }
112
183
  async function asset(file, opts = {}) {
113
184
  if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
114
- const headers = new Headers({ authorization: `Bearer ${options.token}` });
185
+ const { previewToken } = opts;
186
+ if (previewToken !== void 0 && !PREVIEW_TOKEN.test(previewToken)) throw new TypeError("previewToken is not a preview token");
187
+ const url = `${base}/cp1/read/assets/${file}`;
188
+ const headers = new Headers();
189
+ const applied = applyCredential(headers, options, "GET", url);
190
+ if (applied) await applied;
115
191
  for (const name of ["range", "if-range", "if-none-match"]) {
116
192
  const value = opts.headers?.[name];
117
193
  if (value) headers.set(name, value);
118
194
  }
119
- return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
195
+ if (previewToken !== void 0) headers.set(PREVIEW_HEADER, previewToken);
196
+ return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS), ...previewToken === void 0 ? {} : { cache: "no-store" } });
197
+ }
198
+ async function theme(opts = {}) {
199
+ const url = `${base}/cp1/read/theme.css`;
200
+ const headers = new Headers();
201
+ const applied = applyCredential(headers, options, "GET", url);
202
+ if (applied) await applied;
203
+ return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
120
204
  }
121
- return { resolve, mounts, asset };
205
+ return { resolve, mounts, pushPosts, preview, asset, theme };
122
206
  }
123
207
 
124
208
  // src/host-sync.ts
125
209
  var CONTROL_TOKEN_PREFIX = "hyle_tc_";
126
210
  var DEFAULT_TIMEOUT_MS2 = 1e4;
127
211
  var MAX_RESPONSE_BYTES = 1024 * 1024;
128
- var PATH = "/cp1/control/workspace/host-reserved-paths";
129
- async function syncHostReserved(input) {
212
+ async function put(input, path, body, read) {
130
213
  checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
131
- if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
214
+ if (input.token !== void 0 && !input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
132
215
  throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
133
216
  }
134
217
  const fetchImpl = input.fetch ?? fetch;
135
- const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
218
+ const url = `${input.baseUrl.replace(/\/+$/, "")}${path}`;
219
+ const headers = new Headers({ "content-type": "application/json", "idempotency-key": `sync-${crypto.randomUUID()}` });
220
+ await applyCredential(headers, input.auth ? { auth: input.auth, workspaceId: input.workspaceId } : { token: input.token }, "PUT", url);
221
+ headers.set("cp-workspace", input.workspaceId);
222
+ const res = await fetchImpl(url, {
136
223
  method: "PUT",
137
224
  // redirect "error": the bearer token must never follow a redirect to another host.
138
225
  redirect: "error",
139
226
  signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
140
- headers: {
141
- authorization: `Bearer ${input.token}`,
142
- "content-type": "application/json",
143
- "cp-workspace": input.workspaceId,
144
- "idempotency-key": `sync-${crypto.randomUUID()}`
145
- },
146
- body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
227
+ headers,
228
+ body: JSON.stringify(body)
147
229
  });
148
230
  const text = await readCapped(res, MAX_RESPONSE_BYTES);
149
231
  let parsed;
@@ -152,14 +234,18 @@ async function syncHostReserved(input) {
152
234
  } catch {
153
235
  parsed = void 0;
154
236
  }
155
- const data = parsed?.data;
156
- const conflicts = data?.conflicts;
157
- if (res.ok && data && Array.isArray(data.paths) && typeof data.changed === "boolean" && typeof data.synced_at === "string" && typeof conflicts?.total === "number" && Array.isArray(conflicts.offenders)) {
158
- return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
159
- }
237
+ const result = res.ok && parsed?.data ? read(parsed.data) : void 0;
238
+ if (result !== void 0) return result;
160
239
  const err = parsed?.error;
161
240
  throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
162
241
  }
242
+ function syncHostReserved(input) {
243
+ return put(input, "/cp1/control/workspace/host-reserved-paths", { paths: input.paths, host: input.host, build_id: input.buildId }, (data) => {
244
+ const conflicts = data.conflicts;
245
+ if (!Array.isArray(data.paths) || typeof data.changed !== "boolean" || typeof data.synced_at !== "string" || typeof conflicts?.total !== "number" || !Array.isArray(conflicts.offenders)) return void 0;
246
+ return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
247
+ });
248
+ }
163
249
 
164
250
  // src/delivery-dedupe.ts
165
251
  var DeliveryDedupe = class {
@@ -235,6 +321,35 @@ function isValidCacheTag(tag) {
235
321
  // src/revalidation-callback.ts
236
322
  var MAX_BODY_BYTES = 65536;
237
323
  var MAX_TAGS = 1e3;
324
+ var HOOK_WAIT_MS = 3e3;
325
+ var COMMENT_EVENT_TYPES = ["comment.held", "comment.reply", "comment.approved", "comment.hidden"];
326
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
327
+ var isText = (v) => typeof v === "string" && v.length > 0;
328
+ var isTextOrNull = (v) => v === null || isText(v);
329
+ var isEventPath = (v) => typeof v === "string" && v.startsWith("/") && !v.startsWith("//") && v.length <= 2048 && !/[\\\u0000-\u001f\u007f]/.test(v);
330
+ function parseCommentEvent(payload) {
331
+ if (!isRecord(payload) || payload.cp !== 1 || !isRecord(payload.data)) return void 0;
332
+ const type = COMMENT_EVENT_TYPES.find((t) => t === payload.type);
333
+ const { id, created_at, workspace_id, event_id, data } = payload;
334
+ if (!type || !isText(id) || !isText(created_at) || !isText(workspace_id) || !isText(event_id)) return void 0;
335
+ const { comment_id, parent_comment_id, publication_path, reader_sub, parent_reader_sub, status } = data;
336
+ if (!isText(comment_id) || !isTextOrNull(parent_comment_id) || !isEventPath(publication_path) || !isTextOrNull(reader_sub) || !isTextOrNull(parent_reader_sub)) return void 0;
337
+ if (status !== "held" && status !== "visible" && status !== "hidden") return void 0;
338
+ return { cp: 1, id, type, created_at, workspace_id, event_id, data: { comment_id, parent_comment_id, publication_path, reader_sub, parent_reader_sub, status } };
339
+ }
340
+ async function runHook(hook, event) {
341
+ let timer;
342
+ try {
343
+ await Promise.race([
344
+ Promise.resolve().then(() => hook(event)),
345
+ new Promise((_, reject) => timer = setTimeout(() => reject(new Error("timeout")), HOOK_WAIT_MS))
346
+ ]);
347
+ } catch {
348
+ console.error(`hyle: onCommentEvent failed or timed out for ${event.type} ${event.id}`);
349
+ } finally {
350
+ clearTimeout(timer);
351
+ }
352
+ }
238
353
  function createRevalidationCallbackRoute(options) {
239
354
  const dedupe = new DeliveryDedupe(options.dedupeCapacity);
240
355
  return {
@@ -269,7 +384,7 @@ function createRevalidationCallbackRoute(options) {
269
384
  if (body.workspace_id !== options.workspaceId) {
270
385
  return okResponse(0);
271
386
  }
272
- const deliveryId = req.headers.get("hyle-delivery-id");
387
+ const deliveryId = typeof body.id === "string" ? body.id : void 0;
273
388
  if (deliveryId && dedupe.has(deliveryId)) {
274
389
  return okResponse(0);
275
390
  }
@@ -284,6 +399,9 @@ function createRevalidationCallbackRoute(options) {
284
399
  return new Response(null, { status: 500 });
285
400
  }
286
401
  if (deliveryId) dedupe.add(deliveryId);
402
+ const hook = options.onCommentEvent;
403
+ const event = hook && parseCommentEvent(body);
404
+ if (hook && event) await runHook(hook, event);
287
405
  return okResponse(purged);
288
406
  }
289
407
  };
@@ -314,6 +432,106 @@ function okResponse(purged) {
314
432
  });
315
433
  }
316
434
 
435
+ // src/push.ts
436
+ var MAX_PUSH_BODY_BYTES = 2 * 1024 * 1024;
437
+ var seqKey = (sectionId, publicationId) => `${sectionId}:${publicationId}`;
438
+ var TYPES = /* @__PURE__ */ new Set(["post.published", "post.updated", "post.unpublished", "post.deleted", "post.moved", "section.moved"]);
439
+ var WITH_POST = /* @__PURE__ */ new Set(["post.published", "post.updated", "post.moved"]);
440
+ var ok = (applied) => new Response(JSON.stringify({ ok: true, applied }), { status: 200, headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" } });
441
+ function parseEvent(body) {
442
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return void 0;
443
+ const e = body;
444
+ if (e.type === "webhook.test") return "ignore";
445
+ if (e.schema !== "hyle.push/1") return "ignore";
446
+ const section = e.section;
447
+ const hasPost = typeof e.post === "object" && e.post !== null;
448
+ if (typeof e.type !== "string" || !TYPES.has(e.type) || typeof e.event_id !== "string" || typeof e.seq !== "number" || !Number.isSafeInteger(e.seq) || typeof section?.id !== "string" || typeof section.site_path !== "string" || hasPost !== WITH_POST.has(e.type) || e.type !== "section.moved" && typeof e.publication_id !== "string") return void 0;
449
+ return e;
450
+ }
451
+ function createPushRoute(options) {
452
+ const secrets = typeof options.secret === "string" ? [options.secret] : options.secret;
453
+ if (secrets.length === 0 || secrets.some((s) => !s)) throw new TypeError("secret is required");
454
+ return {
455
+ async POST(req) {
456
+ const declared = Number(req.headers.get("content-length"));
457
+ if (Number.isFinite(declared) && declared > MAX_PUSH_BODY_BYTES) return new Response(null, { status: 413 });
458
+ const raw = await readCapped3(req);
459
+ if (raw === void 0) return new Response(null, { status: 413 });
460
+ const verified = verifyHyleSignature({
461
+ header: req.headers.get("hyle-signature"),
462
+ rawBody: raw,
463
+ secrets,
464
+ ...options.toleranceSeconds !== void 0 ? { toleranceSeconds: options.toleranceSeconds } : {},
465
+ ...options.now !== void 0 ? { now: options.now } : {}
466
+ });
467
+ if (!verified) return new Response(null, { status: 401 });
468
+ let parsed;
469
+ try {
470
+ parsed = parseEvent(JSON.parse(raw));
471
+ } catch {
472
+ parsed = void 0;
473
+ }
474
+ if (parsed === void 0) return new Response(null, { status: 400 });
475
+ if (parsed === "ignore") return ok(false);
476
+ const event = parsed;
477
+ try {
478
+ if (event.publication_id !== void 0) {
479
+ const last = await options.store.getSeq(seqKey(event.section.id, event.publication_id));
480
+ if (last !== void 0 && event.seq <= last) return ok(false);
481
+ }
482
+ await options.onEvent(event);
483
+ if (event.publication_id !== void 0) await options.store.setSeq(seqKey(event.section.id, event.publication_id), event.seq);
484
+ } catch {
485
+ return new Response(null, { status: 500 });
486
+ }
487
+ return ok(true);
488
+ }
489
+ };
490
+ }
491
+ async function readCapped3(req) {
492
+ if (!req.body) return "";
493
+ const reader = req.body.getReader();
494
+ const chunks = [];
495
+ let total = 0;
496
+ for (; ; ) {
497
+ const { done, value } = await reader.read();
498
+ if (done) break;
499
+ total += value.byteLength;
500
+ if (total > MAX_PUSH_BODY_BYTES) {
501
+ await reader.cancel();
502
+ return void 0;
503
+ }
504
+ chunks.push(value);
505
+ }
506
+ return Buffer.concat(chunks).toString("utf8");
507
+ }
508
+ function staleAfterResync(result, local) {
509
+ const seen = /* @__PURE__ */ new Set([...result.publicationIds, ...result.skipped.map((s) => s.publication_id)]);
510
+ return local.filter((row) => !seen.has(row.publicationId) && row.seq <= result.asOfSeq).map((row) => row.publicationId);
511
+ }
512
+ async function resyncPath(client, options) {
513
+ const ids = [];
514
+ const skipped = [];
515
+ let asOfSeq;
516
+ let cursor;
517
+ for (; ; ) {
518
+ const page = await client.pushPosts({ section: options.section, ...cursor ? { cursor } : {} });
519
+ asOfSeq ??= page.as_of_seq;
520
+ if (asOfSeq === void 0) throw new Error("hyle resync: the first page carried no as_of_seq");
521
+ skipped.push(...page.skipped ?? []);
522
+ for (const post of page.posts) {
523
+ await options.onPost(post);
524
+ if (options.store) {
525
+ const key = seqKey(page.section.id, post.publication_id);
526
+ await options.store.setSeq(key, Math.max(asOfSeq, await options.store.getSeq(key) ?? 0));
527
+ }
528
+ ids.push(post.publication_id);
529
+ }
530
+ if (page.complete || page.next_cursor === null) return { asOfSeq, publicationIds: ids, skipped };
531
+ cursor = page.next_cursor;
532
+ }
533
+ }
534
+
317
535
  // src/sitemap.ts
318
536
  var PAGE_LIMIT = 100;
319
537
  var DEFAULT_MAX_PAGES = 20;
@@ -567,6 +785,8 @@ function cleanDisplayName(raw) {
567
785
  export {
568
786
  Cp1ClientError,
569
787
  readCapped,
788
+ isNotFoundBody,
789
+ isNotFoundResponse,
570
790
  checkBaseUrl,
571
791
  createHyleClient,
572
792
  syncHostReserved,
@@ -575,7 +795,12 @@ export {
575
795
  verifyHyleSignature,
576
796
  CACHE_TAG_PATTERN,
577
797
  isValidCacheTag,
798
+ parseCommentEvent,
578
799
  createRevalidationCallbackRoute,
800
+ MAX_PUSH_BODY_BYTES,
801
+ createPushRoute,
802
+ staleAfterResync,
803
+ resyncPath,
579
804
  listPublicationPaths,
580
805
  normalizeRoute,
581
806
  hostRoutesFromManifests,
@@ -7,15 +7,15 @@ var VIEWER_LABELS_EN = {
7
7
  zoomIn: "Zoom in",
8
8
  zoomOut: "Zoom out",
9
9
  fit: "Fit to window",
10
- actual: "Actual size",
10
+ actual: "100%: actual size",
11
11
  search: "Find in diagram",
12
12
  searchPlaceholder: "Find",
13
13
  noMatch: "No match",
14
14
  matchOf: "{n} of {total}",
15
- copySource: "Copy diagram source",
16
- downloadSvg: "Download SVG",
17
- downloadPng: "Download PNG",
18
- copyImage: "Copy as image",
15
+ copySource: "MMD: copy diagram source",
16
+ downloadSvg: "SVG: download",
17
+ downloadPng: "PNG: download",
18
+ copyImage: "IMG: copy as image",
19
19
  pngScale: "PNG scale",
20
20
  fullscreen: "Fullscreen",
21
21
  exitFullscreen: "Exit fullscreen",
@@ -28,7 +28,16 @@ var VIEWER_LABELS_EN = {
28
28
  legendDownstream: "Downstream",
29
29
  outgoing: "outgoing",
30
30
  tracing: "{label}: {up} upstream, {down} downstream",
31
- map: "Overview map"
31
+ map: "Overview map",
32
+ largeTitle: "Large diagram, not drawn automatically",
33
+ largeBody: "Drawing a diagram this size can freeze this page for a few seconds, so it waits until you ask. Press Draw diagram: it takes a couple of seconds (a few more on a phone) and the page may pause while it works.",
34
+ drawLarge: "Draw diagram",
35
+ drawing: "Drawing\u2026",
36
+ drawingBody: "Drawing the diagram\u2026 this takes a couple of seconds.",
37
+ drawAgain: "Draw again",
38
+ showSource: "Show full source",
39
+ hideSource: "Show less",
40
+ printPreparing: "Preparing diagrams for print\u2026 Esc cancels between steps."
32
41
  };
33
42
  var fill = (template, values) => template.replace(/\{(\w+)\}/g, (m, k) => k in values ? String(values[k]) : m);
34
43
 
@@ -0,0 +1,178 @@
1
+ // src/react/mermaid-config.ts
2
+ var MAX_MERMAID_SOURCE = 1024 * 1024;
3
+ var MAX_MERMAID_EDGES = 500;
4
+ var AUTO_RENDER_EDGES = 100;
5
+ var AUTO_RENDER_CHARS = 6e3;
6
+ var AUTO_RENDER_STATEMENTS = 250;
7
+ var AUTO_RENDER_WORDS = 800;
8
+ var AUTO_RENDER_GROUPS = 25;
9
+ var CLAMP_LINES = 12;
10
+ var isClampedSource = (source) => source.trimEnd().split("\n").length > CLAMP_LINES;
11
+ var DARK_VARIABLES = { edgeLabelBackground: "#333333" };
12
+ var DIAGRAM_COLOUR_ROLES = ["bg", "node", "node-text", "node-border", "line", "accent", "muted"];
13
+ var THEME_COLOUR = /^(?:#[0-9a-f]{6}(?:[0-9a-f]{2})?|transparent)$/;
14
+ function diagramThemeVariables(colours, dark) {
15
+ const [bg, node, text, border, line, accent, muted] = colours;
16
+ return {
17
+ darkMode: dark,
18
+ background: bg,
19
+ primaryColor: node,
20
+ primaryTextColor: text,
21
+ primaryBorderColor: border,
22
+ secondaryColor: bg,
23
+ secondaryTextColor: text,
24
+ secondaryBorderColor: muted,
25
+ tertiaryColor: bg,
26
+ tertiaryTextColor: text,
27
+ tertiaryBorderColor: muted,
28
+ lineColor: line,
29
+ textColor: text,
30
+ titleColor: text,
31
+ edgeLabelBackground: bg,
32
+ clusterBkg: bg,
33
+ clusterBorder: muted,
34
+ noteBkgColor: bg,
35
+ noteTextColor: text,
36
+ noteBorderColor: accent,
37
+ activationBorderColor: accent,
38
+ actorLineColor: muted,
39
+ signalColor: line,
40
+ signalTextColor: text
41
+ };
42
+ }
43
+ var COLOR = /^(rgba?|oklab|oklch|lab|lch)\(([^)]*)\)$|^color\(srgb ([^)]*)\)$/;
44
+ function isDark(css) {
45
+ const m = COLOR.exec(css.trim());
46
+ if (!m) return void 0;
47
+ const kind = m[1] ?? "color";
48
+ const parts = (m[2] ?? m[3] ?? "").split(/[\s,/]+/).filter(Boolean);
49
+ const [a, b, c] = parts.map((v) => v === "none" ? 0 : Number.parseFloat(v));
50
+ const alpha = parts[3] === void 0 ? 1 : Number.parseFloat(parts[3]) / (parts[3].endsWith("%") ? 100 : 1);
51
+ if (a === void 0 || b === void 0 || c === void 0 || [a, b, c, alpha].some(Number.isNaN) || alpha < 0.5) return void 0;
52
+ if (kind.startsWith("ok")) return (parts[0]?.endsWith("%") ? a / 100 : a) < 0.6;
53
+ if (kind.startsWith("l")) return a < 53;
54
+ const scale = kind === "color" ? 1 : 255;
55
+ return (0.2126 * a + 0.7152 * b + 0.0722 * c) / scale < 0.5;
56
+ }
57
+ function pickMermaidTheme(background, prefersDark, colorScheme = "") {
58
+ const declared = /\bdark\b/.test(colorScheme) === /\blight\b/.test(colorScheme) ? void 0 : /\bdark\b/.test(colorScheme);
59
+ return isDark(background) ?? declared ?? prefersDark ? "dark" : "default";
60
+ }
61
+ function watchPageTheme(el, onTheme) {
62
+ const scheme = window.matchMedia("(prefers-color-scheme: dark)");
63
+ const update = () => {
64
+ const style = getComputedStyle(el);
65
+ const colours = DIAGRAM_COLOUR_ROLES.map((role) => style.getPropertyValue(`--hyle-diagram-${role}`).trim());
66
+ onTheme(pickMermaidTheme(style.backgroundColor, scheme.matches, style.colorScheme), colours.every((c) => THEME_COLOUR.test(c)) ? colours.join(" ") : "");
67
+ };
68
+ update();
69
+ const observer = new MutationObserver(update);
70
+ observer.observe(document.documentElement, { attributes: true });
71
+ observer.observe(document.body, { attributes: true });
72
+ scheme.addEventListener("change", update);
73
+ return () => {
74
+ observer.disconnect();
75
+ scheme.removeEventListener("change", update);
76
+ };
77
+ }
78
+ var RENDER_TIMEOUT_MS = 1e4;
79
+ var NEAR_VIEWPORT_MARGIN = "200px";
80
+ var FRONTMATTER = /\s*-{3}[^\S\n]*\n[\s\S]*?\n[^\S\n]*-{3}[^\S\n]*(?:\n|$)/y;
81
+ var DIRECTIVE = /%%\{(?:(?!\}%%)[\s\S])*(?:\}%%)?/g;
82
+ var MAX_STRIP_ROUNDS = 16;
83
+ function dropFrontmatter(text) {
84
+ let end = 0;
85
+ for (; ; ) {
86
+ FRONTMATTER.lastIndex = end;
87
+ const block = FRONTMATTER.exec(text);
88
+ if (!block) return text.slice(end);
89
+ end += block[0].length;
90
+ }
91
+ }
92
+ function stripMermaidConfig(source) {
93
+ let text = source.replace(/\r\n?/g, "\n");
94
+ for (let round = 0; round < MAX_STRIP_ROUNDS; round++) {
95
+ const next = dropFrontmatter(text).replace(DIRECTIVE, "");
96
+ if (next === text) return text;
97
+ text = next;
98
+ }
99
+ return "";
100
+ }
101
+ var EDGE_TOKEN = /-{2,}|={2,}|~{3}|\.{2,}|\.-|-[>x)]/;
102
+ var ER_TOKEN = /-{2,}|={2,}|~{3}|\.{2,}|\.-|-[>x)]|-\.|to\b/i;
103
+ var AMPERSAND = /\s&(?=\s)/g;
104
+ var GROUP_OPENER = /^(?:subgraph\b|state\b.*\{)/;
105
+ var BLOCK_OPENER = /\bblock\b(?!-)/g;
106
+ var DEFAULT_LIMITS = { statements: AUTO_RENDER_STATEMENTS, words: AUTO_RENDER_WORDS, groups: AUTO_RENDER_GROUPS, edges: AUTO_RENDER_EDGES, blocks: Infinity, token: EDGE_TOKEN };
107
+ var TYPE_LIMITS = {
108
+ mindmap: { statements: 40 },
109
+ kanban: { statements: 100 },
110
+ block: { words: 100, blocks: 8 },
111
+ erDiagram: { statements: 120, edges: 50, token: ER_TOKEN },
112
+ "venn-beta": { statements: 180 },
113
+ classDiagram: { statements: 70, edges: 30 },
114
+ stateDiagram: { statements: 80 }
115
+ };
116
+ var COMMENT_LINE = /^[^\S\n\u2028\u2029]*%%[^\n]+\n?/gm;
117
+ var statementsOf = (code) => code.split(/[\n;]/).map((s) => s.trim()).filter((s) => s && s !== "end");
118
+ var edgeBound = (code, token) => {
119
+ const amps = code.match(AMPERSAND)?.length ?? 0;
120
+ return code.split(token).length - 1 + 2 * amps + Math.floor(amps ** 2 / 4);
121
+ };
122
+ function isLargeDiagram(source) {
123
+ if (source.length > AUTO_RENDER_CHARS) return true;
124
+ const code = stripMermaidConfig(source).replace(COMMENT_LINE, "");
125
+ const statements = statementsOf(code);
126
+ const first = statements.find((line) => !line.startsWith("%%")) ?? "";
127
+ const type = Object.keys(TYPE_LIMITS).find((keyword) => first.startsWith(keyword));
128
+ const limit = { ...DEFAULT_LIMITS, ...type ? TYPE_LIMITS[type] : void 0 };
129
+ const words = statements.reduce((n, line) => n + line.split(/\s+/).length, 0);
130
+ const groups = statements.filter((line) => GROUP_OPENER.test(line)).length;
131
+ const blocks = code.match(BLOCK_OPENER)?.length ?? 0;
132
+ return statements.length > limit.statements || words > limit.words || groups > limit.groups || blocks > limit.blocks || edgeBound(code, limit.token) > limit.edges;
133
+ }
134
+ var counter = 0;
135
+ var nextMermaidId = () => `hyleMermaid-${++counter}`;
136
+ function withTimeout(promise, ms) {
137
+ let timer;
138
+ const timeout = new Promise((_, reject) => {
139
+ timer = setTimeout(() => reject(new Error("timeout")), ms);
140
+ });
141
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
142
+ }
143
+ function whenNearViewport(el, onNear, Observer = globalThis.IntersectionObserver) {
144
+ if (!Observer) {
145
+ onNear();
146
+ return () => {
147
+ };
148
+ }
149
+ const observer = new Observer((entries) => {
150
+ if (entries.some((e) => e.isIntersecting)) {
151
+ observer.disconnect();
152
+ onNear();
153
+ }
154
+ }, { rootMargin: NEAR_VIEWPORT_MARGIN });
155
+ observer.observe(el);
156
+ return () => observer.disconnect();
157
+ }
158
+ function afterFullscreen(within, then) {
159
+ if (document.fullscreenElement && within?.contains(document.fullscreenElement)) void document.exitFullscreen().catch(() => {
160
+ }).then(then);
161
+ else then();
162
+ }
163
+
164
+ export {
165
+ MAX_MERMAID_SOURCE,
166
+ MAX_MERMAID_EDGES,
167
+ isClampedSource,
168
+ DARK_VARIABLES,
169
+ diagramThemeVariables,
170
+ watchPageTheme,
171
+ RENDER_TIMEOUT_MS,
172
+ stripMermaidConfig,
173
+ isLargeDiagram,
174
+ nextMermaidId,
175
+ withTimeout,
176
+ whenNearViewport,
177
+ afterFullscreen
178
+ };