@tdacorp/hyle-sdk 0.14.1 → 0.21.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 (86) hide show
  1. package/README.md +171 -32
  2. package/dist/check-routes-bin.js +48 -21
  3. package/dist/chunk-56Y24XBV.js +840 -0
  4. package/dist/{chunk-MGSUQBDW.js → chunk-75JFLML4.js} +176 -14
  5. package/dist/chunk-HJX57NLI.js +1105 -0
  6. package/dist/chunk-K5VDLROQ.js +145 -0
  7. package/dist/{chunk-BUJFMR3M.js → chunk-QVYQM5R2.js} +15 -6
  8. package/dist/chunk-U74B7AUG.js +398 -0
  9. package/dist/{chunk-6VOHFFA5.js → chunk-X2TLYM7Y.js} +2 -2
  10. package/dist/client-41fU6OY2.d.cts +201 -0
  11. package/dist/client-LwzHwqpM.d.ts +201 -0
  12. package/dist/code-copy.cjs +72 -0
  13. package/dist/code-copy.d.cts +15 -0
  14. package/dist/code-copy.d.ts +15 -0
  15. package/dist/code-copy.js +48 -0
  16. package/dist/comments.cjs +733 -278
  17. package/dist/comments.d.cts +66 -3
  18. package/dist/comments.d.ts +66 -3
  19. package/dist/comments.js +414 -330
  20. package/dist/{diagram-viewer-DYX6R63Y.js → diagram-viewer-XY3CG75U.js} +107 -46
  21. package/dist/{embed-B76zRRPa.d.cts → embed-BUFRQboD.d.ts} +10 -5
  22. package/dist/{embed-SqOBGI-E.d.ts → embed-CYt-q13P.d.cts} +10 -5
  23. package/dist/fragment-alias.cjs +51 -0
  24. package/dist/fragment-alias.d.cts +7 -0
  25. package/dist/fragment-alias.d.ts +7 -0
  26. package/dist/fragment-alias.js +27 -0
  27. package/dist/html.cjs +881 -0
  28. package/dist/html.d.cts +20 -0
  29. package/dist/html.d.ts +20 -0
  30. package/dist/html.js +45 -0
  31. package/dist/index.cjs +181 -14
  32. package/dist/index.d.cts +14 -62
  33. package/dist/index.d.ts +14 -62
  34. package/dist/index.js +11 -1
  35. package/dist/labels-CrA-iqTN.d.cts +46 -0
  36. package/dist/labels-CrA-iqTN.d.ts +46 -0
  37. package/dist/mermaid-diagram.cjs +453 -148
  38. package/dist/mermaid-diagram.d.cts +25 -42
  39. package/dist/mermaid-diagram.d.ts +25 -42
  40. package/dist/mermaid-diagram.js +205 -50
  41. package/dist/mermaid-image.cjs +1456 -0
  42. package/dist/mermaid-image.d.cts +30 -0
  43. package/dist/mermaid-image.d.ts +30 -0
  44. package/dist/mermaid-image.js +93 -0
  45. package/dist/next.cjs +1709 -1134
  46. package/dist/next.d.cts +67 -14
  47. package/dist/next.d.ts +67 -14
  48. package/dist/next.js +950 -794
  49. package/dist/print-coordinator.cjs +157 -0
  50. package/dist/print-coordinator.d.cts +27 -0
  51. package/dist/print-coordinator.d.ts +27 -0
  52. package/dist/print-coordinator.js +83 -0
  53. package/dist/react.cjs +677 -264
  54. package/dist/react.d.cts +161 -31
  55. package/dist/react.d.ts +161 -31
  56. package/dist/react.js +23 -3
  57. package/dist/reactions.cjs +653 -0
  58. package/dist/reactions.d.cts +27 -0
  59. package/dist/reactions.d.ts +27 -0
  60. package/dist/reactions.js +364 -0
  61. package/dist/{resolve-DC2ccfwA.d.ts → resolve-BjAK0k_Y.d.ts} +2 -2
  62. package/dist/{resolve-DKLVftk_.d.cts → resolve-eI1muCKL.d.cts} +2 -2
  63. package/dist/revalidation-callback-BQl77tQR.d.cts +75 -0
  64. package/dist/revalidation-callback-BQl77tQR.d.ts +75 -0
  65. package/dist/sanitize-ijiWjEm9.d.cts +23 -0
  66. package/dist/sanitize-ijiWjEm9.d.ts +23 -0
  67. package/dist/styles.css +107 -47
  68. package/dist/toc-spy.cjs +59 -0
  69. package/dist/toc-spy.d.cts +15 -0
  70. package/dist/toc-spy.d.ts +15 -0
  71. package/dist/toc-spy.js +35 -0
  72. package/dist/{types-ByodIyEv.d.cts → types-3F0wqD-o.d.cts} +44 -4
  73. package/dist/{types-ByodIyEv.d.ts → types-3F0wqD-o.d.ts} +44 -4
  74. package/dist/use-cache.cjs +37 -11
  75. package/dist/use-cache.d.cts +12 -5
  76. package/dist/use-cache.d.ts +12 -5
  77. package/dist/use-cache.js +7 -7
  78. package/dist/youtube-facade.cjs +50 -0
  79. package/dist/youtube-facade.d.cts +17 -0
  80. package/dist/youtube-facade.d.ts +17 -0
  81. package/dist/youtube-facade.js +26 -0
  82. package/package.json +16 -3
  83. package/dist/chunk-4V4VKB3O.js +0 -1471
  84. package/dist/chunk-R5EMI4HQ.js +0 -61
  85. package/dist/revalidation-callback-D7Ms_Puz.d.cts +0 -42
  86. package/dist/revalidation-callback-D7Ms_Puz.d.ts +0 -42
