@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
package/dist/next.js CHANGED
@@ -8,22 +8,26 @@ import {
8
8
  HyleCommentsView,
9
9
  HyleListView,
10
10
  ListPage,
11
+ REACTION_KINDS,
11
12
  absoluteUrl,
12
13
  articleAuthor,
13
14
  bareOrigin,
14
15
  hreflangLanguages,
16
+ isCursor,
15
17
  modifiedAt,
16
18
  parseListing,
17
19
  readingMinutes,
18
- stringsFor,
19
20
  validOgImage,
20
21
  wordCountOf
21
- } from "./chunk-DMK4XQLU.js";
22
+ } from "./chunk-ZIW6FDU2.js";
23
+ import {
24
+ stringsFor
25
+ } from "./chunk-IW3TUD4G.js";
22
26
  import {
23
27
  DEFAULT_REVALIDATE,
24
28
  fetchResolver,
25
29
  workspaceTags
26
- } from "./chunk-6VOHFFA5.js";
30
+ } from "./chunk-7T5EEJHK.js";
27
31
  import {
28
32
  Cp1ClientError,
29
33
  checkBaseUrl,
@@ -31,15 +35,20 @@ import {
31
35
  createHyleClient,
32
36
  createRevalidationCallbackRoute,
33
37
  engagementSigningKey,
38
+ isNotFoundBody,
39
+ isNotFoundResponse,
34
40
  listPublicationPaths,
35
41
  readCapped,
36
42
  signReaderAssertion
37
- } from "./chunk-MGSUQBDW.js";
43
+ } from "./chunk-KU7LWK4E.js";
38
44
  import {
39
45
  ASSET_CONTENT_TYPES,
40
46
  ASSET_FILE,
41
- ASSET_ROUTE_PREFIX
42
- } from "./chunk-67IOIAVW.js";
47
+ ASSET_ROUTE_PREFIX,
48
+ PREVIEW_PARAM,
49
+ PREVIEW_TOKEN,
50
+ THEME_FILE
51
+ } from "./chunk-DUPT6XLB.js";
43
52
 
44
53
  // src/next/page.tsx
45
54
  import { notFound, permanentRedirect, redirect } from "next/navigation";
@@ -66,7 +75,7 @@ function sitePathFrom(basePath, segments) {
66
75
  return void 0;
67
76
  }
68
77
  if (segment !== segment.normalize("NFC")) return void 0;
69
- if (segment === "" || segment === "." || segment === ".." || /[/\\\u0000-\u001f\u007f]/.test(segment)) return void 0;
78
+ if (segment === "" || segment === "." || segment.includes("..") || /[/\\\u0000-\u001f\u007f]|%[0-9a-f]{2}/i.test(segment)) return void 0;
70
79
  decoded.push(segment);
71
80
  }
72
81
  const path = decoded.length === 0 ? basePath || "/" : `${basePath}/${decoded.join("/")}`;
@@ -101,15 +110,17 @@ function routeContext(options, params) {
101
110
  const toHref = (sitePath, linkLocale = locale) => (linkLocale ? prefix(linkLocale) : "") + sitePath;
102
111
  return { basePath, path, locale, toHref };
103
112
  }
