@tdacorp/hyle-sdk 0.21.0 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +110 -18
  2. package/dist/check-routes-bin.js +154 -42
  3. package/dist/{chunk-X2TLYM7Y.js → chunk-7T5EEJHK.js} +1 -1
  4. package/dist/chunk-DUPT6XLB.js +57 -0
  5. package/dist/{chunk-56Y24XBV.js → chunk-IW3TUD4G.js} +4 -3
  6. package/dist/{chunk-75JFLML4.js → chunk-KU7LWK4E.js} +75 -12
  7. package/dist/{chunk-K5VDLROQ.js → chunk-SFFBZFEN.js} +34 -1
  8. package/dist/{chunk-HJX57NLI.js → chunk-ZIW6FDU2.js} +246 -225
  9. package/dist/{client-LwzHwqpM.d.ts → client-BGjmEWhN.d.cts} +7 -1
  10. package/dist/{client-41fU6OY2.d.cts → client-D0LTpr3Y.d.ts} +7 -1
  11. package/dist/code-copy.cjs +4 -2
  12. package/dist/code-copy.d.cts +5 -2
  13. package/dist/code-copy.d.ts +5 -2
  14. package/dist/code-copy.js +5 -3
  15. package/dist/comments.cjs +11 -6
  16. package/dist/comments.js +11 -6
  17. package/dist/docs-enhance.cjs +7 -4
  18. package/dist/docs-enhance.d.cts +5 -3
  19. package/dist/docs-enhance.d.ts +5 -3
  20. package/dist/docs-enhance.js +8 -5
  21. package/dist/{embed-BUFRQboD.d.ts → embed-CbtsbZs3.d.cts} +4 -2
  22. package/dist/{embed-CYt-q13P.d.cts → embed-Cf_2ZR5x.d.ts} +4 -2
  23. package/dist/html.cjs +11 -6
  24. package/dist/html.d.cts +1 -1
  25. package/dist/html.d.ts +1 -1
  26. package/dist/html.js +2 -2
  27. package/dist/index.cjs +65 -12
  28. package/dist/index.d.cts +13 -11
  29. package/dist/index.d.ts +13 -11
  30. package/dist/index.js +2 -2
  31. package/dist/mermaid-diagram.cjs +46 -6
  32. package/dist/mermaid-diagram.js +15 -6
  33. package/dist/mermaid-image.cjs +4 -1
  34. package/dist/mermaid-image.js +1 -1
  35. package/dist/next.cjs +410 -241
  36. package/dist/next.d.cts +39 -17
  37. package/dist/next.d.ts +39 -17
  38. package/dist/next.js +116 -32
  39. package/dist/print-coordinator.js +1 -1
  40. package/dist/react.cjs +230 -197
  41. package/dist/react.d.cts +17 -6
  42. package/dist/react.d.ts +17 -6
  43. package/dist/react.js +5 -3
  44. package/dist/{resolve-eI1muCKL.d.cts → resolve-BnIv7aB7.d.cts} +1 -1
  45. package/dist/{resolve-BjAK0k_Y.d.ts → resolve-BysHtZ_i.d.ts} +1 -1
  46. package/dist/{sanitize-ijiWjEm9.d.cts → sanitize-BpY_AdZh.d.cts} +1 -1
  47. package/dist/{sanitize-ijiWjEm9.d.ts → sanitize-BpY_AdZh.d.ts} +1 -1
  48. package/dist/styles.css +4 -4
  49. package/dist/toc-spy.cjs +2 -1
  50. package/dist/toc-spy.js +2 -1
  51. package/dist/{types-3F0wqD-o.d.cts → types-D09Z072G.d.cts} +32 -1
  52. package/dist/{types-3F0wqD-o.d.ts → types-D09Z072G.d.ts} +32 -1
  53. package/dist/use-cache.cjs +53 -3
  54. package/dist/use-cache.d.cts +3 -3
  55. package/dist/use-cache.d.ts +3 -3
  56. package/dist/use-cache.js +3 -3
  57. package/package.json +3 -3
  58. package/dist/chunk-67IOIAVW.js +0 -35
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";
@@ -113,10 +113,10 @@ const html = hastToHtml(article.content.tree, { baseUrl: "https://example.com/bl
113
113
 
114
114
  | Import | Contents | Needs |
115
115
  |---|---|---|
116
- | `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve`, `mounts` and `asset`), `listPublicationPaths`, `checkRoutes` and the other route-check functions, `Cp1ClientError`, `verifyHyleSignature`, `parseSignatureHeader`, `isValidCacheTag`, `DeliveryDedupe`, `createRevalidationCallbackRoute`, `parseCommentEvent`, the result types | nothing (no framework) |
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
117
  | `@tdacorp/hyle-sdk/react` | `ArticlePage`, `Comments`, `HyleReactions`, `ListPage`, `HyleListView`, `HyleArticleView`, `DocsPage`, `NotFound`, `Redirecting`, `Unavailable`, `HyleBody`, `HyleToc`, `HastContent`, `TrustedServerHtml`, `sanitizeHast` | react >= 19 |
118
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`, `HyleList`, `HyleArticle`, `HyleComments`, `HyleCommentsFallback`, `fetchResolver`, `workspaceTags` | next >= 16 |
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 |
120
120
  | `@tdacorp/hyle-sdk/next/use-cache` | `cachedResolver` | next >= 16 with `cacheComponents: true` |
121
121
  | `@tdacorp/hyle-sdk/styles.css` | the stylesheet | |
122
122
 
@@ -159,7 +159,7 @@ The revalidate route expires tags immediately (`revalidateTag(tag, { expire: 0 }
159
159
 
160
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.
161
161
 
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), 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.
163
163
 
164
164
  ## Errors
165
165
 
@@ -167,11 +167,11 @@ How `hylePage` treats a hyle failure is chosen so a bad moment never replaces a
167
167
 
168
168
  | Failure | Behaviour |
169
169
  |---|---|
170
- | A 4xx rejection of the request (`VALIDATION_ERROR`, `NOT_FOUND`, any 4xx except 401, 403 and 429), a path over 1024 characters, a non-NFC segment | `notFound()` (a real 404; the last two never reach hyle) |
171
- | Network error, timeout, 5xx, 401, 403, 429, 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 |
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 |
172
172
  | `notFound()` and redirects | Next control flow, always propagated (`unstable_rethrow`) |
173
173
 
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: a 4xx rejection gives `{}`, anything else is rethrown, so a transient outage never caches a noindex page.
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.
175
175
 
176
176
  ### More in this section
177
177
 
@@ -222,9 +222,9 @@ Why a REQUIRED catch-all: an optional catch-all at the app root (`[[...hyle]]`)
222
222
  | Situation | Result |
223
223
  |---|---|
224
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) |
225
- | Mounts answer with a 4xx, or 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 transiently (network, timeout, 5xx, 429, 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 transiently 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 |
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 |
228
228
  | Root mount (`/`) and no usable copy | every unmatched URL errors until hyle is back (the root mount could own any of them) |
229
229
  | hyle is down | the host's own pages are unaffected: they never call hyle |
230
230
 
@@ -254,7 +254,7 @@ Run it as the last step of the PRODUCTION build (a `postbuild` script, or the bu
254
254
  | Variable | What |
255
255
  |---|---|
256
256
  | `HYLE_TARGET_BASE_URL`, `HYLE_TARGET_TOKEN` | already set for the site: finds the workspace through `mounts` (the read token only reads) |
257
- | `HYLE_CONTROL_TOKEN` | NEW: a control credential (`hyle_tc_...`) whose principal holds `hyle.workspace.manage` on that workspace. The read token cannot write and is refused before any request. Mint it in hyle under Workspace > Agents (a name like `site-sync`); while hyle authorizes through identity, also link that agent's principal to an identity service principal bound to `hyle.workspace.manage` only (`scripts/link-principal-identity.mjs`, as the Agents screen says), otherwise the write answers 404. Store it as a secret in the Production scope of the host only |
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 |
258
258
  | `HYLE_HOST_ID` | optional name for the audit trail; defaults to `VERCEL_PROJECT_PRODUCTION_URL`, or pass `--host` |
259
259
 
260
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.
@@ -265,6 +265,35 @@ What is sent: `PUT /cp1/control/workspace/host-reserved-paths` with `{ paths, ho
265
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.
266
266
  - `--json` adds a `sync` object. The programmatic form is `syncHostReserved({ baseUrl, token, workspaceId, paths, host, buildId })`.
267
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
+
268
297
  ### Limits
269
298
 
270
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.
@@ -281,7 +310,7 @@ What is sent: `PUT /cp1/control/workspace/host-reserved-paths` with `{ paths, ho
281
310
  Checklist for a site that mounts hyle at the root (details in the sections named):
282
311
 
283
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.
284
- - `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".
285
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.
286
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".
287
316
  - No parent layout or page above the mount may export `dynamicParams = false` (below).
@@ -330,16 +359,78 @@ hyle stores an image, video or audio reference as `/assets/<uuid>.<ext>`, a path
330
359
 
331
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).
332
361
 
333
- 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).
334
363
 
335
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>`).
336
365
 
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:
384
+
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
+
337
428
  ## Comments, votes and reactions
338
429
 
339
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.
340
431
 
341
432
  1. **hyle**: switch engagement on for the workspace and register the site's public key (below).
342
- 2. **A key pair.** `npx hyle-sdk-engage-keygen --out .env.engage` makes an Ed25519 pair: the private key goes to a new file (mode 0600, never overwritten) as `HYLE_ENGAGE_SIGNING_KEY=...`, and the PUBLIC key is printed only after that write succeeded, with a warning if git does not ignore the file. `--stdout` is the only mode that prints the private key; with no arguments the tool prints usage and nothing else. Register the public key in hyle. hyle never sees the private key. To rotate, register the new public key; the old one stays valid for 24 hours.
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.
343
434
  3. **The route file** `app/api/hyle/engage/[...path]/route.ts`:
344
435
 
345
436
  ```ts
@@ -363,7 +454,7 @@ export const { GET, POST, PATCH, PUT, DELETE } = createEngagementRoute({
363
454
 
364
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.
365
456
 
366
- What the route does, per request: it matches (method, path) against a fixed allowlist (`session`, `comments`, `comments/<uuid>`, `reactions`, `votes`), rebuilds the body with only the known keys (a comment is 1 to 4000 characters, a path is a canonical site path, a reaction `kind` is one of `like`, `love`, `insightful`, `celebrate`, a vote is `{ comment_id, value: 1 | -1 }`), accepts on the listing only `path`, `cursor` and `sort=new` or `sort=top`, each once, and calls hyle with the target credential. An anonymous read carries the bearer only. A signed-in reader's read also carries a separate Ed25519 read assertion (`scope: "read"`, 30 s, not single use) so hyle can add that reader's own state; a write carries a fresh single-use assertion (30 s) of the reader `getReader` returned; a missing or invalid reader is a bare 401 before hyle is called. The browser's cookies and `Authorization` are never forwarded. Writes must be same-origin (`Sec-Fetch-Site: same-origin` when sent, and an `Origin` equal to the request's host, with the scheme compared too when the proxy sends `X-Forwarded-Proto`), carry the header `x-hyle-engage: 1` and `application/json` (at most 20 KiB), otherwise 403/415/413. The host is taken from `X-Forwarded-Host`, else `Host`: behind a proxy that rewrites `Host` or terminates TLS without forwarding these headers, pass `allowedOrigins: ["https://www.example.com"]`, which replaces the derivation with an exact list (scheme, host and port). Every response is `Cache-Control: no-store`. Failures are mapped to a fixed set of codes with no text from hyle: hyle 404 stays 404 (a disabled workspace, a banned reader and a hidden comment look the same), 429 keeps a clamped `Retry-After`, a 409 is an edit after the 10 minute window, and everything else, including a 401 from hyle (a wrong key or credential, which a visitor must not learn), is a 502. The kill switch is `HYLE_ENGAGE_ENABLED` (and `HYLE_CONTENT_ENABLED`): unset, empty, `1` or `true` leave the route on, and ANY other non-empty value (`0`, `false`, `off`, `no`, a typo) answers 404 everywhere; a missing or malformed configuration also answers 404 and never throws at build time. Your proxy or middleware matcher must let `/api/hyle/engage` through, and the route sits under `/api/hyle/*`, which hyle's Reserved paths already cover (see "Collision checker": `--print-reserved` and `--sync` always list it).
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).
367
458
 
368
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).
369
460
 
@@ -459,7 +550,7 @@ SEO rules the embeds follow, and one you must:
459
550
  - Nothing in the document head: no `<title>`, `<link>`, `<meta>` or JSON-LD. Your page keeps its own metadata.
460
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).
461
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.
462
- - Failure: an embed never calls `notFound()`, never redirects and never throws on a hyle outage. A missing page, a request hyle rejects and an empty section render nothing (or the `list.empty` slot). Any other failure is logged by name and renders `onError(error)` if you gave one, else nothing. A missing `workspaceId`, a bad `baseUrl` or an empty `token` is a configuration error and throws.
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.
463
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.
464
555
 
465
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.
@@ -471,7 +562,8 @@ Zero setup. A Mermaid fence arrives from hyle as a sandboxed `<iframe srcdoc>` t
471
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).
472
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.
473
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.
474
- - Stored renders: when hyle has a pre-rendered image of the diagram in both themes (the editor renders it in the author's browser, hyle sanitizes and stores it, ADR 0024), the page gets a sized `<img>` (aspect ratio reserved, so no layout shift), the diagram source in a `<details>` for crawlers and no-JS readers, and no Mermaid layout runs in any browser. The image goes through your asset route (`createAssetRoute`, `img-src 'self'`). Click-to-expand fetches that same sanitized SVG for the viewer. Showing a stored render runs no layout, so it is never gated. If the image fails to load, or hyle has no stored render yet, the page renders the diagram client-side as above (a small one with a loader and a reserved height, a large one behind the Draw button).
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).
475
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.
476
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`).
477
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.
@@ -580,4 +672,4 @@ Types in `src/types.ts` mirror `packages/cp1-read/src/resolve.ts`. `src/__tests_
580
672
 
581
673
  ## Identity machine tokens (`auth` instead of `token`)
582
674
 
583
- `createHyleClient`, `syncHostReserved` and `cachedResolver` accept `auth` (a `HyleAuth`) instead of `token`, for a service account of identity (hyle ADR 0027, needs `HYLE_MACHINE_IDENTITY_TOKENS=dual` or `identity` on hyle). The hook is called for every request with `{ method, url }` and returns the headers to send, so the DPoP proof matches that request; with the identity SDK: `auth: (req) => serviceClient.headersFor(token, req)`. `workspaceId` is required and sent as `CP-Workspace`; the token needs `hyle.document.read` on it (`hyle.workspace.manage` for `syncHostReserved`). Page, asset and embed helpers still take `token`.
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`.
@@ -6,9 +6,15 @@ import { join } from "path";
6
6
  var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
7
7
  var ASSET_RESERVED_PATH = "/api/hyle/*";
8
8
  var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
9
- var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg";
9
+ var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg|woff2";
10
10
  var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
11
- var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
11
+ var THEME_FONT = new RegExp(`^/assets/${UUID}\\.woff2$`);
12
+ var PREVIEW_TOKEN_SOURCE = "hyle_pv_[A-Za-z0-9_-]{43}";
13
+ var PREVIEW_TOKEN = new RegExp(`^${PREVIEW_TOKEN_SOURCE}$`);
14
+ var PREVIEW_HEADER = "cp-preview";
15
+ var PREVIEW_PARAM = "hyle_preview";
16
+ var PREVIEW_QUERY_SOURCE = `\\?${PREVIEW_PARAM}=${PREVIEW_TOKEN_SOURCE}`;
17
+ var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)(${PREVIEW_QUERY_SOURCE})?$`, "i");
12
18
 
13
19
  // src/errors.ts
14
20
  var Cp1ClientError = class extends Error {
@@ -26,6 +32,30 @@ var Cp1ClientError = class extends Error {
26
32
  }
27
33
  };
28
34
 
35
+ // src/preview.ts
36
+ var ASSET_PATH = /^\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?:\.[a-z0-9]+)?(?= |$)/i;
37
+ var ASSET_PROPERTIES = ["src", "dataLight", "dataDark"];
38
+ var MAX_DEPTH = 200;
39
+ function mapNode(node, mark, depth) {
40
+ if (typeof node !== "object" || node === null || depth > MAX_DEPTH) return node;
41
+ const { properties, children } = node;
42
+ const marked = properties && Object.fromEntries(ASSET_PROPERTIES.filter((name) => name in properties).map((name) => [name, mark(properties[name])]));
43
+ return {
44
+ ...node,
45
+ ...properties ? { properties: { ...properties, ...marked } } : {},
46
+ ...Array.isArray(children) ? { children: children.map((child) => mapNode(child, mark, depth + 1)) } : {}
47
+ };
48
+ }
49
+ function withPreviewAssets(article, token) {
50
+ const mark = (value) => typeof value === "string" ? value.replace(ASSET_PATH, (path) => `${path}?${PREVIEW_PARAM}=${token}`) : value;
51
+ const { publication, content } = article;
52
+ return {
53
+ ...article,
54
+ publication: publication.cover ? { ...publication, cover: { path: String(mark(publication.cover.path)) } } : publication,
55
+ content: content.format === "hast" ? { ...content, tree: mapNode(content.tree, mark, 0) } : content
56
+ };
57
+ }
58
+
29
59
  // src/client.ts
30
60
  var RENDERER_VERSION = "4";
31
61
  function applyCredential(headers, credential, method, url) {
@@ -138,8 +168,20 @@ function createHyleClient(options) {
138
168
  if (data?.cp === 1 && data.kind === "push_posts" && Array.isArray(data.posts) && typeof data.complete === "boolean") return data;
139
169
  throw failure(reply);
140
170
  }
171
+ async function preview(token) {
172
+ if (typeof token !== "string" || !PREVIEW_TOKEN.test(token)) return { kind: "notfound" };
173
+ const reply = await get("/cp1/read/_preview", new URLSearchParams(), { headers: { [PREVIEW_HEADER]: token }, cache: "no-store" });
174
+ if (reply.status === 404 && reply.parsed?.error?.code === "NOT_FOUND") return { kind: "notfound" };
175
+ const data = reply.parsed?.data;
176
+ if (data?.cp === 1 && data.kind === "disabled") return { kind: "disabled" };
177
+ const article = data?.article;
178
+ if (data?.cp !== 1 || data.kind !== "preview" || typeof data.expires_at !== "string" || article?.kind !== "article" || article.content?.format !== "hast" || !article.publication) throw failure(reply);
179
+ return { kind: "preview", expires_at: data.expires_at, article: withPreviewAssets(article, token) };
180
+ }
141
181
  async function asset(file, opts = {}) {
142
182
  if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
183
+ const { previewToken } = opts;
184
+ if (previewToken !== void 0 && !PREVIEW_TOKEN.test(previewToken)) throw new TypeError("previewToken is not a preview token");
143
185
  const url = `${base}/cp1/read/assets/${file}`;
144
186
  const headers = new Headers();
145
187
  const applied = applyCredential(headers, options, "GET", url);
@@ -148,23 +190,30 @@ function createHyleClient(options) {
148
190
  const value = opts.headers?.[name];
149
191
  if (value) headers.set(name, value);
150
192
  }
193
+ if (previewToken !== void 0) headers.set(PREVIEW_HEADER, previewToken);
194
+ return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS), ...previewToken === void 0 ? {} : { cache: "no-store" } });
195
+ }
196
+ async function theme(opts = {}) {
197
+ const url = `${base}/cp1/read/theme.css`;
198
+ const headers = new Headers();
199
+ const applied = applyCredential(headers, options, "GET", url);
200
+ if (applied) await applied;
151
201
  return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
152
202
  }
153
- return { resolve, mounts, pushPosts, asset };
203
+ return { resolve, mounts, pushPosts, preview, asset, theme };
154
204
  }
155
205
 
156
206
  // src/host-sync.ts
157
207
  var CONTROL_TOKEN_PREFIX = "hyle_tc_";
158
208
  var DEFAULT_TIMEOUT_MS2 = 1e4;
159
209
  var MAX_RESPONSE_BYTES = 1024 * 1024;
160
- var PATH = "/cp1/control/workspace/host-reserved-paths";
161
- async function syncHostReserved(input) {
210
+ async function put(input, path, body, read) {
162
211
  checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
163
212
  if (input.token !== void 0 && !input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
164
213
  throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
165
214
  }
166
215
  const fetchImpl = input.fetch ?? fetch;
167
- const url = `${input.baseUrl.replace(/\/+$/, "")}${PATH}`;
216
+ const url = `${input.baseUrl.replace(/\/+$/, "")}${path}`;
168
217
  const headers = new Headers({ "content-type": "application/json", "idempotency-key": `sync-${crypto.randomUUID()}` });
169
218
  await applyCredential(headers, input.auth ? { auth: input.auth, workspaceId: input.workspaceId } : { token: input.token }, "PUT", url);
170
219
  headers.set("cp-workspace", input.workspaceId);
@@ -174,7 +223,7 @@ async function syncHostReserved(input) {
174
223
  redirect: "error",
175
224
  signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
176
225
  headers,
177
- body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
226
+ body: JSON.stringify(body)
178
227
  });
179
228
  const text = await readCapped(res, MAX_RESPONSE_BYTES);
180
229
  let parsed;
@@ -183,14 +232,24 @@ async function syncHostReserved(input) {
183
232
  } catch {
184
233
  parsed = void 0;
185
234
  }
186
- const data = parsed?.data;
187
- const conflicts = data?.conflicts;
188
- if (res.ok && data && Array.isArray(data.paths) && typeof data.changed === "boolean" && typeof data.synced_at === "string" && typeof conflicts?.total === "number" && Array.isArray(conflicts.offenders)) {
189
- return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
190
- }
235
+ const result = res.ok && parsed?.data ? read(parsed.data) : void 0;
236
+ if (result !== void 0) return result;
191
237
  const err = parsed?.error;
192
238
  throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
193
239
  }
240
+ function syncHostReserved(input) {
241
+ return put(input, "/cp1/control/workspace/host-reserved-paths", { paths: input.paths, host: input.host, build_id: input.buildId }, (data) => {
242
+ const conflicts = data.conflicts;
243
+ if (!Array.isArray(data.paths) || typeof data.changed !== "boolean" || typeof data.synced_at !== "string" || typeof conflicts?.total !== "number" || !Array.isArray(conflicts.offenders)) return void 0;
244
+ return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
245
+ });
246
+ }
247
+ function syncCodeTheme(input) {
248
+ return put(input, "/cp1/control/workspace/code-theme", { theme: input.theme, host: input.host, build_id: input.buildId }, ({ changed, cssChanged, hash, ignored }) => {
249
+ if (typeof changed !== "boolean" || typeof cssChanged !== "boolean" || hash !== null && typeof hash !== "string" || !Array.isArray(ignored)) return void 0;
250
+ return { changed, cssChanged, hash, ignored: ignored.map(String) };
251
+ });
252
+ }
194
253
 
195
254
  // src/next/paths.ts
196
255
  function normalizeBasePath(basePath) {
@@ -421,7 +480,7 @@ async function listPublicationPaths(options) {
421
480
 
422
481
  // src/check-routes-cli.ts
423
482
  var USAGE = `hyle-sdk-check-routes [--next-dir .next] [--base-url URL] [--json] [--print-reserved]
424
- [--sync [--strict] [--no-check] [--host ID] [--build-id ID] [--allow-empty] [--allow-non-production]]
483
+ [--sync [--theme] [--strict] [--no-check] [--host ID] [--build-id ID] [--allow-empty] [--allow-non-production]]
425
484
  [--locales en,fr,es --default-locale en --locale-prefix as-needed|always|never] [--hyle-param hyle]
426
485
 
427
486
  Run after \`next build\`. Reads the build's route manifests and hyle's read-only endpoints (mounts, and the published pages of each mount).
@@ -429,17 +488,20 @@ Credentials: HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN. The tok
429
488
  (a) hyle pages a host static route shadows, (b) host dynamic routes that match hyle URLs, (c) mounts that are host static routes.
430
489
  --print-reserved print the host's routes in hyle's "Reserved paths" format and exit.
431
490
  --sync report that list to hyle (ADR 0016) so nobody maintains it by hand, then run the check. Needs HYLE_CONTROL_TOKEN
432
- (a hyle_tc_ control credential with hyle.workspace.manage; the read token cannot write), read from the environment only.
491
+ (a hyle_tc_ control credential with hyle.workspace.sync_host; the read token cannot write), read from the environment only.
433
492
  A failed sync only warns, so it never fails a deploy, unless --strict (exit 3). Skipped on a non-production Vercel
434
493
  build (VERCEL_ENV) unless --allow-non-production. --no-check syncs without the collision check. The host id comes
435
494
  from --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL; the build id from <next-dir>/BUILD_ID or --build-id.
436
495
  An empty list is refused unless --allow-empty.
496
+ --theme with --sync: also send ./hyle.theme.json as the workspace's code theme (ADR 0036), with the same
497
+ credential and the same failure, preview and --strict rules. The file replaces the code theme.
437
498
  Exit: 0 no collision, 1 collision (a) or (c), 2 cannot run, 3 sync failed under --strict.`;
438
499
  var FLAGS = /* @__PURE__ */ new Set(["--next-dir", "--base-url", "--locales", "--default-locale", "--locale-prefix", "--hyle-param", "--host", "--build-id"]);
439
- var BOOLEAN = /* @__PURE__ */ new Set(["--json", "--print-reserved", "--help", "--sync", "--strict", "--no-check", "--allow-empty", "--allow-non-production"]);
500
+ var BOOLEAN = /* @__PURE__ */ new Set(["--json", "--print-reserved", "--help", "--sync", "--theme", "--strict", "--no-check", "--allow-empty", "--allow-non-production"]);
440
501
  var CANNOT_RUN = 2;
441
502
  var SYNC_FAILED = 3;
442
503
  var MAX_SYNCED_PATHS = 512;
504
+ var THEME_FILE = "hyle.theme.json";
443
505
  function parseArgs(argv) {
444
506
  const args = /* @__PURE__ */ new Map();
445
507
  for (let i = 0; i < argv.length; i++) {
@@ -452,35 +514,36 @@ function parseArgs(argv) {
452
514
  }
453
515
  var readJson = (file) => JSON.parse(readFileSync(file, "utf8"));
454
516
  var SAFE_ID = /[^A-Za-z0-9._-]/g;
455
- async function syncStep(args, io, ctx) {
456
- const fail = (reason) => (io.err(`sync: ${printable(reason)}`), { status: "failed", reason });
457
- const vercelEnv = io.env.VERCEL_ENV;
458
- if (vercelEnv !== void 0 && vercelEnv !== "production" && !args.has("--allow-non-production")) {
459
- io.err(`sync: skipped, this is a ${printable(vercelEnv)} build (a preview must not replace production's list; --allow-non-production overrides)`);
460
- return { status: "skipped" };
461
- }
462
- const { baseUrl, mounts } = ctx.plan;
517
+ function failed(io, step, reason) {
518
+ io.err(`${step}: ${printable(reason)}`);
519
+ return { status: "failed", reason };
520
+ }
521
+ var errorText = (error) => error instanceof Error ? `${error.name}: ${error.message}` : "unknown error";
522
+ function syncTarget(args, io, nextDir, { baseUrl, mounts, mountsError }) {
463
523
  const token = io.env.HYLE_CONTROL_TOKEN;
464
- if (!token) return fail("set HYLE_CONTROL_TOKEN (a hyle_tc_ control credential with hyle.workspace.manage; the read token cannot write)");
465
- if (!baseUrl || !mounts) return fail(ctx.plan.mountsError ?? "set HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN so the workspace can be found");
524
+ if (!token) return "set HYLE_CONTROL_TOKEN (a hyle_tc_ control credential with hyle.workspace.sync_host; the read token cannot write)";
525
+ if (!baseUrl || !mounts) return mountsError ?? "set HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN so the workspace can be found";
466
526
  const host = (args.get("--host") ?? io.env.HYLE_HOST_ID ?? io.env.VERCEL_PROJECT_PRODUCTION_URL)?.replace(SAFE_ID, "-").slice(0, 128);
467
- if (!host) return fail("name this host with --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL");
527
+ if (!host) return "name this host with --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL";
468
528
  let buildId = args.get("--build-id") ?? io.env.VERCEL_GIT_COMMIT_SHA;
469
529
  try {
470
- buildId = readFileSync(join(ctx.nextDir, "BUILD_ID"), "utf8").trim();
530
+ buildId = readFileSync(join(nextDir, "BUILD_ID"), "utf8").trim();
471
531
  } catch {
472
532
  }
473
533
  buildId = buildId?.replace(SAFE_ID, "-").slice(0, 128);
474
- if (!buildId) return fail("no build id: <next-dir>/BUILD_ID is missing; pass --build-id");
475
- const rootMount = mounts.prefixes.includes("/");
476
- const fromHost = reservedFor(ctx.hostRoutes, { ...ctx.locale ? { locale: ctx.locale } : {}, mounts: mounts.prefixes, hyleParam: ctx.hyleParam }).filter((p) => !(rootMount && p === "/"));
534
+ if (!buildId) return "no build id: <next-dir>/BUILD_ID is missing; pass --build-id";
535
+ return { baseUrl, token, workspaceId: mounts.workspaceId, host, buildId, ...io.fetch ? { fetch: io.fetch } : {} };
536
+ }
537
+ async function pathsStep(args, io, target, ctx) {
538
+ const rootMount = ctx.prefixes.includes("/");
539
+ const fromHost = reservedFor(ctx.hostRoutes, { ...ctx.locale ? { locale: ctx.locale } : {}, mounts: ctx.prefixes, hyleParam: ctx.hyleParam }).filter((p) => !(rootMount && p === "/"));
477
540
  const reserved = [.../* @__PURE__ */ new Set([...fromHost, ...SDK_OWN_RESERVED])].sort();
478
- if (fromHost.length === 0 && !args.has("--allow-empty")) return fail("the build has no reservable routes; refusing to replace hyle's list with an empty one (--allow-empty overrides)");
479
- if (reserved.length > MAX_SYNCED_PATHS) return fail(`${reserved.length} reserved paths exceed hyle's limit of ${MAX_SYNCED_PATHS}`);
541
+ if (fromHost.length === 0 && !args.has("--allow-empty")) return failed(io, "sync", "the build has no reservable routes; refusing to replace hyle's list with an empty one (--allow-empty overrides)");
542
+ if (reserved.length > MAX_SYNCED_PATHS) return failed(io, "sync", `${reserved.length} reserved paths exceed hyle's limit of ${MAX_SYNCED_PATHS}`);
480
543
  try {
481
- const result = await syncHostReserved({ baseUrl, token, workspaceId: mounts.workspaceId, paths: reserved, host, buildId, ...io.fetch ? { fetch: io.fetch } : {} });
544
+ const result = await syncHostReserved({ ...target, paths: reserved });
482
545
  if (!args.has("--json")) {
483
- io.out(`sync: ${result.paths.length} reserved paths ${result.changed ? "updated" : "unchanged"} in hyle (host ${printable(host)}, build ${printable(buildId)})`);
546
+ io.out(`sync: ${result.paths.length} reserved paths ${result.changed ? "updated" : "unchanged"} in hyle (host ${printable(target.host)}, build ${printable(target.buildId)})`);
484
547
  if (result.conflicts.total > 0) {
485
548
  io.out(`sync: ${result.conflicts.total} published hyle URL(s) are on paths this host owns (hyle unpublished nothing):`);
486
549
  for (const path of result.conflicts.offenders) io.out(` ${printable(path)}`);
@@ -488,13 +551,62 @@ async function syncStep(args, io, ctx) {
488
551
  }
489
552
  return { status: "ok", result };
490
553
  } catch (error) {
491
- return fail(error instanceof Error ? `${error.name}: ${error.message}` : "unknown error");
554
+ return failed(io, "sync", errorText(error));
555
+ }
556
+ }
557
+ function refusalLines(error) {
558
+ const details = error instanceof Cp1ClientError ? error.details : void 0;
559
+ if (details?.reason !== "theme_refused" || typeof details.keys !== "string") return void 0;
560
+ const messages = typeof details.messages === "string" ? details.messages.split("\n") : [];
561
+ return details.keys.split("\n").map((key, i) => ` ${printable(key) || "(the file)"}: ${printable(messages[i] ?? "not accepted")}`);
562
+ }
563
+ async function themeStep(args, io, target) {
564
+ const dir = io.cwd ?? process.cwd();
565
+ let text;
566
+ try {
567
+ text = readFileSync(join(dir, THEME_FILE), "utf8");
568
+ } catch {
569
+ return failed(io, "theme", `no ${THEME_FILE} in ${dir} (or it cannot be read); run this where the file is`);
570
+ }
571
+ let theme;
572
+ try {
573
+ theme = JSON.parse(text);
574
+ } catch (error) {
575
+ return failed(io, "theme", `${THEME_FILE} is not valid JSON: ${error instanceof Error ? error.message : "unknown error"}`);
576
+ }
577
+ try {
578
+ const result = await syncCodeTheme({ ...target, theme });
579
+ if (result.ignored.length > 0) io.err(`theme: hyle ignored unknown keys: ${printable(result.ignored.join(", "))}`);
580
+ if (!args.has("--json")) io.out(`theme: ${THEME_FILE} synced, the stylesheet ${result.cssChanged ? "changed" : "is unchanged"} (host ${printable(target.host)}, build ${printable(target.buildId)})`);
581
+ return { status: "ok", result };
582
+ } catch (error) {
583
+ const lines = refusalLines(error);
584
+ if (lines) {
585
+ const reason = `hyle refused ${THEME_FILE}, so the theme was not changed:`;
586
+ io.err([`theme: ${reason}`, ...lines].join("\n"));
587
+ return { status: "failed", reason: [reason, ...lines].join("\n") };
588
+ }
589
+ const hint = error instanceof Cp1ClientError && error.status === 404 ? " (does the credential hold hyle.workspace.sync_host on this workspace, and does this hyle have themes?)" : "";
590
+ return failed(io, "theme", `${errorText(error)}${hint}`);
591
+ }
592
+ }
593
+ async function syncSteps(args, io, ctx) {
594
+ const wantsTheme = args.has("--theme");
595
+ const vercelEnv = io.env.VERCEL_ENV;
596
+ if (vercelEnv !== void 0 && vercelEnv !== "production" && !args.has("--allow-non-production")) {
597
+ io.err(`sync: skipped, this is a ${printable(vercelEnv)} build (a preview must not replace what production synced; --allow-non-production overrides)`);
598
+ return { sync: { status: "skipped" }, ...wantsTheme ? { theme: { status: "skipped" } } : {} };
492
599
  }
600
+ const target = syncTarget(args, io, ctx.nextDir, ctx.plan);
601
+ if (typeof target === "string") return { sync: failed(io, "sync", target), ...wantsTheme ? { theme: failed(io, "theme", target) } : {} };
602
+ const sync = await pathsStep(args, io, target, ctx);
603
+ return { sync, ...wantsTheme ? { theme: await themeStep(args, io, target) } : {} };
493
604
  }
494
605
  async function runCli(argv, io) {
495
606
  try {
496
607
  const args = parseArgs(argv);
497
608
  if (args.has("--help")) return io.out(USAGE), 0;
609
+ if (args.has("--theme") && !args.has("--sync")) throw new Error("--theme needs --sync");
498
610
  const nextDir = args.get("--next-dir") ?? ".next";
499
611
  const hyleParam = args.get("--hyle-param") ?? "hyle";
500
612
  let locale;
@@ -536,12 +648,13 @@ async function runCli(argv, io) {
536
648
  }
537
649
  const prefixes = mounts?.mounts.map((m) => m.prefix);
538
650
  const strict = args.has("--strict");
539
- let sync;
651
+ let synced;
652
+ const exitAfterSync = () => strict && (synced?.sync.status === "failed" || synced?.theme?.status === "failed") ? SYNC_FAILED : 0;
540
653
  if (args.has("--sync")) {
541
- sync = await syncStep(args, io, { nextDir, hostRoutes, locale, hyleParam, plan: { baseUrl, mounts: mounts?.kind === "mounts" && prefixes ? { workspaceId: mounts.workspace_id, prefixes } : void 0, ...mountsError instanceof Error ? { mountsError: `${mountsError.name}: ${mountsError.message}` } : {} } });
654
+ synced = await syncSteps(args, io, { nextDir, hostRoutes, locale, hyleParam, prefixes: prefixes ?? [], plan: { baseUrl, mounts: mounts?.kind === "mounts" ? { workspaceId: mounts.workspace_id } : void 0, ...mountsError instanceof Error ? { mountsError: errorText(mountsError) } : {} } });
542
655
  if (args.has("--no-check")) {
543
- if (args.has("--json")) io.out(JSON.stringify({ sync }));
544
- return sync.status === "failed" && strict ? SYNC_FAILED : 0;
656
+ if (args.has("--json")) io.out(JSON.stringify(synced));
657
+ return exitAfterSync();
545
658
  }
546
659
  }
547
660
  if (args.has("--print-reserved")) {
@@ -567,9 +680,8 @@ async function runCli(argv, io) {
567
680
  }
568
681
  }
569
682
  const report = checkRoutes({ hostRoutes, mounts: mounts.mounts.map((m) => m.prefix), hylePaths: [...hylePaths], hyleParam, ...locale ? { locale } : {} });
570
- io.out(args.has("--json") ? JSON.stringify(sync ? { ...report, sync } : report, null, 2) : formatReport(report));
571
- if (!report.ok) return 1;
572
- return sync?.status === "failed" && strict ? SYNC_FAILED : 0;
683
+ io.out(args.has("--json") ? JSON.stringify({ ...report, ...synced }, null, 2) : formatReport(report));
684
+ return report.ok ? exitAfterSync() : 1;
573
685
  } catch (error) {
574
686
  io.err(`CANNOT RUN: ${error instanceof Error ? printable(`${error.name}: ${error.message}`) : "unknown error"}`);
575
687
  return CANNOT_RUN;