@tdacorp/hyle-sdk 0.17.0 → 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 +155 -28
  2. package/dist/check-routes-bin.js +38 -13
  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 +728 -275
  17. package/dist/comments.d.cts +66 -3
  18. package/dist/comments.d.ts +66 -3
  19. package/dist/comments.js +409 -326
  20. package/dist/{diagram-viewer-FJPED4SN.js → diagram-viewer-XY3CG75U.js} +62 -21
  21. package/dist/{embed-BmdwA2G9.d.cts → embed-BUFRQboD.d.ts} +2 -2
  22. package/dist/{embed-DNTZ2UXv.d.ts → embed-CYt-q13P.d.cts} +2 -2
  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-nmukKYgL.d.ts → labels-CrA-iqTN.d.cts} +9 -0
  36. package/dist/{labels-nmukKYgL.d.cts → labels-CrA-iqTN.d.ts} +9 -0
  37. package/dist/mermaid-diagram.cjs +401 -125
  38. package/dist/mermaid-diagram.d.cts +23 -7
  39. package/dist/mermaid-diagram.d.ts +23 -7
  40. package/dist/mermaid-diagram.js +204 -51
  41. package/dist/mermaid-image.cjs +134 -60
  42. package/dist/mermaid-image.d.cts +4 -3
  43. package/dist/mermaid-image.d.ts +4 -3
  44. package/dist/mermaid-image.js +27 -28
  45. package/dist/next.cjs +627 -264
  46. package/dist/next.d.cts +11 -8
  47. package/dist/next.d.ts +11 -8
  48. package/dist/next.js +39 -12
  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 +556 -226
  54. package/dist/react.d.cts +136 -29
  55. package/dist/react.d.ts +136 -29
  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-Ae7UFjsQ.d.ts → resolve-BjAK0k_Y.d.ts} +2 -2
  62. package/dist/{resolve-euZ4-aC9.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 +96 -25
  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-Czt887Iv.d.cts → types-3F0wqD-o.d.cts} +26 -2
  73. package/dist/{types-Czt887Iv.d.ts → types-3F0wqD-o.d.ts} +26 -2
  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-DMK4XQLU.js +0 -1556
  84. package/dist/chunk-PJMJMP66.js +0 -63
  85. package/dist/revalidation-callback-D7Ms_Puz.d.cts +0 -42
  86. package/dist/revalidation-callback-D7Ms_Puz.d.ts +0 -42