104
- function isRejectedRequest(error) {
113
+ function isNotFoundError(error, cursor) {
105
114
  unstable_rethrow(error);
106
- return error instanceof Cp1ClientError && error.status >= 400 && error.status < 500 && ![401, 403, 429].includes(error.status);
115
+ if (!(error instanceof Cp1ClientError)) return false;
116
+ return error.status === 404 && error.code === "NOT_FOUND" || cursor !== void 0 && error.status === 400 && error.code === "VALIDATION_ERROR";
107
117
  }
108
118
 
109
119
  // src/next/embed.tsx
110
120
  import { unstable_rethrow as unstable_rethrow2 } from "next/navigation";
111
121
 
112
122
  // src/next/engage.ts
123
+ import { createHash } from "crypto";
113
124
  var ENGAGE_CSRF_HEADER = "x-hyle-engage";
114
125
  var DEFAULT_TIMEOUT_MS = 1e4;
115
126
  var DEFAULT_SHARE_MS = 3e3;
@@ -143,9 +154,8 @@ function match(segments) {
143
154
  methods: ["GET", "POST"],
144
155
  rebuild: (method, body, url) => {
145
156
  if (method === "GET") {
146
- const keys = [...url.searchParams.keys()];
147
- const path = url.searchParams.get("path");
148
- return keys.length === 1 && isSitePath(path) ? { upstream: "/comments", query: new URLSearchParams({ path }) } : void 0;
157
+ const query = listingQuery(url.searchParams);
158
+ return query && { upstream: "/comments", query };
149
159
  }
150
160
  const clean = pick(body, ["path", "body", "parent_id"], ["path", "body"]);
151
161
  if (!clean || !isSitePath(clean.path) || !isCommentText(clean.body)) return void 0;
@@ -172,15 +182,38 @@ function match(segments) {
172
182
  methods: ["PUT", "DELETE"],
173
183
  rebuild: (_method, body) => {
174
184
  const type = body?.subject_type;
175
- const clean = type === "article" ? pick(body, ["subject_type", "path"], ["subject_type", "path"]) : type === "comment" ? pick(body, ["subject_type", "comment_id"], ["subject_type", "comment_id"]) : void 0;
176
- if (!clean) return void 0;
185
+ const subject = type === "article" ? "path" : type === "comment" ? "comment_id" : void 0;
186
+ const clean = subject && pick(body, ["subject_type", subject, "kind"], ["subject_type", subject]);
187
+ if (!clean || clean.kind !== void 0 && !REACTION_KINDS.includes(clean.kind)) return void 0;
177
188
  const valid = type === "article" ? isSitePath(clean.path) : typeof clean.comment_id === "string" && UUID.test(clean.comment_id);
178
189
  return valid ? { upstream: "/reactions", body: clean } : void 0;
179
190
  }
180
191
  };
181
192
  }
193
+ if (a === "votes" && b === void 0) {
194
+ return {
195
+ action: (m) => m === "PUT" ? "votes.set" : "votes.remove",
196
+ methods: ["PUT", "DELETE"],
197
+ rebuild: (method, body) => {
198
+ const keys = method === "PUT" ? ["comment_id", "value"] : ["comment_id"];
199
+ const clean = pick(body, keys, keys);
200
+ if (!clean || typeof clean.comment_id !== "string" || !UUID.test(clean.comment_id)) return void 0;
201
+ if (method === "PUT" && clean.value !== 1 && clean.value !== -1) return void 0;
202
+ return { upstream: "/votes", body: clean };
203
+ }
204
+ };
205
+ }
182
206
  return void 0;
183
207
  }
208
+ function listingQuery(params) {
209
+ const keys = [...params.keys()];
210
+ if (new Set(keys).size !== keys.length || keys.some((k) => k !== "path" && k !== "cursor" && k !== "sort")) return void 0;
211
+ const path = params.get("path");
212
+ const cursor = params.get("cursor");
213
+ const sort = params.get("sort");
214
+ if (!isSitePath(path) || cursor !== null && !isCursor(cursor) || sort !== null && sort !== "new" && sort !== "top") return void 0;
215
+ return new URLSearchParams({ path, ...cursor === null ? {} : { cursor }, ...sort === null ? {} : { sort } });
216
+ }
184
217
  function pick(body, allowed, required) {
185
218
  if (!body || Object.keys(body).some((k) => !allowed.includes(k)) || !required.every((k) => k in body)) return void 0;
186
219
  return Object.fromEntries(allowed.filter((k) => k in body).map((k) => [k, body[k]]));
@@ -289,7 +322,7 @@ function createEngagementRoute(options) {
289
322
  entry.result.then(
290
323
  (o) => {
291
324
  if (cache.get(key) !== entry) return;
292
- if (o.status !== 200 && o.status !== 404 || o.noShare || o.text.length > MAX_SHARED_ENTRY_BYTES) return forget(key, entry);
325
+ if (![200, 400, 404].includes(o.status) || o.noShare || o.text.length > MAX_SHARED_ENTRY_BYTES) return forget(key, entry);
293
326
  entry.bytes = o.text.length;
294
327
  cacheBytes += entry.bytes;
295
328
  while ((cacheBytes > MAX_SHARED_BYTES || cache.size > MAX_SHARED) && cache.size > 0) {
@@ -352,7 +385,7 @@ function createEngagementRoute(options) {
352
385
  }
353
386
  if (route.local === "session") {
354
387
  const who = await reader(req, config);
355
- return json(200, { data: { reader: who ? { name: who.reader.name } : null } });
388
+ return json(200, { data: { reader: who ? { id: createHash("sha256").update(who.reader.sub).digest("base64url"), name: who.reader.name } : null } });
356
389
  }
357
390
  let assertion;
358
391
  let viewer = null;
@@ -381,7 +414,9 @@ function createEngagementRoute(options) {
381
414
  redirect: "error",
382
415
  signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
383
416
  });
384
- return { status: res.status, ok: res.ok, text: await readCapped(res, MAX_RESPONSE_BYTES), retryAfter: res.headers.get("retry-after"), throttle: res.headers.get("hyle-throttle") };
417
+ const text = await readCapped(res, MAX_RESPONSE_BYTES);
418
+ const status = res.status === 404 && !isNotFoundBody(res.status, text) ? 502 : res.status;
419
+ return { status, ok: res.ok, text, retryAfter: res.headers.get("retry-after"), throttle: res.headers.get("hyle-throttle") };
385
420
  };
386
421
  try {
387
422
  const out = route.action(req.method) === "comments.list" ? await shared(`${viewer?.reader.sub ?? ""}
@@ -399,11 +434,11 @@ ${built.query.toString()}`, () => listing(viewer, call)) : await call();
399
434
 
400
435
  // src/next/embed.tsx
401
436
  import { jsx } from "react/jsx-runtime";
402
- async function resolveEmbed(options, run) {
437
+ async function resolveEmbed(options, run, cursor) {
403
438
  try {
404
439
  return { result: await run() };
405
440
  } catch (error) {
406
- if (isRejectedRequest(error)) return {};
441
+ if (isNotFoundError(error, cursor)) return {};
407
442
  console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
408
443
  return { failure: options.onError ? options.onError(error) : null };
409
444
  }
@@ -413,10 +448,11 @@ async function HyleList({ options, limit = 5, locale, layout, title, headingLeve
413
448
  const route = routeContext(locale ? { ...options, locale } : options, {});
414
449
  const path = sitePathFrom(route.basePath, void 0);
415
450
  if (path === void 0) return null;
416
- const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale, limit, validCursor(cursor)));
451
+ const after = validCursor(cursor);
452
+ const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale, limit, after), after);
417
453
  if (failure !== void 0) return failure;
418
454
  const next = olderHref && result?.kind === "list" ? validCursor(result.next_cursor) : void 0;
419
- return /* @__PURE__ */ jsx(HyleListView, { items: result?.kind === "list" ? result.items : [], layout, title, headingLevel, moreHref, olderHref: next ? olderHref?.(next) : void 0, components: options.components, slots: options.slots, locale: route.locale, toHref: route.toHref });
455
+ return /* @__PURE__ */ jsx(HyleListView, { items: result?.kind === "list" ? result.items : [], theme: result?.kind === "list" ? result.theme : void 0, layout, title, headingLevel, moreHref, olderHref: next ? olderHref?.(next) : void 0, components: options.components, slots: options.slots, locale: route.locale, toHref: route.toHref });
420
456
  }
421
457
  async function HyleArticle({ options, path, locale, headingLevel }) {
422
458
  if (!isSitePath(path)) return null;
@@ -445,7 +481,7 @@ async function HyleComments({ options, path, revalidate = 60, interactive }) {
445
481
  };
446
482
  const res = await fetch(`${options.baseUrl.replace(/\/+$/, "")}/cp1/engage/comments?${new URLSearchParams({ path })}`, init);
447
483
  if (!res.ok) {
448
- if (res.status !== 404) console.error(`hyle: comments answered HTTP ${res.status}`);
484
+ if (!await isNotFoundResponse(res)) console.error(`hyle: comments answered HTTP ${res.status}`);
449
485
  return null;
450
486
  }
451
487
  listing = parseListing(JSON.parse(await readCapped(res, MAX_LISTING_BYTES)).data);
@@ -476,8 +512,9 @@ function hylePage(options) {
476
512
  return async function HylePage({ params, searchParams }) {
477
513
  const { path, locale, toHref } = routeContext(options, await params ?? {});
478
514
  if (path === void 0) notFound();
515
+ let cursor;
479
516
  try {
480
- const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
517
+ cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
481
518
  const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
482
519
  switch (result.kind) {
483
520
  case "article": {
@@ -505,7 +542,7 @@ function hylePage(options) {
505
542
  notFound();
506
543
  }
507
544
  } catch (error) {
508
- if (isRejectedRequest(error)) notFound();
545
+ if (isNotFoundError(error, cursor)) notFound();
509
546
  if (!options.onError) throw error;
510
547
  console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
511
548
  return options.onError(error);
@@ -606,8 +643,9 @@ function hyleMetadata(options) {
606
643
  };
607
644
  return Object.keys(types).length ? { ...alternates, types } : alternates;
608
645
  };
646
+ let cursor;
609
647
  try {
610
- const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
648
+ cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
611
649
  const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
612
650
  const parentMeta = parent ? await parent : void 0;
613
651
  const parentImages = parentMeta?.openGraph?.images;
@@ -683,7 +721,7 @@ function hyleMetadata(options) {
683
721
  } : {}
684
722
  };
685
723
  } catch (error) {
686
- if (isRejectedRequest(error)) return {};
724
+ if (isNotFoundError(error, cursor)) return {};
687
725
  throw error;
688
726
  }
689
727
  };
@@ -745,7 +783,7 @@ function createRevalidateRoute(options) {
745
783
  if (!workspaceId || secrets.length === 0) return new Response(null, { status: 503 });
746
784
  const key = `${workspaceId}\0${secrets.join("\0")}`;
747
785
  if (cached?.key !== key) {
748
- cached = { key, route: createRevalidationCallbackRoute({ workspaceId, secrets, revalidateTag: (tag2) => revalidateTag(tag2, { expire: 0 }) }) };
786
+ cached = { key, route: createRevalidationCallbackRoute({ workspaceId, secrets, revalidateTag: (tag2) => revalidateTag(tag2, { expire: 0 }), onCommentEvent: options.onCommentEvent }) };
749
787
  }
750
788
  return cached.route.POST(req);
751
789
  }
@@ -753,7 +791,7 @@ function createRevalidateRoute(options) {
753
791
  }
754
792
 
755
793
  // src/next/root.ts
756
- import { notFound as notFound2 } from "next/navigation";
794
+ import { notFound as notFound2, unstable_rethrow as unstable_rethrow4 } from "next/navigation";
757
795
 
758
796
  // src/next/mount-match.ts
759
797
  function activeMounts(mounts) {
@@ -800,10 +838,7 @@ function mountsLoader(config) {
800
838
  lastKnownGood.set(key, { loaded, at: Date.now() });
801
839
  return loaded;
802
840
  } catch (error) {
803
- if (isRejectedRequest(error)) {
804
- lastKnownGood.delete(key);
805
- return NONE;
806
- }
841
+ unstable_rethrow4(error);
807
842
  if (error instanceof Cp1ClientError && (error.status === 401 || error.status === 403)) {
808
843
  lastKnownGood.delete(key);
809
844
  throw error;
@@ -935,7 +970,7 @@ function createMarkdownRoute(options) {
935
970
  }
936
971
  return reply(null, 404);
937
972
  } catch (error) {
938
- if (isRejectedRequest(error)) return reply(null, 404);
973
+ if (isNotFoundError(error)) return reply(null, 404);
939
974
  console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
940
975
  return reply(null, 502);
941
976
  }
@@ -944,7 +979,7 @@ function createMarkdownRoute(options) {
944
979
  }
945
980
 
946
981
  // src/next/llms.ts
947
- import { unstable_rethrow as unstable_rethrow4 } from "next/navigation";
982
+ import { unstable_rethrow as unstable_rethrow5 } from "next/navigation";
948
983
  var oneLine = (text) => text.replace(/\s+/g, " ").trim();
949
984
  var linkTarget = (url) => url.replace(/[()]/g, (c) => c === "(" ? "%28" : "%29");
950
985
  function createLlmsTxtRoute(options, llms) {
@@ -969,7 +1004,7 @@ function createLlmsTxtRoute(options, llms) {
969
1004
  return new Response(`${lines.join("\n")}
970
1005
  `, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
971
1006
  } catch (error) {
972
- unstable_rethrow4(error);
1007
+ unstable_rethrow5(error);
973
1008
  console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
974
1009
  return new Response(null, { status: 503 });
975
1010
  }
@@ -986,8 +1021,34 @@ var DEFAULT_TIMEOUT_MS2 = 3e4;
986
1021
  var CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400";
987
1022
  var PARTIAL_CACHE_CONTROL = "no-store";
988
1023
  var SAFE_HEADERS = { "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" };
1024
+ var PREVIEW_HEADERS = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Robots-Tag": "noindex, nofollow" };
989
1025
  var empty = (status, headers = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers } });
990
1026
  var isSwitchedOff3 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
1027
+ var THEME_CACHE_CONTROL = "public, max-age=31536000, immutable";
1028
+ var OUTDATED_THEME_CACHE_CONTROL = "public, max-age=60";
1029
+ var THEME_SCOPE_HEADER = "cp-theme-scope";
1030
+ var MAX_THEME_BYTES = 256 * 1024;
1031
+ var sha256Hex = async (text) => Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))), (byte) => byte.toString(16).padStart(2, "0")).join("");
1032
+ async function serveTheme(client, scope, hash, timeoutMs, head) {
1033
+ try {
1034
+ const upstream = await client.theme({ timeoutMs });
1035
+ const type = upstream.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
1036
+ if (upstream.status === 404) return empty(await isNotFoundResponse(upstream) ? 404 : 502);
1037
+ if (upstream.status !== 200 || type !== "text/css") {
1038
+ void upstream.body?.cancel().catch(() => {
1039
+ });
1040
+ return empty(502);
1041
+ }
1042
+ const css = await readCapped(upstream, MAX_THEME_BYTES);
1043
+ const current = await sha256Hex(css);
1044
+ if (current !== hash && upstream.headers.get(THEME_SCOPE_HEADER) !== scope) return empty(404);
1045
+ const cache = current === hash ? THEME_CACHE_CONTROL : OUTDATED_THEME_CACHE_CONTROL;
1046
+ const headers = { "Content-Type": "text/css; charset=utf-8", "Cache-Control": cache, ETag: `"${current}"`, ...SAFE_HEADERS };
1047
+ return new Response(head ? null : css, { status: 200, headers });
1048
+ } catch {
1049
+ return empty(502);
1050
+ }
1051
+ }
991
1052
  function capped(body, max) {
992
1053
  let seen = 0;
993
1054
  return body.pipeThrough(
@@ -1004,18 +1065,28 @@ function createAssetRoute(options) {
1004
1065
  let client;
1005
1066
  const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
1006
1067
  async function serve(req, ctx, head) {
1068
+ const previewToken = new URL(req.url).searchParams.get(PREVIEW_PARAM);
1069
+ const res = await relay(req, ctx, head, previewToken);
1070
+ if (previewToken !== null) for (const [name, value] of Object.entries(PREVIEW_HEADERS)) res.headers.set(name, value);
1071
+ return res;
1072
+ }
1073
+ async function relay(req, ctx, head, previewToken) {
1007
1074
  if (isSwitchedOff3((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return empty(404);
1008
1075
  const file = (await ctx.params).file;
1009
- if (typeof file !== "string" || !ASSET_FILE.test(file)) return empty(404);
1076
+ const [, themeScope, themeHash] = typeof file === "string" ? THEME_FILE.exec(file) ?? [] : [];
1077
+ if (typeof file !== "string" || !themeHash && !ASSET_FILE.test(file)) return empty(404);
1078
+ if (previewToken !== null && !PREVIEW_TOKEN.test(previewToken)) return empty(404);
1010
1079
  try {
1011
1080
  client ??= createHyleClient({ baseUrl: options.baseUrl?.trim() ?? "", token: options.token?.trim() ?? "", ...options.fetch ? { fetch: options.fetch } : {} });
1012
1081
  } catch {
1013
1082
  return empty(404);
1014
1083
  }
1084
+ if (themeScope && themeHash) return serveTheme(client, themeScope, themeHash, options.timeoutMs ?? DEFAULT_TIMEOUT_MS2, head);
1015
1085
  let upstream;
1016
1086
  try {
1017
1087
  upstream = await client.asset(file, {
1018
1088
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS2,
1089
+ ...previewToken === null ? {} : { previewToken },
1019
1090
  headers: { range: req.headers.get("range"), "if-range": req.headers.get("if-range"), "if-none-match": req.headers.get("if-none-match") }
1020
1091
  });
1021
1092
  } catch {
@@ -1028,10 +1099,16 @@ function createAssetRoute(options) {
1028
1099
  drop();
1029
1100
  return new Response(null, { status: 304, headers: { "Cache-Control": CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS, ...etag ? { ETag: etag } : {} } });
1030
1101
  }
1031
- if (upstream.status === 404 || upstream.status === 416) {
1102
+ if (upstream.status === 404) return empty(await isNotFoundResponse(upstream) ? 404 : 502);
1103
+ if (upstream.status === 416) {
1032
1104
  drop();
1033
- const range = upstream.status === 416 ? upstream.headers.get("content-range") : null;
1034
- return empty(upstream.status, range ? { "Content-Range": range } : {});
1105
+ const range = upstream.headers.get("content-range");
1106
+ return empty(416, range ? { "Content-Range": range } : {});
1107
+ }
1108
+ if (upstream.status === 429 && previewToken !== null) {
1109
+ drop();
1110
+ const wait = upstream.headers.get("retry-after");
1111
+ return empty(429, wait ? { "Retry-After": wait } : {});
1035
1112
  }
1036
1113
  const type = upstream.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
1037
1114
  const length = Number(upstream.headers.get("content-length"));
@@ -1080,7 +1157,7 @@ function createOgImageRoute(options) {
1080
1157
  if (result.kind !== "article") return new Response(null, { status: 404 });
1081
1158
  title = result.publication.title;
1082
1159
  } catch (error) {
1083
- return new Response(null, { status: isRejectedRequest(error) ? 404 : 502 });
1160
+ return new Response(null, { status: isNotFoundError(error) ? 404 : 502 });
1084
1161
  }
1085
1162
  const chars = [...title];
1086
1163
  const shown = chars.length > MAX_TITLE ? `${chars.slice(0, MAX_TITLE - 1).join("")}\u2026` : title;
@@ -1095,6 +1172,38 @@ function createOgImageRoute(options) {
1095
1172
  }
1096
1173
  };
1097
1174
  }
1175
+
1176
+ // src/next/preview.tsx
1177
+ import { notFound as notFound3 } from "next/navigation";
1178
+ import { Fragment, jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
1179
+ var hylePreviewMetadata = { robots: { index: false, follow: false }, referrer: "no-referrer" };
1180
+ var BANNER = {
1181
+ position: "sticky",
1182
+ top: 0,
1183
+ zIndex: 2147483647,
1184
+ padding: "8px 16px",
1185
+ background: "#fde047",
1186
+ color: "#1a1a1a",
1187
+ font: "600 14px/1.4 system-ui, sans-serif",
1188
+ textAlign: "center"
1189
+ };
1190
+ function hylePreviewPage(options) {
1191
+ return async function HylePreviewPage({ searchParams }) {
1192
+ const { token } = await searchParams ?? {};
1193
+ const result = await createHyleClient(options).preview(typeof token === "string" ? token : void 0);
1194
+ if (result.kind !== "preview") notFound3();
1195
+ const { article } = result;
1196
+ const { locale } = article.publication;
1197
+ const toHref = (sitePath, linkLocale = locale) => (options.localePrefix?.(linkLocale) ?? "") + sitePath;
1198
+ const props = { article, components: options.components, slots: options.slots, locale, toHref };
1199
+ return /* @__PURE__ */ jsxs2(Fragment, { children: [
1200
+ /* @__PURE__ */ jsx4("meta", { name: "robots", content: "noindex, nofollow" }),
1201
+ /* @__PURE__ */ jsx4("meta", { name: "referrer", content: "no-referrer" }),
1202
+ /* @__PURE__ */ jsx4("div", { role: "status", style: BANNER, children: "Unpublished draft preview" }),
1203
+ options.layout === "docs" ? /* @__PURE__ */ jsx4(DocsPage, { ...props }) : /* @__PURE__ */ jsx4(ArticlePage, { ...props })
1204
+ ] });
1205
+ };
1206
+ }
1098
1207
  export {
1099
1208
  ENGAGE_CSRF_HEADER,
1100
1209
  HyleArticle,
@@ -1113,6 +1222,8 @@ export {
1113
1222
  hyleFeedLink,
1114
1223
  hyleMetadata,
1115
1224
  hylePage,
1225
+ hylePreviewMetadata,
1226
+ hylePreviewPage,
1116
1227
  hyleRootMetadata,
1117
1228
  hyleRootPage,
1118
1229
  hyleRootSitemap,
@@ -0,0 +1,157 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/react/print-coordinator.ts
21
+ var print_coordinator_exports = {};
22
+ __export(print_coordinator_exports, {
23
+ holdPrintUntil: () => holdPrintUntil,
24
+ installPrintShortcut: () => installPrintShortcut,
25
+ registerPrintTarget: () => registerPrintTarget
26
+ });
27
+ module.exports = __toCommonJS(print_coordinator_exports);
28
+
29
+ // src/react/mermaid-config.ts
30
+ var MAX_MERMAID_SOURCE = 1024 * 1024;
31
+ var RENDER_TIMEOUT_MS = 1e4;
32
+ function withTimeout(promise, ms) {
33
+ let timer;
34
+ const timeout = new Promise((_, reject) => {
35
+ timer = setTimeout(() => reject(new Error("timeout")), ms);
36
+ });
37
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
38
+ }
39
+
40
+ // src/react/viewer/labels.ts
41
+ var VIEWER_LABELS_EN = {
42
+ expand: "Expand diagram",
43
+ expandHint: "Expand",
44
+ viewer: "Diagram viewer",
45
+ close: "Close",
46
+ zoomIn: "Zoom in",
47
+ zoomOut: "Zoom out",
48
+ fit: "Fit to window",
49
+ actual: "100%: actual size",
50
+ search: "Find in diagram",
51
+ searchPlaceholder: "Find",
52
+ noMatch: "No match",
53
+ matchOf: "{n} of {total}",
54
+ copySource: "MMD: copy diagram source",
55
+ downloadSvg: "SVG: download",
56
+ downloadPng: "PNG: download",
57
+ copyImage: "IMG: copy as image",
58
+ pngScale: "PNG scale",
59
+ fullscreen: "Fullscreen",
60
+ exitFullscreen: "Exit fullscreen",
61
+ copied: "Copied",
62
+ saved: "Saved",
63
+ unavailable: "Not available here",
64
+ hint: "Scroll to zoom, drag to pan, click a node to trace its paths, press / to search",
65
+ legendSelected: "Selected",
66
+ legendUpstream: "Upstream",
67
+ legendDownstream: "Downstream",
68
+ outgoing: "outgoing",
69
+ tracing: "{label}: {up} upstream, {down} downstream",
70
+ map: "Overview map",
71
+ largeTitle: "Large diagram, not drawn automatically",
72
+ 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.",
73
+ drawLarge: "Draw diagram",
74
+ drawing: "Drawing\u2026",
75
+ drawingBody: "Drawing the diagram\u2026 this takes a couple of seconds.",
76
+ drawAgain: "Draw again",
77
+ showSource: "Show full source",
78
+ hideSource: "Show less",
79
+ printPreparing: "Preparing diagrams for print\u2026 Esc cancels between steps."
80
+ };
81
+
82
+ // src/react/print-coordinator.ts
83
+ var targets = /* @__PURE__ */ new Set();
84
+ var loading = /* @__PURE__ */ new Set();
85
+ function holdPrintUntil(loaded) {
86
+ loading.add(loaded);
87
+ const release = () => void loading.delete(loaded);
88
+ void loaded.then(release, release);
89
+ }
90
+ function registerPrintTarget(target) {
91
+ targets.add(target);
92
+ return () => void targets.delete(target);
93
+ }
94
+ function isPrintChord(e) {
95
+ const platform = navigator.userAgentData?.platform || navigator.platform;
96
+ const modifier = /mac/i.test(platform) ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey;
97
+ const nonLatinLetter = /^\p{L}$/u.test(e.key) && !/\p{Script=Latin}/u.test(e.key);
98
+ const isP = e.key.toLowerCase() === "p" || nonLatinLetter && e.code === "KeyP";
99
+ return modifier && !e.altKey && !e.shiftKey && isP;
100
+ }
101
+ function showStatus() {
102
+ const note = document.createElement("div");
103
+ note.className = "hyle-print-status";
104
+ note.setAttribute("role", "status");
105
+ note.textContent = [...targets].find((t) => t.status)?.status ?? VIEWER_LABELS_EN.printPreparing;
106
+ const dialogs = document.querySelectorAll("dialog[open]");
107
+ (dialogs[dialogs.length - 1] ?? document.body).append(note);
108
+ return () => note.remove();
109
+ }
110
+ var cancel = null;
111
+ var installs = 0;
112
+ async function printWhenDrawn() {
113
+ let cancelled = false;
114
+ const escaped = new Promise((resolve) => {
115
+ cancel = () => {
116
+ cancelled = true;
117
+ resolve();
118
+ };
119
+ });
120
+ const hideStatus = showStatus();
121
+ const drawn = withTimeout(Promise.all(loading).then(() => Promise.all([...targets].map((t) => t.prepare?.()))), RENDER_TIMEOUT_MS).catch((error) => {
122
+ loading.clear();
123
+ throw error;
124
+ }).then(() => withTimeout(Promise.all([...targets].map((t) => t.ensureDrawn())), RENDER_TIMEOUT_MS)).catch(() => void 0);
125
+ await Promise.race([drawn, escaped]);
126
+ cancel = null;
127
+ hideStatus();
128
+ if (!cancelled) window.print();
129
+ }
130
+ function onKeyDown(e) {
131
+ if (e.defaultPrevented) return;
132
+ if (cancel && e.key === "Escape") {
133
+ e.preventDefault();
134
+ return cancel();
135
+ }
136
+ if (!isPrintChord(e)) return;
137
+ if (!cancel && loading.size === 0 && [...targets].every((t) => t.settled())) return;
138
+ e.preventDefault();
139
+ if (!cancel) void printWhenDrawn();
140
+ }
141
+ function installPrintShortcut() {
142
+ if (installs++ === 0) document.addEventListener("keydown", onKeyDown);
143
+ let installed = true;
144
+ return () => {
145
+ if (!installed) return;
146
+ installed = false;
147
+ if (--installs > 0) return;
148
+ document.removeEventListener("keydown", onKeyDown);
149
+ cancel?.();
150
+ };
151
+ }
152
+ // Annotate the CommonJS export names for ESM import in node:
153
+ 0 && (module.exports = {
154
+ holdPrintUntil,
155
+ installPrintShortcut,
156
+ registerPrintTarget
157
+ });
@@ -0,0 +1,27 @@
1
+ /** One mounted diagram, as the print shortcut sees it. */
2
+ interface PrintTarget {
3
+ /** True once the diagram is drawn, has failed, or is a large one the reader has not asked for (print shows its source). */
4
+ settled: () => boolean;
5
+ /** Fetches the code drawing needs (Mermaid), so a slow download is not counted against the draw budget. */
6
+ prepare?: () => Promise<unknown>;
7
+ /** Forces the diagram to draw; resolves once it is settled (at once when it already is, which includes a large one not asked for). */
8
+ ensureDrawn: () => Promise<void>;
9
+ /** The note shown while the print waits, in the diagram's locale (English when omitted). */
10
+ status?: string;
11
+ }
12
+ /** `loaded` must settle (never reject) once every diagram it mounts has registered; a failed load settles it too. */
13
+ declare function holdPrintUntil(loaded: Promise<unknown>): void;
14
+ /** Called by each mounted diagram; returns the cleanup. */
15
+ declare function registerPrintTarget(target: PrintTarget): () => void;
16
+ /**
17
+ * Ctrl/Cmd+P while a diagram is not drawn yet: hold the browser's print, draw every diagram, then call `window.print()`.
18
+ * Otherwise the key is left alone. Escape during the wait cancels the print.
19
+ * File > Print cannot be intercepted and still prints the source.
20
+ * Every MermaidDiagram installs it. One document listener serves every caller: it goes with the last cleanup, which
21
+ * also cancels a wait in progress.
22
+ * shortcut: the budgets and Escape are only served between tasks. Mermaid lays a diagram out in one synchronous task, so a diagram that
23
+ * is one huge layout holds the press until that layout ends, timers and Escape included; upgrade by not drawing such diagrams at all.
24
+ */
25
+ declare function installPrintShortcut(): () => void;
26
+
27
+ export { type PrintTarget, holdPrintUntil, installPrintShortcut, registerPrintTarget };
@@ -0,0 +1,27 @@
1
+ /** One mounted diagram, as the print shortcut sees it. */
2
+ interface PrintTarget {
3
+ /** True once the diagram is drawn, has failed, or is a large one the reader has not asked for (print shows its source). */
4
+ settled: () => boolean;
5
+ /** Fetches the code drawing needs (Mermaid), so a slow download is not counted against the draw budget. */
6
+ prepare?: () => Promise<unknown>;
7
+ /** Forces the diagram to draw; resolves once it is settled (at once when it already is, which includes a large one not asked for). */
8
+ ensureDrawn: () => Promise<void>;
9
+ /** The note shown while the print waits, in the diagram's locale (English when omitted). */
10
+ status?: string;
11
+ }
12
+ /** `loaded` must settle (never reject) once every diagram it mounts has registered; a failed load settles it too. */
13
+ declare function holdPrintUntil(loaded: Promise<unknown>): void;
14
+ /** Called by each mounted diagram; returns the cleanup. */
15
+ declare function registerPrintTarget(target: PrintTarget): () => void;
16
+ /**
17
+ * Ctrl/Cmd+P while a diagram is not drawn yet: hold the browser's print, draw every diagram, then call `window.print()`.
18
+ * Otherwise the key is left alone. Escape during the wait cancels the print.
19
+ * File > Print cannot be intercepted and still prints the source.
20
+ * Every MermaidDiagram installs it. One document listener serves every caller: it goes with the last cleanup, which
21
+ * also cancels a wait in progress.
22
+ * shortcut: the budgets and Escape are only served between tasks. Mermaid lays a diagram out in one synchronous task, so a diagram that
23
+ * is one huge layout holds the press until that layout ends, timers and Escape included; upgrade by not drawing such diagrams at all.
24
+ */
25
+ declare function installPrintShortcut(): () => void;
26
+
27
+ export { type PrintTarget, holdPrintUntil, installPrintShortcut, registerPrintTarget };