@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.
- package/README.md +261 -42
- package/dist/check-routes-bin.js +190 -53
- package/dist/{chunk-6VOHFFA5.js → chunk-7T5EEJHK.js} +2 -2
- package/dist/chunk-DUPT6XLB.js +57 -0
- package/dist/chunk-IW3TUD4G.js +841 -0
- package/dist/{chunk-MGSUQBDW.js → chunk-KU7LWK4E.js} +249 -24
- package/dist/{chunk-BUJFMR3M.js → chunk-QVYQM5R2.js} +15 -6
- package/dist/chunk-SFFBZFEN.js +178 -0
- package/dist/chunk-U74B7AUG.js +398 -0
- package/dist/chunk-ZIW6FDU2.js +1126 -0
- package/dist/client-BGjmEWhN.d.cts +207 -0
- package/dist/client-D0LTpr3Y.d.ts +207 -0
- package/dist/code-copy.cjs +74 -0
- package/dist/code-copy.d.cts +18 -0
- package/dist/code-copy.d.ts +18 -0
- package/dist/code-copy.js +50 -0
- package/dist/comments.cjs +738 -280
- package/dist/comments.d.cts +66 -3
- package/dist/comments.d.ts +66 -3
- package/dist/comments.js +419 -331
- package/dist/{diagram-viewer-FJPED4SN.js → diagram-viewer-XY3CG75U.js} +62 -21
- package/dist/docs-enhance.cjs +7 -4
- package/dist/docs-enhance.d.cts +5 -3
- package/dist/docs-enhance.d.ts +5 -3
- package/dist/docs-enhance.js +8 -5
- package/dist/{embed-DNTZ2UXv.d.ts → embed-CbtsbZs3.d.cts} +5 -3
- package/dist/{embed-BmdwA2G9.d.cts → embed-Cf_2ZR5x.d.ts} +5 -3
- package/dist/fragment-alias.cjs +51 -0
- package/dist/fragment-alias.d.cts +7 -0
- package/dist/fragment-alias.d.ts +7 -0
- package/dist/fragment-alias.js +27 -0
- package/dist/html.cjs +886 -0
- package/dist/html.d.cts +20 -0
- package/dist/html.d.ts +20 -0
- package/dist/html.js +45 -0
- package/dist/index.cjs +244 -24
- package/dist/index.d.cts +22 -68
- package/dist/index.d.ts +22 -68
- package/dist/index.js +12 -2
- package/dist/{labels-nmukKYgL.d.cts → labels-CrA-iqTN.d.cts} +9 -0
- package/dist/{labels-nmukKYgL.d.ts → labels-CrA-iqTN.d.ts} +9 -0
- package/dist/mermaid-diagram.cjs +441 -125
- package/dist/mermaid-diagram.d.cts +23 -7
- package/dist/mermaid-diagram.d.ts +23 -7
- package/dist/mermaid-diagram.js +213 -51
- package/dist/mermaid-image.cjs +137 -60
- package/dist/mermaid-image.d.cts +4 -3
- package/dist/mermaid-image.d.ts +4 -3
- package/dist/mermaid-image.js +27 -28
- package/dist/next.cjs +836 -304
- package/dist/next.d.cts +45 -20
- package/dist/next.d.ts +45 -20
- package/dist/next.js +151 -40
- package/dist/print-coordinator.cjs +157 -0
- package/dist/print-coordinator.d.cts +27 -0
- package/dist/print-coordinator.d.ts +27 -0
- package/dist/print-coordinator.js +83 -0
- package/dist/react.cjs +603 -240
- package/dist/react.d.cts +148 -30
- package/dist/react.d.ts +148 -30
- package/dist/react.js +26 -4
- package/dist/reactions.cjs +653 -0
- package/dist/reactions.d.cts +27 -0
- package/dist/reactions.d.ts +27 -0
- package/dist/reactions.js +364 -0
- package/dist/{resolve-euZ4-aC9.d.cts → resolve-BnIv7aB7.d.cts} +2 -2
- package/dist/{resolve-Ae7UFjsQ.d.ts → resolve-BysHtZ_i.d.ts} +2 -2
- package/dist/revalidation-callback-BQl77tQR.d.cts +75 -0
- package/dist/revalidation-callback-BQl77tQR.d.ts +75 -0
- package/dist/sanitize-BpY_AdZh.d.cts +23 -0
- package/dist/sanitize-BpY_AdZh.d.ts +23 -0
- package/dist/styles.css +100 -29
- package/dist/toc-spy.cjs +60 -0
- package/dist/toc-spy.d.cts +15 -0
- package/dist/toc-spy.d.ts +15 -0
- package/dist/toc-spy.js +36 -0
- package/dist/{types-Czt887Iv.d.cts → types-D09Z072G.d.cts} +57 -2
- package/dist/{types-Czt887Iv.d.ts → types-D09Z072G.d.ts} +57 -2
- package/dist/use-cache.cjs +89 -13
- package/dist/use-cache.d.cts +12 -5
- package/dist/use-cache.d.ts +12 -5
- package/dist/use-cache.js +8 -8
- package/dist/youtube-facade.cjs +50 -0
- package/dist/youtube-facade.d.cts +17 -0
- package/dist/youtube-facade.d.ts +17 -0
- package/dist/youtube-facade.js +26 -0
- package/package.json +16 -3
- package/dist/chunk-67IOIAVW.js +0 -35
- package/dist/chunk-DMK4XQLU.js +0 -1556
- package/dist/chunk-PJMJMP66.js +0 -63
- package/dist/revalidation-callback-D7Ms_Puz.d.cts +0 -42
- package/dist/revalidation-callback-D7Ms_Puz.d.ts +0 -42
package/README.md
CHANGED
|
@@ -43,7 +43,7 @@ import { createRevalidateRoute } from "@tdacorp/hyle-sdk/next";
|
|
|
43
43
|
export const { POST } = createRevalidateRoute({ workspaceId: process.env.HYLE_WORKSPACE_ID, secrets: [process.env.HYLE_WEBHOOK_SECRET] });
|
|
44
44
|
```
|
|
45
45
|
|
|
46
|
-
`app/api/hyle/assets/[file]/route.ts` (images, video and audio in hyle content; see "Media"):
|
|
46
|
+
`app/api/hyle/assets/[file]/route.ts` (images, video and audio in hyle content, and the workspace theme; see "Media" and "Themes"):
|
|
47
47
|
|
|
48
48
|
```ts
|
|
49
49
|
import { createAssetRoute } from "@tdacorp/hyle-sdk/next";
|
|
@@ -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 |
|
|
80
|
-
| `@tdacorp/hyle-sdk/
|
|
116
|
+
| `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve`, `mounts`, `preview` 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) |
|
|
119
|
+
| `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleFeed`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createMarkdownRoute`, `markdownRewritePath`, `createLlmsTxtRoute`, `createRevalidateRoute`, `createAssetRoute`, `createOgImageRoute`, `createEngagementRoute`, `hylePreviewPage`, `hylePreviewMetadata`, `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
|
-
|
|
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
|
|
|
@@ -120,7 +159,7 @@ The revalidate route expires tags immediately (`revalidateTag(tag, { expire: 0 }
|
|
|
120
159
|
|
|
121
160
|
`list: { title, description }` sets the list page's h1, `<title>`, description and Open Graph. Each wins over hyle's section title (which is the slug, "Posts") and falls back separately: no `list.title` keeps the section title, no `list.description` shows none. Articles are unaffected.
|
|
122
161
|
|
|
123
|
-
List pages show the first page of results (`listLimit`, server default 20, maximum 100). `paginate: "searchParams"` turns on cursor pagination: `?cursor=` is read (it must be 1 to 256 characters of `A-Za-z0-9_-`, otherwise it is ignored; a well-formed cursor hyle rejects is a 404), sent to hyle, and "Older posts" links to `?cursor=<next_cursor>`. It is off by default because reading `searchParams` makes the route dynamic: it can no longer be statically generated or served from ISR (hyle's fetch cache and tags still apply per request). Leave it off when one page is enough. `generateMetadata` reads the cursor too (also under `hyleRootMetadata`), so page 2 has its own canonical and an "Older posts" title suffix.
|
|
162
|
+
List pages show the first page of results (`listLimit`, server default 20, maximum 100). `paginate: "searchParams"` turns on cursor pagination: `?cursor=` is read (it must be 1 to 256 characters of `A-Za-z0-9_-`, otherwise it is ignored; a well-formed cursor hyle rejects is a 404, because the cursor names no page), sent to hyle, and "Older posts" links to `?cursor=<next_cursor>`. It is off by default because reading `searchParams` makes the route dynamic: it can no longer be statically generated or served from ISR (hyle's fetch cache and tags still apply per request). Leave it off when one page is enough. `generateMetadata` reads the cursor too (also under `hyleRootMetadata`), so page 2 has its own canonical and an "Older posts" title suffix.
|
|
124
163
|
|
|
125
164
|
## Errors
|
|
126
165
|
|
|
@@ -128,11 +167,11 @@ How `hylePage` treats a hyle failure is chosen so a bad moment never replaces a
|
|
|
128
167
|
|
|
129
168
|
| Failure | Behaviour |
|
|
130
169
|
|---|---|
|
|
131
|
-
|
|
|
132
|
-
| Network error, timeout, 5xx,
|
|
170
|
+
| hyle's own not-found (`kind: "notfound"`, or a 404 with code `NOT_FOUND`), hyle's `VALIDATION_ERROR` for a request that carried the visitor's `cursor`, a path over 1024 characters, a non-NFC segment, `..` or a double-encoded `%XX` in a segment | `notFound()` (a real 404; the last three never reach hyle) |
|
|
171
|
+
| Network error, timeout, 5xx, **every other 4xx** (400 included, and a 404 from a proxy or firewall in front of hyle), a malformed response, a refused redirect target | **Rethrown.** Under ISR, Next keeps serving the last good page when a revalidation fails; a failure on a first render is an uncached 500 |
|
|
133
172
|
| `notFound()` and redirects | Next control flow, always propagated (`unstable_rethrow`) |
|
|
134
173
|
|
|
135
|
-
Why rethrow: a rendered "unavailable" page is a normal 200 render, so ISR would cache it and replace the last good article for everyone for the revalidate window. `onError: (error) => ReactElement` is the opt-in for a custom UI anyway; its element IS cached like any render, and the `error` it receives can contain `Cp1ClientError.message` and `requestId`, so never render it (only its name is logged, never the token or message). The `Unavailable` component (en, fr, es; `data-hyle-page="unavailable"`, `role="status"`, no error text) is exported from `./react` for `onError` or your own `error.tsx`. `hyleMetadata` follows the same split:
|
|
174
|
+
Why rethrow: a rendered "unavailable" page is a normal 200 render, so ISR would cache it and replace the last good article for everyone for the revalidate window. `onError: (error) => ReactElement` is the opt-in for a custom UI anyway; its element IS cached like any render, and the `error` it receives can contain `Cp1ClientError.message` and `requestId`, so never render it (only its name is logged, never the token or message). The `Unavailable` component (en, fr, es; `data-hyle-page="unavailable"`, `role="status"`, no error text) is exported from `./react` for `onError` or your own `error.tsx`. `hyleMetadata` follows the same split: hyle's not-found gives `{}`, anything else is rethrown, so an outage never caches a noindex page.
|
|
136
175
|
|
|
137
176
|
### More in this section
|
|
138
177
|
|
|
@@ -183,9 +222,9 @@ Why a REQUIRED catch-all: an optional catch-all at the app root (`[[...hyle]]`)
|
|
|
183
222
|
| Situation | Result |
|
|
184
223
|
|---|---|
|
|
185
224
|
| Mounts answer 401 or 403 (revoked token, deprovisioned workspace) | the last good copy is dropped and the error is rethrown (Next keeps the last good ISR page; a first render is an uncached 500) |
|
|
186
|
-
|
|
|
187
|
-
| Mounts fail
|
|
188
|
-
| Mounts fail
|
|
225
|
+
| The read surface is switched off (`kind: "disabled"`) | nothing is served: 404. The last good copy is dropped, so the kill switch is not undone by a later outage |
|
|
226
|
+
| Mounts fail any other way (network, timeout, 5xx, any other 4xx, malformed body) and a copy read within the last 15 minutes exists | that copy decides: unmatched URLs stay a plain 404, mounted pages go on to `hylePage` (which keeps its own last-good-page rule) |
|
|
227
|
+
| Mounts fail that way and there is no usable copy (a cold server, or a copy older than `MOUNTS_MAX_STALE_MS`, 15 minutes) | the error is rethrown: Next keeps the last good ISR page, a first render is an uncached 500. It is not guessed to be a 404, because the URL might be a mounted page |
|
|
189
228
|
| Root mount (`/`) and no usable copy | every unmatched URL errors until hyle is back (the root mount could own any of them) |
|
|
190
229
|
| hyle is down | the host's own pages are unaffected: they never call hyle |
|
|
191
230
|
|
|
@@ -215,7 +254,7 @@ Run it as the last step of the PRODUCTION build (a `postbuild` script, or the bu
|
|
|
215
254
|
| Variable | What |
|
|
216
255
|
|---|---|
|
|
217
256
|
| `HYLE_TARGET_BASE_URL`, `HYLE_TARGET_TOKEN` | already set for the site: finds the workspace through `mounts` (the read token only reads) |
|
|
218
|
-
| `HYLE_CONTROL_TOKEN` | NEW: a control credential (`hyle_tc_...`)
|
|
257
|
+
| `HYLE_CONTROL_TOKEN` | NEW: a control credential (`hyle_tc_...`) carrying `hyle.workspace.sync_host` on that workspace. The read token cannot write and is refused before any request. The Workspace > Agents screen issues read and write only, so an operator issues this one with `scripts/issue-control-credential.mjs --codes hyle.workspace.sync_host` in the hyle repository (a hyle that accepts only identity machine tokens, ADR 0027 there, refuses it, and this command does not send identity tokens). Without the permission the write answers 404. Store it as a secret in the Production scope of the host only |
|
|
219
258
|
| `HYLE_HOST_ID` | optional name for the audit trail; defaults to `VERCEL_PROJECT_PRODUCTION_URL`, or pass `--host` |
|
|
220
259
|
|
|
221
260
|
What is sent: `PUT /cp1/control/workspace/host-reserved-paths` with `{ paths, host, build_id }` (the build id is `.next/BUILD_ID`). The list: static routes exact; a segment with two or more routes becomes `/x/*`; a dynamic route becomes the wildcard on its static prefix (`/shop/[id]` is `/shop/*`, `/docs/[...slug]` is `/docs/*`); skipped are your hyle catch-all (`--hyle-param`), a route with no static prefix, anything on a mount's segment (the checker reports those as (b)), per-build hashed metadata routes (`/opengraph-image-1ycygp`), and `/` when hyle is mounted at the root. At most 512 entries. hyle stores it as a separate set (the workspace's own Reserved paths are never touched), enforces the union when publishing, renaming and re-prefixing, and shows it read-only in the workspace settings with the host, build and time.
|
|
@@ -226,6 +265,35 @@ What is sent: `PUT /cp1/control/workspace/host-reserved-paths` with `{ paths, ho
|
|
|
226
265
|
- **Conflicts.** If a path you now own already has a published hyle page, hyle unpublishes nothing: the result lists those URLs (CLI output and the settings page). Your own route wins in Next, so the hyle page is simply not shown; move or unpublish it in hyle.
|
|
227
266
|
- `--json` adds a `sync` object. The programmatic form is `syncHostReserved({ baseUrl, token, workspaceId, paths, host, buildId })`.
|
|
228
267
|
|
|
268
|
+
### Syncing the theme
|
|
269
|
+
|
|
270
|
+
Keep the site's theme in your repository as `hyle.theme.json` and send it with the same command:
|
|
271
|
+
|
|
272
|
+
```
|
|
273
|
+
hyle-sdk-check-routes --sync --theme --no-check
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
```json
|
|
277
|
+
{
|
|
278
|
+
"v": 1,
|
|
279
|
+
"scheme": "attr+media",
|
|
280
|
+
"values": {
|
|
281
|
+
"light.accent": "#b4400f",
|
|
282
|
+
"dark.accent": "#ff8a3d",
|
|
283
|
+
"radius": "12px",
|
|
284
|
+
"font-heading": { "family": "Fraunces", "fallback": "serif" }
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
- The file is read from the directory you run the command in, and **replaces** the workspace's code theme: a key you remove from it is removed in hyle, and `{ "v": 1, "values": {} }` clears the layer. Without `--theme` nothing happens to it. Precedence per key is hyle's defaults, then the organization theme, then this file, then overrides on hyle's Site theme screen.
|
|
290
|
+
- `scheme` is how dark is chosen: `attr` (a `data-theme` or `data-act` attribute on the root element), `media` (the system preference), `attr+media` (both, the attribute winning; the default), `light-only` or `dark-only`. The keys and their limits are hyle's (ADR 0036 there); hyle validates the file. Font files are uploaded in hyle and named by asset id.
|
|
291
|
+
- **It stays until replaced.** Deleting the file or dropping `--theme` keeps the last synced theme; clear it by syncing `{ "v": 1, "values": {} }`.
|
|
292
|
+
- **Written at build time.** hyle serves the synced theme to whatever deployment is live, so a deploy that fails or is rolled back after the sync leaves the old deployment with the new theme (sync the previous file to undo it). Only non-production Vercel builds are skipped: on any other CI, run `--sync --theme` in production builds only, or a preview build writes the production theme.
|
|
293
|
+
- Credential: the same `HYLE_CONTROL_TOKEN` as above (`hyle.workspace.sync_host`).
|
|
294
|
+
- A refused value changes nothing, and each key is printed with hyle's reason. Keys your hyle does not know are dropped and listed. Failures follow the path sync: a `theme:` warning and exit 0, or exit 3 under `--strict`; non-production Vercel builds are skipped. `--json` adds a `theme` object.
|
|
295
|
+
- Sites are revalidated only when the stylesheet they are served changes.
|
|
296
|
+
|
|
229
297
|
### Limits
|
|
230
298
|
|
|
231
299
|
- A junk URL still renders a 404 page in your site chrome; whether and how long Next keeps that render is Next's own ISR behaviour (not measured here). It never reaches hyle either way.
|
|
@@ -242,7 +310,7 @@ What is sent: `PUT /cp1/control/workspace/host-reserved-paths` with `{ paths, ho
|
|
|
242
310
|
Checklist for a site that mounts hyle at the root (details in the sections named):
|
|
243
311
|
|
|
244
312
|
- A REQUIRED catch-all `app/(site)/[...hyle]/page.tsx` (not `[[...hyle]]`), see "Root catch-all". A single mount that you name (`hylePage` at `/learn`) needs only its own route.
|
|
245
|
-
- `app/api/hyle/assets/[file]/route.ts` exporting `GET` and `HEAD` from `createAssetRoute`, if content has images, video or audio, see "Media".
|
|
313
|
+
- `app/api/hyle/assets/[file]/route.ts` exporting `GET` and `HEAD` from `createAssetRoute`, if content has images, video or audio, or the workspace has a theme, see "Media" and "Themes".
|
|
246
314
|
- `app/api/hyle/og/[...path]/route.ts` exporting `GET` from `createOgImageRoute(options)` (the same options as `hylePage`), and `ogImageRoute: true` in the page options, if you want the default card (needs `siteOrigin`, no `ogImage`): it draws the 1200x630 card, see "Not included". `/api/hyle/og` is reserved by the SDK.
|
|
247
315
|
- hyle's reserved paths must cover `/api/hyle/*` and your other routes: run `hyle-sdk-check-routes --sync` after `next build` (needs `HYLE_CONTROL_TOKEN`), see "Syncing reserved paths".
|
|
248
316
|
- No parent layout or page above the mount may export `dynamicParams = false` (below).
|
|
@@ -281,22 +349,88 @@ Verify after `next build`: `.next/prerender-manifest.json` must not show `"fallb
|
|
|
281
349
|
|
|
282
350
|
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
351
|
|
|
352
|
+
## Push mode
|
|
353
|
+
|
|
354
|
+
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".
|
|
355
|
+
|
|
284
356
|
## Media
|
|
285
357
|
|
|
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
|
|
358
|
+
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
359
|
|
|
288
360
|
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
361
|
|
|
290
|
-
Safety: the only input is the `file` segment and it must match `<lowercase uuid>[.png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg]` before anything is sent, so the route is not an open proxy. Only `Range`, `If-Range` and `If-None-Match` are forwarded (never the visitor's cookies or `Authorization`); the token goes to hyle only. Response headers are built by the SDK, the content type must be on the asset allowlist (an HTML or script answer is refused), the body is capped at 16 MiB (`maxBytes`) and the upstream call times out after 30 s (`timeoutMs`). Failures are empty responses: 404 for an unknown or unpublished asset, a bad name, a missing configuration or `HYLE_CONTENT_ENABLED=0`, 502 for any upstream error, so hyle's state and your token never leak. SVG is served as `image/svg+xml` with `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox` and `nosniff` (an `<img>` never runs SVG script; navigating to the URL runs none either).
|
|
362
|
+
Safety: the only input is the `file` segment (a draft preview adds its token, see "Draft preview") and it must match `<lowercase uuid>[.png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg|woff2]`, or the theme stylesheet's name `theme-<16 hex>-<64 hex>.css` (see "Themes"; fetched from `GET /cp1/read/theme.css` with nothing from the visitor's request, `text/css` only, at most 256 KiB), before anything is sent, so the route is not an open proxy. Only `Range`, `If-Range` and `If-None-Match` are forwarded (never the visitor's cookies or `Authorization`); the token goes to hyle only. Response headers are built by the SDK, the content type must be on the asset allowlist (an HTML or script answer is refused), the body is capped at 16 MiB (`maxBytes`) and the upstream call times out after 30 s (`timeoutMs`). Failures are empty responses: 404 for an unknown or unpublished asset, a bad name, a missing configuration or `HYLE_CONTENT_ENABLED=0`, 502 for any upstream error (a 404 without hyle's `NOT_FOUND` body included), so hyle's state and your token never leak. SVG is served as `image/svg+xml` with `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox` and `nosniff` (an `<img>` never runs SVG script; navigating to the URL runs none either).
|
|
291
363
|
|
|
292
364
|
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
365
|
|
|
294
|
-
##
|
|
366
|
+
## Themes
|
|
367
|
+
|
|
368
|
+
A theme is set in hyle (the organization's, your repository's `hyle.theme.json`, or the Site theme screen; hyle ADR 0036). When a workspace has one, hyle's answers carry `theme { hash, scope, css, preload }` and the SDK's pages and embeds style themselves. A workspace without a theme renders exactly as before.
|
|
369
|
+
|
|
370
|
+
- **What renders.** `ArticlePage`, `DocsPage`, `ListPage`, `HyleArticleView` and `HyleListView` (pass it the list answer's `theme`; `HyleList` does) render `<HyleTheme>`: a stylesheet link to `/api/hyle/assets/theme-<scope>-<hash>.css` and a preload for up to two theme fonts. For `HyleBody`, `HyleToc` or comments in your own page, render `<HyleTheme theme={article.theme} />` yourself.
|
|
371
|
+
- **What you need.** The asset route above, and `@tdacorp/hyle-sdk/styles.css`. Without the route the link is a 404 and pages keep the default look.
|
|
372
|
+
- **No flash, strict CSP.** React 19 puts the link in the head (`precedence`) and holds the paint until it loads. It is a same-origin file, so the theme needs only `style-src 'self'` and `font-src 'self'`; no inline style is added. Diagrams drawn in the browser still need what "Mermaid diagrams" says.
|
|
373
|
+
- **Caching.** The name holds the hash of the bytes (and `scope`, which names the workspace), so a name that matches the current stylesheet is served `public, max-age=31536000, immutable`. When the theme changes hyle sends the usual revalidation webhook and pages link the new name. A page that still links an older name of the same workspace gets the current stylesheet with `public, max-age=60`. Another workspace's name, and any name when the workspace has no theme, is an uncached 404.
|
|
374
|
+
- **Your own variables.** The theme declares on `.hyle` only the keys it sets, so your `--hyle-*` values on `:root`, `body` or a wrapper keep applying to everything else. For a key the theme sets, the theme wins: move your value into the theme or remove the key from it. A colour the theme sets for light only is `inherit` in dark, so dark shows your own value or the SDK default. Once the theme gives diagrams colours of their own it declares all seven `--hyle-diagram-*` variables, replacing yours. A rule of yours on `.hyle` with the same specificity competes by stylesheet order, which is not something to rely on.
|
|
375
|
+
- **Dark mode** follows the theme's `scheme` (below, "Syncing the theme"); only `hyle.theme.json` sets it. The scheme picks which of the theme's values apply: colours the theme leaves unset still follow your site, under `light-only` and `dark-only` too, so a single-mode theme on a site that switches modes should set every colour it depends on.
|
|
376
|
+
- **One workspace per asset route.** The route holds one credential, so on a host that mounts several workspaces (`hyleRootPage`) only that workspace's theme file is served; the others keep the default look. A theme stylesheet styles every `.hyle` element in the document.
|
|
377
|
+
- After a theme is removed, a browser that navigates client-side keeps the stylesheet it already loaded until the next full load.
|
|
378
|
+
|
|
379
|
+
## Draft preview
|
|
380
|
+
|
|
381
|
+
hyle's editor has "Open on site": it opens `https://<your site>/hyle-preview?token=hyle_pv_...` in a new tab, where `<your site>` is the workspace's site URL in Workspace settings (hyle ADR 0037). The link shows the text as it rendered when it was made, published or not, for 30 minutes. Making a link needs permission to edit documents; a newer link for the same document replaces the older one, and removing its author or making them a viewer closes it. Your site draws it, with its own templates and styles and the workspace's theme, as a published page. Needs the asset route from the quickstart.
|
|
382
|
+
|
|
383
|
+
`app/hyle-preview/page.tsx`, ready made:
|
|
295
384
|
|
|
296
|
-
|
|
385
|
+
```tsx
|
|
386
|
+
import { hylePreviewMetadata, hylePreviewPage } from "@tdacorp/hyle-sdk/next";
|
|
387
|
+
|
|
388
|
+
export const metadata = hylePreviewMetadata;
|
|
389
|
+
export default hylePreviewPage({ baseUrl: process.env.HYLE_TARGET_BASE_URL!, token: process.env.HYLE_TARGET_TOKEN! });
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
The ready page opens with an "Unpublished draft preview" banner that needs no stylesheet, so a visitor can tell a draft from your published pages.
|
|
393
|
+
|
|
394
|
+
It takes `components`, `slots`, `layout` (`"article"` or `"docs"`) and `localePrefix` as `hylePage` does. It also accepts `auth` with `workspaceId` in place of `token`; the asset route that serves the images still takes `token`. A link that is wrong, expired, from another workspace or whose document is gone is `notFound()`.
|
|
395
|
+
|
|
396
|
+
Inside your own template, use the fetch, and say on the page that it is an unpublished draft (the ready page's banner is yours to draw here):
|
|
397
|
+
|
|
398
|
+
```tsx
|
|
399
|
+
import { notFound } from "next/navigation";
|
|
400
|
+
import { createHyleClient } from "@tdacorp/hyle-sdk";
|
|
401
|
+
import { HyleBody, HyleTheme } from "@tdacorp/hyle-sdk/react";
|
|
402
|
+
|
|
403
|
+
const client = createHyleClient({ baseUrl: process.env.HYLE_TARGET_BASE_URL!, token: process.env.HYLE_TARGET_TOKEN! });
|
|
404
|
+
|
|
405
|
+
export const metadata = { robots: { index: false, follow: false }, referrer: "no-referrer" as const };
|
|
406
|
+
|
|
407
|
+
export default async function Preview({ searchParams }: { searchParams: Promise<{ token?: string }> }) {
|
|
408
|
+
const result = await client.preview((await searchParams).token);
|
|
409
|
+
if (result.kind !== "preview") notFound();
|
|
410
|
+
return (
|
|
411
|
+
<MyArticle title={result.article.publication.title}>
|
|
412
|
+
<p role="status">Unpublished draft preview</p>
|
|
413
|
+
<HyleTheme theme={result.article.theme} />
|
|
414
|
+
<HyleBody article={result.article} />
|
|
415
|
+
</MyArticle>
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
The result has `article` (the shape `resolve` returns, always `format: "hast"`; navigation, previous and next, breadcrumbs and translations are empty) and `expires_at`. It also carries the workspace's current `theme` when there is one: `ArticlePage`, `DocsPage` and so `hylePreviewPage` link it, and in your own template you render `<HyleTheme>` ("Themes"). The theme stylesheet and fonts load as on a published page, without the token. Its asset addresses, the cover's `path` too, end in `?hyle_preview=<token>`: keep that query, and `createAssetRoute` forwards it so images that are not published yet load. A `next/image` slot also needs `images.localPatterns` to allow it.
|
|
421
|
+
|
|
422
|
+
The token is a bearer secret for that draft, together with your read credential, which never leaves your server. The SDK sends it to hyle in a header only, fetches with `cache: "no-store"`, never logs it, and refuses to send anything that is not shaped like one. On your side:
|
|
423
|
+
|
|
424
|
+
- Do not wrap the page or the fetch in `use cache` or any cache, and keep `/hyle-preview` and `?hyle_preview=` out of CDN caching rules. The asset route answers them `no-store`.
|
|
425
|
+
- The token is in the page URL and the image URLs, so your access logs and the browser's history record it, and any script on the page can read it from `location.href`. Keep analytics, error reporting and other third-party scripts off this route, including ones your root layout adds to every page.
|
|
426
|
+
- Your proxy or middleware must let `/hyle-preview` through without a sign-in redirect that copies the URL elsewhere, and a catch-all must not claim it.
|
|
427
|
+
|
|
428
|
+
## Comments, votes and reactions
|
|
429
|
+
|
|
430
|
+
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
431
|
|
|
298
432
|
1. **hyle**: switch engagement on for the workspace and register the site's public key (below).
|
|
299
|
-
2. **A key pair.** `npx hyle-sdk-engage-keygen --out .env.engage`
|
|
433
|
+
2. **A key pair.** In hyle, workspace Engagement settings, "Create signing key" (or "Rotate key") makes an Ed25519 pair in your browser, shows `HYLE_ENGAGE_SIGNING_KEY=...` once for your site's environment, and registers only the PUBLIC key after you confirm you saved the line. To make the pair on your own machine instead, `npx hyle-sdk-engage-keygen --out .env.engage` writes the private key to a new file (mode 0600, never overwritten) in the same form, and prints the PUBLIC key 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, and with no arguments the tool prints usage and nothing else. Register that public key in the same dialog under "Use a public key I already made" (an operator can also run `hyctl engagement key set`). hyle's server never receives the private key. When you rotate, the old key stays valid for 24 hours.
|
|
300
434
|
3. **The route file** `app/api/hyle/engage/[...path]/route.ts`:
|
|
301
435
|
|
|
302
436
|
```ts
|
|
@@ -316,15 +450,75 @@ export const { GET, POST, PATCH, PUT, DELETE } = createEngagementRoute({
|
|
|
316
450
|
});
|
|
317
451
|
```
|
|
318
452
|
|
|
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 `
|
|
453
|
+
**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
454
|
|
|
321
455
|
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
456
|
|
|
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
|
|
457
|
+
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's `NOT_FOUND` 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).
|
|
458
|
+
|
|
459
|
+
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).
|
|
460
|
+
|
|
461
|
+
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.
|
|
462
|
+
|
|
463
|
+
**Votes, reactions, order and pages.**
|
|
464
|
+
|
|
465
|
+
- 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.
|
|
466
|
+
- 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.
|
|
467
|
+
- 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.
|
|
468
|
+
- 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.
|
|
469
|
+
- 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.
|
|
470
|
+
- 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.
|
|
471
|
+
- An older hyle sends no score, reaction counts or cursor: the section then shows likes only, with no vote, picker or sort controls.
|
|
472
|
+
|
|
473
|
+
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.
|
|
324
474
|
|
|
325
|
-
|
|
475
|
+
An edit can put a visible comment back in the moderation queue, in which case it moves to the reader's pending list.
|
|
326
476
|
|
|
327
|
-
|
|
477
|
+
### Load on approach, and cached pages
|
|
478
|
+
|
|
479
|
+
`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:
|
|
480
|
+
|
|
481
|
+
```tsx
|
|
482
|
+
import { Comments, stringsFor } from "@tdacorp/hyle-sdk/react";
|
|
483
|
+
|
|
484
|
+
<div className="hyle hyle-embed">
|
|
485
|
+
<Comments lazy path="/learn/computing-reading-time" endpoint="/api/hyle/engage" signInHref="/sign-in" locale="en" labels={stringsFor("en").comments} />
|
|
486
|
+
</div>
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
`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.
|
|
490
|
+
|
|
491
|
+
### Article reactions on their own
|
|
492
|
+
|
|
493
|
+
`HyleReactions` puts the article's reactions anywhere, for example under the title:
|
|
494
|
+
|
|
495
|
+
```tsx
|
|
496
|
+
import { HyleReactions } from "@tdacorp/hyle-sdk/react";
|
|
497
|
+
|
|
498
|
+
<HyleReactions path={publication.canonical_path} engagement={{ signInHref: "/sign-in" }} locale="en" />
|
|
499
|
+
```
|
|
500
|
+
|
|
501
|
+
`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.
|
|
502
|
+
|
|
503
|
+
### Comment notifications
|
|
504
|
+
|
|
505
|
+
Switch comment notifications on for the webhook endpoint in hyle, then give your revalidate route `onCommentEvent`:
|
|
506
|
+
|
|
507
|
+
```ts
|
|
508
|
+
export const { POST } = createRevalidateRoute({
|
|
509
|
+
workspaceId: process.env.HYLE_WORKSPACE_ID,
|
|
510
|
+
secrets: [process.env.HYLE_WEBHOOK_SECRET],
|
|
511
|
+
onCommentEvent: async (event) => {
|
|
512
|
+
// event.type: "comment.held" | "comment.reply" | "comment.approved" | "comment.hidden"
|
|
513
|
+
await queue.add("hyle-comment", event); // yours: enqueue, then send mail from a worker
|
|
514
|
+
},
|
|
515
|
+
});
|
|
516
|
+
```
|
|
517
|
+
|
|
518
|
+
- 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).
|
|
519
|
+
- **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.
|
|
520
|
+
- 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.
|
|
521
|
+
- `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
522
|
|
|
329
523
|
## Embeds
|
|
330
524
|
|
|
@@ -348,7 +542,7 @@ import { HyleArticle, HyleComments, HyleCommentsFallback, HyleList } from "@tdac
|
|
|
348
542
|
|
|
349
543
|
- `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
544
|
- `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
|
|
545
|
+
- `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
546
|
|
|
353
547
|
SEO rules the embeds follow, and one you must:
|
|
354
548
|
|
|
@@ -356,28 +550,48 @@ SEO rules the embeds follow, and one you must:
|
|
|
356
550
|
- Nothing in the document head: no `<title>`, `<link>`, `<meta>` or JSON-LD. Your page keeps its own metadata.
|
|
357
551
|
- **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
552
|
- 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
|
-
- Failure: an embed never calls `notFound()`, never redirects and never throws on a hyle outage. A missing page, a
|
|
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.
|
|
553
|
+
- Failure: an embed never calls `notFound()`, never redirects and never throws on a hyle outage. A missing page, a `cursor` hyle refuses 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.
|
|
554
|
+
- 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
555
|
|
|
362
556
|
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
557
|
|
|
364
558
|
## Mermaid diagrams
|
|
365
559
|
|
|
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.
|
|
560
|
+
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
561
|
|
|
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.
|
|
369
|
-
- Rendering: a diagram renders when it is within 200 px of the viewport, one at a time
|
|
370
|
-
- Themes:
|
|
371
|
-
-
|
|
562
|
+
- 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).
|
|
563
|
+
- 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.
|
|
564
|
+
- 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.
|
|
565
|
+
- Diagram colours from a Hyle theme: when a theme gives diagrams colours of their own (a `diagram-*` key, or a colour they follow: surface, surface-2, text, border, text-muted, accent), its stylesheet declares `--hyle-diagram-bg`, `-node`, `-node-text`, `-node-border`, `-line`, `-accent` and `-muted`, and the diagram is drawn with Mermaid's `base` theme in those colours, light or dark as above. All seven must be on the figure as `#rrggbb`, `#rrggbbaa` or `transparent` (you can declare them yourself without a theme); otherwise Mermaid's own themes apply. Contrast is the theme author's responsibility.
|
|
566
|
+
- Stored renders: when hyle has a pre-rendered image of the diagram in both themes (only the one it shows under a `light-only` or `dark-only` theme), drawn in the workspace theme's current diagram colours or, until the editor has stored those, in earlier ones (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
567
|
- 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
568
|
- 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
|
|
569
|
+
- 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.
|
|
570
|
+
|
|
571
|
+
### Large diagrams
|
|
572
|
+
|
|
573
|
+
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.
|
|
574
|
+
|
|
575
|
+
- 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.
|
|
576
|
+
- 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.
|
|
577
|
+
- 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.
|
|
578
|
+
- 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.
|
|
579
|
+
- 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).
|
|
580
|
+
|
|
581
|
+
### Printing
|
|
582
|
+
|
|
583
|
+
- 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.
|
|
584
|
+
- 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.
|
|
585
|
+
- 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.
|
|
586
|
+
- 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.
|
|
587
|
+
|
|
588
|
+
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
589
|
|
|
376
590
|
## Diagram viewer
|
|
377
591
|
|
|
378
|
-
Every Mermaid diagram
|
|
592
|
+
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
593
|
|
|
380
|
-
- Lazy: the viewer is its own chunk, fetched by the first click and never before
|
|
594
|
+
- 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
595
|
- 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
596
|
- 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
597
|
- 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 +625,13 @@ Import `@tdacorp/hyle-sdk/styles.css`. It is the design kit's stylesheet: every
|
|
|
411
625
|
:root { --hyle-accent: #ff8a3d; --hyle-radius: 12px; --hyle-font-heading: "Fraunces", serif; }
|
|
412
626
|
```
|
|
413
627
|
|
|
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.
|
|
628
|
+
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
629
|
|
|
416
630
|
## Customization
|
|
417
631
|
|
|
418
632
|
`components` replaces how a part is drawn, `slots` fills named places. Both are props of the pages and options of `hylePage`.
|
|
419
633
|
|
|
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
|
|
634
|
+
- 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
635
|
- 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
636
|
- 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
637
|
|
|
@@ -427,15 +641,16 @@ Chrome strings exist for en, fr and es (fr and es are unreviewed drafts). The pa
|
|
|
427
641
|
|
|
428
642
|
- 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
643
|
- 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`
|
|
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 (`
|
|
433
|
-
- The
|
|
434
|
-
-
|
|
644
|
+
- 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.
|
|
645
|
+
- 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'`.
|
|
646
|
+
- 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`).
|
|
647
|
+
- 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.
|
|
648
|
+
- 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.
|
|
649
|
+
- 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
650
|
|
|
436
651
|
## Not included
|
|
437
652
|
|
|
438
|
-
Docs versions
|
|
653
|
+
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
654
|
|
|
440
655
|
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
656
|
|
|
@@ -454,3 +669,7 @@ export async function generateMetadata(props: PageProps) {
|
|
|
454
669
|
## Contract
|
|
455
670
|
|
|
456
671
|
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.
|
|
672
|
+
|
|
673
|
+
## Identity machine tokens (`auth` instead of `token`)
|
|
674
|
+
|
|
675
|
+
`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.sync_host` for `syncHostReserved`). Page, asset and embed helpers still take `token`.
|