@tdacorp/hyle-sdk 0.17.0 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +261 -42
  2. package/dist/check-routes-bin.js +190 -53
  3. package/dist/{chunk-6VOHFFA5.js → chunk-7T5EEJHK.js} +2 -2
  4. package/dist/chunk-DUPT6XLB.js +57 -0
  5. package/dist/chunk-IW3TUD4G.js +841 -0
  6. package/dist/{chunk-MGSUQBDW.js → chunk-KU7LWK4E.js} +249 -24
  7. package/dist/{chunk-BUJFMR3M.js → chunk-QVYQM5R2.js} +15 -6
  8. package/dist/chunk-SFFBZFEN.js +178 -0
  9. package/dist/chunk-U74B7AUG.js +398 -0
  10. package/dist/chunk-ZIW6FDU2.js +1126 -0
  11. package/dist/client-BGjmEWhN.d.cts +207 -0
  12. package/dist/client-D0LTpr3Y.d.ts +207 -0
  13. package/dist/code-copy.cjs +74 -0
  14. package/dist/code-copy.d.cts +18 -0
  15. package/dist/code-copy.d.ts +18 -0
  16. package/dist/code-copy.js +50 -0
  17. package/dist/comments.cjs +738 -280
  18. package/dist/comments.d.cts +66 -3
  19. package/dist/comments.d.ts +66 -3
  20. package/dist/comments.js +419 -331
  21. package/dist/{diagram-viewer-FJPED4SN.js → diagram-viewer-XY3CG75U.js} +62 -21
  22. package/dist/docs-enhance.cjs +7 -4
  23. package/dist/docs-enhance.d.cts +5 -3
  24. package/dist/docs-enhance.d.ts +5 -3
  25. package/dist/docs-enhance.js +8 -5
  26. package/dist/{embed-DNTZ2UXv.d.ts → embed-CbtsbZs3.d.cts} +5 -3
  27. package/dist/{embed-BmdwA2G9.d.cts → embed-Cf_2ZR5x.d.ts} +5 -3
  28. package/dist/fragment-alias.cjs +51 -0
  29. package/dist/fragment-alias.d.cts +7 -0
  30. package/dist/fragment-alias.d.ts +7 -0
  31. package/dist/fragment-alias.js +27 -0
  32. package/dist/html.cjs +886 -0
  33. package/dist/html.d.cts +20 -0
  34. package/dist/html.d.ts +20 -0
  35. package/dist/html.js +45 -0
  36. package/dist/index.cjs +244 -24
  37. package/dist/index.d.cts +22 -68
  38. package/dist/index.d.ts +22 -68
  39. package/dist/index.js +12 -2
  40. package/dist/{labels-nmukKYgL.d.cts → labels-CrA-iqTN.d.cts} +9 -0
  41. package/dist/{labels-nmukKYgL.d.ts → labels-CrA-iqTN.d.ts} +9 -0
  42. package/dist/mermaid-diagram.cjs +441 -125
  43. package/dist/mermaid-diagram.d.cts +23 -7
  44. package/dist/mermaid-diagram.d.ts +23 -7
  45. package/dist/mermaid-diagram.js +213 -51
  46. package/dist/mermaid-image.cjs +137 -60
  47. package/dist/mermaid-image.d.cts +4 -3
  48. package/dist/mermaid-image.d.ts +4 -3
  49. package/dist/mermaid-image.js +27 -28
  50. package/dist/next.cjs +836 -304
  51. package/dist/next.d.cts +45 -20
  52. package/dist/next.d.ts +45 -20
  53. package/dist/next.js +151 -40
  54. package/dist/print-coordinator.cjs +157 -0
  55. package/dist/print-coordinator.d.cts +27 -0
  56. package/dist/print-coordinator.d.ts +27 -0
  57. package/dist/print-coordinator.js +83 -0
  58. package/dist/react.cjs +603 -240
  59. package/dist/react.d.cts +148 -30
  60. package/dist/react.d.ts +148 -30
  61. package/dist/react.js +26 -4
  62. package/dist/reactions.cjs +653 -0
  63. package/dist/reactions.d.cts +27 -0
  64. package/dist/reactions.d.ts +27 -0
  65. package/dist/reactions.js +364 -0
  66. package/dist/{resolve-euZ4-aC9.d.cts → resolve-BnIv7aB7.d.cts} +2 -2
  67. package/dist/{resolve-Ae7UFjsQ.d.ts → resolve-BysHtZ_i.d.ts} +2 -2
  68. package/dist/revalidation-callback-BQl77tQR.d.cts +75 -0
  69. package/dist/revalidation-callback-BQl77tQR.d.ts +75 -0
  70. package/dist/sanitize-BpY_AdZh.d.cts +23 -0
  71. package/dist/sanitize-BpY_AdZh.d.ts +23 -0
  72. package/dist/styles.css +100 -29
  73. package/dist/toc-spy.cjs +60 -0
  74. package/dist/toc-spy.d.cts +15 -0
  75. package/dist/toc-spy.d.ts +15 -0
  76. package/dist/toc-spy.js +36 -0
  77. package/dist/{types-Czt887Iv.d.cts → types-D09Z072G.d.cts} +57 -2
  78. package/dist/{types-Czt887Iv.d.ts → types-D09Z072G.d.ts} +57 -2
  79. package/dist/use-cache.cjs +89 -13
  80. package/dist/use-cache.d.cts +12 -5
  81. package/dist/use-cache.d.ts +12 -5
  82. package/dist/use-cache.js +8 -8
  83. package/dist/youtube-facade.cjs +50 -0
  84. package/dist/youtube-facade.d.cts +17 -0
  85. package/dist/youtube-facade.d.ts +17 -0
  86. package/dist/youtube-facade.js +26 -0
  87. package/package.json +16 -3
  88. package/dist/chunk-67IOIAVW.js +0 -35
  89. package/dist/chunk-DMK4XQLU.js +0 -1556
  90. package/dist/chunk-PJMJMP66.js +0 -63
  91. package/dist/revalidation-callback-D7Ms_Puz.d.cts +0 -42
  92. package/dist/revalidation-callback-D7Ms_Puz.d.ts +0 -42