package/README.md CHANGED
@@ -70,18 +70,57 @@ export const GET = () => hyleFeed({ ...options, siteOrigin: "https://tdacorp.in"
70
70
  - The channel title and description come from `list.title` and `list.description`, else hyle's section title. Each item carries the title, the link on the mount (through `localePrefix`), a permalink `guid` equal to the link, `pubDate` from `published_at` and the description when there is one. Every value is XML-escaped, and an item whose `canonical_path` does not start with `/` is dropped.
71
71
  - The list is read through the same resolver as `hylePage`, so it shares its fetch cache and publish tags. `export const revalidate` is Next's own route-handler setting and decides how long Next keeps the generated XML; the SDK adds no `cache-control`.
72
72
  - A hyle failure answers 503 with an empty body instead of throwing; Next control flow still propagates.
73
+ - `hyleFeed` carries titles and descriptions only. For full-content feeds that you build yourself, see "Feed content".
74
+
75
+ ## Article body in your own page
76
+
77
+ When the page is yours (your title, metadata, JSON-LD, sitemap and feeds) and hyle draws only the article body:
78
+
79
+ ```tsx
80
+ import { HyleBody, HyleToc } from "@tdacorp/hyle-sdk/react";
81
+ import "@tdacorp/hyle-sdk/styles.css";
82
+
83
+ // `article` is a resolve result with `content.format === "hast"` (check `kind` and `format` first).
84
+ <h1>{article.publication.title}</h1>
85
+ <HyleToc toc={article.toc} variant="inline" locale="en" />
86
+ <HyleBody tree={article.content.tree} title={article.publication.title} description={article.publication.description} components={{ Link }} locale="en" />
87
+ <HyleToc toc={article.toc} variant="rail" aside={<Newsletter />} locale="en" />
88
+ ```
89
+
90
+ - `HyleBody({ tree, title?, description?, components?, locale?, id? })` renders `div.hyle.hyle-body.hyle-prose` around the same content as `HastContent`, plus its client islands: code copy buttons, the fragment alias and the YouTube player. It carries `hyle` itself, so the `--hyle-*` tokens apply with no wrapper; keep `hyle-prose` selectable if something of yours (an offline search, say) reads the body by it. `title` and `description` drop a leading body h1 and paragraph that repeat them (never a paragraph with an embed link, so a body that opens with a video keeps it). `id` is generated when omitted. The element is a size container (`container: hyle / inline-size`), so give it a width from its parent: in a flex row or an auto-sized grid track, let it grow (`flex: 1; min-width: 0`).
91
+ - `HyleToc({ toc, variant, aside?, locale? })`: `"rail"` is a sticky `aside` (offset by `--hyle-sticky-top`) with scroll-spy (`aria-current="location"`), `"inline"` a collapsed `<details>`. `aside` shows under the rail's list. Only h2 and h3 are listed, and with nothing to list (and no `aside`) nothing renders. Both are shown wherever you put them: render both and hide one per breakpoint in your own CSS. `rail` is sticky only inside a parent taller than itself.
92
+ - `HastContent` on its own stays free of client code: no copy button and no player (a YouTube link stays a link).
93
+
94
+ What the body does, here and on the SDK's own pages:
95
+
96
+ - **Code blocks** have a copy button in `figure.hyle-codeblock > header`. One delegated listener per body writes the code to the clipboard; "Copied" or "Copy blocked" shows and is announced for 1.5 s. A successful copy dispatches a bubbling `hyle:code-copied` event on the figure (`event.detail.language`), if you count copies. A `components.CodeBlock` override replaces the block, button included.
97
+ - **Fragments**: when `#x` matches no element but `#user-content-x` does, the history entry is replaced with the latter, on load and on `hashchange`.
98
+ - **YouTube**: a paragraph that is only a link the renderer marked (`data-embed="youtube"`, with exactly `https://www.youtube.com/watch?v=<11 characters>`) becomes a thumbnail and a play button, with the link (through your `a` override) under it. Before the click the only third-party request is the thumbnail; the click swaps in a `youtube-nocookie.com` frame with a fixed `sandbox`, `allow` and title. A host with a CSP adds `img-src https://i.ytimg.com` and `frame-src https://www.youtube-nocookie.com`. Without them the thumbnail or the player is blocked and the link still works.
99
+ - **Images**: a paragraph that is one image (linked or not) renders `figure[data-slot-component="Image"] > img + figcaption`, the caption from the image title. The image is eager and high priority only when the body, after the dropped title and description, opens with such a figure; every other image is lazy.
100
+ - **Headings** h2 to h4 with an id get an empty `a.hyle-anchor` labelled "Link to this section"; the stylesheet draws the `#`, so heading text never contains it. A heading with the class `sr-only` gets none.
101
+
102
+ ### Feed content
103
+
104
+ ```ts
105
+ import { hastToHtml } from "@tdacorp/hyle-sdk/html"; // server only
106
+
107
+ const html = hastToHtml(article.content.tree, { baseUrl: "https://example.com/blog/post", title: article.publication.title });
108
+ ```
109
+
110
+ `hastToHtml(tree, { baseUrl, title?, description?, locale? })` runs the same allowlist as the pages and returns a string for `content:encoded`, Atom `content` or JSON Feed `content_html` (escape it, or wrap it in CDATA, as your feed format needs). Callouts and figures are applied; every `href` and `src` is made absolute against `baseUrl` (pass the article's own URL, so `#footnote` links point back to it); there are no anchors, copy buttons, players or client code; a diagram is its source in `pre > code.language-mermaid`; a YouTube embed is its link. Asset URLs point at your own `/api/hyle/assets` route. It throws `TypeError` for a `baseUrl` that is not absolute http(s) and `HastLimitError` (exported here too) for a tree over the caps: leave the body out of that item.
73
111
 
74
112
  ## Entry points
75
113
 
76
114
  | Import | Contents | Needs |
77
115
  |---|---|---|
78
- | `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve`, `mounts` and `asset`), `listPublicationPaths`, `checkRoutes` and the other route-check functions, `Cp1ClientError`, `verifyHyleSignature`, `parseSignatureHeader`, `isValidCacheTag`, `DeliveryDedupe`, `createRevalidationCallbackRoute`, the result types | nothing (no framework) |
79
- | `@tdacorp/hyle-sdk/react` | `ArticlePage`, `Comments`, `ListPage`, `HyleListView`, `HyleArticleView`, `DocsPage`, `NotFound`, `Redirecting`, `Unavailable`, `HastContent`, `TrustedServerHtml`, `sanitizeHast` | react >= 19 |
116
+ | `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve`, `mounts` and `asset`), `listPublicationPaths`, `checkRoutes` and the other route-check functions, `Cp1ClientError`, `verifyHyleSignature`, `parseSignatureHeader`, `isValidCacheTag`, `DeliveryDedupe`, `createRevalidationCallbackRoute`, `parseCommentEvent`, the result types | nothing (no framework) |
117
+ | `@tdacorp/hyle-sdk/react` | `ArticlePage`, `Comments`, `HyleReactions`, `ListPage`, `HyleListView`, `HyleArticleView`, `DocsPage`, `NotFound`, `Redirecting`, `Unavailable`, `HyleBody`, `HyleToc`, `HastContent`, `TrustedServerHtml`, `sanitizeHast` | react >= 19 |
118
+ | `@tdacorp/hyle-sdk/html` | `hastToHtml`, `HastLimitError` (server only) | nothing (no framework) |
80
119
  | `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleFeed`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createMarkdownRoute`, `markdownRewritePath`, `createLlmsTxtRoute`, `createRevalidateRoute`, `createAssetRoute`, `createOgImageRoute`, `createEngagementRoute`, `HyleList`, `HyleArticle`, `HyleComments`, `HyleCommentsFallback`, `fetchResolver`, `workspaceTags` | next >= 16 |
81
120
  | `@tdacorp/hyle-sdk/next/use-cache` | `cachedResolver` | next >= 16 with `cacheComponents: true` |
82
121
  | `@tdacorp/hyle-sdk/styles.css` | the stylesheet | |
83
122
 
84
- The only runtime dependency is `hast-util-to-jsx-runtime` (MIT, unified collective, the library behind react-markdown): it maps hast nodes and properties to React elements correctly, which is more than a short hand-rolled function would get right. Everything else is hand-written.
123
+ Runtime dependencies are `hast-util-to-jsx-runtime` (hast to React elements, the library behind react-markdown), `hast-util-to-html` (hast to a string, used only by `./html`), both MIT from the unified collective and both doing more than a short hand-rolled function would get right, and `mermaid` (see "Mermaid diagrams"). Everything else is hand-written.
85
124
 
86
125
  ## Locale
87
126
 
@@ -281,9 +320,13 @@ Verify after `next build`: `.next/prerender-manifest.json` must not show `"fallb
281
320
 
282
321
  Locale-prefixed hosts: you may keep `generateStaticParams` for the locales, but validate the locale in the layout (call `notFound()` for an unknown one) and set `dynamicParams = true` there, so unknown locales are still rejected.
283
322
 
323
+ ## Push mode
324
+
325
+ A path in push mode delivers whole posts to your route (`createPushRoute`) and rebuilds from `resyncPath`; see `docs/cp1-spec.md` 5.3.3 and 5.3.4 in the hyle repository. Store `html` (sanitized) and render that. The `markdown` field is the author's source: never render it with raw HTML enabled. Sweep after a resync with `staleAfterResync`, never "everything not returned".
326
+
284
327
  ## Media
285
328
 
286
- hyle stores an image, video or audio reference as `/assets/<uuid>.<ext>`, a path that exists only on hyle's own (authenticated) origin. On a host site it would 404, so the SDK rewrites it while rendering (`HastContent`, so every page component, and the `format: "html"` escape hatch) to `/api/hyle/assets/<uuid>.<ext>` on the host's own origin. That path is answered by the one route file in the quickstart, `app/api/hyle/assets/[file]/route.ts`; nothing else is needed per site, and a strict CSP such as `img-src 'self' data:` (and `media-src` left at `default-src 'self'`) works unchanged. The `Image` slot receives the rewritten `src`, so a `next/image` slot also works; the default is a plain `<img loading="lazy">`.
329
+ hyle stores an image, video or audio reference as `/assets/<uuid>.<ext>`, a path that exists only on hyle's own (authenticated) origin. On a host site it would 404, so the SDK rewrites it while rendering (`HastContent`, so every page component, and the `format: "html"` escape hatch) to `/api/hyle/assets/<uuid>.<ext>` on the host's own origin. That path is answered by the one route file in the quickstart, `app/api/hyle/assets/[file]/route.ts`; nothing else is needed per site, and a strict CSP such as `img-src 'self' data:` (and `media-src` left at `default-src 'self'`) works unchanged. The `Image` slot receives the rewritten `src`, so a `next/image` slot also works; the default is a plain `<img>`, lazy unless it opens the body.
287
330
 
288
331
  How it works: `createAssetRoute` asks hyle for exactly that file (`GET /cp1/read/assets/<file>`, ADR 0015) with the target credential and streams the bytes back. hyle answers only for an asset that a currently published, non-trashed page of this workspace references, so a draft, unpublished or other workspace's asset is a 404 on your site too. Responses carry `Cache-Control: public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400`, hyle's strong `ETag` (revalidation is a 304) and `Accept-Ranges`; `Range` is forwarded, so video and audio seek. After an unpublish a cached copy can still be served for up to the cache window (about a day on a CDN).
289
332
 
@@ -291,9 +334,9 @@ Safety: the only input is the `file` segment and it must match `<lowercase uuid>
291
334
 
292
335
  The route sits under `/api/hyle/*`, which hyle's Reserved paths must cover (`hyle-sdk-check-routes --print-reserved` always lists `/api/hyle/*`, and so does `--sync`), and the checker prints a note when the build has no `/api/hyle/assets/...` route. If your proxy or middleware matcher intercepts `/api`, exclude `/api/hyle/assets`. Nothing renders `/assets/...` for you outside the SDK's components: a custom renderer of the `hast` tree should map `src` the same way (`/assets/<id>.<ext>` to `/api/hyle/assets/<id>.<ext>`).
293
336
 
294
- ## Comments and likes
337
+ ## Comments, votes and reactions
295
338
 
296
- Readers can comment and like under an article (hyle ADR 0017, `docs/cp1-spec.md` section 3.11). It is off unless you turn it on in three places, and nothing on a cached page changes when someone likes: the section is fetched in the browser, uncached, after the article has rendered.
339
+ Readers can comment under an article, vote comments up or down and react (like, love, insightful, celebrate) to the article and to comments (hyle ADR 0017 and 0021, `docs/cp1-spec.md` section 3.11). It is off unless you turn it on in three places, and nothing on a cached page changes when someone reacts or votes: the section is fetched in the browser, uncached, after the article has rendered.
297
340
 
298
341
  1. **hyle**: switch engagement on for the workspace and register the site's public key (below).
299
342
  2. **A key pair.** `npx hyle-sdk-engage-keygen --out .env.engage` makes an Ed25519 pair: the private key goes to a new file (mode 0600, never overwritten) as `HYLE_ENGAGE_SIGNING_KEY=...`, and the PUBLIC key is printed only after that write succeeded, with a warning if git does not ignore the file. `--stdout` is the only mode that prints the private key; with no arguments the tool prints usage and nothing else. Register the public key in hyle. hyle never sees the private key. To rotate, register the new public key; the old one stays valid for 24 hours.
@@ -316,15 +359,75 @@ export const { GET, POST, PATCH, PUT, DELETE } = createEngagementRoute({
316
359
  });
317
360
  ```
318
361
 
319
- **Rate-limit this route yourself.** hyle limits per reader and per site, but every anonymous read of `/api/hyle/engage/comments` and every `session` check reaches your server first. The route shares ANONYMOUS listings between visitors for 3 seconds (`cacheTtlMs`, 0 turns it off); a signed-in reader's listing is shared only with that same reader (never across readers), a fallback answer is never kept, bodies over 256 KB are never kept, and the whole share is capped at 8 MB (least recently used out first); a write on that server makes everything stale at once, other servers catch up within the window, and `onRequest(req, { action })` runs before any work so you can answer with your own 429 (`action` is `session`, `comments.list`, `comments.create`, `comments.edit`, `comments.delete`, `reactions.add` or `reactions.remove`); put a limit on `/api/hyle/engage` in your middleware or CDN as well. `getReader` runs once per request and its answer is never kept for the next one, so keep it cheap. The name you return is cleaned as hyle cleans it (control, bidi and invisible characters stripped, spaces collapsed, 80 characters) and a reader whose assertion would pass hyle's 2 KiB cap is treated as signed out.
362
+ **Rate-limit this route yourself.** hyle limits per reader and per site, but every anonymous read of `/api/hyle/engage/comments` and every `session` check reaches your server first. The route shares ANONYMOUS listings between visitors for 3 seconds (`cacheTtlMs`, 0 turns it off); a signed-in reader's listing is shared only with that same reader (never across readers), a fallback answer is never kept, bodies over 256 KB are never kept, and the whole share is capped at 8 MB (least recently used out first); a write on that server makes everything stale at once, other servers catch up within the window, and `onRequest(req, { action })` runs before any work so you can answer with your own 429 (`action` is `session`, `comments.list`, `comments.create`, `comments.edit`, `comments.delete`, `reactions.add`, `reactions.remove`, `votes.set` or `votes.remove`); put a limit on `/api/hyle/engage` in your middleware or CDN as well. A `400` from hyle (an older hyle refusing `sort=new`) is shared for the same window. The listing share is keyed by path, `sort` and `cursor`, and a cursor is only checked for its alphabet and length (hyle decodes it), so a caller who varies it gets past the 3 s share and spends your site's hyle read allowance (100 reads, then 20 per second, per credential): this limit is what stops that. hyle counts votes in the same bucket as comments (per reader: 5, then 1 every 30 seconds), so a reader who votes quickly is also held back from posting for a while; reactions have their own bucket (30, then 1 every 2 seconds). `getReader` runs once per request and its answer is never kept for the next one, so keep it cheap. The name you return is cleaned as hyle cleans it (control, bidi and invisible characters stripped, spaces collapsed, 80 characters) and a reader whose assertion would pass hyle's 2 KiB cap is treated as signed out.
320
363
 
321
364
  Then pass `engagement` to the page: `hylePage({ ..., engagement: { signInHref: "/sign-in" } })`, or `<ArticlePage engagement={{ signInHref: "/sign-in" }} />`. `engagement.endpoint` defaults to `/api/hyle/engage`. `layout: "docs"` has no comments.
322
365
 
323
- What the route does, per request: it matches (method, path) against a fixed allowlist (`session`, `comments`, `comments/<uuid>`, `reactions`), rebuilds the body with only the known keys (a comment is 1 to 4000 characters, a path is a canonical site path), and calls hyle with the target credential. An anonymous read carries the bearer only. A signed-in reader's read also carries a separate Ed25519 read assertion (`scope: "read"`, 30 s, not single use) so hyle can add that reader's own state; a write carries a fresh single-use assertion (30 s) of the reader `getReader` returned; a missing or invalid reader is a bare 401 before hyle is called. The browser's cookies and `Authorization` are never forwarded. Writes must be same-origin (`Sec-Fetch-Site: same-origin` when sent, and an `Origin` equal to the request's host, with the scheme compared too when the proxy sends `X-Forwarded-Proto`), carry the header `x-hyle-engage: 1` and `application/json` (at most 20 KiB), otherwise 403/415/413. The host is taken from `X-Forwarded-Host`, else `Host`: behind a proxy that rewrites `Host` or terminates TLS without forwarding these headers, pass `allowedOrigins: ["https://www.example.com"]`, which replaces the derivation with an exact list (scheme, host and port). Every response is `Cache-Control: no-store`. Failures are mapped to a fixed set of codes with no text from hyle: hyle 404 stays 404 (a disabled workspace, a banned reader and a hidden comment look the same), 429 keeps a clamped `Retry-After`, a 409 is an edit after the 10 minute window, and everything else, including a 401 from hyle (a wrong key or credential, which a visitor must not learn), is a 502. The kill switch is `HYLE_ENGAGE_ENABLED` (and `HYLE_CONTENT_ENABLED`): unset, empty, `1` or `true` leave the route on, and ANY other non-empty value (`0`, `false`, `off`, `no`, a typo) answers 404 everywhere; a missing or malformed configuration also answers 404 and never throws at build time. Your proxy or middleware matcher must let `/api/hyle/engage` through, and the route sits under `/api/hyle/*`, which hyle's Reserved paths already cover (see "Collision checker": `--print-reserved` and `--sync` always list it).
366
+ What the route does, per request: it matches (method, path) against a fixed allowlist (`session`, `comments`, `comments/<uuid>`, `reactions`, `votes`), rebuilds the body with only the known keys (a comment is 1 to 4000 characters, a path is a canonical site path, a reaction `kind` is one of `like`, `love`, `insightful`, `celebrate`, a vote is `{ comment_id, value: 1 | -1 }`), accepts on the listing only `path`, `cursor` and `sort=new` or `sort=top`, each once, and calls hyle with the target credential. An anonymous read carries the bearer only. A signed-in reader's read also carries a separate Ed25519 read assertion (`scope: "read"`, 30 s, not single use) so hyle can add that reader's own state; a write carries a fresh single-use assertion (30 s) of the reader `getReader` returned; a missing or invalid reader is a bare 401 before hyle is called. The browser's cookies and `Authorization` are never forwarded. Writes must be same-origin (`Sec-Fetch-Site: same-origin` when sent, and an `Origin` equal to the request's host, with the scheme compared too when the proxy sends `X-Forwarded-Proto`), carry the header `x-hyle-engage: 1` and `application/json` (at most 20 KiB), otherwise 403/415/413. The host is taken from `X-Forwarded-Host`, else `Host`: behind a proxy that rewrites `Host` or terminates TLS without forwarding these headers, pass `allowedOrigins: ["https://www.example.com"]`, which replaces the derivation with an exact list (scheme, host and port). Every response is `Cache-Control: no-store`. Failures are mapped to a fixed set of codes with no text from hyle: hyle 404 stays 404 (a disabled workspace, a banned reader and a hidden comment look the same), 429 keeps a clamped `Retry-After`, a 409 is an edit after the 10 minute window, and everything else, including a 401 from hyle (a wrong key or credential, which a visitor must not learn), is a 502. The kill switch is `HYLE_ENGAGE_ENABLED` (and `HYLE_CONTENT_ENABLED`): unset, empty, `1` or `true` leave the route on, and ANY other non-empty value (`0`, `false`, `off`, `no`, a typo) answers 404 everywhere; a missing or malformed configuration also answers 404 and never throws at build time. Your proxy or middleware matcher must let `/api/hyle/engage` through, and the route sits under `/api/hyle/*`, which hyle's Reserved paths already cover (see "Collision checker": `--print-reserved` and `--sync` always list it).
367
+
368
+ The component (`Comments`, a client component with no dependency) renders the states of the design kit: signed out, composer, threads to depth 4 (no Reply at depth 4), up and down votes, reactions with a pressed state and optimistic counts, a Newest/Top control, a reader's own pending comment ("Awaiting approval", visible only to them), edited marks, tombstones for removed and deleted comments, a notice for a comment hyle cannot render (`unrenderable`; its author keeps Edit and Delete), empty, loading, load error with Try again, post error that keeps the text, rate limited (the box is disabled, the button is `aria-disabled` and stays focusable), banned, and Load more (20 threads at a time, then hyle's next page). A write that answers 404 is not taken for a ban: the listing and the session are reloaded and a plain error shows; only a second 404 for a still valid session shows the banned message. Comment bodies are the sanitized hast hyle renders; the client sanitizes again with a narrower allowlist (links, emphasis, code, quotes, lists) and builds React elements, never HTML strings. Ctrl or Cmd+Enter posts, Escape closes a reply and returns focus to its button. Styling uses the existing `--hyle-*` variables plus six optional ones: `--hyle-comments-indent`, `--hyle-comments-gap`, `--hyle-comments-avatar-size`, `--hyle-comments-rule`, `--hyle-comments-held` and `--hyle-comments-like-on`. Strings are in en, fr and es (fr and es are unreviewed drafts).
369
+
370
+ The listing is viewer-aware (hyle cp1 spec section 3.11): for a signed-in reader the route sends a separate read assertion (`scope: "read"`, 30 s, not single use) with the `GET`, and hyle adds the reader's own state, so a reload restores their pending comment (`mine_held`), their pressed reactions of all four kinds (`my_reactions`, on the article and each comment) and Edit (only while `can_edit_until` is in the future; Delete stays available on the reader's own comments, as hyle allows it at any time). Edit after a reload starts from Markdown rebuilt from the rendered comment (hyle lists rendered comments, not their source), which can differ from the original in whitespace and escaping. Viewer reads are never shared between readers; a 401 on the read assertion is re-signed once and retried. If the viewer read cannot be served for the reader's own sake (a 401 after one re-sign, which means a wrong or rotated key; a 404, which means no key is registered at hyle yet; or a 429 that hyle marks `Hyle-Throttle: viewer`, the reader's own view bucket) the route answers with the public listing, so a signed-in reader never loses the section. Any other 429, the site-wide read bucket, is passed on with its `Retry-After` and not retried. A reader hyle has never seen, a banned reader and an anonymous visitor all get the public listing (no viewer members). Tombstones say whether a moderator removed the comment or its author deleted it.
371
+
372
+ **Votes, reactions, order and pages.**
373
+
374
+ - Votes: each visible comment shows its score between an up and a down button (`aria-pressed`); pressing the pressed one again retracts the vote. A reader's own comment shows the score only. A tombstone has no votes.
375
+ - Reactions: the like is always there; another kind appears once somebody used it, and "React" reveals the rest (focus moves into them, Escape returns it to the button). A reader may hold one of each kind.
376
+ - Changes show at once, are announced through a polite live region, and are put back with an error message if hyle refuses them. A signed-out visitor gets links to the sign-in prompt instead of buttons.
377
+ - Order: with votes available the thread shows newest threads first (`sort=new`), with a Top control (`sort=top`, best score first). Replies stay oldest first. Against a hyle without votes the thread stays oldest first with no control.
378
+ - A comment the reader has just posted is on screen at once, even when no loaded page holds it yet; as soon as a listing has it, the listing decides. A new thread goes on top under Newest and at the end under Top.
379
+ - Pages: Load more first reveals what is already loaded, then fetches `next_cursor` with the sort that issued it and merges the page by comment id (a long thread continues on later pages, which repeat its ancestors). Changing the order starts again from the first page, as does a cursor hyle refuses. A refresh after a write refetches every loaded page. The section starts over, session check included, when `path` or `endpoint` changes, and when a write that met an ended session (or followed one) finds another reader signed in (told apart by the `reader.id` of the `session` answer, a digest of the reader's `sub`, so two accounts with one name are two readers). A switch of account that no write runs into is not noticed until then. A page that brings no comment, or hands back the cursor it was asked with, ends the walk.
380
+ - An older hyle sends no score, reaction counts or cursor: the section then shows likes only, with no vote, picker or sort controls.
381
+
382
+ Older hyle versions: one that has votes but refuses `sort=new` with a `400` gets the default (oldest first) listing instead, without an error; the section turns the loaded pages newest first and says that newer comments appear as more are loaded. In each page view `Comments` and `HyleReactions` then each ask for `sort=new` once first (one shared request when they load together); the route shares the refusal like any listing, and each one that does reach hyle spends your site's read allowance. One without `my_reactions` restores pressed likes only, so after a reload a reader's love, insightful or celebrate shows its count without the pressed state (pressing it again adds nothing, a second press removes it). One without cursors for long pages answers `truncated` with no `next_cursor`: nothing after the cut can be loaded and the section says only the first part is shown.
383
+
384
+ An edit can put a visible comment back in the moderation queue, in which case it moves to the reader's pending list.
385
+
386
+ ### Load on approach, and cached pages
387
+
388
+ `lazy` makes the island fetch nothing (neither listing nor session) until it is within 600px of the viewport. Compose it in a page you cache statically; there is no server fetch, so the page's caching is untouched:
389
+
390
+ ```tsx
391
+ import { Comments, stringsFor } from "@tdacorp/hyle-sdk/react";
392
+
393
+ <div className="hyle hyle-embed">
394
+ <Comments lazy path="/learn/computing-reading-time" endpoint="/api/hyle/engage" signInHref="/sign-in" locale="en" labels={stringsFor("en").comments} />
395
+ </div>
396
+ ```
397
+
398
+ `Comments` is a client component and every prop above is a plain string or object, so a server component can render it. Without `initial` the comments are not in the server HTML; use `HyleComments` (below) where search engines must see them.
324
399
 
325
- The component (`Comments`, a client component with no dependency) renders the states of the design kit: signed out, composer, threads to depth 4 (no Reply at depth 4), likes with a pressed state and an optimistic count, a reader's own pending comment ("Awaiting approval", visible only to them), edited marks, tombstones for removed and deleted comments, empty, loading, load error with Try again, post error that keeps the text, rate limited (the box is disabled, the button is `aria-disabled` and stays focusable), banned, and Load more (20 threads at a time). A write that answers 404 is not taken for a ban: the listing and the session are reloaded and a plain error shows; only a second 404 for a still valid session shows the banned message. Comment bodies are the sanitized hast hyle renders; the client sanitizes again with a narrower allowlist (links, emphasis, code, quotes, lists) and builds React elements, never HTML strings. Ctrl or Cmd+Enter posts, Escape closes a reply and returns focus to its button. Styling uses the existing `--hyle-*` variables plus six optional ones: `--hyle-comments-indent`, `--hyle-comments-gap`, `--hyle-comments-avatar-size`, `--hyle-comments-rule`, `--hyle-comments-held` and `--hyle-comments-like-on`. Strings are in en, fr and es (fr and es are unreviewed drafts).
400
+ ### Article reactions on their own
326
401
 
327
- The listing is viewer-aware (hyle cp1 spec section 3.11): for a signed-in reader the route sends a separate read assertion (`scope: "read"`, 30 s, not single use) with the `GET`, and hyle adds the reader's own state, so a reload restores their pending comment (`mine_held`), their pressed likes (`liked_by_me`) and Edit (only while `can_edit_until` is in the future; Delete stays available on the reader's own comments, as hyle allows it at any time). Edit after a reload starts from Markdown rebuilt from the rendered comment (hyle lists rendered comments, not their source), which can differ from the original in whitespace and escaping. Viewer reads are never shared between readers; a 401 on the read assertion is re-signed once and retried. If the viewer read cannot be served for the reader's own sake (a 401 after one re-sign, which means a wrong or rotated key; a 404, which means no key is registered at hyle yet; or a 429 that hyle marks `Hyle-Throttle: viewer`, the reader's own view bucket) the route answers with the public listing, so a signed-in reader never loses the section. Any other 429, the site-wide read bucket, is passed on with its `Retry-After` and not retried. A reader hyle has never seen, a banned reader and an anonymous visitor all get the public listing (no viewer members). Tombstones say whether a moderator removed the comment or its author deleted it. Known limits: there is no cursor, so a page holds at most 500 comments (and at most 100 000 characters of comment source are rendered per response); an edit can put a visible comment back in the moderation queue, in which case it moves to the reader's pending list.
402
+ `HyleReactions` puts the article's reactions anywhere, for example under the title:
403
+
404
+ ```tsx
405
+ import { HyleReactions } from "@tdacorp/hyle-sdk/react";
406
+
407
+ <HyleReactions path={publication.canonical_path} engagement={{ signInHref: "/sign-in" }} locale="en" />
408
+ ```
409
+
410
+ `engagement` is the object `ArticlePage` takes (`endpoint` defaults to `/api/hyle/engage`; without `signInHref` the buttons are inert for signed-out visitors). It renders nothing when engagement is off or the article is unknown. It is its own `.hyle` block, so give it a block-level parent (the stylesheet sizes by container width). hyle has no counts-only endpoint, so it reads the first page of the comment listing (the one `Comments` reads), one request plus the session check, when it mounts, whether or not a `Comments` on the page is `lazy`. If the same page also renders `Comments`, pass that one `articleReactions={false}` so the two never disagree; two islands loading at the same moment share the requests.
411
+
412
+ ### Comment notifications
413
+
414
+ Switch comment notifications on for the webhook endpoint in hyle, then give your revalidate route `onCommentEvent`:
415
+
416
+ ```ts
417
+ export const { POST } = createRevalidateRoute({
418
+ workspaceId: process.env.HYLE_WORKSPACE_ID,
419
+ secrets: [process.env.HYLE_WEBHOOK_SECRET],
420
+ onCommentEvent: async (event) => {
421
+ // event.type: "comment.held" | "comment.reply" | "comment.approved" | "comment.hidden"
422
+ await queue.add("hyle-comment", event); // yours: enqueue, then send mail from a worker
423
+ },
424
+ });
425
+ ```
426
+
427
+ - The hook runs only after the signature, workspace and shape checks, once per delivery id (the signed `event.id`, not the request header) per server instance (dedupe in your queue on `event.id` if you run several).
428
+ - **It is not retried.** A throw, or no answer within 3 seconds, is logged (type and delivery id only) and the delivery is still answered 200. A failing answer would be retried, then dead-lettered, and hyle disables an endpoint after five dead-lettered deliveries in a row, which would also stop your content revalidation. Anything that must not be lost belongs on a durable queue inside the hook. On a serverless host, work left running after the 3 seconds may be frozen.
429
+ - The event carries ids, the article path, a status and `reader_sub` / `parent_reader_sub` (your own reader ids, null after erasure), never comment text. Treat the subs as personal data: do not log them, and delete what you stored when you erase a reader. A reply held for review sends `comment.held`, then `comment.approved` and `comment.reply` once approved. For `comment.reply`, decide who to notify from `parent_reader_sub` and skip a reader replying to themselves.
430
+ - `parseCommentEvent(payload)` is exported for a receiver of your own. It checks the shape only (including that `publication_path` is a site path), so verify the signature first.
328
431
 
329
432
  ## Embeds
330
433
 
@@ -348,7 +451,7 @@ import { HyleArticle, HyleComments, HyleCommentsFallback, HyleList } from "@tdac
348
451
 
349
452
  - `HyleList`: `limit` (default 5, at most 100), `layout` (`"list"` or `"grid"`, default list), `title`, `headingLevel` (2, 3 or 4, default 2), `moreHref` (a "View all" link to a URL you choose, usually the mount) and `locale` (needed when `options.locale` is a function of route params, which a component cannot evaluate). It is a flat list, newest first, with no month groups. Pagination is opt-in: `cursor` (the page's `?cursor=`) starts after a `next_cursor`, and `olderHref={(next) => `/blog?cursor=${next}`}` is called with the list's `next_cursor`, when there is one, to build the "Older posts" link. The slots `list.item` and `list.empty` of `options.slots` apply. The `list.item` slot's item also carries the document's authored fields when the server sends them: `tags` (slug tokens), `kicker`, `status` (a free label), `cover` (`{ path }`, root-relative `/assets/<id>`, or `null`) and `author` (`{ name, url }` or `null`); an older server omits them. An article's `publication` carries the same fields, and its `author` is the byline used for the page metadata and JSON-LD ahead of `jsonLd.author` and `frontmatter.author`.
350
453
  - `HyleArticle`: `path`, `headingLevel` (default 2), `locale`. Title, date, description, the body, and a visible "Read at source" link. No table of contents, pager, languages bar, comments or JSON-LD. A path that is not an article (a redirect included) renders nothing.
351
- - `HyleComments`: `options: { baseUrl, token, locale? }`, `path` (the article's canonical path), `revalidate` (seconds, default 60) and `interactive`. The listing is public and cached for `revalidate` seconds, not purged by a webhook. It renders the thread as server HTML (`ol > li > article`, names, dates, sanitized bodies, links `rel="nofollow ugc"`, removed comments as tombstones) and nothing at all when there are no comments or hyle answers 404 (engagement off, unknown article) or fails. With `interactive` (`true`, or `{ endpoint?, signInHref? }`) the `Comments` island is rendered INSTEAD, seeded from the same listing: the thread is still in the server HTML, there is no skeleton flash, readers can comment and like (it needs `createEngagementRoute`, as in "Comments and likes"), and it refetches silently on mount. The listing is serialized once into the page for the island (up to 500 comments), so leave `interactive` off where you only need to show comments.
454
+ - `HyleComments`: `options: { baseUrl, token, locale? }`, `path` (the article's canonical path), `revalidate` (seconds, default 60) and `interactive`. The listing is public and cached for `revalidate` seconds, not purged by a webhook. It renders the thread as server HTML (`ol > li > article`, names, dates, sanitized bodies, links `rel="nofollow ugc"`, removed comments as tombstones) and nothing at all when there are no comments or hyle answers 404 (engagement off, unknown article) or fails. With `interactive` (`true`, or `{ endpoint?, signInHref? }`) the `Comments` island is rendered INSTEAD, seeded from the same listing: the thread is still in the server HTML, there is no skeleton flash, readers can comment, vote and react (it needs `createEngagementRoute`, as in "Comments, votes and reactions"; the island, its server HTML included, shows newest threads first when hyle has votes), and it refetches silently on mount with `sort=new` (the seed is the oldest-first first page, so on a thread longer than one page the newest threads arrive with that refetch). The listing is serialized once into the page for the island (up to 500 comments), so leave `interactive` off where you only need to show comments.
352
455
 
353
456
  SEO rules the embeds follow, and one you must:
354
457
 
@@ -357,27 +460,46 @@ SEO rules the embeds follow, and one you must:
357
460
  - **Canonical:** a page that embeds a full article with `HyleArticle` must set its own canonical URL to the article's URL on the mount (for example `alternates.canonical` in `generateMetadata`), or the two pages compete as duplicates. A list or a comments embed needs nothing. The embeds build no absolute URLs; those belong to the mount (see its documentation).
358
461
  - Headings: the default level is 2, and the article body's headings are h2 and below (a body `h1` is demoted), so under your page's `h1` and a section heading of your own, set `headingLevel` to 3.
359
462
  - Failure: an embed never calls `notFound()`, never redirects and never throws on a hyle outage. A missing page, a request hyle rejects and an empty section render nothing (or the `list.empty` slot). Any other failure is logged by name and renders `onError(error)` if you gave one, else nothing. A missing `workspaceId`, a bad `baseUrl` or an empty `token` is a configuration error and throws.
360
- - The token is used only in the server-side request. `HyleComments` sends the target credential and nothing else (no reader assertion, no cookie, no header of the visitor), so every visitor shares one cached listing. The `Comments` island receives the listing, the path, your own `/api/hyle/engage` route and the chrome strings: never the token or hyle's URL.
463
+ - The token is used only in the server-side request. `HyleComments` sends the target credential and nothing else (no reader assertion, no cookie, no header of the visitor), so every visitor shares one cached listing. The server-rendered thread (without `interactive`) is oldest first and has no votes or reactions. The `Comments` island receives the listing, the path, your own `/api/hyle/engage` route and the chrome strings: never the token or hyle's URL.
361
464
 
362
465
  Styling: import `@tdacorp/hyle-sdk/styles.css`. An embed is a `.hyle.hyle-embed` block with no page padding or maximum width, so the host's layout sets its width; `data-layout="grid"` lays the items out as cards (260px minimum columns). The pure markup is also exported as `HyleListView` and `HyleArticleView` from `@tdacorp/hyle-sdk/react` for hosts that fetch for themselves.
363
466
 
364
467
  ## Mermaid diagrams
365
468
 
366
- Zero setup. A Mermaid fence arrives from hyle as a sandboxed `<iframe srcdoc>` that loads a script from cdnjs, and a `srcdoc` frame inherits the host page's CSP, so a host with `script-src 'self'` would show a blank box. The SDK therefore reads the diagram text out of that document (only after it matched hyle's exact template) and renders it in your page with the Mermaid library it bundles as a dependency (`mermaid` `~11.9.0`, MIT). No cdnjs, no extra package, no config.
469
+ Zero setup. A Mermaid fence arrives from hyle as a sandboxed `<iframe srcdoc>` that loads a script from cdnjs, and a `srcdoc` frame inherits the host page's CSP, so a host with `script-src 'self'` would show a blank box. The SDK therefore reads the diagram text out of that document (only after it matched hyle's exact template) and renders it in your page with the Mermaid library it bundles as a dependency (`mermaid` `~11.16.0`, MIT). No cdnjs, no extra package, no config.
367
470
 
368
- - What loads when: the server renders a no-JavaScript fallback, a `<figure class="hyle-mermaid">` holding the source as a `language-mermaid` code block. On a page with a diagram, the browser then imports `mermaid` (a dynamic import, so your bundler emits it as lazy chunks served from your own origin) and swaps in the SVG. Pages without a diagram never load it: the client component is not even in their JavaScript. In the e2e app (Next 16.2.7, Turbopack) the lazy chunks total about 2.8 MB raw, 0.8 MB gzipped across every diagram type; a page loads only the ones its diagram type needs. `mermaid` itself is 64 MB on disk in `node_modules` (it is not shipped to browsers).
369
- - Rendering: a diagram renders when it is within 200 px of the viewport, one at a time, each limited to 10 s (a slower one falls back to the code block and the note). Per-diagram configuration (`%%{init}%%` directives and frontmatter) is stripped, see Security model. A re-render (theme change) keeps the previous SVG on screen until the new one is ready, and keeps it if the new one fails.
370
- - Themes: dark or default is chosen from the figure's computed background (falling back to `prefers-color-scheme`), and the diagram re-renders when `data-act`, `data-theme` or `class` change on `<html>` or the OS scheme changes.
371
- - Stored renders: when hyle has a pre-rendered image of the diagram in both themes (the editor renders it in the author's browser, hyle sanitizes and stores it, ADR 0024), the page gets a sized `<img>` (aspect ratio reserved, so no layout shift), the diagram source in a `<details>` for crawlers and no-JS readers, and no Mermaid layout runs in any browser. The image goes through your asset route (`createAssetRoute`, `img-src 'self'`). Click-to-expand fetches that same sanitized SVG for the viewer. If the image fails to load, or hyle has no stored render yet, the page renders the diagram client-side as above, with a loader and a reserved height.
471
+ - What loads when: the server renders a no-JavaScript fallback, a `<figure class="hyle-mermaid">` holding the source as a `language-mermaid` code block. On a page with a diagram, the browser then imports `mermaid` (a dynamic import, so your bundler emits it as lazy chunks served from your own origin) and swaps in the SVG. Pages without a diagram never load it: the client component is not even in their JavaScript. A page loads only the chunks its diagram type needs. `mermaid` itself is 83 MB on disk in `node_modules` (it is not shipped to browsers).
472
+ - Rendering: a small diagram renders when it is within 200 px of the viewport, one at a time; a large one waits for a click (below). The 10 s limit starts after the Mermaid chunk has loaded and covers drawing: past it the code block and the note appear and the next diagram starts, and a result that still arrives is shown. Per-diagram configuration (`%%{init}%%` directives and frontmatter) is stripped, see Security model. A re-render (theme change) keeps the previous SVG on screen until the new one is ready, and keeps it if the new one fails. A throw anywhere in a diagram or its viewer shows that figure's source instead of blanking the page.
473
+ - Themes: your CSS decides, however you switch themes. The figure's computed background picks dark or default (`rgb`, `color(srgb)`, `lab`, `lch`, `oklab`, `oklch`); when it is transparent or unreadable, its computed `color-scheme` does (if it names exactly one scheme), then `prefers-color-scheme`. The diagram redraws when that answer changes after any attribute of `<html>` or `<body>` changes (a class, a `data-*` flag, an inline style) or the OS scheme changes. A switch made only on a wrapper deeper in the page is not watched. The drawn figure carries `data-mermaid-theme`. The dark theme gets a darker edge label box so label text passes WCAG AA.
474
+ - Stored renders: when hyle has a pre-rendered image of the diagram in both themes (the editor renders it in the author's browser, hyle sanitizes and stores it, ADR 0024), the page gets a sized `<img>` (aspect ratio reserved, so no layout shift), the diagram source in a `<details>` for crawlers and no-JS readers, and no Mermaid layout runs in any browser. The image goes through your asset route (`createAssetRoute`, `img-src 'self'`). Click-to-expand fetches that same sanitized SVG for the viewer. Showing a stored render runs no layout, so it is never gated. If the image fails to load, or hyle has no stored render yet, the page renders the diagram client-side as above (a small one with a loader and a reserved height, a large one behind the Draw button).
372
475
  - A source that is not the renderer's template is dropped. There is no length cap on the diagram beyond the 1 MiB `srcdoc` guard, and no cdnjs frame. If Mermaid cannot render the source (a syntax error), the code block stays and a short "diagram could not be rendered" note appears.
373
476
  - Host CSP: `script-src 'self'` is enough (plus `'unsafe-inline'` or nonces for Next's own inline scripts, as for any Next app); `style-src 'unsafe-inline'` is required because Mermaid's SVG carries inline styles; `img-src` decides whether images that a diagram label references load. Checked under `default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:` in headless Chromium on Next 16.2.7, 16.3.4 and 16.4.2 (`node scripts/e2e-next-build.mjs --browser`).
374
- - Override: `components.Mermaid` still replaces all of this. It receives `{ srcDoc, source, title }`; `source` is the diagram text, or `undefined` when it could not be extracted. `MermaidDiagram` (`{ source, title, errorText }`) is exported from `./react` if you want to wrap it. It is the SDK's only client component and takes nothing but those strings: no token or client ever crosses the boundary.
477
+ - Override: `components.Mermaid` still replaces all of this. It receives `{ srcDoc, source, title }`; `source` is the diagram text, or `undefined` when it could not be extracted. `MermaidDiagram` (`{ source, title, errorText, loadingText?, labels? }`) is exported from `./react` if you want to wrap it. It takes nothing but those strings: no token or client ever crosses the boundary.
478
+
479
+ ### Large diagrams
480
+
481
+ Mermaid lays a diagram out in one synchronous task. Nothing can interrupt it, no timeout included, so a few hundred edges freeze the tab for seconds, longer on a phone. The SDK therefore does not draw a large diagram until the reader presses Draw diagram.
482
+
483
+ - What counts as large (`isLargeDiagram`, exported from `./react`): more than 100 flowchart link tokens (an upper bound on edges, not a parse, so label text such as `--flag` counts), 6000 characters, 250 statements, 800 words or 25 groups, with lower limits for mindmap, kanban, block, ER, venn, class and state diagrams, whose statements cost more. It errs toward asking. It reads the source in linear time and never calls Mermaid.
484
+ - Before the click: a notice with the button, then the source, clamped behind a Show full source toggle when over 12 lines (all of it stays in the DOM). The server renders these boxes, so nothing moves at hydration. Until then the notice and toggle are `inert`, and CSS shows them, and clamps the source, only under `@media (scripting: enabled)`: a reader without JavaScript and a crawler get the whole source and no notice. A reader whose scripts are blocked or fail sees the inert notice above the scrollable source.
485
+ - After the click: a "Drawing" placeholder is painted first (Mermaid waits two animation frames), then the layout blocks the page. The spinner animates `transform` only, so the compositor keeps turning it while the main thread is busy. Focus moves to Expand if the reader has not moved it elsewhere. A failure keeps the source and offers Draw again. Once drawn, a theme change redraws it without asking.
486
+ - Hard limit: Mermaid's `maxEdges` is 500. A flowchart above it fails with the "could not be rendered" note; a stored render of it still shows.
487
+ - Keep drawing cheap in your own CSS: a draw changes the DOM over a thousand times and forces style recalculation each time, and a `:has()` rule on `html`, `body` or another wide ancestor is re-checked on each one, whether or not its element is on the page. In one measured host a 295-edge flowchart took 16.7 s to draw with such rules in its stylesheet and 0.85 s without them (desktop Chromium). Prefer a class you set yourself, as the viewer does for scroll lock and fullscreen. `styles.css` still has a few `:has()` rules of its own (one on `html` for the docs drawer, one for the docs tree, one for task lists).
488
+
489
+ ### Printing
490
+
491
+ - Starting a print draws every small diagram, however far down. A large one nobody asked to draw, and one that failed, prints its whole source.
492
+ - Ctrl+P or Cmd+P while a diagram is still undrawn is held: a note shows, the diagrams draw, then `window.print()` runs (it waits at most 10 s for the download and 10 s for drawing, though a layout in progress cannot be cut short). Escape cancels. File > Print cannot be intercepted: what is not drawn by then prints as source.
493
+ - A diagram drawn in the browser in the dark theme is printed on white with its colours inverted (hue kept). A stored render prints as the image on screen.
494
+ - A host that loads `MermaidDiagram` lazily itself should call `installPrintShortcut()` (it returns the cleanup) and pass the load promise to `holdPrintUntil()`, so a press during the download waits for the diagrams.
495
+
496
+ A host that writes the server markup itself can reuse `isLargeDiagram`, `isClampedSource`, `stripMermaidConfig` and `VIEWER_LABELS_EN` from `./react`; the class names are the ones in `styles.css`.
375
497
 
376
498
  ## Diagram viewer
377
499
 
378
- Every Mermaid diagram is a button. Click it, press Enter or Space on it, or tap it, and it opens in a dialog you can zoom, pan, trace and search. Nothing to install or configure: it ships in the package, has no extra dependency, uses no host UI library, and works under the same strict CSP as the inline diagram.
500
+ Every drawn Mermaid diagram has an Expand button. Click or tap anywhere on the diagram, or press Enter or Space on the button, and it opens in a dialog you can zoom, pan, trace and search. Nothing to install or configure: it ships in the package, has no extra dependency, uses no host UI library, and works under the same strict CSP as the inline diagram.
379
501
 
380
- - Lazy: the viewer is its own chunk, fetched by the first click and never before. A page whose diagrams are never opened pays only for the trigger: about 2.2 KB raw (1 KB gzipped) more than 0.3.0, the button markup in `MermaidDiagram` and the English strings; the viewer itself is about 48 KB raw (14 KB gzipped) fetched on the first click. It shows the SVG the page already rendered (ids and `#id` CSS scoping rewritten to a unique id), so Mermaid does not lay the diagram out a second time; after a theme change the dialog swaps in the re-rendered SVG and keeps your zoom and your pinned node.
502
+ - Lazy: the viewer is its own chunk, fetched by the first click and never before (about 52 KB as published and 15 KB gzipped; about 30 KB raw once a Next production build minifies it). It shows the SVG the page already rendered (ids and `#id` CSS scoping rewritten to a unique id), so Mermaid does not lay the diagram out a second time; after a theme change the dialog swaps in the re-rendered SVG and keeps your zoom and your pinned node.
381
503
  - Dialog: a native `<dialog>` opened with `showModal()`: the page behind is inert and focus cannot leave, `Esc` or a click on the backdrop closes it, focus returns to the trigger, page scroll is locked (a class on `<html>`), the open animation and the flowing dashes switch off under `prefers-reduced-motion`, and on a phone it fills the screen with 44 px touch targets.
382
504
  - Zoom and pan: the wheel (or a trackpad pinch) zooms around the cursor from 0.2x to 10x; drag pans with pointer events (mouse, touch, pen) and glides on release; two fingers pinch and pan; double-click or double-tap zooms 2x (on a node: to that node); a readout shows the percentage; it opens fitted to the dialog.
383
505
  - Flowchart, state, class and ER diagrams (anything Mermaid draws as `g.node` elements): hover or keyboard-focus a node and it, its direct neighbours and the edges between them stay lit while everything else dims. Click or press Enter and the node is pinned and traced: every upstream path in one tone, every downstream path in another (colours in the legend), with dashes flowing along the traced edges. Click the background to clear. `F` or a double-click zooms to the node and its neighbours with an eased transition. A minimap with a draggable viewport rectangle appears from 12 nodes. The graph is read from the rendered SVG (node ids, edge ids, or where each edge path starts and ends), never from the Mermaid source.
@@ -411,13 +533,13 @@ Import `@tdacorp/hyle-sdk/styles.css`. It is the design kit's stylesheet: every
411
533
  :root { --hyle-accent: #ff8a3d; --hyle-radius: 12px; --hyle-font-heading: "Fraunces", serif; }
412
534
  ```
413
535
 
414
- The 52 variables are listed in the token block at the top of `styles.css`. Layout reacts to the width of the mount (container queries), not the window. Code uses highlight.js token classes (`hljs-*`, mapped to `--hyle-syn-*`). Math arrives as KaTeX HTML from the server: load `katex/dist/katex.min.css` in the host (it brings the fonts and resolves their URLs relative to itself). It is not bundled here because the fonts are about 1 MB of binary assets that would tie this package's version to KaTeX's and double-load in hosts that already use KaTeX.
536
+ The 52 variables are listed in the token block at the top of `styles.css`. Layout reacts to the width of the mount (container queries), not the window. Code uses highlight.js token classes (`hljs-*`, mapped to `--hyle-syn-*`). Math arrives as KaTeX HTML from the server: load `katex/dist/katex.min.css` from KaTeX 0.16 in the host (it brings the fonts and resolves their URLs relative to itself; hyle emits 0.16 markup, and the 0.18 stylesheet renamed classes it needs, so superscript sizes and rules break). It is not bundled here because the fonts are about 1 MB of binary assets that would tie this package's version to KaTeX's and double-load in hosts that already use KaTeX.
415
537
 
416
538
  ## Customization
417
539
 
418
540
  `components` replaces how a part is drawn, `slots` fills named places. Both are props of the pages and options of `hylePage`.
419
541
 
420
- - Component slots: `Link` (every internal link, breadcrumb and in-page link: pass your router's Link), `Image`, `CodeBlock` (receives `code`, `language`, and the default `children`; the stock block has no copy button because that needs client JavaScript), `Mermaid` (receives hyle's sandboxed `srcDoc` and the extracted `source`; the default renders the diagram in the page, see "Mermaid diagrams"), `Callout` (GFM alerts such as `> [!NOTE]`). The raw element overrides `a`, `img`, `code`, `pre`, `table`, `blockquote` and `h1` to `h6` also work.
542
+ - Component slots: `Link` (every internal link, breadcrumb and in-page link: pass your router's Link), `Image`, `CodeBlock` (receives `code`, `language`, and the default `children`; the stock block's copy button goes with it), `Mermaid` (receives hyle's sandboxed `srcDoc` and the extracted `source`; the default renders the diagram in the page, see "Mermaid diagrams"), `Callout` (GFM alerts such as `> [!NOTE]`; `kind` is `note`, `tip`, `important`, `warning` or `caution`). The raw element overrides `a`, `img`, `code`, `pre`, `table`, `blockquote` and `h1` to `h6` also work.
421
543
  - Visual slots: `article.before`, `article.meta`, `article.aside`, `article.after`, `list.header`, `list.item` (a component that receives the item), `list.empty`, `docs.sidebar-header`, `docs.version`, `docs.sidebar-footer`, `docs.after`, `notfound.body`, `notfound.actions`, `redirecting.body`. An unfilled slot renders nothing.
422
544
  - Layout: `layout: "docs"` renders articles as `DocsPage`, with no host code. The sidebar is the whole section (hyle sends it when the request carries `nav=tree`, which the layout adds; hidden pages are excluded and their children promoted, one locale): collapsible groups (`<details>`, so it works without JavaScript), the path to the current page open and the page marked `aria-current="page"`. Also a breadcrumb, previous and next links, an on-page contents list with scroll-spy (`aria-current="location"`, an IntersectionObserver, no dependency, no inline script), "Last updated" from the document's `updated_at`, and on a narrow mount (container width under 760px) a Menu button that opens the sidebar as a drawer (the native `popover` attribute: Escape and an outside click close it, focus returns to the button). A section above 2,000 pages in one locale is sent without the tree, and so is an older hyle: the sidebar then shows only the path to the page and its children. Restyle with the `--hyle-*` variables (`--hyle-nav-width`, `--hyle-toc-width`, `--hyle-sticky-top` for a sticky host header) and the slots above. A version badge is only what you put in `docs.version`: hyle has no docs-version data.
423
545
 
@@ -427,15 +549,16 @@ Chrome strings exist for en, fr and es (fr and es are unreviewed drafts). The pa
427
549
 
428
550
  - The token is sent only as an `Authorization` header from the server. It is never placed in a URL, logged or put in an error message. Keep it out of client components. The client requires an https `baseUrl` (http only for localhost, or with `allowInsecureHttp`), refuses redirects, aborts after `timeoutMs` (default 10 s) and refuses responses over `maxResponseBytes` (default 5 MiB).
429
551
  - The path is sent as a query parameter (encoded once); catch-all segments are decoded and refused if they contain `/`, `\`, control characters, `.` or `..`.
430
- - The `hast` tree is rendered through an allowlist (`sanitizeHast`) even though hyle sanitizes server-side: only known tags and properties with accepted value shapes survive; no `on*` attributes, `style` only inside KaTeX output and only for the properties KaTeX emits with small values (no `position:absolute`, `z-index`, `left` or large sizes), ids and in-page fragments scoped with the server's `user-content-` prefix (so heading ids, footnote links and TOC links still resolve), `href` and `src` limited to site-relative paths and `http(s)` (and `mailto` for links), unknown tags are unwrapped, `script` and `style` are dropped, and an `iframe` is kept only with `sandbox="allow-scripts"` and a `srcdoc` that is exactly the document hyle's renderer builds for a Mermaid fence (pinned script URL, at most 1 MiB); the SDK never renders that frame, it only reads the diagram text out of it. `data-light` and `data-dark` on it are kept only as `/assets/<uuid>.svg <width> <height>`. A tree over 20,000 nodes or 512 KiB of text fails closed with `HastLimitError` and a safe notice. `dangerouslySetInnerHTML` is used in exactly three places: the Mermaid SVG sink (below), the same SVG with rewritten ids in the diagram viewer's stage (below), and `TrustedServerHtml`, the escape hatch for `content.format === "html"`: it renders HTML as is, so pass it only HTML that came straight from hyle's resolve endpoint, never user input.
431
- - Mermaid renders into your page, so: the source comes only from hyle content, passes the exact-template check and the 1 MiB `srcdoc` guard, and is rendered with `securityLevel: "strict"` (Mermaid's own DOMPurify pass, no raw HTML labels), `maxTextSize` set to that bound and `maxEdges` 5000. The SDK strips every `%%{ ... }%%` directive (multi-line, unterminated and `init`, `initialize`, `config`, `wrap` forms) and a leading YAML frontmatter block from the source before rendering, and keeps plain `%% comment` lines. Reason: Mermaid's `themeCSS` (set by a directive or by frontmatter `config:`) is injected into the page as CSS and its sanitizer only checks brace balance, so a diagram could make the page fetch a URL or overlay the host UI; verified against Mermaid 11.9.0 with a loopback canary server, which received requests when the stripping was disabled and none with it. Consequence: authors cannot configure a diagram per diagram; a diagram that carries an init directive renders with the SDK's defaults. As a second guard `.hyle-mermaid-svg` uses `contain: paint` and the SVG is `position: static !important`, so diagram CSS cannot place anything over the host page. Flowchart `style` and `classDef` lines cannot carry `url(...)` (they fail to parse). What remains: Mermaid keeps an `<img>` inside a label (event handlers are stripped), so an author can make the page request an image, and your CSP `img-src` governs that exactly as for Markdown images (the e2e proves a strict `img-src 'self' data:` stops it); a `click A "https://..."` line makes a clickable link, a phishing-link capability inside author-controlled content, so treat hyle authors as trusted to link. Nothing is executed: the SDK ignores Mermaid's `bindFunctions`, and the hostile `click ... call`, `<img onerror>` and `securityLevel: "loose"` payloads did nothing in the browser check. The host CSP needs `style-src 'unsafe-inline'`.
432
- - The diagram viewer adds no network request, no `eval`, no storage and no new way to write HTML: its stage receives the very string the inline diagram holds (Mermaid's strict-mode DOMPurify output) after one rewrite of the SDK-generated render id (`hyle-mermaid-N`) to another SDK-generated token (`hyle-viewer-N`), applied only inside tags and `<style>` bodies and only for `[\w-]+` tokens, so it cannot add a quote, a tag or a script; the node and edge decoration only sets classes, `tabindex`, `role` and `aria-*` on elements that already exist. Export builds `blob:` and `data:` URLs from that same string on click, and the clipboard is only touched inside the click that asked for it. A unit test pins these properties by reading the viewer's source (no `fetch`, `eval`, `innerHTML =`, storage or `document.write`, exactly one `dangerouslySetInnerHTML`).
433
- - The comments client talks only to the host's own `createEngagementRoute` (same origin; no credential, no hyle URL, no storage, no cookie access in the browser bundle, which a test pins). The route is an allowlist, not a proxy, and writes need same-origin plus a custom header (see "Comments and likes"). The private signing key stays on the server and is never logged; a malformed key is refused with a message that does not contain it.
434
- - Webhooks are verified with HMAC-SHA256 over the raw body (read with a running 64 KiB cap), a 300 s timestamp tolerance and constant-time comparison, with dual-secret rotation (empty secrets are never candidates), a payload shape check (400, not 500), tag validation, and delivery-id dedupe that records an id only after every purge succeeded, so a failed delivery can be retried.
552
+ - The `hast` tree is rendered through an allowlist (`sanitizeHast`) even though hyle sanitizes server-side: only known tags and properties with accepted value shapes survive; no `on*` attributes, `style` only inside KaTeX output and only for the properties KaTeX emits with small values (no `position:absolute`, `z-index`, `left` or large sizes), ids and in-page fragments scoped with the server's `user-content-` prefix (so heading ids, footnote links and TOC links still resolve), `href` and `src` limited to site-relative paths and `http(s)` (and `mailto` for links), `kbd` with no property, an image `title` as a string only, a link's `data-embed` only as `youtube` and only on exactly `https://www.youtube.com/watch?v=<11 characters>`, `figure` and `figcaption` never taken from the input (the SDK builds them for image paragraphs), unknown tags are unwrapped, `script` and `style` are dropped, and an `iframe` is kept only with `sandbox="allow-scripts"` and a `srcdoc` that is exactly the document hyle's renderer builds for a Mermaid fence (pinned script URL, at most 1 MiB); the SDK never renders that frame, it only reads the diagram text out of it. `data-light` and `data-dark` on it are kept only as `/assets/<uuid>.svg <width> <height>`. A tree over 20,000 nodes or 512 KiB of text fails closed with `HastLimitError` and a safe notice. `dangerouslySetInnerHTML` is used in exactly three places: the Mermaid SVG sink (below), the same SVG with rewritten ids in the diagram viewer's stage (below), and `TrustedServerHtml`, the escape hatch for `content.format === "html"`: it renders HTML as is, so pass it only HTML that came straight from hyle's resolve endpoint, never user input.
553
+ - Mermaid renders into your page, so: the source comes only from hyle content, passes the exact-template check and the 1 MiB `srcdoc` guard, and is rendered with `securityLevel: "strict"` (Mermaid's own DOMPurify pass, no raw HTML labels), `maxTextSize` set to that bound and `maxEdges` 500. The SDK strips every `%%{ ... }%%` directive (multi-line, unterminated and `init`, `initialize`, `config`, `wrap` forms) and every leading YAML frontmatter block (indented ones too, which Mermaid 11.16 reads; a source still changing after 16 rounds is dropped whole) from the source before rendering, and keeps plain `%% comment` lines. Reason: Mermaid's `themeCSS` (set by a directive or by frontmatter `config:`) is injected into the page as CSS and its sanitizer only checks brace balance, so a diagram could make the page fetch a URL or overlay the host UI; the browser check serves such payloads against a loopback canary server and expects no request, and a unit test asks Mermaid itself that no config survives the stripping. Consequence: authors cannot configure a diagram per diagram; a diagram that carries an init directive renders with the SDK's defaults. As a second guard `.hyle-mermaid-svg` uses `contain: paint` and the SVG is `position: static !important`, so diagram CSS cannot place anything over the host page. Flowchart `style` and `classDef` lines cannot carry `url(...)` (they fail to parse). What remains: Mermaid keeps an `<img>` inside a label (event handlers are stripped), so an author can make the page request an image, and your CSP `img-src` governs that exactly as for Markdown images (the e2e proves a strict `img-src 'self' data:` stops it); a `click A "https://..."` line makes a clickable link, a phishing-link capability inside author-controlled content, so treat hyle authors as trusted to link. Nothing is executed: the SDK ignores Mermaid's `bindFunctions`, and the hostile `click ... call`, `<img onerror>` and `securityLevel: "loose"` payloads did nothing in the browser check. The host CSP needs `style-src 'unsafe-inline'`.
554
+ - The diagram viewer adds no network request, no `eval`, no storage and no new way to write HTML: its stage receives the very string the inline diagram holds (Mermaid's strict-mode DOMPurify output) after one rewrite of the SDK-generated render id (`hyleMermaid-N`) to another SDK-generated token (`hyleViewer-N`), which also replaces the render-id prefix on node ids, applied only inside tags and `<style>` bodies and only for `[\w-]+` tokens, so it cannot add a quote, a tag or a script; the node and edge decoration only sets classes, `tabindex`, `role` and `aria-*` on elements that already exist. Export builds `blob:` and `data:` URLs from that same string on click, and the clipboard is only touched inside the click that asked for it. A unit test pins these properties by reading the viewer's source (no `fetch`, `eval`, `innerHTML =`, storage or `document.write`, exactly one `dangerouslySetInnerHTML`).
555
+ - The article islands receive ids and chrome strings only (the player a video id the server validated). The copy button reads the block's text on click and writes it to the clipboard; none of them writes HTML. The YouTube frame is another origin, which is why it may have `allow-scripts` with `allow-same-origin`; its source is built from the 11 character id alone.
556
+ - The comments client talks only to the host's own `createEngagementRoute` (same origin; no credential, no hyle URL, no storage, no cookie access in the browser bundle, which a test pins). The route is an allowlist, not a proxy, and writes need same-origin plus a custom header (see "Comments, votes and reactions"). The private signing key stays on the server and is never logged; a malformed key is refused with a message that does not contain it.
557
+ - Webhooks are verified with HMAC-SHA256 over the raw body (read with a running 64 KiB cap), a 300 s timestamp tolerance and constant-time comparison, with dual-secret rotation (empty secrets are never candidates), a payload shape check (400, not 500), tag validation, and delivery-id dedupe that records an id only after every purge succeeded, so a failed delivery can be retried. `onCommentEvent` is the exception: its failures are not retried (see "Comment notifications").
435
558
 
436
559
  ## Not included
437
560
 
438
- Docs versions, "closest matches" on the 404 page and a copy-code button: hyle does not provide that data or the page would need client JavaScript. Image URLs in content such as `/assets/<id>` are no longer passed through unchanged: see "Media".
561
+ Docs versions and "closest matches" on the 404 page: hyle does not provide that data. Image URLs in content such as `/assets/<id>` are no longer passed through unchanged: see "Media".
439
562
 
440
563
  Reading time: when the server sends `publication.word_count` (a positive integer; older servers omit it), article pages show the locale's "N min read" in the meta row (275 words per minute, at least 1), the BlogPosting carries `wordCount`, and the metadata adds `twitter:label1`/`twitter:data1` through `other`, keeping the host's own `other` keys read from `parent`. Nothing is shown or emitted without it.
441
564
 
@@ -454,3 +577,7 @@ export async function generateMetadata(props: PageProps) {
454
577
  ## Contract
455
578
 
456
579
  Types in `src/types.ts` mirror `packages/cp1-read/src/resolve.ts`. `src/__tests__/contract.test.ts` pins them against fixture JSON for every result kind, so a server-side shape change fails a test here.
580
+
581
+ ## Identity machine tokens (`auth` instead of `token`)
582
+
583
+ `createHyleClient`, `syncHostReserved` and `cachedResolver` accept `auth` (a `HyleAuth`) instead of `token`, for a service account of identity (hyle ADR 0027, needs `HYLE_MACHINE_IDENTITY_TOKENS=dual` or `identity` on hyle). The hook is called for every request with `{ method, url }` and returns the headers to send, so the DPoP proof matches that request; with the identity SDK: `auth: (req) => serviceClient.headersFor(token, req)`. `workspaceId` is required and sent as `CP-Workspace`; the token needs `hyle.document.read` on it (`hyle.workspace.manage` for `syncHostReserved`). Page, asset and embed helpers still take `token`.
@@ -27,6 +27,18 @@ var Cp1ClientError = class extends Error {
27
27
  };
28
28
 
29
29
  // src/client.ts
30
+ var RENDERER_VERSION = "4";
31
+ function applyCredential(headers, credential, method, url) {
32
+ if (!credential.auth) {
33
+ headers.set("authorization", `Bearer ${credential.token}`);
34
+ return void 0;
35
+ }
36
+ const { workspaceId } = credential;
37
+ return credential.auth({ method, url }).then((extra) => {
38
+ for (const [name, value] of Object.entries(extra)) headers.set(name, value);
39
+ headers.set("cp-workspace", workspaceId);
40
+ });
41
+ }
30
42
  var DEFAULT_TIMEOUT_MS = 1e4;
31
43
  var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
32
44
  var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -68,14 +80,16 @@ function checkBaseUrl(baseUrl, allowInsecureHttp) {
68
80
  }
69
81
  function createHyleClient(options) {
70
82
  checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
71
- if (!options.token) throw new TypeError("token is required");
83
+ if (!options.auth && !options.token) throw new TypeError("token is required");
72
84
  const base = options.baseUrl.replace(/\/+$/, "");
73
85
  const fetchImpl = options.fetch ?? fetch;
74
86
  async function get(pathname, query, init) {
75
87
  const url = new URL(`${base}${pathname}`);
76
88
  url.search = query.toString();
77
89
  const headers = new Headers(init?.headers);
78
- headers.set("authorization", `Bearer ${options.token}`);
90
+ headers.set("cp-renderer-version", RENDERER_VERSION);
91
+ const applied = applyCredential(headers, options, "GET", url.toString());
92
+ if (applied) await applied;
79
93
  const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
80
94
  const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
81
95
  const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
@@ -115,16 +129,28 @@ function createHyleClient(options) {
115
129
  if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
116
130
  throw failure(reply);
117
131
  }
132
+ async function pushPosts(opts) {
133
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(opts.section)) throw new TypeError("section must be a section slug");
134
+ const query = new URLSearchParams();
135
+ if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
136
+ const reply = await get(`/cp1/read/sections/${opts.section}/posts`, query, opts.init);
137
+ const data = reply.parsed?.data;
138
+ if (data?.cp === 1 && data.kind === "push_posts" && Array.isArray(data.posts) && typeof data.complete === "boolean") return data;
139
+ throw failure(reply);
140
+ }
118
141
  async function asset(file, opts = {}) {
119
142
  if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
120
- const headers = new Headers({ authorization: `Bearer ${options.token}` });
143
+ const url = `${base}/cp1/read/assets/${file}`;
144
+ const headers = new Headers();
145
+ const applied = applyCredential(headers, options, "GET", url);
146
+ if (applied) await applied;
121
147
  for (const name of ["range", "if-range", "if-none-match"]) {
122
148
  const value = opts.headers?.[name];
123
149
  if (value) headers.set(name, value);
124
150
  }
125
- return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
151
+ return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
126
152
  }
127
- return { resolve, mounts, asset };
153
+ return { resolve, mounts, pushPosts, asset };
128
154
  }
129
155
 
130
156
  // src/host-sync.ts
@@ -134,21 +160,20 @@ var MAX_RESPONSE_BYTES = 1024 * 1024;
134
160
  var PATH = "/cp1/control/workspace/host-reserved-paths";
135
161
  async function syncHostReserved(input) {
136
162
  checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
137
- if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
163
+ if (input.token !== void 0 && !input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
138
164
  throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
139
165
  }
140
166
  const fetchImpl = input.fetch ?? fetch;
141
- const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
167
+ const url = `${input.baseUrl.replace(/\/+$/, "")}${PATH}`;
168
+ const headers = new Headers({ "content-type": "application/json", "idempotency-key": `sync-${crypto.randomUUID()}` });
169
+ await applyCredential(headers, input.auth ? { auth: input.auth, workspaceId: input.workspaceId } : { token: input.token }, "PUT", url);
170
+ headers.set("cp-workspace", input.workspaceId);
171
+ const res = await fetchImpl(url, {
142
172
  method: "PUT",
143
173
  // redirect "error": the bearer token must never follow a redirect to another host.
144
174
  redirect: "error",
145
175
  signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
146
- headers: {
147
- authorization: `Bearer ${input.token}`,
148
- "content-type": "application/json",
149
- "cp-workspace": input.workspaceId,
150
- "idempotency-key": `sync-${crypto.randomUUID()}`
151
- },
176
+ headers,
152
177
  body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
153
178
  });
154
179
  const text = await readCapped(res, MAX_RESPONSE_BYTES);