package/dist/next.js CHANGED
@@ -8,20 +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
- stringsFor,
18
- validOgImage
19
- } from "./chunk-4V4VKB3O.js";
19
+ readingMinutes,
20
+ validOgImage,
21
+ wordCountOf
22
+ } from "./chunk-HJX57NLI.js";
23
+ import {
24
+ stringsFor
25
+ } from "./chunk-56Y24XBV.js";
20
26
  import {
21
27
  DEFAULT_REVALIDATE,
22
28
  fetchResolver,
23
29
  workspaceTags
24
- } from "./chunk-6VOHFFA5.js";
30
+ } from "./chunk-X2TLYM7Y.js";
25
31
  import {
26
32
  Cp1ClientError,
27
33
  checkBaseUrl,
@@ -32,7 +38,7 @@ import {
32
38
  listPublicationPaths,
33
39
  readCapped,
34
40
  signReaderAssertion
35
- } from "./chunk-MGSUQBDW.js";
41
+ } from "./chunk-75JFLML4.js";
36
42
  import {
37
43
  ASSET_CONTENT_TYPES,
38
44
  ASSET_FILE,
@@ -79,6 +85,12 @@ function safeRedirectTarget(to) {
79
85
  function resolverFor(options) {
80
86
  return options.resolver ?? fetchResolver(options);
81
87
  }
88
+ function articleImage(options, article) {
89
+ const { canonical_path, locale, title, updated_at } = article.publication;
90
+ const edited = Date.parse(updated_at);
91
+ const fallback = { url: `/api/hyle/og${canonical_path.split("/").map(encodeURIComponent).join("/")}?locale=${encodeURIComponent(locale)}${Number.isNaN(edited) ? "" : `&v=${edited}`}`, width: 1200, height: 630, alt: title };
92
+ return validOgImage(options.ogImage ? options.ogImage(article) : options.ogImageRoute ? fallback : void 0, bareOrigin(options.siteOrigin));
93
+ }
82
94
  var CURSOR = /^[A-Za-z0-9_-]{1,256}$/;
83
95
  var validCursor = (value) => typeof value === "string" && CURSOR.test(value) ? value : void 0;
84
96
  var LOCALE_TAG = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
@@ -98,875 +110,1017 @@ function isRejectedRequest(error) {
98
110
  return error instanceof Cp1ClientError && error.status >= 400 && error.status < 500 && ![401, 403, 429].includes(error.status);
99
111
  }
100
112
 
101
- // src/next/page.tsx
102
- import { jsx } from "react/jsx-runtime";
103
- function hylePage(options) {
104
- const resolve = resolverFor(options);
105
- return async function HylePage({ params, searchParams }) {
106
- const { path, locale, toHref } = routeContext(options, await params ?? {});
107
- if (path === void 0) notFound();
108
- try {
109
- const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
110
- const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
111
- switch (result.kind) {
112
- case "article": {
113
- const image = validOgImage(options.ogImage?.(result), bareOrigin(options.siteOrigin));
114
- const props = { article: result, components: options.components, slots: options.slots, locale, toHref };
115
- return options.layout === "docs" ? /* @__PURE__ */ jsx(DocsPage, { ...props }) : /* @__PURE__ */ jsx(ArticlePage, { ...props, origin: options.siteOrigin, jsonLd: options.jsonLd, imageUrl: image?.url, ...options.engagement ? { engagement: options.engagement } : {} });
116
- }
117
- case "list": {
118
- const list = options.list?.title ? { ...result, section: { ...result.section, title: options.list.title } } : result;
119
- const next = options.paginate === "searchParams" ? validCursor(result.next_cursor) : void 0;
120
- const olderHref = next ? `${toHref(path)}?cursor=${next}` : void 0;
121
- return /* @__PURE__ */ jsx(ListPage, { list, ...olderHref ? { olderHref } : {}, ...options.list?.description ? { description: options.list.description } : {}, components: options.components, slots: options.slots, locale, toHref, origin: options.siteOrigin, path });
122
- }
123
- case "redirect": {
124
- const to = safeRedirectTarget(result.to);
125
- if (to === void 0) throw new Cp1ClientError("INVALID_RESPONSE", "hyle returned an unsafe redirect target", 502, "");
126
- const target = safeRedirectTarget(toHref(to));
127
- if (target === void 0) throw new Cp1ClientError("INVALID_RESPONSE", "hyle returned an unsafe redirect target", 502, "");
128
- if (target === toHref(path)) notFound();
129
- return result.status === 301 ? permanentRedirect(target) : redirect(target);
113
+ // src/next/embed.tsx
114
+ import { unstable_rethrow as unstable_rethrow2 } from "next/navigation";
115
+
116
+ // src/next/engage.ts
117
+ import { createHash } from "crypto";
118
+ var ENGAGE_CSRF_HEADER = "x-hyle-engage";
119
+ var DEFAULT_TIMEOUT_MS = 1e4;
120
+ var DEFAULT_SHARE_MS = 3e3;
121
+ var MAX_SHARED = 100;
122
+ var MAX_SHARED_BYTES = 8 * 1024 * 1024;
123
+ var MAX_SHARED_ENTRY_BYTES = 256 * 1024;
124
+ var MAX_BODY_BYTES = 20 * 1024;
125
+ var MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
126
+ var MAX_COMMENT_CHARACTERS = 4e3;
127
+ var MAX_PATH_LENGTH2 = 1024;
128
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
129
+ var CONTROL = /[\u0000-\u001f\u007f\\]/;
130
+ var HEADERS = { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" };
131
+ var isSwitchedOff = (value) => {
132
+ const v = value?.trim().toLowerCase() ?? "";
133
+ return v !== "" && v !== "1" && v !== "true";
134
+ };
135
+ var json = (status, body, extra = {}) => new Response(JSON.stringify(body), { status, headers: { ...HEADERS, "Content-Type": "application/json; charset=utf-8", ...extra } });
136
+ var refuse = (status, code, extra = {}) => json(status, { error: { code } }, extra);
137
+ function isSitePath(value) {
138
+ if (typeof value !== "string" || value.length > MAX_PATH_LENGTH2 || !value.startsWith("/") || value.startsWith("//")) return false;
139
+ if (CONTROL.test(value) || /[?#]/.test(value)) return false;
140
+ return !value.split("/").some((segment) => segment === "." || segment === "..");
141
+ }
142
+ function match(segments) {
143
+ const [a, b, ...rest] = segments;
144
+ if (a === "session" && b === void 0) return { local: "session", action: () => "session", methods: ["GET"], rebuild: () => void 0 };
145
+ if (a === "comments" && b === void 0) {
146
+ return {
147
+ action: (m) => m === "GET" ? "comments.list" : "comments.create",
148
+ methods: ["GET", "POST"],
149
+ rebuild: (method, body, url) => {
150
+ if (method === "GET") {
151
+ const query = listingQuery(url.searchParams);
152
+ return query && { upstream: "/comments", query };
130
153
  }
131
- case "notfound":
132
- case "disabled":
133
- notFound();
154
+ const clean = pick(body, ["path", "body", "parent_id"], ["path", "body"]);
155
+ if (!clean || !isSitePath(clean.path) || !isCommentText(clean.body)) return void 0;
156
+ if (clean.parent_id === null) delete clean.parent_id;
157
+ if (clean.parent_id !== void 0 && !(typeof clean.parent_id === "string" && UUID.test(clean.parent_id))) return void 0;
158
+ return { upstream: "/comments", body: clean };
134
159
  }
135
- } catch (error) {
136
- if (isRejectedRequest(error)) notFound();
137
- if (!options.onError) throw error;
138
- console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
139
- return options.onError(error);
140
- }
141
- };
142
- }
143
-
144
- // src/next/sitemap.ts
145
- var ISO_DATE = /^\d{4}-\d{2}-\d{2}T/;
146
- var isoTime = (value) => value && ISO_DATE.test(value) ? Date.parse(value) : NaN;
147
- function httpsOrigin(origin) {
148
- let url;
149
- try {
150
- url = new URL(origin);
151
- } catch {
152
- throw new TypeError("hyleSitemap: `origin` must be an https origin such as https://example.com");
160
+ };
153
161
  }
154
- if (url.protocol !== "https:" || url.origin !== origin.replace(/\/$/, "")) {
155
- throw new TypeError("hyleSitemap: `origin` must be an https origin with no path, query or credentials");
162
+ if (a === "comments" && typeof b === "string" && UUID.test(b) && rest.length === 0) {
163
+ return {
164
+ action: (m) => m === "PATCH" ? "comments.edit" : "comments.delete",
165
+ methods: ["PATCH", "DELETE"],
166
+ rebuild: (method, body) => {
167
+ if (method === "DELETE") return body === void 0 ? { upstream: `/comments/${b}` } : void 0;
168
+ const clean = pick(body, ["body"], ["body"]);
169
+ return clean && isCommentText(clean.body) ? { upstream: `/comments/${b}`, body: clean } : void 0;
170
+ }
171
+ };
156
172
  }
157
- return url.origin;
158
- }
159
- async function hyleSitemap(options) {
160
- const origin = httpsOrigin(options.origin);
161
- const resolve = resolverFor(options);
162
- const locale = typeof options.locale === "string" ? options.locale : void 0;
163
- const { basePath, toHref } = routeContext({ ...options, locale: () => locale }, {});
164
- const client = { resolve: ({ path, locale: l, limit, cursor }) => resolve(path, l, limit, cursor) };
165
- const { paths, complete } = await listPublicationPaths({ client, basePath, ...locale ? { locale } : {} });
166
- if (!complete && (options.onIncomplete === "throw" || options.onIncomplete === void 0 && paths.length === 0)) {
167
- throw new Error("hyleSitemap: hyle could not be listed completely (see onIncomplete)");
173
+ if (a === "reactions" && b === void 0) {
174
+ return {
175
+ action: (m) => m === "PUT" ? "reactions.add" : "reactions.remove",
176
+ methods: ["PUT", "DELETE"],
177
+ rebuild: (_method, body) => {
178
+ const type = body?.subject_type;
179
+ const subject = type === "article" ? "path" : type === "comment" ? "comment_id" : void 0;
180
+ const clean = subject && pick(body, ["subject_type", subject, "kind"], ["subject_type", subject]);
181
+ if (!clean || clean.kind !== void 0 && !REACTION_KINDS.includes(clean.kind)) return void 0;
182
+ const valid = type === "article" ? isSitePath(clean.path) : typeof clean.comment_id === "string" && UUID.test(clean.comment_id);
183
+ return valid ? { upstream: "/reactions", body: clean } : void 0;
184
+ }
185
+ };
168
186
  }
169
- const memberUrl = (a) => origin + encodeURI(toHref(a.path, a.locale));
170
- return paths.map(({ path, publishedAt, updatedAt, alternates }) => {
171
- const latest = [publishedAt, updatedAt].filter((v) => !Number.isNaN(isoTime(v))).sort((x, y) => isoTime(y) - isoTime(x))[0];
172
- const modified = latest && new Date(latest).toISOString();
173
- const url = origin + encodeURI(toHref(path));
187
+ if (a === "votes" && b === void 0) {
174
188
  return {
175
- url,
176
- ...modified ? { lastModified: modified } : {},
177
- // Same gate as the page's hreflang: a group of one is not an alternate set.
178
- ...alternates && alternates.length > 1 ? { alternates: { languages: options.defaultLocale === void 0 ? Object.fromEntries(alternates.map((a) => [a.locale, memberUrl(a)])) : hreflangLanguages(alternates, options.defaultLocale, url, memberUrl) } } : {}
189
+ action: (m) => m === "PUT" ? "votes.set" : "votes.remove",
190
+ methods: ["PUT", "DELETE"],
191
+ rebuild: (method, body) => {
192
+ const keys = method === "PUT" ? ["comment_id", "value"] : ["comment_id"];
193
+ const clean = pick(body, keys, keys);
194
+ if (!clean || typeof clean.comment_id !== "string" || !UUID.test(clean.comment_id)) return void 0;
195
+ if (method === "PUT" && clean.value !== 1 && clean.value !== -1) return void 0;
196
+ return { upstream: "/votes", body: clean };
197
+ }
179
198
  };
180
- });
199
+ }
200
+ return void 0;
181
201
  }
182
-
183
- // src/next/metadata.ts
184
- var titled = (template, title) => template?.includes("%s") ? { absolute: template.replace("%s", () => title) } : title;
185
- function hyleMetadata(options) {
186
- const resolve = resolverFor(options);
187
- const origin = bareOrigin(options.siteOrigin);
188
- return async function generateMetadata({ params, searchParams }) {
189
- const { path, locale, toHref } = routeContext(options, await params ?? {});
190
- if (path === void 0) return {};
191
- const link = (sitePath, linkLocale) => {
192
- const href = toHref(sitePath, linkLocale);
193
- return origin ? absoluteUrl(origin, href) : href;
194
- };
195
- try {
196
- const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
197
- const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
198
- if (result.kind === "list") {
199
- const title = (options.list?.title || result.section.title) + (cursor ? ` - ${stringsFor(locale).older}` : "");
200
- const description2 = options.list?.description;
201
- return {
202
- title: titled(options.titleTemplate, title),
203
- ...description2 ? { description: description2 } : {},
204
- alternates: { canonical: link(path) + (cursor ? `?cursor=${cursor}` : "") },
205
- openGraph: { title, ...description2 ? { description: description2 } : {} }
206
- };
207
- }
208
- if (result.kind !== "article") return {};
209
- const { publication: pub, alternates, default_locale } = result;
210
- const canonical = link(pub.canonical_path, pub.locale);
211
- const description = pub.description ?? void 0;
212
- const author = articleAuthor(result, options.jsonLd)?.name;
213
- const modified = modifiedAt(pub);
214
- const image = validOgImage(options.ogImage?.(result), origin);
215
- const alternateLocale = options.ogLocale ? alternates.filter((a) => a.locale !== pub.locale).flatMap((a) => options.ogLocale?.(a.locale) ?? []) : [];
216
- const { twitter } = options;
217
- return {
218
- title: titled(options.titleTemplate, pub.title),
219
- ...description ? { description } : {},
220
- alternates: {
221
- canonical,
222
- ...alternates.length > 1 ? { languages: hreflangLanguages(alternates, default_locale, canonical, (a) => link(a.canonical_path, a.locale)) } : {}
223
- },
224
- openGraph: {
225
- type: "article",
226
- title: pub.title,
227
- ...description ? { description } : {},
228
- url: canonical,
229
- ...options.siteName ? { siteName: options.siteName } : {},
230
- locale: options.ogLocale?.(pub.locale) ?? pub.locale,
231
- ...alternateLocale.length ? { alternateLocale } : {},
232
- publishedTime: pub.published_at,
233
- ...modified ? { modifiedTime: modified } : {},
234
- ...author ? { authors: [author] } : {},
235
- ...image ? { images: [image] } : {}
236
- },
237
- ...image ? {
238
- twitter: {
239
- card: "summary_large_image",
240
- ...twitter?.site ? { site: twitter.site } : {},
241
- ...twitter?.creator ? { creator: twitter.creator } : {},
242
- title: pub.title,
243
- ...description ? { description } : {},
244
- images: [image]
245
- }
246
- } : {}
247
- };
248
- } catch (error) {
249
- if (isRejectedRequest(error)) return {};
250
- throw error;
251
- }
252
- };
202
+ function listingQuery(params) {
203
+ const keys = [...params.keys()];
204
+ if (new Set(keys).size !== keys.length || keys.some((k) => k !== "path" && k !== "cursor" && k !== "sort")) return void 0;
205
+ const path = params.get("path");
206
+ const cursor = params.get("cursor");
207
+ const sort = params.get("sort");
208
+ if (!isSitePath(path) || cursor !== null && !isCursor(cursor) || sort !== null && sort !== "new" && sort !== "top") return void 0;
209
+ return new URLSearchParams({ path, ...cursor === null ? {} : { cursor }, ...sort === null ? {} : { sort } });
253
210
  }
254
-
255
- // src/next/feed.ts
256
- import { unstable_rethrow as unstable_rethrow2 } from "next/navigation";
257
- var xml = (value) => value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
258
- var tag = (name, value) => `<${name}>${xml(value)}</${name}>`;
259
- var response = (body, status, headers) => new Response(body, { status, ...headers ? { headers } : {} });
260
- async function hyleFeed(options) {
261
- const origin = options.siteOrigin;
262
- if (!origin || !BARE_HTTPS_ORIGIN.test(origin)) {
263
- console.error("hyle: hyleFeed needs `siteOrigin`, a bare https origin such as https://example.com");
264
- return response(null, 404);
211
+ function pick(body, allowed, required) {
212
+ if (!body || Object.keys(body).some((k) => !allowed.includes(k)) || !required.every((k) => k in body)) return void 0;
213
+ return Object.fromEntries(allowed.filter((k) => k in body).map((k) => [k, body[k]]));
214
+ }
215
+ function isCommentText(value) {
216
+ return typeof value === "string" && value.trim().length > 0 && [...value].length <= MAX_COMMENT_CHARACTERS && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value);
217
+ }
218
+ function sameOriginProblem(req, write, allowedOrigins) {
219
+ const site = req.headers.get("sec-fetch-site");
220
+ if (site !== null && site !== "same-origin") return true;
221
+ if (!write) return false;
222
+ const origin = req.headers.get("origin");
223
+ if (origin === null) return true;
224
+ let parsed;
225
+ try {
226
+ parsed = new URL(origin);
227
+ } catch {
228
+ return true;
265
229
  }
266
- const { path, locale, toHref } = routeContext(options, {});
267
- if (path === void 0) return response(null, 404);
268
- const url = (sitePath) => origin + encodeURI(toHref(sitePath));
230
+ if (req.headers.get(ENGAGE_CSRF_HEADER) !== "1") return true;
231
+ if (allowedOrigins) return !allowedOrigins.some((o) => safeOrigin(o) === parsed.origin);
232
+ const host = req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || req.headers.get("host") || new URL(req.url).host;
233
+ const proto = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
234
+ if (proto && proto !== parsed.protocol.slice(0, -1)) return true;
235
+ return parsed.host !== host;
236
+ }
237
+ var safeOrigin = (value) => {
269
238
  try {
270
- const result = await resolverFor(options)(path, locale, options.limit ?? 50);
271
- if (result.kind !== "list") return response(null, 503);
272
- const items = result.items.filter((item) => item.canonical_path.startsWith("/")).map((item) => {
273
- const link = url(item.canonical_path);
274
- const published = new Date(item.published_at);
275
- return `<item>${tag("title", item.title)}${tag("link", link)}<guid isPermaLink="true">${xml(link)}</guid>${Number.isNaN(published.getTime()) ? "" : tag("pubDate", published.toUTCString())}${item.description ? tag("description", item.description) : ""}</item>`;
276
- });
277
- const channel = [
278
- tag("title", options.list?.title || result.section.title),
279
- tag("link", url(path)),
280
- tag("description", options.list?.description ?? ""),
281
- locale ? tag("language", locale) : "",
282
- `<atom:link href="${xml(origin + encodeURI(options.feedPath ?? "/feed.xml"))}" rel="self" type="application/rss+xml"/>`,
283
- ...items
284
- ].join("");
285
- return response(
286
- `<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel>${channel}</channel></rss>`,
287
- 200,
288
- { "content-type": "application/rss+xml; charset=utf-8" }
289
- );
290
- } catch (error) {
291
- unstable_rethrow2(error);
292
- console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
293
- return response(null, 503);
239
+ return new URL(value).origin;
240
+ } catch {
241
+ return void 0;
294
242
  }
295
- }
296
-
297
- // src/next/revalidate.ts
298
- import { revalidateTag } from "next/cache";
299
- var isSwitchedOff = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
300
- function createRevalidateRoute(options) {
301
- let cached;
302
- return {
303
- async POST(req) {
304
- if (isSwitchedOff((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return new Response(null, { status: 404 });
305
- const workspaceId = options.workspaceId?.trim();
306
- const secrets = options.secrets.map((s) => s?.trim()).filter((s) => Boolean(s));
307
- if (!workspaceId && secrets.length === 0) return new Response(null, { status: 404 });
308
- if (!workspaceId || secrets.length === 0) return new Response(null, { status: 503 });
309
- const key = `${workspaceId}\0${secrets.join("\0")}`;
310
- if (cached?.key !== key) {
311
- cached = { key, route: createRevalidationCallbackRoute({ workspaceId, secrets, revalidateTag: (tag2) => revalidateTag(tag2, { expire: 0 }) }) };
312
- }
313
- return cached.route.POST(req);
314
- }
315
- };
316
- }
317
-
318
- // src/next/root.ts
319
- import { notFound as notFound2 } from "next/navigation";
320
-
321
- // src/next/mount-match.ts
322
- function activeMounts(mounts) {
323
- const out = [];
324
- for (const { prefix, default_section, name, locales } of mounts) {
325
- try {
326
- const normalized = normalizeBasePath(prefix);
327
- out.push({
328
- prefix: normalized,
329
- defaultSection: default_section,
330
- depth: normalized === "" ? 0 : normalized.split("/").length - 1,
331
- ...name ? { name } : {},
332
- ...locales ? { locales } : {}
243
+ };
244
+ async function readBody(req, expected) {
245
+ if (!expected) return { kind: "ok", body: void 0 };
246
+ if (!/^application\/json(\s*;|$)/i.test(req.headers.get("content-type") ?? "")) return { kind: "refused", response: refuse(415, "UNSUPPORTED_MEDIA_TYPE") };
247
+ if (Number(req.headers.get("content-length")) > MAX_BODY_BYTES) return { kind: "refused", response: refuse(413, "PAYLOAD_TOO_LARGE") };
248
+ if (!req.body) return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
249
+ const reader = req.body.getReader();
250
+ const chunks = [];
251
+ let total = 0;
252
+ for (; ; ) {
253
+ const { done, value } = await reader.read();
254
+ if (done) break;
255
+ total += value.byteLength;
256
+ if (total > MAX_BODY_BYTES) {
257
+ await reader.cancel().catch(() => {
333
258
  });
334
- } catch (error) {
335
- console.error(`hyle: ignoring a mount with an invalid prefix (${error instanceof Error ? error.name : "Error"})`);
259
+ return { kind: "refused", response: refuse(413, "PAYLOAD_TOO_LARGE") };
336
260
  }
261
+ chunks.push(value);
337
262
  }
338
- return out;
263
+ try {
264
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
265
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return { kind: "ok", body: parsed };
266
+ } catch {
267
+ }
268
+ return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
339
269
  }
340
- var prefixMatches = (prefix, path) => prefix === "" || path === prefix || path.startsWith(`${prefix}/`);
341
- function isReserved(path, reserved) {
342
- return reserved.some((entry) => entry.endsWith("/*") ? prefixMatches(entry.slice(0, -2), path) : entry === path);
270
+ var SUB_CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
271
+ function validReader(r) {
272
+ if (!r || typeof r.sub !== "string" || typeof r.name !== "string") return null;
273
+ if (r.sub.length < 1 || [...r.sub].length > 255 || SUB_CONTROL.test(r.sub)) return null;
274
+ const name = cleanDisplayName(r.name);
275
+ return name === void 0 ? null : { sub: r.sub, name };
343
276
  }
344
-
345
- // src/next/root.ts
346
- var MOUNTS_MAX_STALE_MS = 15 * 60 * 1e3;
347
- var SECTION_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
348
- var NONE = { mounts: [], reserved: [], defaultLocale: "" };
349
- var lastKnownGood = /* @__PURE__ */ new Map();
350
- function mountsLoader(config) {
351
- if (!config.workspaceId) throw new TypeError("hyleRootPage: `workspaceId` is required for the fetch cache");
352
- const client = createHyleClient({ baseUrl: config.baseUrl, token: config.token });
353
- const init = { next: { revalidate: config.revalidate ?? DEFAULT_REVALIDATE, tags: workspaceTags(config.workspaceId).slice(0, 1) } };
354
- const key = `${new URL(config.baseUrl).origin}|${config.workspaceId}`;
355
- return async function load() {
277
+ function relayFailure(status, retryAfter) {
278
+ if (status === 400) return refuse(400, "VALIDATION_ERROR");
279
+ if (status === 404) return refuse(404, "NOT_FOUND");
280
+ if (status === 409) return refuse(409, "INVALID_TRANSITION");
281
+ if (status === 413) return refuse(413, "PAYLOAD_TOO_LARGE");
282
+ if (status === 429) {
283
+ const seconds = Math.min(3600, Math.max(1, Math.trunc(Number(retryAfter)) || 60));
284
+ return refuse(429, "RATE_LIMITED", { "Retry-After": String(seconds) });
285
+ }
286
+ return refuse(502, "UPSTREAM_ERROR");
287
+ }
288
+ function createEngagementRoute(options) {
289
+ let ready;
290
+ const fetchImpl = options.fetch ?? fetch;
291
+ const cache = /* @__PURE__ */ new Map();
292
+ let cacheBytes = 0;
293
+ const clearCache = () => {
294
+ cache.clear();
295
+ cacheBytes = 0;
296
+ };
297
+ async function listing(viewer, call) {
298
+ if (!viewer) return call(void 0);
299
+ let out = await call(viewer.sign("read"));
300
+ if (out.status === 401) out = await call(viewer.sign("read"));
301
+ if (out.status !== 401 && out.status !== 404 && !(out.status === 429 && out.throttle === "viewer")) return out;
302
+ return { ...await call(void 0), noShare: true };
303
+ }
304
+ function shared(key, call) {
305
+ const ttl = options.cacheTtlMs ?? DEFAULT_SHARE_MS;
306
+ if (ttl <= 0) return call();
307
+ const hit = cache.get(key);
308
+ if (hit && Date.now() - hit.at < ttl) {
309
+ cache.delete(key);
310
+ cache.set(key, hit);
311
+ return hit.result;
312
+ }
313
+ if (hit) forget(key, hit);
314
+ const entry = { at: Date.now(), result: call(), bytes: 0 };
315
+ cache.set(key, entry);
316
+ entry.result.then(
317
+ (o) => {
318
+ if (cache.get(key) !== entry) return;
319
+ if (![200, 400, 404].includes(o.status) || o.noShare || o.text.length > MAX_SHARED_ENTRY_BYTES) return forget(key, entry);
320
+ entry.bytes = o.text.length;
321
+ cacheBytes += entry.bytes;
322
+ while ((cacheBytes > MAX_SHARED_BYTES || cache.size > MAX_SHARED) && cache.size > 0) {
323
+ const oldest = cache.entries().next().value;
324
+ forget(oldest[0], oldest[1]);
325
+ }
326
+ },
327
+ () => forget(key, entry)
328
+ );
329
+ return entry.result;
330
+ }
331
+ function forget(key, entry) {
332
+ if (cache.get(key) !== entry) return;
333
+ cache.delete(key);
334
+ cacheBytes -= entry.bytes;
335
+ }
336
+ function configured() {
337
+ if (ready !== void 0) return ready;
356
338
  try {
357
- const result = await client.mounts({ init });
358
- if (result.kind !== "mounts") {
359
- lastKnownGood.delete(key);
360
- return NONE;
361
- }
362
- const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved, defaultLocale: result.default_locale };
363
- lastKnownGood.set(key, { loaded, at: Date.now() });
364
- return loaded;
365
- } catch (error) {
366
- if (isRejectedRequest(error)) {
367
- lastKnownGood.delete(key);
368
- return NONE;
369
- }
370
- if (error instanceof Cp1ClientError && (error.status === 401 || error.status === 403)) {
371
- lastKnownGood.delete(key);
372
- throw error;
339
+ const baseUrl = options.baseUrl?.trim() ?? "";
340
+ checkBaseUrl(baseUrl);
341
+ if (!options.token?.trim() || !options.workspaceId?.trim() || !options.signingKey) throw new TypeError("not provisioned");
342
+ ready = { base: baseUrl.replace(/\/+$/, ""), key: engagementSigningKey(options.signingKey.trim()) };
343
+ } catch {
344
+ ready = null;
345
+ }
346
+ return ready;
347
+ }
348
+ async function reader(req, config) {
349
+ try {
350
+ const found = validReader(await options.getReader(req));
351
+ if (!found) return null;
352
+ const claims = { sub: found.sub, name: found.name, workspace: options.workspaceId.trim() };
353
+ const sign = (scope) => signReaderAssertion(config.key, claims, void 0, scope);
354
+ return { reader: found, assertion: sign(), sign };
355
+ } catch {
356
+ return null;
357
+ }
358
+ }
359
+ async function handle(req, ctx) {
360
+ const env = options.env ?? process.env;
361
+ if (isSwitchedOff(env.HYLE_ENGAGE_ENABLED) || isSwitchedOff(env.HYLE_CONTENT_ENABLED)) return refuse(404, "NOT_FOUND");
362
+ const config = configured();
363
+ const route = match((await ctx.params).path ?? []);
364
+ if (!config || !route) return refuse(404, "NOT_FOUND");
365
+ if (!route.methods.includes(req.method)) return refuse(405, "METHOD_NOT_ALLOWED", { Allow: route.methods.join(", ") });
366
+ const write = req.method !== "GET";
367
+ if (sameOriginProblem(req, write, options.allowedOrigins)) return refuse(403, "FORBIDDEN");
368
+ if (options.onRequest) {
369
+ try {
370
+ const early = await options.onRequest(req, { action: route.action(req.method) });
371
+ if (early instanceof Response) {
372
+ const headers = new Headers(early.headers);
373
+ headers.set("cache-control", "no-store");
374
+ return new Response(early.body, { status: early.status, headers });
375
+ }
376
+ } catch {
377
+ return refuse(502, "UPSTREAM_ERROR");
373
378
  }
374
- const kept = lastKnownGood.get(key);
375
- if (kept && Date.now() - kept.at <= MOUNTS_MAX_STALE_MS) return kept.loaded;
376
- throw error;
377
379
  }
378
- };
379
- }
380
- var asArray = (options) => Array.isArray(options) ? options : [options];
381
- function setup(options) {
382
- const configs = asArray(options);
383
- if (configs.length === 0) throw new TypeError("hyleRootPage: pass at least one workspace config");
384
- const param = configs[0].param ?? "hyle";
385
- if (configs.some((c) => (c.param ?? "hyle") !== param)) throw new TypeError("hyleRootPage: every config must use the same `param`");
386
- return { configs, param, loaders: configs.map(mountsLoader) };
387
- }
388
- var sectionsOf = (config, mount) => [
389
- ...config.sections ?? [],
390
- ...SECTION_SLUG.test(mount.defaultSection) ? [mount.defaultSection] : []
391
- ];
392
- function mountOptionsOf(config, mount) {
393
- const { mountOptions, ...rest } = config;
394
- return { ...rest, ...mountOptions?.[mount.prefix === "" ? "/" : mount.prefix], basePath: mount.prefix, sections: sectionsOf(config, mount) };
395
- }
396
- function rootMounts(options) {
397
- const { configs, param, loaders } = setup(options);
398
- return {
399
- param,
400
- async locate(path) {
401
- const loaded = await Promise.all(loaders.map((load) => load()));
402
- let best;
403
- loaded.forEach(({ mounts, reserved }, index2) => {
404
- if (isReserved(path, reserved)) return;
405
- for (const mount2 of mounts) if (prefixMatches(mount2.prefix, path) && (!best || mount2.depth > best.mount.depth)) best = { index: index2, mount: mount2 };
380
+ if (route.local === "session") {
381
+ const who = await reader(req, config);
382
+ return json(200, { data: { reader: who ? { id: createHash("sha256").update(who.reader.sub).digest("base64url"), name: who.reader.name } : null } });
383
+ }
384
+ let assertion;
385
+ let viewer = null;
386
+ if (route.action(req.method) === "comments.list") viewer = await reader(req, config);
387
+ if (write) {
388
+ const who = await reader(req, config);
389
+ if (!who) return refuse(401, "UNAUTHENTICATED");
390
+ assertion = who.assertion;
391
+ }
392
+ const url = new URL(req.url);
393
+ const hasBody = write && !(req.method === "DELETE" && (await ctx.params).path?.[0] === "comments");
394
+ const body = await readBody(req, hasBody);
395
+ if (body.kind === "refused") return body.response;
396
+ const built = route.rebuild(req.method, body.body, url);
397
+ if (!built) return refuse(400, "VALIDATION_ERROR");
398
+ const baseHeaders = new Headers({ authorization: `Bearer ${options.token.trim()}`, accept: "application/json" });
399
+ if (built.body) baseHeaders.set("content-type", "application/json");
400
+ const target = `${config.base}/cp1/engage${built.upstream}${built.query ? `?${built.query}` : ""}`;
401
+ const call = async (withAssertion = assertion) => {
402
+ const headers = new Headers(baseHeaders);
403
+ if (withAssertion) headers.set("hyle-reader-assertion", withAssertion);
404
+ const res = await fetchImpl(target, {
405
+ method: req.method,
406
+ headers,
407
+ ...built.body ? { body: JSON.stringify(built.body) } : {},
408
+ redirect: "error",
409
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
406
410
  });
407
- if (!best) return void 0;
408
- const { index, mount } = best;
409
- return { options: mountOptionsOf(configs[index], mount), mount, index };
410
- },
411
- async all() {
412
- const out = [];
413
- for (const [index, load] of loaders.entries()) {
414
- const { mounts, defaultLocale } = await load();
415
- for (const mount of mounts) out.push({ options: mountOptionsOf(configs[index], mount), mount, index, defaultLocale });
416
- }
417
- return out;
411
+ 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") };
412
+ };
413
+ try {
414
+ const out = route.action(req.method) === "comments.list" ? await shared(`${viewer?.reader.sub ?? ""}
415
+ ${built.query.toString()}`, () => listing(viewer, call)) : await call();
416
+ if (!out.ok) return relayFailure(out.status, out.retryAfter);
417
+ if (write) clearCache();
418
+ const data = JSON.parse(out.text).data;
419
+ return typeof data === "object" && data !== null ? json(out.status === 201 ? 201 : 200, { data }) : refuse(502, "UPSTREAM_ERROR");
420
+ } catch {
421
+ return refuse(502, "UPSTREAM_ERROR");
418
422
  }
419
- };
423
+ }
424
+ return { GET: handle, POST: handle, PATCH: handle, PUT: handle, DELETE: handle };
420
425
  }
421
- function createRouter(options, make) {
422
- const mounts = rootMounts(options);
423
- const handlers = /* @__PURE__ */ new Map();
424
- return async function route(params) {
425
- const raw = params[mounts.param];
426
- const segments = typeof raw === "string" ? [raw] : raw;
427
- const path = sitePathFrom("", segments);
428
- if (path === void 0 || path === "/" || !segments) return void 0;
429
- const hit = await mounts.locate(path);
430
- if (!hit) return void 0;
431
- const { mount, index } = hit;
432
- const id = `${index}|${mount.prefix}|${mount.defaultSection}`;
433
- let handler = handlers.get(id);
434
- if (!handler) {
435
- handler = make(hit.options);
436
- handlers.set(id, handler);
437
- }
438
- return { handler, params: { ...params, [mounts.param]: segments.slice(mount.depth) } };
439
- };
426
+
427
+ // src/next/embed.tsx
428
+ import { jsx } from "react/jsx-runtime";
429
+ async function resolveEmbed(options, run) {
430
+ try {
431
+ return { result: await run() };
432
+ } catch (error) {
433
+ if (isRejectedRequest(error)) return {};
434
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
435
+ return { failure: options.onError ? options.onError(error) : null };
436
+ }
440
437
  }
441
- function hyleRootPage(options) {
442
- const route = createRouter(options, hylePage);
443
- return async function HyleRootPage({ params, searchParams }) {
444
- const hit = await route(await params ?? {});
445
- if (!hit) notFound2();
446
- return hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} });
447
- };
438
+ async function HyleList({ options, limit = 5, locale, layout, title, headingLevel, moreHref, cursor, olderHref }) {
439
+ const resolve = resolverFor(options);
440
+ const route = routeContext(locale ? { ...options, locale } : options, {});
441
+ const path = sitePathFrom(route.basePath, void 0);
442
+ if (path === void 0) return null;
443
+ const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale, limit, validCursor(cursor)));
444
+ if (failure !== void 0) return failure;
445
+ const next = olderHref && result?.kind === "list" ? validCursor(result.next_cursor) : void 0;
446
+ 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 });
448
447
  }
449
- function hyleRootMetadata(options) {
450
- const route = createRouter(options, hyleMetadata);
451
- return async function generateMetadata({ params }) {
452
- const hit = await route(await params ?? {});
453
- return hit ? hit.handler({ params: Promise.resolve(hit.params) }) : {};
454
- };
448
+ async function HyleArticle({ options, path, locale, headingLevel }) {
449
+ if (!isSitePath(path)) return null;
450
+ const resolve = resolverFor(options);
451
+ const route = routeContext(locale ? { ...options, locale } : options, {});
452
+ const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale));
453
+ if (failure !== void 0) return failure;
454
+ if (result?.kind !== "article") return null;
455
+ return /* @__PURE__ */ jsx(HyleArticleView, { article: result, headingLevel, components: options.components, slots: options.slots, locale: route.locale, toHref: route.toHref });
455
456
  }
456
- async function hyleRootSitemap(options, sitemap) {
457
- const entries = /* @__PURE__ */ new Map();
458
- for (const { options: mountOptions, mount, defaultLocale } of await rootMounts(options).all()) {
459
- for (const locale of mount.locales ?? [defaultLocale]) {
460
- for (const entry of await hyleSitemap({ ...mountOptions, ...sitemap, locale, defaultLocale })) entries.set(entry.url, entry);
457
+ var MAX_LISTING_BYTES = 4 * 1024 * 1024;
458
+ var COMMENTS_TIMEOUT_MS = 1e4;
459
+ async function HyleComments({ options, path, revalidate = 60, interactive }) {
460
+ checkBaseUrl(options.baseUrl);
461
+ if (!options.token) throw new TypeError("token is required");
462
+ if (!isSitePath(path)) return null;
463
+ const locale = options.locale ?? "en";
464
+ let listing;
465
+ let fetchedAt;
466
+ try {
467
+ const init = {
468
+ headers: { authorization: `Bearer ${options.token}`, accept: "application/json" },
469
+ redirect: "error",
470
+ signal: AbortSignal.timeout(COMMENTS_TIMEOUT_MS),
471
+ next: { revalidate }
472
+ };
473
+ const res = await fetch(`${options.baseUrl.replace(/\/+$/, "")}/cp1/engage/comments?${new URLSearchParams({ path })}`, init);
474
+ if (!res.ok) {
475
+ if (res.status !== 404) console.error(`hyle: comments answered HTTP ${res.status}`);
476
+ return null;
461
477
  }
478
+ listing = parseListing(JSON.parse(await readCapped(res, MAX_LISTING_BYTES)).data);
479
+ const date = Date.parse(res.headers.get("date") ?? "");
480
+ fetchedAt = Number.isFinite(date) ? date : void 0;
481
+ } catch (error) {
482
+ unstable_rethrow2(error);
483
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
484
+ return null;
462
485
  }
463
- return [...entries.values()];
486
+ if (!listing) return null;
487
+ if (!interactive) return /* @__PURE__ */ jsx(HyleCommentsView, { listing, locale });
488
+ const config = interactive === true ? {} : interactive;
489
+ return /* @__PURE__ */ jsx("div", { className: "hyle hyle-embed", children: /* @__PURE__ */ jsx(Comments, { path, endpoint: config.endpoint ?? "/api/hyle/engage", signInHref: config.signInHref, locale, labels: stringsFor(locale).comments, initial: listing, initialAt: fetchedAt }) });
464
490
  }
465
491
 
466
- // src/next/markdown.ts
467
- var MD_ROUTE_PREFIX = "/api/hyle/md";
468
- function markdownRewritePath(pathname) {
469
- if (!pathname.startsWith("/") || !pathname.endsWith(".md") || pathname.endsWith("/.md") || pathname.startsWith("/api/")) return void 0;
470
- return MD_ROUTE_PREFIX + pathname.slice(0, -3);
471
- }
472
- var reply = (body, status, headers = {}) => (
473
- // noindex on every answer: the .md twin must never compete with the page it mirrors.
474
- new Response(body, { status, headers: { "X-Robots-Tag": "noindex", ...headers } })
475
- );
476
- function createMarkdownRoute(options) {
477
- const mounts = rootMounts(options);
478
- return {
479
- async GET(_req, ctx) {
480
- const params = await ctx.params ?? {};
481
- const segments = params.path;
482
- const path = sitePathFrom("", typeof segments === "string" ? [segments] : segments);
483
- if (path === void 0 || path === "/") return reply(null, 404);
484
- try {
485
- const hit = await mounts.locate(path);
486
- if (!hit) return reply(null, 404);
487
- const { locale, toHref } = routeContext({ ...hit.options, basePath: "", param: "path" }, params);
488
- const result = await resolverFor(hit.options)(path, locale, void 0, void 0, void 0, "md");
489
- if (result.kind === "article" && result.content.format === "md") {
490
- const markdown = result.content.markdown.replaceAll("](/assets/", `](${ASSET_ROUTE_PREFIX}/`);
491
- return reply(markdown, 200, { "Content-Type": "text/markdown; charset=utf-8" });
492
+ // src/next/page.tsx
493
+ import { jsx as jsx2 } from "react/jsx-runtime";
494
+ function hylePage(options) {
495
+ const resolve = resolverFor(options);
496
+ async function relatedItems(article) {
497
+ const { limit = 5, title } = options.related ?? {};
498
+ const section = article.breadcrumbs[0]?.canonical_path ?? (normalizeBasePath(options.basePath) || "/");
499
+ const { result } = await resolveEmbed(options, () => resolve(section, article.publication.locale, limit + 1));
500
+ const items = result?.kind === "list" ? result.items.filter((item) => item.canonical_path !== article.publication.canonical_path).slice(0, limit) : [];
501
+ return { title, items };
502
+ }
503
+ return async function HylePage({ params, searchParams }) {
504
+ const { path, locale, toHref } = routeContext(options, await params ?? {});
505
+ if (path === void 0) notFound();
506
+ try {
507
+ const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
508
+ const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
509
+ switch (result.kind) {
510
+ case "article": {
511
+ const image = articleImage(options, result);
512
+ const related = options.related && options.layout !== "docs" ? await relatedItems(result) : void 0;
513
+ const props = { article: result, components: options.components, slots: options.slots, locale, toHref };
514
+ return options.layout === "docs" ? /* @__PURE__ */ jsx2(DocsPage, { ...props }) : /* @__PURE__ */ jsx2(ArticlePage, { ...props, origin: options.siteOrigin, jsonLd: options.jsonLd, imageUrl: image?.url, imageWidth: image?.width, imageHeight: image?.height, related, ...options.engagement ? { engagement: options.engagement } : {} });
492
515
  }
493
- if (result.kind === "redirect") {
516
+ case "list": {
517
+ const list = options.list?.title ? { ...result, section: { ...result.section, title: options.list.title } } : result;
518
+ const next = options.paginate === "searchParams" ? validCursor(result.next_cursor) : void 0;
519
+ const olderHref = next ? `${toHref(path)}?cursor=${next}` : void 0;
520
+ return /* @__PURE__ */ jsx2(ListPage, { list, ...olderHref ? { olderHref } : {}, ...options.list?.description ? { description: options.list.description } : {}, components: options.components, slots: options.slots, locale, toHref, origin: options.siteOrigin, path, jsonLd: options.jsonLd, cursor });
521
+ }
522
+ case "redirect": {
494
523
  const to = safeRedirectTarget(result.to);
495
- const target = to === void 0 ? void 0 : safeRedirectTarget(toHref(to));
496
- if (target === void 0) return reply(null, 502);
497
- return target === toHref(path) ? reply(null, 404) : reply(null, result.status === 301 ? 308 : 307, { Location: `${target}.md` });
524
+ if (to === void 0) throw new Cp1ClientError("INVALID_RESPONSE", "hyle returned an unsafe redirect target", 502, "");
525
+ const target = safeRedirectTarget(toHref(to));
526
+ if (target === void 0) throw new Cp1ClientError("INVALID_RESPONSE", "hyle returned an unsafe redirect target", 502, "");
527
+ if (target === toHref(path)) notFound();
528
+ return result.status === 301 ? permanentRedirect(target) : redirect(target);
498
529
  }
499
- return reply(null, 404);
500
- } catch (error) {
501
- if (isRejectedRequest(error)) return reply(null, 404);
502
- console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
503
- return reply(null, 502);
530
+ case "notfound":
531
+ case "disabled":
532
+ notFound();
533
+ }
534
+ } catch (error) {
535
+ if (isRejectedRequest(error)) notFound();
536
+ if (!options.onError) throw error;
537
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
538
+ return options.onError(error);
539
+ }
540
+ };
541
+ }
542
+
543
+ // src/next/sitemap.ts
544
+ var ISO_DATE = /^\d{4}-\d{2}-\d{2}T/;
545
+ var isoTime = (value) => value && ISO_DATE.test(value) ? Date.parse(value) : NaN;
546
+ function httpsOrigin(origin) {
547
+ let url;
548
+ try {
549
+ url = new URL(origin);
550
+ } catch {
551
+ throw new TypeError("hyleSitemap: `origin` must be an https origin such as https://example.com");
552
+ }
553
+ if (url.protocol !== "https:" || url.origin !== origin.replace(/\/$/, "")) {
554
+ throw new TypeError("hyleSitemap: `origin` must be an https origin with no path, query or credentials");
555
+ }
556
+ return url.origin;
557
+ }
558
+ async function hyleSitemap(options) {
559
+ const origin = httpsOrigin(options.origin);
560
+ const resolve = resolverFor(options);
561
+ const locale = typeof options.locale === "string" ? options.locale : void 0;
562
+ const { basePath, toHref } = routeContext({ ...options, locale: () => locale }, {});
563
+ const client = { resolve: ({ path, locale: l, limit, cursor }) => resolve(path, l, limit, cursor) };
564
+ const { paths, complete } = await listPublicationPaths({ client, basePath, ...locale ? { locale } : {} });
565
+ if (!complete && (options.onIncomplete === "throw" || options.onIncomplete === void 0 && paths.length === 0)) {
566
+ throw new Error("hyleSitemap: hyle could not be listed completely (see onIncomplete)");
567
+ }
568
+ const memberUrl = (a) => origin + encodeURI(toHref(a.path, a.locale));
569
+ return paths.map(({ path, publishedAt, updatedAt, alternates }) => {
570
+ const latest = [publishedAt, updatedAt].filter((v) => !Number.isNaN(isoTime(v))).sort((x, y) => isoTime(y) - isoTime(x))[0];
571
+ const modified = latest && new Date(latest).toISOString();
572
+ const url = origin + encodeURI(toHref(path));
573
+ return {
574
+ url,
575
+ ...modified ? { lastModified: modified } : {},
576
+ // Same gate as the page's hreflang: a group of one is not an alternate set.
577
+ ...alternates && alternates.length > 1 ? { alternates: { languages: options.defaultLocale === void 0 ? Object.fromEntries(alternates.map((a) => [a.locale, memberUrl(a)])) : hreflangLanguages(alternates, options.defaultLocale, url, memberUrl) } } : {}
578
+ };
579
+ });
580
+ }
581
+
582
+ // src/next/metadata.ts
583
+ var titled = (template, title) => template?.includes("%s") ? { absolute: template.replace("%s", () => title) } : title;
584
+ var LARGE_PREVIEW = "max-image-preview:large";
585
+ var addDirective = (inherited) => {
586
+ const tokens = (inherited ?? "").split(",").map((t) => t.trim()).filter(Boolean);
587
+ return (tokens.includes(LARGE_PREVIEW) ? tokens : [...tokens, LARGE_PREVIEW]).join(", ");
588
+ };
589
+ var ROBOTS_KEYS = /* @__PURE__ */ new Set(["noarchive", "nosnippet", "noimageindex", "nocache", "notranslate", "indexifembedded", "nositelinkssearchbox", "unavailable_after", "max-video-preview", "max-image-preview", "max-snippet"]);
590
+ var ROBOTS_ALIASES = {
591
+ none: { index: false, follow: false },
592
+ all: { index: true, follow: true },
593
+ index: { index: true },
594
+ noindex: { index: false },
595
+ follow: { follow: true },
596
+ nofollow: { follow: false }
597
+ };
598
+ function composeRobots(inherited) {
599
+ const basic = addDirective(inherited?.basic);
600
+ const object = {};
601
+ for (const token of basic.split(", ")) {
602
+ const colon = token.indexOf(":");
603
+ const key = colon < 0 ? token : token.slice(0, colon);
604
+ if (ROBOTS_KEYS.has(key)) object[key] = colon < 0 ? true : token.slice(colon + 1);
605
+ else if (ROBOTS_ALIASES[key] && colon < 0) Object.assign(object, ROBOTS_ALIASES[key]);
606
+ else return basic;
607
+ }
608
+ return { ...object, googleBot: addDirective(inherited?.googleBot) };
609
+ }
610
+ function hyleFeedLink(options, locale) {
611
+ const { feed } = options;
612
+ if (!feed || typeof feed.path === "function" && !locale) return void 0;
613
+ const href = typeof feed.path === "function" ? feed.path(locale) : feed.path;
614
+ const origin = bareOrigin(options.siteOrigin);
615
+ return { url: origin ? absoluteUrl(origin, href) : href, title: feed.title ?? (options.siteName ? `${options.siteName} feed` : "Feed") };
616
+ }
617
+ function hyleMetadata(options) {
618
+ const resolve = resolverFor(options);
619
+ const origin = bareOrigin(options.siteOrigin);
620
+ return async function generateMetadata({ params, searchParams }, parent) {
621
+ const { path, locale, toHref } = routeContext(options, await params ?? {});
622
+ if (path === void 0) return {};
623
+ const link = (sitePath, linkLocale) => {
624
+ const href = toHref(sitePath, linkLocale);
625
+ return origin ? absoluteUrl(origin, href) : href;
626
+ };
627
+ const withTypes = async (alternates, markdown) => {
628
+ const feed = hyleFeedLink(options, locale);
629
+ const types = {
630
+ ...parent ? (await parent).alternates?.types : void 0,
631
+ ...feed ? { "application/rss+xml": [feed] } : {},
632
+ ...markdown ? { "text/markdown": [{ url: markdown }] } : {}
633
+ };
634
+ return Object.keys(types).length ? { ...alternates, types } : alternates;
635
+ };
636
+ try {
637
+ const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
638
+ const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
639
+ const parentMeta = parent ? await parent : void 0;
640
+ const parentImages = parentMeta?.openGraph?.images;
641
+ if (result.kind === "list") {
642
+ const title = (options.list?.title || result.section.title) + (cursor ? ` - ${stringsFor(locale).older}` : "");
643
+ const description2 = options.list?.description;
644
+ const ogLocale = locale && options.ogLocale?.(locale) || locale;
645
+ const canonical2 = link(path) + (cursor ? `?cursor=${cursor}` : "");
646
+ return {
647
+ title: titled(options.titleTemplate, title),
648
+ ...description2 ? { description: description2 } : {},
649
+ alternates: await withTypes({ canonical: canonical2 }),
650
+ openGraph: {
651
+ type: "website",
652
+ title,
653
+ ...description2 ? { description: description2 } : {},
654
+ url: canonical2,
655
+ ...options.siteName ? { siteName: options.siteName } : {},
656
+ ...ogLocale ? { locale: ogLocale } : {},
657
+ ...parentImages?.length ? { images: parentImages } : {}
658
+ }
659
+ };
504
660
  }
661
+ if (result.kind !== "article") return {};
662
+ const { publication: pub, alternates, default_locale } = result;
663
+ const canonical = link(pub.canonical_path, pub.locale);
664
+ const description = pub.description ?? void 0;
665
+ const author = articleAuthor(result, options.jsonLd)?.name;
666
+ const modified = modifiedAt(pub);
667
+ const image = articleImage(options, result);
668
+ const alternateLocale = options.ogLocale ? alternates.filter((a) => a.locale !== pub.locale).flatMap((a) => options.ogLocale?.(a.locale) ?? []) : [];
669
+ const { twitter } = options;
670
+ const inherited = parentMeta?.robots;
671
+ const section = result.breadcrumbs[0]?.title;
672
+ const words = wordCountOf(pub);
673
+ return {
674
+ title: titled(options.titleTemplate, pub.title),
675
+ ...description ? { description } : {},
676
+ // Next replaces a parent's robots per key, so keep the inherited directives (a host's noindex) and add ours once.
677
+ robots: composeRobots(inherited),
678
+ alternates: await withTypes(
679
+ {
680
+ canonical,
681
+ ...alternates.length > 1 ? { languages: hreflangLanguages(alternates, default_locale, canonical, (a) => link(a.canonical_path, a.locale)) } : {}
682
+ },
683
+ options.markdownTwin ? `${canonical}.md` : void 0
684
+ ),
685
+ openGraph: {
686
+ type: "article",
687
+ title: pub.title,
688
+ ...description ? { description } : {},
689
+ url: canonical,
690
+ ...options.siteName ? { siteName: options.siteName } : {},
691
+ locale: options.ogLocale?.(pub.locale) ?? pub.locale,
692
+ ...alternateLocale.length ? { alternateLocale } : {},
693
+ publishedTime: pub.published_at,
694
+ ...modified ? { modifiedTime: modified } : {},
695
+ ...section ? { section } : {},
696
+ ...author ? { authors: [author] } : {},
697
+ ...image ? { images: [image] } : parentImages?.length ? { images: parentImages } : {}
698
+ },
699
+ // Next replaces a parent's `other` whole, so the inherited keys are carried over.
700
+ ...words ? { other: { ...parentMeta?.other, "twitter:label1": stringsFor(locale).readingTimeLabel, "twitter:data1": stringsFor(locale).readingTime.replace("{n}", String(readingMinutes(words))) } } : {},
701
+ ...image ? {
702
+ twitter: {
703
+ card: "summary_large_image",
704
+ ...twitter?.site ? { site: twitter.site } : {},
705
+ ...twitter?.creator ? { creator: twitter.creator } : {},
706
+ title: pub.title,
707
+ ...description ? { description } : {},
708
+ images: [image]
709
+ }
710
+ } : {}
711
+ };
712
+ } catch (error) {
713
+ if (isRejectedRequest(error)) return {};
714
+ throw error;
505
715
  }
506
716
  };
507
717
  }
508
718
 
509
- // src/next/llms.ts
719
+ // src/next/feed.ts
510
720
  import { unstable_rethrow as unstable_rethrow3 } from "next/navigation";
511
- var oneLine = (text) => text.replace(/\s+/g, " ").trim();
512
- var linkTarget = (url) => url.replace(/[()]/g, (c) => c === "(" ? "%28" : "%29");
513
- function createLlmsTxtRoute(options, llms) {
514
- const origin = bareOrigin(llms.origin);
515
- if (!origin) throw new TypeError("createLlmsTxtRoute: `origin` must be a bare https origin such as https://example.com");
516
- const mounts = rootMounts(options);
721
+ var xml = (value) => value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
722
+ var tag = (name, value) => `<${name}>${xml(value)}</${name}>`;
723
+ var response = (body, status, headers) => new Response(body, { status, ...headers ? { headers } : {} });
724
+ async function hyleFeed(options) {
725
+ const origin = options.siteOrigin;
726
+ if (!origin || !BARE_HTTPS_ORIGIN.test(origin)) {
727
+ console.error("hyle: hyleFeed needs `siteOrigin`, a bare https origin such as https://example.com");
728
+ return response(null, 404);
729
+ }
730
+ const { path, locale, toHref } = routeContext(options, {});
731
+ if (path === void 0) return response(null, 404);
732
+ const url = (sitePath) => origin + encodeURI(toHref(sitePath));
733
+ try {
734
+ const result = await resolverFor(options)(path, locale, options.limit ?? 50);
735
+ if (result.kind !== "list") return response(null, 503);
736
+ const items = result.items.filter((item) => item.canonical_path.startsWith("/")).map((item) => {
737
+ const link = url(item.canonical_path);
738
+ const published = new Date(item.published_at);
739
+ return `<item>${tag("title", item.title)}${tag("link", link)}<guid isPermaLink="true">${xml(link)}</guid>${Number.isNaN(published.getTime()) ? "" : tag("pubDate", published.toUTCString())}${item.description ? tag("description", item.description) : ""}</item>`;
740
+ });
741
+ const channel = [
742
+ tag("title", options.list?.title || result.section.title),
743
+ tag("link", url(path)),
744
+ tag("description", options.list?.description ?? ""),
745
+ locale ? tag("language", locale) : "",
746
+ `<atom:link href="${xml(origin + encodeURI(options.feedPath ?? "/feed.xml"))}" rel="self" type="application/rss+xml"/>`,
747
+ ...items
748
+ ].join("");
749
+ return response(
750
+ `<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel>${channel}</channel></rss>`,
751
+ 200,
752
+ { "content-type": "application/rss+xml; charset=utf-8" }
753
+ );
754
+ } catch (error) {
755
+ unstable_rethrow3(error);
756
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
757
+ return response(null, 503);
758
+ }
759
+ }
760
+
761
+ // src/next/revalidate.ts
762
+ import { revalidateTag } from "next/cache";
763
+ var isSwitchedOff2 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
764
+ function createRevalidateRoute(options) {
765
+ let cached;
517
766
  return {
518
- async GET() {
519
- try {
520
- const lines = [`# ${oneLine(llms.title ?? new URL(origin).host)}`, ...llms.description ? ["", `> ${oneLine(llms.description)}`] : []];
521
- for (const { options: mountOptions, mount, defaultLocale } of await mounts.all()) {
522
- if (mount.locales && !mount.locales.includes(defaultLocale)) continue;
523
- const { basePath, toHref } = routeContext({ ...mountOptions, locale: () => defaultLocale }, {});
524
- const resolve = resolverFor(mountOptions);
525
- const client = { resolve: ({ path, locale, limit, cursor }) => resolve(path, locale, limit, cursor) };
526
- const { paths } = await listPublicationPaths({ client, basePath, locale: defaultLocale });
527
- lines.push("", `## ${oneLine(mount.name ?? mount.defaultSection)}`, "");
528
- for (const { path, title, description } of paths) {
529
- lines.push(`- [${oneLine(title).replace(/[[\]]/g, "")}](${linkTarget(absoluteUrl(origin, toHref(path)))}.md)${description ? `: ${oneLine(description)}` : ""}`);
530
- }
531
- }
532
- return new Response(`${lines.join("\n")}
533
- `, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
534
- } catch (error) {
535
- unstable_rethrow3(error);
536
- console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
537
- return new Response(null, { status: 503 });
767
+ async POST(req) {
768
+ if (isSwitchedOff2((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return new Response(null, { status: 404 });
769
+ const workspaceId = options.workspaceId?.trim();
770
+ const secrets = options.secrets.map((s) => s?.trim()).filter((s) => Boolean(s));
771
+ if (!workspaceId && secrets.length === 0) return new Response(null, { status: 404 });
772
+ if (!workspaceId || secrets.length === 0) return new Response(null, { status: 503 });
773
+ const key = `${workspaceId}\0${secrets.join("\0")}`;
774
+ if (cached?.key !== key) {
775
+ cached = { key, route: createRevalidationCallbackRoute({ workspaceId, secrets, revalidateTag: (tag2) => revalidateTag(tag2, { expire: 0 }), onCommentEvent: options.onCommentEvent }) };
538
776
  }
777
+ return cached.route.POST(req);
539
778
  }
540
779
  };
541
780
  }
542
781
 
543
- // src/next/asset.ts
544
- var DEFAULT_MAX_BYTES = 16 * 1024 * 1024;
545
- var DEFAULT_TIMEOUT_MS = 3e4;
546
- var CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400";
547
- var PARTIAL_CACHE_CONTROL = "no-store";
548
- var SAFE_HEADERS = { "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" };
549
- var empty = (status, headers = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers } });
550
- var isSwitchedOff2 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
551
- function capped(body, max) {
552
- let seen = 0;
553
- return body.pipeThrough(
554
- new TransformStream({
555
- transform(chunk, controller) {
556
- seen += chunk.byteLength;
557
- if (seen > max) return controller.error(new Error("asset too large"));
558
- controller.enqueue(chunk);
559
- }
560
- })
561
- );
562
- }
563
- function createAssetRoute(options) {
564
- let client;
565
- const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
566
- async function serve(req, ctx, head) {
567
- if (isSwitchedOff2((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return empty(404);
568
- const file = (await ctx.params).file;
569
- if (typeof file !== "string" || !ASSET_FILE.test(file)) return empty(404);
570
- try {
571
- client ??= createHyleClient({ baseUrl: options.baseUrl?.trim() ?? "", token: options.token?.trim() ?? "", ...options.fetch ? { fetch: options.fetch } : {} });
572
- } catch {
573
- return empty(404);
574
- }
575
- let upstream;
782
+ // src/next/root.ts
783
+ import { notFound as notFound2 } from "next/navigation";
784
+
785
+ // src/next/mount-match.ts
786
+ function activeMounts(mounts) {
787
+ const out = [];
788
+ for (const { prefix, default_section, name, locales } of mounts) {
576
789
  try {
577
- upstream = await client.asset(file, {
578
- timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
579
- headers: { range: req.headers.get("range"), "if-range": req.headers.get("if-range"), "if-none-match": req.headers.get("if-none-match") }
790
+ const normalized = normalizeBasePath(prefix);
791
+ out.push({
792
+ prefix: normalized,
793
+ defaultSection: default_section,
794
+ depth: normalized === "" ? 0 : normalized.split("/").length - 1,
795
+ ...name ? { name } : {},
796
+ ...locales ? { locales } : {}
580
797
  });
581
- } catch {
582
- return empty(502);
583
- }
584
- const drop = () => void upstream.body?.cancel().catch(() => {
585
- });
586
- const etag = upstream.headers.get("etag");
587
- if (upstream.status === 304) {
588
- drop();
589
- return new Response(null, { status: 304, headers: { "Cache-Control": CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS, ...etag ? { ETag: etag } : {} } });
590
- }
591
- if (upstream.status === 404 || upstream.status === 416) {
592
- drop();
593
- const range = upstream.status === 416 ? upstream.headers.get("content-range") : null;
594
- return empty(upstream.status, range ? { "Content-Range": range } : {});
595
- }
596
- const type = upstream.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
597
- const length = Number(upstream.headers.get("content-length"));
598
- const expectedStatus = upstream.status === 200 || upstream.status === 206;
599
- if (!expectedStatus || !upstream.body || !type || !ASSET_CONTENT_TYPES.has(type) || Number.isFinite(length) && length > maxBytes) {
600
- drop();
601
- return empty(502);
602
- }
603
- const headers = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
604
- if (etag) headers.set("ETag", etag);
605
- const contentRange = upstream.headers.get("content-range");
606
- if (upstream.status === 206 && contentRange) headers.set("Content-Range", contentRange);
607
- if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers.set("Content-Length", String(length));
608
- if (head) {
609
- drop();
610
- return new Response(null, { status: upstream.status, headers });
798
+ } catch (error) {
799
+ console.error(`hyle: ignoring a mount with an invalid prefix (${error instanceof Error ? error.name : "Error"})`);
611
800
  }
612
- return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
613
801
  }
614
- return { GET: (req, ctx) => serve(req, ctx, false), HEAD: (req, ctx) => serve(req, ctx, true) };
615
- }
616
-
617
- // src/next/embed.tsx
618
- import { unstable_rethrow as unstable_rethrow4 } from "next/navigation";
619
-
620
- // src/next/engage.ts
621
- var ENGAGE_CSRF_HEADER = "x-hyle-engage";
622
- var DEFAULT_TIMEOUT_MS2 = 1e4;
623
- var DEFAULT_SHARE_MS = 3e3;
624
- var MAX_SHARED = 100;
625
- var MAX_SHARED_BYTES = 8 * 1024 * 1024;
626
- var MAX_SHARED_ENTRY_BYTES = 256 * 1024;
627
- var MAX_BODY_BYTES = 20 * 1024;
628
- var MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
629
- var MAX_COMMENT_CHARACTERS = 4e3;
630
- var MAX_PATH_LENGTH2 = 1024;
631
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
632
- var CONTROL = /[\u0000-\u001f\u007f\\]/;
633
- var HEADERS = { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" };
634
- var isSwitchedOff3 = (value) => {
635
- const v = value?.trim().toLowerCase() ?? "";
636
- return v !== "" && v !== "1" && v !== "true";
637
- };
638
- var json = (status, body, extra = {}) => new Response(JSON.stringify(body), { status, headers: { ...HEADERS, "Content-Type": "application/json; charset=utf-8", ...extra } });
639
- var refuse = (status, code, extra = {}) => json(status, { error: { code } }, extra);
640
- function isSitePath(value) {
641
- if (typeof value !== "string" || value.length > MAX_PATH_LENGTH2 || !value.startsWith("/") || value.startsWith("//")) return false;
642
- if (CONTROL.test(value) || /[?#]/.test(value)) return false;
643
- return !value.split("/").some((segment) => segment === "." || segment === "..");
802
+ return out;
644
803
  }
645
- function match(segments) {
646
- const [a, b, ...rest] = segments;
647
- if (a === "session" && b === void 0) return { local: "session", action: () => "session", methods: ["GET"], rebuild: () => void 0 };
648
- if (a === "comments" && b === void 0) {
649
- return {
650
- action: (m) => m === "GET" ? "comments.list" : "comments.create",
651
- methods: ["GET", "POST"],
652
- rebuild: (method, body, url) => {
653
- if (method === "GET") {
654
- const keys = [...url.searchParams.keys()];
655
- const path = url.searchParams.get("path");
656
- return keys.length === 1 && isSitePath(path) ? { upstream: "/comments", query: new URLSearchParams({ path }) } : void 0;
657
- }
658
- const clean = pick(body, ["path", "body", "parent_id"], ["path", "body"]);
659
- if (!clean || !isSitePath(clean.path) || !isCommentText(clean.body)) return void 0;
660
- if (clean.parent_id === null) delete clean.parent_id;
661
- if (clean.parent_id !== void 0 && !(typeof clean.parent_id === "string" && UUID.test(clean.parent_id))) return void 0;
662
- return { upstream: "/comments", body: clean };
804
+ var prefixMatches = (prefix, path) => prefix === "" || path === prefix || path.startsWith(`${prefix}/`);
805
+ function isReserved(path, reserved) {
806
+ return reserved.some((entry) => entry.endsWith("/*") ? prefixMatches(entry.slice(0, -2), path) : entry === path);
807
+ }
808
+
809
+ // src/next/root.ts
810
+ var MOUNTS_MAX_STALE_MS = 15 * 60 * 1e3;
811
+ var SECTION_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
812
+ var NONE = { mounts: [], reserved: [], defaultLocale: "" };
813
+ var lastKnownGood = /* @__PURE__ */ new Map();
814
+ function mountsLoader(config) {
815
+ if (!config.workspaceId) throw new TypeError("hyleRootPage: `workspaceId` is required for the fetch cache");
816
+ const client = createHyleClient({ baseUrl: config.baseUrl, token: config.token });
817
+ const init = { next: { revalidate: config.revalidate ?? DEFAULT_REVALIDATE, tags: workspaceTags(config.workspaceId).slice(0, 1) } };
818
+ const key = `${new URL(config.baseUrl).origin}|${config.workspaceId}`;
819
+ return async function load() {
820
+ try {
821
+ const result = await client.mounts({ init });
822
+ if (result.kind !== "mounts") {
823
+ lastKnownGood.delete(key);
824
+ return NONE;
663
825
  }
664
- };
665
- }
666
- if (a === "comments" && typeof b === "string" && UUID.test(b) && rest.length === 0) {
667
- return {
668
- action: (m) => m === "PATCH" ? "comments.edit" : "comments.delete",
669
- methods: ["PATCH", "DELETE"],
670
- rebuild: (method, body) => {
671
- if (method === "DELETE") return body === void 0 ? { upstream: `/comments/${b}` } : void 0;
672
- const clean = pick(body, ["body"], ["body"]);
673
- return clean && isCommentText(clean.body) ? { upstream: `/comments/${b}`, body: clean } : void 0;
826
+ const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved, defaultLocale: result.default_locale };
827
+ lastKnownGood.set(key, { loaded, at: Date.now() });
828
+ return loaded;
829
+ } catch (error) {
830
+ if (isRejectedRequest(error)) {
831
+ lastKnownGood.delete(key);
832
+ return NONE;
674
833
  }
675
- };
676
- }
677
- if (a === "reactions" && b === void 0) {
678
- return {
679
- action: (m) => m === "PUT" ? "reactions.add" : "reactions.remove",
680
- methods: ["PUT", "DELETE"],
681
- rebuild: (_method, body) => {
682
- const type = body?.subject_type;
683
- 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;
684
- if (!clean) return void 0;
685
- const valid = type === "article" ? isSitePath(clean.path) : typeof clean.comment_id === "string" && UUID.test(clean.comment_id);
686
- return valid ? { upstream: "/reactions", body: clean } : void 0;
834
+ if (error instanceof Cp1ClientError && (error.status === 401 || error.status === 403)) {
835
+ lastKnownGood.delete(key);
836
+ throw error;
687
837
  }
688
- };
689
- }
690
- return void 0;
691
- }
692
- function pick(body, allowed, required) {
693
- if (!body || Object.keys(body).some((k) => !allowed.includes(k)) || !required.every((k) => k in body)) return void 0;
694
- return Object.fromEntries(allowed.filter((k) => k in body).map((k) => [k, body[k]]));
838
+ const kept = lastKnownGood.get(key);
839
+ if (kept && Date.now() - kept.at <= MOUNTS_MAX_STALE_MS) return kept.loaded;
840
+ throw error;
841
+ }
842
+ };
695
843
  }
696
- function isCommentText(value) {
697
- return typeof value === "string" && value.trim().length > 0 && [...value].length <= MAX_COMMENT_CHARACTERS && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value);
844
+ var asArray = (options) => Array.isArray(options) ? options : [options];
845
+ function setup(options) {
846
+ const configs = asArray(options);
847
+ if (configs.length === 0) throw new TypeError("hyleRootPage: pass at least one workspace config");
848
+ const param = configs[0].param ?? "hyle";
849
+ if (configs.some((c) => (c.param ?? "hyle") !== param)) throw new TypeError("hyleRootPage: every config must use the same `param`");
850
+ return { configs, param, loaders: configs.map(mountsLoader) };
698
851
  }
699
- function sameOriginProblem(req, write, allowedOrigins) {
700
- const site = req.headers.get("sec-fetch-site");
701
- if (site !== null && site !== "same-origin") return true;
702
- if (!write) return false;
703
- const origin = req.headers.get("origin");
704
- if (origin === null) return true;
705
- let parsed;
706
- try {
707
- parsed = new URL(origin);
708
- } catch {
709
- return true;
710
- }
711
- if (req.headers.get(ENGAGE_CSRF_HEADER) !== "1") return true;
712
- if (allowedOrigins) return !allowedOrigins.some((o) => safeOrigin(o) === parsed.origin);
713
- const host = req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || req.headers.get("host") || new URL(req.url).host;
714
- const proto = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
715
- if (proto && proto !== parsed.protocol.slice(0, -1)) return true;
716
- return parsed.host !== host;
852
+ var sectionsOf = (config, mount) => [
853
+ ...config.sections ?? [],
854
+ ...SECTION_SLUG.test(mount.defaultSection) ? [mount.defaultSection] : []
855
+ ];
856
+ function mountOptionsOf(config, mount) {
857
+ const { mountOptions, ...rest } = config;
858
+ return { ...rest, ...mountOptions?.[mount.prefix === "" ? "/" : mount.prefix], basePath: mount.prefix, sections: sectionsOf(config, mount) };
717
859
  }
718
- var safeOrigin = (value) => {
719
- try {
720
- return new URL(value).origin;
721
- } catch {
722
- return void 0;
723
- }
724
- };
725
- async function readBody(req, expected) {
726
- if (!expected) return { kind: "ok", body: void 0 };
727
- if (!/^application\/json(\s*;|$)/i.test(req.headers.get("content-type") ?? "")) return { kind: "refused", response: refuse(415, "UNSUPPORTED_MEDIA_TYPE") };
728
- if (Number(req.headers.get("content-length")) > MAX_BODY_BYTES) return { kind: "refused", response: refuse(413, "PAYLOAD_TOO_LARGE") };
729
- if (!req.body) return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
730
- const reader = req.body.getReader();
731
- const chunks = [];
732
- let total = 0;
733
- for (; ; ) {
734
- const { done, value } = await reader.read();
735
- if (done) break;
736
- total += value.byteLength;
737
- if (total > MAX_BODY_BYTES) {
738
- await reader.cancel().catch(() => {
860
+ function rootMounts(options) {
861
+ const { configs, param, loaders } = setup(options);
862
+ return {
863
+ param,
864
+ async locate(path) {
865
+ const loaded = await Promise.all(loaders.map((load) => load()));
866
+ let best;
867
+ loaded.forEach(({ mounts, reserved }, index2) => {
868
+ if (isReserved(path, reserved)) return;
869
+ for (const mount2 of mounts) if (prefixMatches(mount2.prefix, path) && (!best || mount2.depth > best.mount.depth)) best = { index: index2, mount: mount2 };
739
870
  });
740
- return { kind: "refused", response: refuse(413, "PAYLOAD_TOO_LARGE") };
871
+ if (!best) return void 0;
872
+ const { index, mount } = best;
873
+ return { options: mountOptionsOf(configs[index], mount), mount, index };
874
+ },
875
+ async all() {
876
+ const out = [];
877
+ for (const [index, load] of loaders.entries()) {
878
+ const { mounts, defaultLocale } = await load();
879
+ for (const mount of mounts) out.push({ options: mountOptionsOf(configs[index], mount), mount, index, defaultLocale });
880
+ }
881
+ return out;
741
882
  }
742
- chunks.push(value);
743
- }
744
- try {
745
- const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
746
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return { kind: "ok", body: parsed };
747
- } catch {
748
- }
749
- return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
883
+ };
750
884
  }
751
- var SUB_CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
752
- function validReader(r) {
753
- if (!r || typeof r.sub !== "string" || typeof r.name !== "string") return null;
754
- if (r.sub.length < 1 || [...r.sub].length > 255 || SUB_CONTROL.test(r.sub)) return null;
755
- const name = cleanDisplayName(r.name);
756
- return name === void 0 ? null : { sub: r.sub, name };
885
+ function createRouter(options, make) {
886
+ const mounts = rootMounts(options);
887
+ const handlers = /* @__PURE__ */ new Map();
888
+ return async function route(params) {
889
+ const raw = params[mounts.param];
890
+ const segments = typeof raw === "string" ? [raw] : raw;
891
+ const path = sitePathFrom("", segments);
892
+ if (path === void 0 || path === "/" || !segments) return void 0;
893
+ const hit = await mounts.locate(path);
894
+ if (!hit) return void 0;
895
+ const { mount, index } = hit;
896
+ const id = `${index}|${mount.prefix}|${mount.defaultSection}`;
897
+ let handler = handlers.get(id);
898
+ if (!handler) {
899
+ handler = make(hit.options);
900
+ handlers.set(id, handler);
901
+ }
902
+ return { handler, params: { ...params, [mounts.param]: segments.slice(mount.depth) } };
903
+ };
757
904
  }
758
- function relayFailure(status, retryAfter) {
759
- if (status === 400) return refuse(400, "VALIDATION_ERROR");
760
- if (status === 404) return refuse(404, "NOT_FOUND");
761
- if (status === 409) return refuse(409, "INVALID_TRANSITION");
762
- if (status === 413) return refuse(413, "PAYLOAD_TOO_LARGE");
763
- if (status === 429) {
764
- const seconds = Math.min(3600, Math.max(1, Math.trunc(Number(retryAfter)) || 60));
765
- return refuse(429, "RATE_LIMITED", { "Retry-After": String(seconds) });
766
- }
767
- return refuse(502, "UPSTREAM_ERROR");
905
+ function hyleRootPage(options) {
906
+ const route = createRouter(options, hylePage);
907
+ return async function HyleRootPage({ params, searchParams }) {
908
+ const hit = await route(await params ?? {});
909
+ if (!hit) notFound2();
910
+ return hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} });
911
+ };
768
912
  }
769
- function createEngagementRoute(options) {
770
- let ready;
771
- const fetchImpl = options.fetch ?? fetch;
772
- const cache = /* @__PURE__ */ new Map();
773
- let cacheBytes = 0;
774
- const clearCache = () => {
775
- cache.clear();
776
- cacheBytes = 0;
913
+ function hyleRootMetadata(options) {
914
+ const route = createRouter(options, hyleMetadata);
915
+ return async function generateMetadata({ params, searchParams }, parent) {
916
+ const hit = await route(await params ?? {});
917
+ return hit ? hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} }, parent) : {};
777
918
  };
778
- async function listing(viewer, call) {
779
- if (!viewer) return call(void 0);
780
- let out = await call(viewer.sign("read"));
781
- if (out.status === 401) out = await call(viewer.sign("read"));
782
- if (out.status !== 401 && out.status !== 404 && !(out.status === 429 && out.throttle === "viewer")) return out;
783
- return { ...await call(void 0), noShare: true };
919
+ }
920
+ async function hyleRootSitemap(options, sitemap) {
921
+ const entries = /* @__PURE__ */ new Map();
922
+ for (const { options: mountOptions, mount, defaultLocale } of await rootMounts(options).all()) {
923
+ for (const locale of mount.locales ?? [defaultLocale]) {
924
+ for (const entry of await hyleSitemap({ ...mountOptions, ...sitemap, locale, defaultLocale })) entries.set(entry.url, entry);
925
+ }
784
926
  }
785
- function shared(key, call) {
786
- const ttl = options.cacheTtlMs ?? DEFAULT_SHARE_MS;
787
- if (ttl <= 0) return call();
788
- const hit = cache.get(key);
789
- if (hit && Date.now() - hit.at < ttl) {
790
- cache.delete(key);
791
- cache.set(key, hit);
792
- return hit.result;
927
+ return [...entries.values()];
928
+ }
929
+
930
+ // src/next/markdown.ts
931
+ var MD_ROUTE_PREFIX = "/api/hyle/md";
932
+ function markdownRewritePath(pathname) {
933
+ if (!pathname.startsWith("/") || !pathname.endsWith(".md") || pathname.endsWith("/.md") || pathname.startsWith("/api/")) return void 0;
934
+ return MD_ROUTE_PREFIX + pathname.slice(0, -3);
935
+ }
936
+ var reply = (body, status, headers = {}) => (
937
+ // noindex on every answer: the .md twin must never compete with the page it mirrors.
938
+ new Response(body, { status, headers: { "X-Robots-Tag": "noindex", ...headers } })
939
+ );
940
+ function createMarkdownRoute(options) {
941
+ const mounts = rootMounts(options);
942
+ return {
943
+ async GET(_req, ctx) {
944
+ const params = await ctx.params ?? {};
945
+ const segments = params.path;
946
+ const path = sitePathFrom("", typeof segments === "string" ? [segments] : segments);
947
+ if (path === void 0 || path === "/") return reply(null, 404);
948
+ try {
949
+ const hit = await mounts.locate(path);
950
+ if (!hit) return reply(null, 404);
951
+ const { locale, toHref } = routeContext({ ...hit.options, basePath: "", param: "path" }, params);
952
+ const result = await resolverFor(hit.options)(path, locale, void 0, void 0, void 0, "md");
953
+ if (result.kind === "article" && result.content.format === "md") {
954
+ const markdown = result.content.markdown.replaceAll("](/assets/", `](${ASSET_ROUTE_PREFIX}/`);
955
+ return reply(markdown, 200, { "Content-Type": "text/markdown; charset=utf-8" });
956
+ }
957
+ if (result.kind === "redirect") {
958
+ const to = safeRedirectTarget(result.to);
959
+ const target = to === void 0 ? void 0 : safeRedirectTarget(toHref(to));
960
+ if (target === void 0) return reply(null, 502);
961
+ return target === toHref(path) ? reply(null, 404) : reply(null, result.status === 301 ? 308 : 307, { Location: `${target}.md` });
962
+ }
963
+ return reply(null, 404);
964
+ } catch (error) {
965
+ if (isRejectedRequest(error)) return reply(null, 404);
966
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
967
+ return reply(null, 502);
968
+ }
793
969
  }
794
- if (hit) forget(key, hit);
795
- const entry = { at: Date.now(), result: call(), bytes: 0 };
796
- cache.set(key, entry);
797
- entry.result.then(
798
- (o) => {
799
- if (cache.get(key) !== entry) return;
800
- if (o.status !== 200 && o.status !== 404 || o.noShare || o.text.length > MAX_SHARED_ENTRY_BYTES) return forget(key, entry);
801
- entry.bytes = o.text.length;
802
- cacheBytes += entry.bytes;
803
- while ((cacheBytes > MAX_SHARED_BYTES || cache.size > MAX_SHARED) && cache.size > 0) {
804
- const oldest = cache.entries().next().value;
805
- forget(oldest[0], oldest[1]);
970
+ };
971
+ }
972
+
973
+ // src/next/llms.ts
974
+ import { unstable_rethrow as unstable_rethrow4 } from "next/navigation";
975
+ var oneLine = (text) => text.replace(/\s+/g, " ").trim();
976
+ var linkTarget = (url) => url.replace(/[()]/g, (c) => c === "(" ? "%28" : "%29");
977
+ function createLlmsTxtRoute(options, llms) {
978
+ const origin = bareOrigin(llms.origin);
979
+ if (!origin) throw new TypeError("createLlmsTxtRoute: `origin` must be a bare https origin such as https://example.com");
980
+ const mounts = rootMounts(options);
981
+ return {
982
+ async GET() {
983
+ try {
984
+ const lines = [`# ${oneLine(llms.title ?? new URL(origin).host)}`, ...llms.description ? ["", `> ${oneLine(llms.description)}`] : []];
985
+ for (const { options: mountOptions, mount, defaultLocale } of await mounts.all()) {
986
+ if (mount.locales && !mount.locales.includes(defaultLocale)) continue;
987
+ const { basePath, toHref } = routeContext({ ...mountOptions, locale: () => defaultLocale }, {});
988
+ const resolve = resolverFor(mountOptions);
989
+ const client = { resolve: ({ path, locale, limit, cursor }) => resolve(path, locale, limit, cursor) };
990
+ const { paths } = await listPublicationPaths({ client, basePath, locale: defaultLocale });
991
+ lines.push("", `## ${oneLine(mount.name ?? mount.defaultSection)}`, "");
992
+ for (const { path, title, description } of paths) {
993
+ lines.push(`- [${oneLine(title).replace(/[[\]]/g, "")}](${linkTarget(absoluteUrl(origin, toHref(path)))}.md)${description ? `: ${oneLine(description)}` : ""}`);
994
+ }
806
995
  }
807
- },
808
- () => forget(key, entry)
809
- );
810
- return entry.result;
811
- }
812
- function forget(key, entry) {
813
- if (cache.get(key) !== entry) return;
814
- cache.delete(key);
815
- cacheBytes -= entry.bytes;
816
- }
817
- function configured() {
818
- if (ready !== void 0) return ready;
996
+ return new Response(`${lines.join("\n")}
997
+ `, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
998
+ } catch (error) {
999
+ unstable_rethrow4(error);
1000
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
1001
+ return new Response(null, { status: 503 });
1002
+ }
1003
+ }
1004
+ };
1005
+ }
1006
+
1007
+ // src/next/og.tsx
1008
+ import { ImageResponse } from "next/og";
1009
+
1010
+ // src/next/asset.ts
1011
+ var DEFAULT_MAX_BYTES = 16 * 1024 * 1024;
1012
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
1013
+ var CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400";
1014
+ var PARTIAL_CACHE_CONTROL = "no-store";
1015
+ var SAFE_HEADERS = { "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" };
1016
+ var empty = (status, headers = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers } });
1017
+ var isSwitchedOff3 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
1018
+ function capped(body, max) {
1019
+ let seen = 0;
1020
+ return body.pipeThrough(
1021
+ new TransformStream({
1022
+ transform(chunk, controller) {
1023
+ seen += chunk.byteLength;
1024
+ if (seen > max) return controller.error(new Error("asset too large"));
1025
+ controller.enqueue(chunk);
1026
+ }
1027
+ })
1028
+ );
1029
+ }
1030
+ function createAssetRoute(options) {
1031
+ let client;
1032
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
1033
+ async function serve(req, ctx, head) {
1034
+ if (isSwitchedOff3((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return empty(404);
1035
+ const file = (await ctx.params).file;
1036
+ if (typeof file !== "string" || !ASSET_FILE.test(file)) return empty(404);
819
1037
  try {
820
- const baseUrl = options.baseUrl?.trim() ?? "";
821
- checkBaseUrl(baseUrl);
822
- if (!options.token?.trim() || !options.workspaceId?.trim() || !options.signingKey) throw new TypeError("not provisioned");
823
- ready = { base: baseUrl.replace(/\/+$/, ""), key: engagementSigningKey(options.signingKey.trim()) };
1038
+ client ??= createHyleClient({ baseUrl: options.baseUrl?.trim() ?? "", token: options.token?.trim() ?? "", ...options.fetch ? { fetch: options.fetch } : {} });
824
1039
  } catch {
825
- ready = null;
1040
+ return empty(404);
826
1041
  }
827
- return ready;
828
- }
829
- async function reader(req, config) {
1042
+ let upstream;
830
1043
  try {
831
- const found = validReader(await options.getReader(req));
832
- if (!found) return null;
833
- const claims = { sub: found.sub, name: found.name, workspace: options.workspaceId.trim() };
834
- const sign = (scope) => signReaderAssertion(config.key, claims, void 0, scope);
835
- return { reader: found, assertion: sign(), sign };
1044
+ upstream = await client.asset(file, {
1045
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS2,
1046
+ headers: { range: req.headers.get("range"), "if-range": req.headers.get("if-range"), "if-none-match": req.headers.get("if-none-match") }
1047
+ });
836
1048
  } catch {
837
- return null;
1049
+ return empty(502);
838
1050
  }
839
- }
840
- async function handle(req, ctx) {
841
- const env = options.env ?? process.env;
842
- if (isSwitchedOff3(env.HYLE_ENGAGE_ENABLED) || isSwitchedOff3(env.HYLE_CONTENT_ENABLED)) return refuse(404, "NOT_FOUND");
843
- const config = configured();
844
- const route = match((await ctx.params).path ?? []);
845
- if (!config || !route) return refuse(404, "NOT_FOUND");
846
- if (!route.methods.includes(req.method)) return refuse(405, "METHOD_NOT_ALLOWED", { Allow: route.methods.join(", ") });
847
- const write = req.method !== "GET";
848
- if (sameOriginProblem(req, write, options.allowedOrigins)) return refuse(403, "FORBIDDEN");
849
- if (options.onRequest) {
850
- try {
851
- const early = await options.onRequest(req, { action: route.action(req.method) });
852
- if (early instanceof Response) {
853
- const headers = new Headers(early.headers);
854
- headers.set("cache-control", "no-store");
855
- return new Response(early.body, { status: early.status, headers });
856
- }
857
- } catch {
858
- return refuse(502, "UPSTREAM_ERROR");
859
- }
1051
+ const drop = () => void upstream.body?.cancel().catch(() => {
1052
+ });
1053
+ const etag = upstream.headers.get("etag");
1054
+ if (upstream.status === 304) {
1055
+ drop();
1056
+ return new Response(null, { status: 304, headers: { "Cache-Control": CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS, ...etag ? { ETag: etag } : {} } });
860
1057
  }
861
- if (route.local === "session") {
862
- const who = await reader(req, config);
863
- return json(200, { data: { reader: who ? { name: who.reader.name } : null } });
1058
+ if (upstream.status === 404 || upstream.status === 416) {
1059
+ drop();
1060
+ const range = upstream.status === 416 ? upstream.headers.get("content-range") : null;
1061
+ return empty(upstream.status, range ? { "Content-Range": range } : {});
864
1062
  }
865
- let assertion;
866
- let viewer = null;
867
- if (route.action(req.method) === "comments.list") viewer = await reader(req, config);
868
- if (write) {
869
- const who = await reader(req, config);
870
- if (!who) return refuse(401, "UNAUTHENTICATED");
871
- assertion = who.assertion;
1063
+ const type = upstream.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
1064
+ const length = Number(upstream.headers.get("content-length"));
1065
+ const expectedStatus = upstream.status === 200 || upstream.status === 206;
1066
+ if (!expectedStatus || !upstream.body || !type || !ASSET_CONTENT_TYPES.has(type) || Number.isFinite(length) && length > maxBytes) {
1067
+ drop();
1068
+ return empty(502);
872
1069
  }
873
- const url = new URL(req.url);
874
- const hasBody = write && !(req.method === "DELETE" && (await ctx.params).path?.[0] === "comments");
875
- const body = await readBody(req, hasBody);
876
- if (body.kind === "refused") return body.response;
877
- const built = route.rebuild(req.method, body.body, url);
878
- if (!built) return refuse(400, "VALIDATION_ERROR");
879
- const baseHeaders = new Headers({ authorization: `Bearer ${options.token.trim()}`, accept: "application/json" });
880
- if (built.body) baseHeaders.set("content-type", "application/json");
881
- const target = `${config.base}/cp1/engage${built.upstream}${built.query ? `?${built.query}` : ""}`;
882
- const call = async (withAssertion = assertion) => {
883
- const headers = new Headers(baseHeaders);
884
- if (withAssertion) headers.set("hyle-reader-assertion", withAssertion);
885
- const res = await fetchImpl(target, {
886
- method: req.method,
887
- headers,
888
- ...built.body ? { body: JSON.stringify(built.body) } : {},
889
- redirect: "error",
890
- signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS2)
891
- });
892
- 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") };
893
- };
894
- try {
895
- const out = route.action(req.method) === "comments.list" ? await shared(`${viewer?.reader.sub ?? ""}
896
- ${built.query.toString()}`, () => listing(viewer, call)) : await call();
897
- if (!out.ok) return relayFailure(out.status, out.retryAfter);
898
- if (write) clearCache();
899
- const data = JSON.parse(out.text).data;
900
- return typeof data === "object" && data !== null ? json(out.status === 201 ? 201 : 200, { data }) : refuse(502, "UPSTREAM_ERROR");
901
- } catch {
902
- return refuse(502, "UPSTREAM_ERROR");
1070
+ const headers = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
1071
+ if (etag) headers.set("ETag", etag);
1072
+ const contentRange = upstream.headers.get("content-range");
1073
+ if (upstream.status === 206 && contentRange) headers.set("Content-Range", contentRange);
1074
+ if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers.set("Content-Length", String(length));
1075
+ if (head) {
1076
+ drop();
1077
+ return new Response(null, { status: upstream.status, headers });
903
1078
  }
1079
+ return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
904
1080
  }
905
- return { GET: handle, POST: handle, PATCH: handle, PUT: handle, DELETE: handle };
1081
+ return { GET: (req, ctx) => serve(req, ctx, false), HEAD: (req, ctx) => serve(req, ctx, true) };
906
1082
  }
907
1083
 
908
- // src/next/embed.tsx
909
- import { jsx as jsx2 } from "react/jsx-runtime";
910
- async function resolveEmbed(options, run) {
911
- try {
912
- return { result: await run() };
913
- } catch (error) {
914
- if (isRejectedRequest(error)) return {};
915
- console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
916
- return { failure: options.onError ? options.onError(error) : null };
917
- }
918
- }
919
- async function HyleList({ options, limit = 5, locale, layout, title, headingLevel, moreHref }) {
1084
+ // src/next/og.tsx
1085
+ import { jsx as jsx3, jsxs } from "react/jsx-runtime";
1086
+ var SIZE = { width: 1200, height: 630 };
1087
+ var MAX_TITLE = 140;
1088
+ function createOgImageRoute(options) {
920
1089
  const resolve = resolverFor(options);
921
- const route = routeContext(locale ? { ...options, locale } : options, {});
922
- const path = sitePathFrom(route.basePath, void 0);
923
- if (path === void 0) return null;
924
- const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale, limit));
925
- if (failure !== void 0) return failure;
926
- return /* @__PURE__ */ jsx2(HyleListView, { items: result?.kind === "list" ? result.items : [], layout, title, headingLevel, moreHref, components: options.components, slots: options.slots, locale: route.locale, toHref: route.toHref });
927
- }
928
- async function HyleArticle({ options, path, locale, headingLevel }) {
929
- if (!isSitePath(path)) return null;
930
- const resolve = resolverFor(options);
931
- const route = routeContext(locale ? { ...options, locale } : options, {});
932
- const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale));
933
- if (failure !== void 0) return failure;
934
- if (result?.kind !== "article") return null;
935
- return /* @__PURE__ */ jsx2(HyleArticleView, { article: result, headingLevel, components: options.components, slots: options.slots, locale: route.locale, toHref: route.toHref });
936
- }
937
- var MAX_LISTING_BYTES = 4 * 1024 * 1024;
938
- var COMMENTS_TIMEOUT_MS = 1e4;
939
- async function HyleComments({ options, path, revalidate = 60, interactive }) {
940
- checkBaseUrl(options.baseUrl);
941
- if (!options.token) throw new TypeError("token is required");
942
- if (!isSitePath(path)) return null;
943
- const locale = options.locale ?? "en";
944
- let listing;
945
- let fetchedAt;
946
- try {
947
- const init = {
948
- headers: { authorization: `Bearer ${options.token}`, accept: "application/json" },
949
- redirect: "error",
950
- signal: AbortSignal.timeout(COMMENTS_TIMEOUT_MS),
951
- next: { revalidate }
952
- };
953
- const res = await fetch(`${options.baseUrl.replace(/\/+$/, "")}/cp1/engage/comments?${new URLSearchParams({ path })}`, init);
954
- if (!res.ok) {
955
- if (res.status !== 404) console.error(`hyle: comments answered HTTP ${res.status}`);
956
- return null;
1090
+ return {
1091
+ async GET(req, ctx) {
1092
+ if (isSwitchedOff3(process.env.HYLE_CONTENT_ENABLED)) return new Response(null, { status: 404 });
1093
+ const segments = (await ctx.params).path;
1094
+ const route = routeContext({ ...options, basePath: "", param: "path" }, { path: segments });
1095
+ if (!segments?.length || route.path === void 0) return new Response(null, { status: 404 });
1096
+ const path = route.path;
1097
+ const load = async (locale) => {
1098
+ const first = await resolve(path, locale);
1099
+ const target = first.kind === "redirect" ? safeRedirectTarget(first.to) : void 0;
1100
+ return target ? resolve(target, locale) : first;
1101
+ };
1102
+ let title;
1103
+ try {
1104
+ let result = await load();
1105
+ const wanted = new URL(req.url).searchParams.get("locale");
1106
+ if (result.kind === "article" && wanted && wanted !== result.publication.locale && result.alternates.some((a) => a.locale === wanted)) result = await load(wanted);
1107
+ if (result.kind !== "article") return new Response(null, { status: 404 });
1108
+ title = result.publication.title;
1109
+ } catch (error) {
1110
+ return new Response(null, { status: isRejectedRequest(error) ? 404 : 502 });
1111
+ }
1112
+ const chars = [...title];
1113
+ const shown = chars.length > MAX_TITLE ? `${chars.slice(0, MAX_TITLE - 1).join("")}\u2026` : title;
1114
+ return new ImageResponse(
1115
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", flexDirection: "column", justifyContent: "space-between", width: "100%", height: "100%", padding: 80, background: "#111827", color: "#ffffff" }, children: [
1116
+ /* @__PURE__ */ jsx3("div", { style: { fontSize: 64, fontWeight: 700, lineHeight: 1.2 }, children: shown }),
1117
+ options.siteName ? /* @__PURE__ */ jsx3("div", { style: { fontSize: 32, color: "#9ca3af" }, children: options.siteName }) : null
1118
+ ] }),
1119
+ // shortcut: @vercel/og fetches Google Fonts / emoji assets at render time for non-Latin titles and emoji (no switch to disable it), upgrade to a satori render with bundled fonts if a host needs zero egress.
1120
+ { ...SIZE, headers: { "cache-control": "public, max-age=3600, s-maxage=31536000, immutable" } }
1121
+ );
957
1122
  }
958
- listing = parseListing(JSON.parse(await readCapped(res, MAX_LISTING_BYTES)).data);
959
- const date = Date.parse(res.headers.get("date") ?? "");
960
- fetchedAt = Number.isFinite(date) ? date : void 0;
961
- } catch (error) {
962
- unstable_rethrow4(error);
963
- console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
964
- return null;
965
- }
966
- if (!listing) return null;
967
- if (!interactive) return /* @__PURE__ */ jsx2(HyleCommentsView, { listing, locale });
968
- const config = interactive === true ? {} : interactive;
969
- return /* @__PURE__ */ jsx2("div", { className: "hyle hyle-embed", children: /* @__PURE__ */ jsx2(Comments, { path, endpoint: config.endpoint ?? "/api/hyle/engage", signInHref: config.signInHref, locale, labels: stringsFor(locale).comments, initial: listing, initialAt: fetchedAt }) });
1123
+ };
970
1124
  }
971
1125
  export {
972
1126
  ENGAGE_CSRF_HEADER,
@@ -979,9 +1133,11 @@ export {
979
1133
  createEngagementRoute,
980
1134
  createLlmsTxtRoute,
981
1135
  createMarkdownRoute,
1136
+ createOgImageRoute,
982
1137
  createRevalidateRoute,
983
1138
  fetchResolver,
984
1139
  hyleFeed,
1140
+ hyleFeedLink,
985
1141
  hyleMetadata,
986
1142
  hylePage,
987
1143
  hyleRootMetadata,