@@ -0,0 +1,20 @@
1
+ export { H as HastLimitError } from './sanitize-BpY_AdZh.cjs';
2
+ import 'hast';
3
+
4
+ interface HastToHtmlOptions {
5
+ /** The article's own absolute http(s) URL: relative links, images and `#fragments` are resolved against it. */
6
+ readonly baseUrl: string;
7
+ /** As in `HastContent`: a leading body h1 that repeats it is dropped. */
8
+ readonly title?: string | undefined;
9
+ /** As in `HastContent`: a leading body paragraph that starts with it is dropped. */
10
+ readonly description?: string | null | undefined;
11
+ /** Language of the callout titles and checkbox names. */
12
+ readonly locale?: string | undefined;
13
+ }
14
+ /**
15
+ * @throws TypeError when `baseUrl` is not an absolute http(s) URL.
16
+ * @throws HastLimitError when the tree is over the sanitizer's caps, so a feed never silently publishes an empty body.
17
+ */
18
+ declare function hastToHtml(tree: unknown, { baseUrl, title, description, locale }: HastToHtmlOptions): string;
19
+
20
+ export { type HastToHtmlOptions, hastToHtml };
package/dist/html.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ export { H as HastLimitError } from './sanitize-BpY_AdZh.js';
2
+ import 'hast';
3
+
4
+ interface HastToHtmlOptions {
5
+ /** The article's own absolute http(s) URL: relative links, images and `#fragments` are resolved against it. */
6
+ readonly baseUrl: string;
7
+ /** As in `HastContent`: a leading body h1 that repeats it is dropped. */
8
+ readonly title?: string | undefined;
9
+ /** As in `HastContent`: a leading body paragraph that starts with it is dropped. */
10
+ readonly description?: string | null | undefined;
11
+ /** Language of the callout titles and checkbox names. */
12
+ readonly locale?: string | undefined;
13
+ }
14
+ /**
15
+ * @throws TypeError when `baseUrl` is not an absolute http(s) URL.
16
+ * @throws HastLimitError when the tree is over the sanitizer's caps, so a feed never silently publishes an empty body.
17
+ */
18
+ declare function hastToHtml(tree: unknown, { baseUrl, title, description, locale }: HastToHtmlOptions): string;
19
+
20
+ export { type HastToHtmlOptions, hastToHtml };
package/dist/html.js ADDED
@@ -0,0 +1,45 @@
1
+ import {
2
+ HastLimitError,
3
+ mermaidSource,
4
+ sanitizeHast,
5
+ stringsFor
6
+ } from "./chunk-IW3TUD4G.js";
7
+ import "./chunk-DUPT6XLB.js";
8
+
9
+ // src/html.ts
10
+ import { toHtml } from "hast-util-to-html";
11
+ var el = (tagName, properties, children) => ({ type: "element", tagName, properties, children });
12
+ var text = (value) => ({ type: "text", value });
13
+ var URL_ATTRS = ["href", "src"];
14
+ function forFeed(node, base, s) {
15
+ if (node.type !== "element") return node;
16
+ if (node.tagName === "iframe") {
17
+ const source = mermaidSource(String(node.properties.srcdoc)) ?? "";
18
+ return el("pre", {}, [el("code", { className: ["language-mermaid"] }, [text(source)])]);
19
+ }
20
+ const children = node.children.map((child) => forFeed(child, base, s));
21
+ if (node.tagName === "callout") {
22
+ const kind = String(node.properties.kind);
23
+ return el("aside", { className: ["hyle-callout"], dataKind: kind, role: "note" }, [
24
+ el("div", {}, [el("p", { className: ["ttl"] }, [text(s[kind])]), el("div", { className: ["bd"] }, children)])
25
+ ]);
26
+ }
27
+ const { dataEmbed: _embed, dataLight: _light, dataDark: _dark, ...properties } = node.properties;
28
+ for (const key of URL_ATTRS) {
29
+ const value = properties[key];
30
+ if (typeof value === "string") properties[key] = new URL(value, base).href;
31
+ }
32
+ if (node.tagName === "input") properties.ariaLabel = properties.checked ? s.done : s.notDone;
33
+ return el(node.tagName, properties, children);
34
+ }
35
+ function hastToHtml(tree, { baseUrl, title, description, locale }) {
36
+ const base = new URL(baseUrl);
37
+ if (base.protocol !== "https:" && base.protocol !== "http:") throw new TypeError("hastToHtml: baseUrl must be an absolute http(s) URL");
38
+ const s = stringsFor(locale);
39
+ const root = sanitizeHast(tree, title, description);
40
+ return toHtml({ type: "root", children: root.children.map((child) => forFeed(child, base, s)) });
41
+ }
42
+ export {
43
+ HastLimitError,
44
+ hastToHtml
45
+ };
package/dist/index.cjs CHANGED
@@ -23,9 +23,11 @@ __export(src_exports, {
23
23
  CACHE_TAG_PATTERN: () => CACHE_TAG_PATTERN,
24
24
  Cp1ClientError: () => Cp1ClientError,
25
25
  DeliveryDedupe: () => DeliveryDedupe,
26
+ MAX_PUSH_BODY_BYTES: () => MAX_PUSH_BODY_BYTES,
26
27
  SDK_OWN_RESERVED: () => SDK_OWN_RESERVED,
27
28
  checkRoutes: () => checkRoutes,
28
29
  createHyleClient: () => createHyleClient,
30
+ createPushRoute: () => createPushRoute,
29
31
  createRevalidationCallbackRoute: () => createRevalidationCallbackRoute,
30
32
  engagementPublicKey: () => engagementPublicKey,
31
33
  formatReport: () => formatReport,
@@ -34,9 +36,12 @@ __export(src_exports, {
34
36
  isValidCacheTag: () => isValidCacheTag,
35
37
  listPublicationPaths: () => listPublicationPaths,
36
38
  normalizeRoute: () => normalizeRoute,
39
+ parseCommentEvent: () => parseCommentEvent,
37
40
  parseSignatureHeader: () => parseSignatureHeader,
38
41
  reservedFor: () => reservedFor,
42
+ resyncPath: () => resyncPath,
39
43
  routeMatches: () => routeMatches,
44
+ staleAfterResync: () => staleAfterResync,
40
45
  syncHostReserved: () => syncHostReserved,
41
46
  verifyHyleSignature: () => verifyHyleSignature
42
47
  });
@@ -46,9 +51,15 @@ module.exports = __toCommonJS(src_exports);
46
51
  var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
47
52
  var ASSET_RESERVED_PATH = "/api/hyle/*";
48
53
  var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
49
- var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg";
54
+ var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg|woff2";
50
55
  var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
51
- var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
56
+ var THEME_FONT = new RegExp(`^/assets/${UUID}\\.woff2$`);
57
+ var PREVIEW_TOKEN_SOURCE = "hyle_pv_[A-Za-z0-9_-]{43}";
58
+ var PREVIEW_TOKEN = new RegExp(`^${PREVIEW_TOKEN_SOURCE}$`);
59
+ var PREVIEW_HEADER = "cp-preview";
60
+ var PREVIEW_PARAM = "hyle_preview";
61
+ var PREVIEW_QUERY_SOURCE = `\\?${PREVIEW_PARAM}=${PREVIEW_TOKEN_SOURCE}`;
62
+ var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)(${PREVIEW_QUERY_SOURCE})?$`, "i");
52
63
 
53
64
  // src/errors.ts
54
65
  var Cp1ClientError = class extends Error {
@@ -66,7 +77,43 @@ var Cp1ClientError = class extends Error {
66
77
  }
67
78
  };
68
79
 
80
+ // src/preview.ts
81
+ var ASSET_PATH = /^\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?:\.[a-z0-9]+)?(?= |$)/i;
82
+ var ASSET_PROPERTIES = ["src", "dataLight", "dataDark"];
83
+ var MAX_DEPTH = 200;
84
+ function mapNode(node, mark, depth) {
85
+ if (typeof node !== "object" || node === null || depth > MAX_DEPTH) return node;
86
+ const { properties, children } = node;
87
+ const marked = properties && Object.fromEntries(ASSET_PROPERTIES.filter((name) => name in properties).map((name) => [name, mark(properties[name])]));
88
+ return {
89
+ ...node,
90
+ ...properties ? { properties: { ...properties, ...marked } } : {},
91
+ ...Array.isArray(children) ? { children: children.map((child) => mapNode(child, mark, depth + 1)) } : {}
92
+ };
93
+ }
94
+ function withPreviewAssets(article, token) {
95
+ const mark = (value) => typeof value === "string" ? value.replace(ASSET_PATH, (path) => `${path}?${PREVIEW_PARAM}=${token}`) : value;
96
+ const { publication, content } = article;
97
+ return {
98
+ ...article,
99
+ publication: publication.cover ? { ...publication, cover: { path: String(mark(publication.cover.path)) } } : publication,
100
+ content: content.format === "hast" ? { ...content, tree: mapNode(content.tree, mark, 0) } : content
101
+ };
102
+ }
103
+
69
104
  // src/client.ts
105
+ var RENDERER_VERSION = "4";
106
+ function applyCredential(headers, credential, method, url) {
107
+ if (!credential.auth) {
108
+ headers.set("authorization", `Bearer ${credential.token}`);
109
+ return void 0;
110
+ }
111
+ const { workspaceId } = credential;
112
+ return credential.auth({ method, url }).then((extra) => {
113
+ for (const [name, value] of Object.entries(extra)) headers.set(name, value);
114
+ headers.set("cp-workspace", workspaceId);
115
+ });
116
+ }
70
117
  var DEFAULT_TIMEOUT_MS = 1e4;
71
118
  var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
72
119
  var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -108,14 +155,16 @@ function checkBaseUrl(baseUrl, allowInsecureHttp) {
108
155
  }
109
156
  function createHyleClient(options) {
110
157
  checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
111
- if (!options.token) throw new TypeError("token is required");
158
+ if (!options.auth && !options.token) throw new TypeError("token is required");
112
159
  const base = options.baseUrl.replace(/\/+$/, "");
113
160
  const fetchImpl = options.fetch ?? fetch;
114
161
  async function get(pathname, query, init) {
115
162
  const url = new URL(`${base}${pathname}`);
116
163
  url.search = query.toString();
117
164
  const headers = new Headers(init?.headers);
118
- headers.set("authorization", `Bearer ${options.token}`);
165
+ headers.set("cp-renderer-version", RENDERER_VERSION);
166
+ const applied = applyCredential(headers, options, "GET", url.toString());
167
+ if (applied) await applied;
119
168
  const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
120
169
  const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
121
170
  const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
@@ -155,41 +204,71 @@ function createHyleClient(options) {
155
204
  if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
156
205
  throw failure(reply);
157
206
  }
207
+ async function pushPosts(opts) {
208
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(opts.section)) throw new TypeError("section must be a section slug");
209
+ const query = new URLSearchParams();
210
+ if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
211
+ const reply = await get(`/cp1/read/sections/${opts.section}/posts`, query, opts.init);
212
+ const data = reply.parsed?.data;
213
+ if (data?.cp === 1 && data.kind === "push_posts" && Array.isArray(data.posts) && typeof data.complete === "boolean") return data;
214
+ throw failure(reply);
215
+ }
216
+ async function preview(token) {
217
+ if (typeof token !== "string" || !PREVIEW_TOKEN.test(token)) return { kind: "notfound" };
218
+ const reply = await get("/cp1/read/_preview", new URLSearchParams(), { headers: { [PREVIEW_HEADER]: token }, cache: "no-store" });
219
+ if (reply.status === 404 && reply.parsed?.error?.code === "NOT_FOUND") return { kind: "notfound" };
220
+ const data = reply.parsed?.data;
221
+ if (data?.cp === 1 && data.kind === "disabled") return { kind: "disabled" };
222
+ const article = data?.article;
223
+ if (data?.cp !== 1 || data.kind !== "preview" || typeof data.expires_at !== "string" || article?.kind !== "article" || article.content?.format !== "hast" || !article.publication) throw failure(reply);
224
+ return { kind: "preview", expires_at: data.expires_at, article: withPreviewAssets(article, token) };
225
+ }
158
226
  async function asset(file, opts = {}) {
159
227
  if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
160
- const headers = new Headers({ authorization: `Bearer ${options.token}` });
228
+ const { previewToken } = opts;
229
+ if (previewToken !== void 0 && !PREVIEW_TOKEN.test(previewToken)) throw new TypeError("previewToken is not a preview token");
230
+ const url = `${base}/cp1/read/assets/${file}`;
231
+ const headers = new Headers();
232
+ const applied = applyCredential(headers, options, "GET", url);
233
+ if (applied) await applied;
161
234
  for (const name of ["range", "if-range", "if-none-match"]) {
162
235
  const value = opts.headers?.[name];
163
236
  if (value) headers.set(name, value);
164
237
  }
165
- return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
238
+ if (previewToken !== void 0) headers.set(PREVIEW_HEADER, previewToken);
239
+ return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS), ...previewToken === void 0 ? {} : { cache: "no-store" } });
240
+ }
241
+ async function theme(opts = {}) {
242
+ const url = `${base}/cp1/read/theme.css`;
243
+ const headers = new Headers();
244
+ const applied = applyCredential(headers, options, "GET", url);
245
+ if (applied) await applied;
246
+ return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
166
247
  }
167
- return { resolve, mounts, asset };
248
+ return { resolve, mounts, pushPosts, preview, asset, theme };
168
249
  }
169
250
 
170
251
  // src/host-sync.ts
171
252
  var CONTROL_TOKEN_PREFIX = "hyle_tc_";
172
253
  var DEFAULT_TIMEOUT_MS2 = 1e4;
173
254
  var MAX_RESPONSE_BYTES = 1024 * 1024;
174
- var PATH = "/cp1/control/workspace/host-reserved-paths";
175
- async function syncHostReserved(input) {
255
+ async function put(input, path, body, read) {
176
256
  checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
177
- if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
257
+ if (input.token !== void 0 && !input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
178
258
  throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
179
259
  }
180
260
  const fetchImpl = input.fetch ?? fetch;
181
- const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
261
+ const url = `${input.baseUrl.replace(/\/+$/, "")}${path}`;
262
+ const headers = new Headers({ "content-type": "application/json", "idempotency-key": `sync-${crypto.randomUUID()}` });
263
+ await applyCredential(headers, input.auth ? { auth: input.auth, workspaceId: input.workspaceId } : { token: input.token }, "PUT", url);
264
+ headers.set("cp-workspace", input.workspaceId);
265
+ const res = await fetchImpl(url, {
182
266
  method: "PUT",
183
267
  // redirect "error": the bearer token must never follow a redirect to another host.
184
268
  redirect: "error",
185
269
  signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
186
- headers: {
187
- authorization: `Bearer ${input.token}`,
188
- "content-type": "application/json",
189
- "cp-workspace": input.workspaceId,
190
- "idempotency-key": `sync-${crypto.randomUUID()}`
191
- },
192
- body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
270
+ headers,
271
+ body: JSON.stringify(body)
193
272
  });
194
273
  const text = await readCapped(res, MAX_RESPONSE_BYTES);
195
274
  let parsed;
@@ -198,14 +277,18 @@ async function syncHostReserved(input) {
198
277
  } catch {
199
278
  parsed = void 0;
200
279
  }
201
- const data = parsed?.data;
202
- const conflicts = data?.conflicts;
203
- if (res.ok && data && Array.isArray(data.paths) && typeof data.changed === "boolean" && typeof data.synced_at === "string" && typeof conflicts?.total === "number" && Array.isArray(conflicts.offenders)) {
204
- return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
205
- }
280
+ const result = res.ok && parsed?.data ? read(parsed.data) : void 0;
281
+ if (result !== void 0) return result;
206
282
  const err = parsed?.error;
207
283
  throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
208
284
  }
285
+ function syncHostReserved(input) {
286
+ return put(input, "/cp1/control/workspace/host-reserved-paths", { paths: input.paths, host: input.host, build_id: input.buildId }, (data) => {
287
+ const conflicts = data.conflicts;
288
+ if (!Array.isArray(data.paths) || typeof data.changed !== "boolean" || typeof data.synced_at !== "string" || typeof conflicts?.total !== "number" || !Array.isArray(conflicts.offenders)) return void 0;
289
+ return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
290
+ });
291
+ }
209
292
 
210
293
  // src/delivery-dedupe.ts
211
294
  var DeliveryDedupe = class {
@@ -281,6 +364,35 @@ function isValidCacheTag(tag) {
281
364
  // src/revalidation-callback.ts
282
365
  var MAX_BODY_BYTES = 65536;
283
366
  var MAX_TAGS = 1e3;
367
+ var HOOK_WAIT_MS = 3e3;
368
+ var COMMENT_EVENT_TYPES = ["comment.held", "comment.reply", "comment.approved", "comment.hidden"];
369
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
370
+ var isText = (v) => typeof v === "string" && v.length > 0;
371
+ var isTextOrNull = (v) => v === null || isText(v);
372
+ var isEventPath = (v) => typeof v === "string" && v.startsWith("/") && !v.startsWith("//") && v.length <= 2048 && !/[\\\u0000-\u001f\u007f]/.test(v);
373
+ function parseCommentEvent(payload) {
374
+ if (!isRecord(payload) || payload.cp !== 1 || !isRecord(payload.data)) return void 0;
375
+ const type = COMMENT_EVENT_TYPES.find((t) => t === payload.type);
376
+ const { id, created_at, workspace_id, event_id, data } = payload;
377
+ if (!type || !isText(id) || !isText(created_at) || !isText(workspace_id) || !isText(event_id)) return void 0;
378
+ const { comment_id, parent_comment_id, publication_path, reader_sub, parent_reader_sub, status } = data;
379
+ if (!isText(comment_id) || !isTextOrNull(parent_comment_id) || !isEventPath(publication_path) || !isTextOrNull(reader_sub) || !isTextOrNull(parent_reader_sub)) return void 0;
380
+ if (status !== "held" && status !== "visible" && status !== "hidden") return void 0;
381
+ return { cp: 1, id, type, created_at, workspace_id, event_id, data: { comment_id, parent_comment_id, publication_path, reader_sub, parent_reader_sub, status } };
382
+ }
383
+ async function runHook(hook, event) {
384
+ let timer;
385
+ try {
386
+ await Promise.race([
387
+ Promise.resolve().then(() => hook(event)),
388
+ new Promise((_, reject) => timer = setTimeout(() => reject(new Error("timeout")), HOOK_WAIT_MS))
389
+ ]);
390
+ } catch {
391
+ console.error(`hyle: onCommentEvent failed or timed out for ${event.type} ${event.id}`);
392
+ } finally {
393
+ clearTimeout(timer);
394
+ }
395
+ }
284
396
  function createRevalidationCallbackRoute(options) {
285
397
  const dedupe = new DeliveryDedupe(options.dedupeCapacity);
286
398
  return {
@@ -315,7 +427,7 @@ function createRevalidationCallbackRoute(options) {
315
427
  if (body.workspace_id !== options.workspaceId) {
316
428
  return okResponse(0);
317
429
  }
318
- const deliveryId = req.headers.get("hyle-delivery-id");
430
+ const deliveryId = typeof body.id === "string" ? body.id : void 0;
319
431
  if (deliveryId && dedupe.has(deliveryId)) {
320
432
  return okResponse(0);
321
433
  }
@@ -330,6 +442,9 @@ function createRevalidationCallbackRoute(options) {
330
442
  return new Response(null, { status: 500 });
331
443
  }
332
444
  if (deliveryId) dedupe.add(deliveryId);
445
+ const hook = options.onCommentEvent;
446
+ const event = hook && parseCommentEvent(body);
447
+ if (hook && event) await runHook(hook, event);
333
448
  return okResponse(purged);
334
449
  }
335
450
  };
@@ -360,6 +475,106 @@ function okResponse(purged) {
360
475
  });
361
476
  }
362
477
 
478
+ // src/push.ts
479
+ var MAX_PUSH_BODY_BYTES = 2 * 1024 * 1024;
480
+ var seqKey = (sectionId, publicationId) => `${sectionId}:${publicationId}`;
481
+ var TYPES = /* @__PURE__ */ new Set(["post.published", "post.updated", "post.unpublished", "post.deleted", "post.moved", "section.moved"]);
482
+ var WITH_POST = /* @__PURE__ */ new Set(["post.published", "post.updated", "post.moved"]);
483
+ var ok = (applied) => new Response(JSON.stringify({ ok: true, applied }), { status: 200, headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" } });
484
+ function parseEvent(body) {
485
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return void 0;
486
+ const e = body;
487
+ if (e.type === "webhook.test") return "ignore";
488
+ if (e.schema !== "hyle.push/1") return "ignore";
489
+ const section = e.section;
490
+ const hasPost = typeof e.post === "object" && e.post !== null;
491
+ if (typeof e.type !== "string" || !TYPES.has(e.type) || typeof e.event_id !== "string" || typeof e.seq !== "number" || !Number.isSafeInteger(e.seq) || typeof section?.id !== "string" || typeof section.site_path !== "string" || hasPost !== WITH_POST.has(e.type) || e.type !== "section.moved" && typeof e.publication_id !== "string") return void 0;
492
+ return e;
493
+ }
494
+ function createPushRoute(options) {
495
+ const secrets = typeof options.secret === "string" ? [options.secret] : options.secret;
496
+ if (secrets.length === 0 || secrets.some((s) => !s)) throw new TypeError("secret is required");
497
+ return {
498
+ async POST(req) {
499
+ const declared = Number(req.headers.get("content-length"));
500
+ if (Number.isFinite(declared) && declared > MAX_PUSH_BODY_BYTES) return new Response(null, { status: 413 });
501
+ const raw = await readCapped3(req);
502
+ if (raw === void 0) return new Response(null, { status: 413 });
503
+ const verified = verifyHyleSignature({
504
+ header: req.headers.get("hyle-signature"),
505
+ rawBody: raw,
506
+ secrets,
507
+ ...options.toleranceSeconds !== void 0 ? { toleranceSeconds: options.toleranceSeconds } : {},
508
+ ...options.now !== void 0 ? { now: options.now } : {}
509
+ });
510
+ if (!verified) return new Response(null, { status: 401 });
511
+ let parsed;
512
+ try {
513
+ parsed = parseEvent(JSON.parse(raw));
514
+ } catch {
515
+ parsed = void 0;
516
+ }
517
+ if (parsed === void 0) return new Response(null, { status: 400 });
518
+ if (parsed === "ignore") return ok(false);
519
+ const event = parsed;
520
+ try {
521
+ if (event.publication_id !== void 0) {
522
+ const last = await options.store.getSeq(seqKey(event.section.id, event.publication_id));
523
+ if (last !== void 0 && event.seq <= last) return ok(false);
524
+ }
525
+ await options.onEvent(event);
526
+ if (event.publication_id !== void 0) await options.store.setSeq(seqKey(event.section.id, event.publication_id), event.seq);
527
+ } catch {
528
+ return new Response(null, { status: 500 });
529
+ }
530
+ return ok(true);
531
+ }
532
+ };
533
+ }
534
+ async function readCapped3(req) {
535
+ if (!req.body) return "";
536
+ const reader = req.body.getReader();
537
+ const chunks = [];
538
+ let total = 0;
539
+ for (; ; ) {
540
+ const { done, value } = await reader.read();
541
+ if (done) break;
542
+ total += value.byteLength;
543
+ if (total > MAX_PUSH_BODY_BYTES) {
544
+ await reader.cancel();
545
+ return void 0;
546
+ }
547
+ chunks.push(value);
548
+ }
549
+ return Buffer.concat(chunks).toString("utf8");
550
+ }
551
+ function staleAfterResync(result, local) {
552
+ const seen = /* @__PURE__ */ new Set([...result.publicationIds, ...result.skipped.map((s) => s.publication_id)]);
553
+ return local.filter((row) => !seen.has(row.publicationId) && row.seq <= result.asOfSeq).map((row) => row.publicationId);
554
+ }
555
+ async function resyncPath(client, options) {
556
+ const ids = [];
557
+ const skipped = [];
558
+ let asOfSeq;
559
+ let cursor;
560
+ for (; ; ) {
561
+ const page = await client.pushPosts({ section: options.section, ...cursor ? { cursor } : {} });
562
+ asOfSeq ??= page.as_of_seq;
563
+ if (asOfSeq === void 0) throw new Error("hyle resync: the first page carried no as_of_seq");
564
+ skipped.push(...page.skipped ?? []);
565
+ for (const post of page.posts) {
566
+ await options.onPost(post);
567
+ if (options.store) {
568
+ const key = seqKey(page.section.id, post.publication_id);
569
+ await options.store.setSeq(key, Math.max(asOfSeq, await options.store.getSeq(key) ?? 0));
570
+ }
571
+ ids.push(post.publication_id);
572
+ }
573
+ if (page.complete || page.next_cursor === null) return { asOfSeq, publicationIds: ids, skipped };
574
+ cursor = page.next_cursor;
575
+ }
576
+ }
577
+
363
578
  // src/sitemap.ts
364
579
  var PAGE_LIMIT = 100;
365
580
  var DEFAULT_MAX_PAGES = 20;
@@ -599,9 +814,11 @@ function engagementPublicKey(seed) {
599
814
  CACHE_TAG_PATTERN,
600
815
  Cp1ClientError,
601
816
  DeliveryDedupe,
817
+ MAX_PUSH_BODY_BYTES,
602
818
  SDK_OWN_RESERVED,
603
819
  checkRoutes,
604
820
  createHyleClient,
821
+ createPushRoute,
605
822
  createRevalidationCallbackRoute,
606
823
  engagementPublicKey,
607
824
  formatReport,
@@ -610,9 +827,12 @@ function engagementPublicKey(seed) {
610
827
  isValidCacheTag,
611
828
  listPublicationPaths,
612
829
  normalizeRoute,
830
+ parseCommentEvent,
613
831
  parseSignatureHeader,
614
832
  reservedFor,
833
+ resyncPath,
615
834
  routeMatches,
835
+ staleAfterResync,
616
836
  syncHostReserved,
617
837
  verifyHyleSignature
618
838
  });
package/dist/index.d.cts CHANGED
@@ -1,60 +1,7 @@
1
- import { R as Resolved, M as MountsResult } from './types-Czt887Iv.cjs';
2
- export { A as Alternate, a as ArticleContent, B as Breadcrumb, C as CacheInfo, D as DocumentMetaFields, E as EngageComment, b as EngageHeldComment, c as EngageListing, F as Fallback, L as ListItem, d as Mount, e as Mounts, N as NavItem, f as NavNode, g as NavTree, h as ResolvedArticle, i as ResolvedDisabled, j as ResolvedList, k as ResolvedNotFound, l as ResolvedRedirect, T as TocEntry } from './types-Czt887Iv.cjs';
3
- export { R as RevalidationCallbackOptions, a as RevalidationCallbackRoute, b as RevalidationPayload, c as createRevalidationCallbackRoute } from './revalidation-callback-D7Ms_Puz.cjs';
4
-
5
- /** `next` is a Next.js fetch extension with no lib.dom type; typed structurally so this module needs no Next import. */
6
- type HyleRequestInit = Omit<RequestInit, "method" | "body"> & {
7
- readonly next?: {
8
- readonly revalidate?: number | false;
9
- readonly tags?: readonly string[];
10
- };
11
- };
12
- interface HyleClientOptions {
13
- /** hyle's origin, for example https://hyle.tdacorp.in. */
14
- readonly baseUrl: string;
15
- /** A target credential (hyle_tr_...). Server-side only: it is sent as a header and never put in a URL. */
16
- readonly token: string;
17
- /** Injectable for tests; defaults to the global fetch. */
18
- readonly fetch?: typeof fetch;
19
- /** Abort a request after this many milliseconds. Default 10000. */
20
- readonly timeoutMs?: number;
21
- /** Refuse a response body larger than this many bytes. Default 5 MiB. */
22
- readonly maxResponseBytes?: number;
23
- /** Allow a plain http baseUrl on a non-loopback host (tests, private networks). Default false: the token would travel unencrypted. */
24
- readonly allowInsecureHttp?: boolean;
25
- }
26
- interface ResolveOptions {
27
- /** The site path as a visitor sees it, including the workspace's path prefix. Sent as a query parameter, so it is encoded once. */
28
- readonly path: string;
29
- readonly locale?: string;
30
- readonly format?: "hast" | "html" | "md";
31
- /** "tree" adds the whole section's navigation (`article.nav`); the docs layout asks for it. An older hyle ignores it. */
32
- readonly nav?: "tree";
33
- readonly cursor?: string;
34
- readonly limit?: number;
35
- /** Extra fetch options (for example Next's `next: { tags, revalidate }`). Method, body and the auth header cannot be overridden. */
36
- readonly init?: HyleRequestInit;
37
- }
38
- interface MountsOptions {
39
- /** Extra fetch options (for example Next's `next: { tags, revalidate }`). Method, body and the auth header cannot be overridden. */
40
- readonly init?: HyleRequestInit;
41
- }
42
- interface AssetOptions {
43
- /** Only these request headers are sent upstream: a browser's own cache validators and byte range. Everything else is dropped. */
44
- readonly headers?: {
45
- readonly range?: string | null;
46
- readonly "if-range"?: string | null;
47
- readonly "if-none-match"?: string | null;
48
- };
49
- /** Abort after this many milliseconds, body included. Default: the client's `timeoutMs`. */
50
- readonly timeoutMs?: number;
51
- }
52
- declare function createHyleClient(options: HyleClientOptions): {
53
- resolve: (opts: ResolveOptions) => Promise<Resolved>;
54
- mounts: (opts?: MountsOptions) => Promise<MountsResult>;
55
- asset: (file: string, opts?: AssetOptions) => Promise<Response>;
56
- };
57
- type HyleClient = ReturnType<typeof createHyleClient>;
1
+ import { H as HyleAuth, a as HyleClient } from './client-BGjmEWhN.cjs';
2
+ export { A as AssetOptions, b as HyleClientOptions, c as HyleCredential, d as HyleRequestInit, M as MAX_PUSH_BODY_BYTES, e as MountsOptions, P as PushEvent, f as PushEventType, g as PushPage, h as PushPost, i as PushRoute, j as PushRouteOptions, k as PushStore, R as ResolveOptions, l as ResyncOptions, m as ResyncResult, n as createHyleClient, o as createPushRoute, r as resyncPath, s as staleAfterResync } from './client-BGjmEWhN.cjs';
3
+ export { A as Alternate, a as ArticleContent, B as Breadcrumb, C as CacheInfo, D as DocumentMetaFields, E as EngageComment, b as EngageHeldComment, c as EngageListing, F as Fallback, H as HylePreview, L as ListItem, M as Mount, d as Mounts, e as MountsResult, N as NavItem, f as NavNode, g as NavTree, R as ReactionCounts, h as ReactionKind, i as Resolved, j as ResolvedArticle, k as ResolvedDisabled, l as ResolvedList, m as ResolvedNotFound, n as ResolvedRedirect, T as ThemeRef, o as TocEntry, V as VoteValue } from './types-D09Z072G.cjs';
4
+ export { C as CommentEvent, a as CommentEventType, R as RevalidationCallbackOptions, b as RevalidationCallbackRoute, c as RevalidationPayload, d as createRevalidationCallbackRoute, p as parseCommentEvent } from './revalidation-callback-BQl77tQR.cjs';
58
5
 
59
6
  declare class Cp1ClientError extends Error {
60
7
  readonly code: string;
@@ -64,21 +11,29 @@ declare class Cp1ClientError extends Error {
64
11
  constructor(code: string, message: string, status: number, requestId: string, details?: Record<string, unknown>);
65
12
  }
66
13
 
67
- interface HostSyncInput {
14
+ /** Where a build writes to hyle's control surface, and as whom. */
15
+ type ControlTarget = {
68
16
  /** hyle's origin. */
69
17
  readonly baseUrl: string;
70
- /** A CONTROL credential (hyle_tc_...) holding hyle.workspace.manage on the workspace. Never a target (read) token. */
71
- readonly token: string;
72
18
  /** The workspace to write, from `client.mounts()`; the credential must be granted on it. */
73
19
  readonly workspaceId: string;
74
- /** The host's complete list of reserved paths (a replace). */
75
- readonly paths: readonly string[];
76
20
  readonly host: string;
77
21
  readonly buildId: string;
78
22
  readonly fetch?: typeof fetch;
79
23
  readonly timeoutMs?: number;
80
24
  readonly allowInsecureHttp?: boolean;
81
- }
25
+ } & ({
26
+ /** A CONTROL credential (hyle_tc_...) holding the route's permission on the workspace. Never a target (read) token. */
27
+ readonly token: string;
28
+ readonly auth?: never;
29
+ } | {
30
+ readonly auth: HyleAuth;
31
+ readonly token?: never;
32
+ });
33
+ type HostSyncInput = ControlTarget & {
34
+ /** The host's complete list of reserved paths (a replace). */
35
+ readonly paths: readonly string[];
36
+ };
82
37
  interface HostSyncResult {
83
38
  /** What hyle stored: sorted, de-duplicated. */
84
39
  readonly paths: readonly string[];
@@ -92,10 +47,9 @@ interface HostSyncResult {
92
47
  };
93
48
  }
94
49
  /**
95
- * Reports the host's reserved paths to hyle (ADR 0016): `PUT /cp1/control/workspace/host-reserved-paths`. Idempotent (resending the
96
- * same list changes nothing), so a retry or a repeated deploy is safe; the random Idempotency-Key only satisfies the control
97
- * surface's mutation rule. Throws `TypeError` before any request for a wrong token kind or an insecure URL, and `Cp1ClientError`
98
- * for anything hyle answers or the network does.
50
+ * Reports the host's reserved paths to hyle (ADR 0016): `PUT /cp1/control/workspace/host-reserved-paths`, with
51
+ * hyle.workspace.sync_host. Idempotent (resending the same list changes nothing), so a retry or a
52
+ * repeated deploy is safe. Throws as `put` describes.
99
53
  */
100
54
  declare function syncHostReserved(input: HostSyncInput): Promise<HostSyncResult>;
101
55
 
@@ -289,4 +243,4 @@ declare function generateEngagementKeyPair(): {
289
243
  /** The public half to register in hyle, from the private seed. */
290
244
  declare function engagementPublicKey(seed: string): string;
291
245
 
292
- export { type AssetOptions, CACHE_TAG_PATTERN, Cp1ClientError, DeliveryDedupe, type DynamicOverlap, type HostSyncInput, type HostSyncResult, type HyleClient, type HyleClientOptions, type HyleRequestInit, type ListPublicationPathsOptions, type LocaleOptions, type LocalePrefix, type MountsOptions, MountsResult, type NextManifests, type ParsedSignatureHeader, type PublicationPath, type PublicationPaths, type ResolveOptions, Resolved, type RouteCheckInput, type RouteCheckReport, SDK_OWN_RESERVED, type VerifySignatureParams, checkRoutes, createHyleClient, engagementPublicKey, formatReport, generateEngagementKeyPair, hostRoutesFromManifests, isValidCacheTag, listPublicationPaths, normalizeRoute, parseSignatureHeader, reservedFor, routeMatches, syncHostReserved, verifyHyleSignature };
246
+ export { CACHE_TAG_PATTERN, Cp1ClientError, DeliveryDedupe, type DynamicOverlap, type HostSyncInput, type HostSyncResult, HyleAuth, HyleClient, type ListPublicationPathsOptions, type LocaleOptions, type LocalePrefix, type NextManifests, type ParsedSignatureHeader, type PublicationPath, type PublicationPaths, type RouteCheckInput, type RouteCheckReport, SDK_OWN_RESERVED, type VerifySignatureParams, checkRoutes, engagementPublicKey, formatReport, generateEngagementKeyPair, hostRoutesFromManifests, isValidCacheTag, listPublicationPaths, normalizeRoute, parseSignatureHeader, reservedFor, routeMatches, syncHostReserved, verifyHyleSignature };