@tdacorp/hyle-sdk 0.5.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -8
- package/dist/check-routes-bin.js +168 -19
- package/dist/{chunk-4OB77ZOD.js → chunk-54JF4E53.js} +93 -11
- package/dist/chunk-67IOIAVW.js +35 -0
- package/dist/{chunk-SO6H2UGL.js → chunk-6LW33475.js} +110 -66
- package/dist/{chunk-OW6S7IZX.js → chunk-XKR74Y5G.js} +3 -2
- package/dist/docs-enhance.cjs +97 -0
- package/dist/docs-enhance.d.cts +16 -0
- package/dist/docs-enhance.d.ts +16 -0
- package/dist/docs-enhance.js +73 -0
- package/dist/index.cjs +97 -11
- package/dist/index.d.cts +61 -7
- package/dist/index.d.ts +61 -7
- package/dist/index.js +6 -1
- package/dist/next.cjs +211 -56
- package/dist/next.d.cts +47 -5
- package/dist/next.d.ts +47 -5
- package/dist/next.js +84 -5
- package/dist/react.cjs +118 -65
- package/dist/react.d.cts +35 -32
- package/dist/react.d.ts +35 -32
- package/dist/react.js +2 -1
- package/dist/{resolve-1rQntRBh.d.ts → resolve-D2rnnho9.d.cts} +2 -2
- package/dist/{resolve-36-Ng1H0.d.cts → resolve-Dpb6Orsj.d.ts} +2 -2
- package/dist/styles.css +32 -21
- package/dist/{types-DnPzhrFx.d.cts → types-BPPZrYOZ.d.cts} +1 -1
- package/dist/{types-BoyBWF2F.d.ts → types-C1eCQ2As.d.ts} +1 -1
- package/dist/{types-CwBCPh6K.d.cts → types-CHxH5E0S.d.cts} +15 -1
- package/dist/{types-CwBCPh6K.d.ts → types-CHxH5E0S.d.ts} +15 -1
- package/dist/use-cache.cjs +26 -7
- package/dist/use-cache.d.cts +2 -2
- package/dist/use-cache.d.ts +2 -2
- package/dist/use-cache.js +6 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -43,15 +43,22 @@ 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
|
-
|
|
46
|
+
`app/api/hyle/assets/[file]/route.ts` (images, video and audio in hyle content; see "Media"):
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { createAssetRoute } from "@tdacorp/hyle-sdk/next";
|
|
50
|
+
export const { GET, HEAD } = createAssetRoute({ baseUrl: process.env.HYLE_TARGET_BASE_URL, token: process.env.HYLE_TARGET_TOKEN });
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Register the revalidate URL as the workspace's webhook endpoint in hyle. Set `metadataBase` in your root layout so canonical and hreflang URLs are absolute.
|
|
47
54
|
|
|
48
55
|
## Entry points
|
|
49
56
|
|
|
50
57
|
| Import | Contents | Needs |
|
|
51
58
|
|---|---|---|
|
|
52
|
-
| `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve` and `
|
|
59
|
+
| `@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) |
|
|
53
60
|
| `@tdacorp/hyle-sdk/react` | `ArticlePage`, `ListPage`, `DocsPage`, `NotFound`, `Redirecting`, `Unavailable`, `HastContent`, `TrustedServerHtml`, `sanitizeHast` | react >= 19 |
|
|
54
|
-
| `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createRevalidateRoute`, `fetchResolver`, `workspaceTags` | next >= 16 |
|
|
61
|
+
| `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createRevalidateRoute`, `createAssetRoute`, `fetchResolver`, `workspaceTags` | next >= 16 |
|
|
55
62
|
| `@tdacorp/hyle-sdk/next/use-cache` | `cachedResolver` | next >= 16 with `cacheComponents: true` |
|
|
56
63
|
| `@tdacorp/hyle-sdk/styles.css` | the stylesheet | |
|
|
57
64
|
|
|
@@ -163,19 +170,43 @@ The last good copy is in process memory, keyed by hyle origin plus workspace id
|
|
|
163
170
|
|
|
164
171
|
### Adopting it on a Next 16 + next-intl site
|
|
165
172
|
|
|
166
|
-
1.
|
|
173
|
+
1. Add the reserved-paths sync to your production build (see "Syncing reserved paths" below); nothing is pasted into hyle by hand. `--print-reserved` still prints what would be sent.
|
|
167
174
|
2. Replace `app/[locale]/[...rest]/page.tsx` (the `notFound()` catch-all) with `app/[locale]/(site)/[...hyle]/page.tsx`, put it under the layout group that carries the site chrome, and keep your `not-found.tsx` in that group: a 404 from the catch-all then renders inside the chrome. Pass `locale: (p) => String(p.locale)` and `localePrefix` as for `hylePage`.
|
|
168
175
|
3. Keep `dynamicParams` true (see Host requirements). Keep the proxy matcher as is.
|
|
169
176
|
4. Add `hyleRootSitemap` to `app/sitemap.ts`, run the checker (below), deploy.
|
|
170
177
|
|
|
171
178
|
### Collision checker
|
|
172
179
|
|
|
173
|
-
`hyle-sdk-check-routes` (bin of this package) reads `.next/routes-manifest.json` and `.next/server/app-paths-manifest.json` of a finished `next build`, and hyle's `mounts` plus the published pages of each mount (read-only; `HYLE_TARGET_BASE_URL` or `--base-url`, and `HYLE_TARGET_TOKEN` from the environment only). It reports (a) hyle pages shadowed by a host static route, (b) host dynamic routes that match hyle URLs, with a verdict from route specificity (`[x]` before `[...x]` before `[[...x]]`; the hyle catch-all itself is fine), (c) mounts whose prefix is a host static route. Exit 1 on (a) or (c), 0 otherwise, 2 when it cannot run (no build, no credentials, hyle unreachable or the listing incomplete). `--json` prints the report; `--print-reserved` prints the host's
|
|
180
|
+
`hyle-sdk-check-routes` (bin of this package) reads `.next/routes-manifest.json` and `.next/server/app-paths-manifest.json` of a finished `next build`, and hyle's `mounts` plus the published pages of each mount (read-only; `HYLE_TARGET_BASE_URL` or `--base-url`, and `HYLE_TARGET_TOKEN` from the environment only). It reports (a) hyle pages shadowed by a host static route, (b) host dynamic routes that match hyle URLs, with a verdict from route specificity (`[x]` before `[...x]` before `[[...x]]`; the hyle catch-all itself is fine), (c) mounts whose prefix is a host static route. Exit 1 on (a) or (c), 0 otherwise, 2 when it cannot run (no build, no credentials, hyle unreachable or the listing incomplete). `--json` prints the report; `--print-reserved` prints the host's routes in hyle's Reserved paths format (see "Syncing reserved paths" for the derivation). `--locales`, `--default-locale` and `--locale-prefix as-needed|always|never` expand a leading `[locale]` segment (next-intl). `--sections a,b` lists extra sections; `--hyle-param` names the catch-all param. A root mount over the host's home page is a note, not a failure. In CI, run it after `next build` as a required step. The same functions are exported from `@tdacorp/hyle-sdk` (`hostRoutesFromManifests`, `checkRoutes`, `reservedFor`, `formatReport`).
|
|
181
|
+
|
|
182
|
+
### Syncing reserved paths
|
|
183
|
+
|
|
184
|
+
Reserved paths are the URLs your app owns, which hyle refuses to publish onto. They are derived from your build and sent to hyle, so nobody maintains them in hyle's UI:
|
|
185
|
+
|
|
186
|
+
```
|
|
187
|
+
hyle-sdk-check-routes --sync --no-check --locales en,fr,es --default-locale en --locale-prefix as-needed
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Run it as the last step of the PRODUCTION build (a `postbuild` script, or the build command after `next build`). It needs, from the environment only:
|
|
191
|
+
|
|
192
|
+
| Variable | What |
|
|
193
|
+
|---|---|
|
|
194
|
+
| `HYLE_TARGET_BASE_URL`, `HYLE_TARGET_TOKEN` | already set for the site: finds the workspace through `mounts` (the read token only reads) |
|
|
195
|
+
| `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 |
|
|
196
|
+
| `HYLE_HOST_ID` | optional name for the audit trail; defaults to `VERCEL_PROJECT_PRODUCTION_URL`, or pass `--host` |
|
|
197
|
+
|
|
198
|
+
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.
|
|
199
|
+
|
|
200
|
+
- **Never fails your deploy.** A failed sync (hyle down, wrong token, not granted) prints a `sync:` warning and exits 0. Add `--strict` to exit 3 instead. Without `--no-check` the collision check also runs and keeps its own exit codes (1 collision, 2 cannot run).
|
|
201
|
+
- **Production only.** When `VERCEL_ENV` is set and is not `production` the sync is skipped, so a preview cannot replace production's list (`--allow-non-production` overrides). Elsewhere, only run it in production builds.
|
|
202
|
+
- **Idempotent.** The same list changes nothing in hyle (`unchanged`). An empty list is refused (`--allow-empty` overrides) so a broken manifest read cannot erase the reservations.
|
|
203
|
+
- **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.
|
|
204
|
+
- `--json` adds a `sync` object. The programmatic form is `syncHostReserved({ baseUrl, token, workspaceId, paths, host, buildId })`.
|
|
174
205
|
|
|
175
206
|
### Limits
|
|
176
207
|
|
|
177
208
|
- 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.
|
|
178
|
-
- The checker sees the published default-locale pages of each mount (at most 10,000 per mount) and host routes known to the build; routes that only a proxy rewrite creates, or translated pathnames, are invisible to it, so list those in Reserved paths by hand.
|
|
209
|
+
- The checker sees the published default-locale pages of each mount (at most 10,000 per mount) and host routes known to the build; routes that only a proxy rewrite creates, or translated pathnames, are invisible to it, so list those in the workspace's own Reserved paths by hand (that list is separate from the synced one and is never overwritten by a sync).
|
|
179
210
|
- Matching uses the mounts of the last successful read: a new mount is served after the mounts revalidate window (default 300 s) or a workspace-tag purge.
|
|
180
211
|
- A reserved or mounted URL can only be reached if no host route matches it first; that is the intended precedence.
|
|
181
212
|
|
|
@@ -193,6 +224,16 @@ Verify after `next build`: `.next/prerender-manifest.json` must not show `"fallb
|
|
|
193
224
|
|
|
194
225
|
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.
|
|
195
226
|
|
|
227
|
+
## Media
|
|
228
|
+
|
|
229
|
+
hyle stores an image, video or audio reference as `/assets/<uuid>.<ext>`, a path that exists only on hyle's own (authenticated) origin. On a host site it would 404, so the SDK rewrites it while rendering (`HastContent`, so every page component, and the `format: "html"` escape hatch) to `/api/hyle/assets/<uuid>.<ext>` on the host's own origin. That path is answered by the one route file in the quickstart, `app/api/hyle/assets/[file]/route.ts`; nothing else is needed per site, and a strict CSP such as `img-src 'self' data:` (and `media-src` left at `default-src 'self'`) works unchanged. The `Image` slot receives the rewritten `src`, so a `next/image` slot also works; the default is a plain `<img loading="lazy">`.
|
|
230
|
+
|
|
231
|
+
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).
|
|
232
|
+
|
|
233
|
+
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).
|
|
234
|
+
|
|
235
|
+
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>`).
|
|
236
|
+
|
|
196
237
|
## Mermaid diagrams
|
|
197
238
|
|
|
198
239
|
Zero setup. A Mermaid fence arrives from hyle as a sandboxed `<iframe srcdoc>` that loads a script from cdnjs, and a `srcdoc` frame inherits the host page's CSP, so a host with `script-src 'self'` would show a blank box. The SDK therefore reads the diagram text out of that document (only after it matched hyle's exact template) and renders it in your page with the Mermaid library it bundles as a dependency (`mermaid` `~11.9.0`, MIT). No cdnjs, no extra package, no config.
|
|
@@ -250,7 +291,7 @@ The 52 variables are listed in the token block at the top of `styles.css`. Layou
|
|
|
250
291
|
|
|
251
292
|
- Component slots: `Link` (every internal link, breadcrumb and in-page link: pass your router's Link), `Image`, `CodeBlock` (receives `code`, `language`, and the default `children`; the stock block has no copy button because that needs client JavaScript), `Mermaid` (receives hyle's sandboxed `srcDoc` and the extracted `source`; the default renders the diagram in the page, see "Mermaid diagrams"), `Callout` (GFM alerts such as `> [!NOTE]`). The raw element overrides `a`, `img`, `code`, `pre`, `table`, `blockquote` and `h1` to `h6` also work.
|
|
252
293
|
- 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.
|
|
253
|
-
- Layout: `layout: "docs"` renders articles as `DocsPage
|
|
294
|
+
- 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.
|
|
254
295
|
|
|
255
296
|
Chrome strings exist for en, fr and es (fr and es are unreviewed drafts). The page title is the only `h1`: a body `h1` becomes `h2`, and a leading body `h1` that repeats the title is dropped.
|
|
256
297
|
|
|
@@ -265,7 +306,7 @@ Chrome strings exist for en, fr and es (fr and es are unreviewed drafts). The pa
|
|
|
265
306
|
|
|
266
307
|
## Not included
|
|
267
308
|
|
|
268
|
-
Docs versions, reading time,
|
|
309
|
+
Docs versions, reading time, "closest matches" on the 404 page and a copy-code button: hyle does not provide that data or the page would need client JavaScript. Image URLs in content such as `/assets/<id>` are no longer passed through unchanged: see "Media".
|
|
269
310
|
|
|
270
311
|
## Contract
|
|
271
312
|
|
package/dist/check-routes-bin.js
CHANGED
|
@@ -2,6 +2,14 @@
|
|
|
2
2
|
import { readFileSync } from "fs";
|
|
3
3
|
import { join } from "path";
|
|
4
4
|
|
|
5
|
+
// src/asset-path.ts
|
|
6
|
+
var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
|
|
7
|
+
var ASSET_RESERVED_PATH = "/api/hyle/*";
|
|
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";
|
|
10
|
+
var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
|
|
11
|
+
var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
|
|
12
|
+
|
|
5
13
|
// src/errors.ts
|
|
6
14
|
var Cp1ClientError = class extends Error {
|
|
7
15
|
code;
|
|
@@ -47,16 +55,19 @@ function isMounts(data) {
|
|
|
47
55
|
const mounts = data.mounts;
|
|
48
56
|
return typeof data.workspace_id === "string" && isStrings(data.reserved) && isStrings(data.supported_locales) && Array.isArray(mounts) && mounts.every((m) => typeof m?.prefix === "string" && typeof m.default_section === "string");
|
|
49
57
|
}
|
|
50
|
-
function
|
|
58
|
+
function checkBaseUrl(baseUrl, allowInsecureHttp) {
|
|
51
59
|
let origin;
|
|
52
60
|
try {
|
|
53
|
-
origin = new URL(
|
|
61
|
+
origin = new URL(baseUrl);
|
|
54
62
|
} catch {
|
|
55
63
|
throw new TypeError("baseUrl must be an https origin");
|
|
56
64
|
}
|
|
57
|
-
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (
|
|
65
|
+
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
|
|
58
66
|
throw new TypeError("baseUrl must be https (http is allowed only for localhost, or with allowInsecureHttp)");
|
|
59
67
|
}
|
|
68
|
+
}
|
|
69
|
+
function createHyleClient(options) {
|
|
70
|
+
checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
|
|
60
71
|
if (!options.token) throw new TypeError("token is required");
|
|
61
72
|
const base = options.baseUrl.replace(/\/+$/, "");
|
|
62
73
|
const fetchImpl = options.fetch ?? fetch;
|
|
@@ -85,6 +96,7 @@ function createHyleClient(options) {
|
|
|
85
96
|
const query = new URLSearchParams({ path: opts.path });
|
|
86
97
|
if (opts.locale !== void 0) query.set("locale", opts.locale);
|
|
87
98
|
if (opts.format !== void 0) query.set("format", opts.format);
|
|
99
|
+
if (opts.nav !== void 0) query.set("nav", opts.nav);
|
|
88
100
|
if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
|
|
89
101
|
if (opts.limit !== void 0) query.set("limit", String(opts.limit));
|
|
90
102
|
const reply = await get("/cp1/read/resolve", query, opts.init);
|
|
@@ -99,7 +111,56 @@ function createHyleClient(options) {
|
|
|
99
111
|
if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
|
|
100
112
|
throw failure(reply);
|
|
101
113
|
}
|
|
102
|
-
|
|
114
|
+
async function asset(file, opts = {}) {
|
|
115
|
+
if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
|
|
116
|
+
const headers = new Headers({ authorization: `Bearer ${options.token}` });
|
|
117
|
+
for (const name of ["range", "if-range", "if-none-match"]) {
|
|
118
|
+
const value = opts.headers?.[name];
|
|
119
|
+
if (value) headers.set(name, value);
|
|
120
|
+
}
|
|
121
|
+
return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
|
|
122
|
+
}
|
|
123
|
+
return { resolve, mounts, asset };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// src/host-sync.ts
|
|
127
|
+
var CONTROL_TOKEN_PREFIX = "hyle_tc_";
|
|
128
|
+
var DEFAULT_TIMEOUT_MS2 = 1e4;
|
|
129
|
+
var MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
130
|
+
var PATH = "/cp1/control/workspace/host-reserved-paths";
|
|
131
|
+
async function syncHostReserved(input) {
|
|
132
|
+
checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
|
|
133
|
+
if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
|
|
134
|
+
throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
|
|
135
|
+
}
|
|
136
|
+
const fetchImpl = input.fetch ?? fetch;
|
|
137
|
+
const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
|
|
138
|
+
method: "PUT",
|
|
139
|
+
// redirect "error": the bearer token must never follow a redirect to another host.
|
|
140
|
+
redirect: "error",
|
|
141
|
+
signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
|
|
142
|
+
headers: {
|
|
143
|
+
authorization: `Bearer ${input.token}`,
|
|
144
|
+
"content-type": "application/json",
|
|
145
|
+
"cp-workspace": input.workspaceId,
|
|
146
|
+
"idempotency-key": `sync-${crypto.randomUUID()}`
|
|
147
|
+
},
|
|
148
|
+
body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
|
|
149
|
+
});
|
|
150
|
+
const text = await readCapped(res, MAX_RESPONSE_BYTES);
|
|
151
|
+
let parsed;
|
|
152
|
+
try {
|
|
153
|
+
parsed = JSON.parse(text);
|
|
154
|
+
} catch {
|
|
155
|
+
parsed = void 0;
|
|
156
|
+
}
|
|
157
|
+
const data = parsed?.data;
|
|
158
|
+
const conflicts = data?.conflicts;
|
|
159
|
+
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)) {
|
|
160
|
+
return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
|
|
161
|
+
}
|
|
162
|
+
const err = parsed?.error;
|
|
163
|
+
throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
|
|
103
164
|
}
|
|
104
165
|
|
|
105
166
|
// src/next/paths.ts
|
|
@@ -205,29 +266,50 @@ function checkRoutes(input) {
|
|
|
205
266
|
const shown = hostWins.length > 0 ? hostWins : matched;
|
|
206
267
|
dynamicOverlaps.push({ route, verdict: hostWins.length > 0 ? "host-wins" : "hyle-wins", matches: shown.length, examples: shown.slice(0, MAX_EXAMPLES) });
|
|
207
268
|
}
|
|
269
|
+
if (!routes.some((r) => r.startsWith(`${ASSET_ROUTE_PREFIX}/`))) {
|
|
270
|
+
notes.push(`no asset route (${ASSET_ROUTE_PREFIX}/[file], createAssetRoute) was found in the host routes: images, video and audio in hyle content will 404`);
|
|
271
|
+
}
|
|
208
272
|
if (catchAlls.length === 0) notes.push(`no hyle catch-all route (a "[...${hyleParam}]" or "[[...${hyleParam}]]" page) was found in the host routes`);
|
|
209
273
|
return { shadowedHylePaths, mountCollisions, dynamicOverlaps, notes, ok: shadowedHylePaths.length === 0 && mountCollisions.length === 0 };
|
|
210
274
|
}
|
|
275
|
+
var SDK_OWN_RESERVED = [ASSET_RESERVED_PATH];
|
|
276
|
+
var HASHED_METADATA_ROUTE = /^(opengraph-image|twitter-image|icon|apple-icon)-[a-z0-9]{5,8}$/;
|
|
277
|
+
var isHashedMetadataRoute = (route) => HASHED_METADATA_ROUTE.test(segmentsOf(route).at(-1) ?? "");
|
|
278
|
+
var covers = (entry, path) => {
|
|
279
|
+
if (!entry.endsWith("/*")) return entry === path;
|
|
280
|
+
const base = entry.slice(0, -2);
|
|
281
|
+
return path === base || path.startsWith(`${base}/`);
|
|
282
|
+
};
|
|
211
283
|
function reservedFor(hostRoutes, options = {}) {
|
|
212
284
|
const dropLocale = (route) => {
|
|
213
285
|
const [first, ...rest] = segmentsOf(route);
|
|
214
286
|
return options.locale && first === `[${LOCALE_PARAM}]` ? `/${rest.join("/")}` : route;
|
|
215
287
|
};
|
|
216
|
-
const
|
|
288
|
+
const hyleParam = options.hyleParam ?? "hyle";
|
|
289
|
+
const routes = hostRoutes.map(dropLocale).filter((r) => !isHashedMetadataRoute(r));
|
|
290
|
+
const exact = new Set(routes.filter((r) => !isDynamic(r)));
|
|
217
291
|
const mounts = options.mounts?.filter((m) => m !== "/");
|
|
292
|
+
const onMount = (segment) => mounts?.some((m) => m === `/${segment}` || m.startsWith(`/${segment}/`)) ?? true;
|
|
218
293
|
const groups = /* @__PURE__ */ new Map();
|
|
219
294
|
for (const route of exact) {
|
|
220
295
|
const [first, ...rest] = segmentsOf(route);
|
|
221
296
|
if (first !== void 0 && rest.length > 0) groups.set(first, [...groups.get(first) ?? [], route]);
|
|
222
297
|
}
|
|
298
|
+
const wildcards = /* @__PURE__ */ new Set();
|
|
223
299
|
for (const [first, members] of groups) {
|
|
224
|
-
|
|
225
|
-
if (members.length < 2 || onMount) continue;
|
|
226
|
-
for (const m of members) exact.delete(m);
|
|
227
|
-
exact.delete(`/${first}`);
|
|
228
|
-
exact.add(`/${first}/*`);
|
|
300
|
+
if (members.length >= 2 && !onMount(first)) wildcards.add(`/${first}/*`);
|
|
229
301
|
}
|
|
230
|
-
|
|
302
|
+
for (const route of routes.filter(isDynamic)) {
|
|
303
|
+
const segments = parse(route);
|
|
304
|
+
const last = segments.at(-1);
|
|
305
|
+
if ((last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam) continue;
|
|
306
|
+
const dir = segments.slice(0, segments.findIndex((seg) => seg.kind !== "static")).map((seg) => seg.kind === "static" ? seg.value : "").join("/");
|
|
307
|
+
if (dir === "" || !mounts) continue;
|
|
308
|
+
if (!mounts.some((m) => m === `/${dir}` || m.startsWith(`/${dir}/`))) wildcards.add(`/${dir}/*`);
|
|
309
|
+
}
|
|
310
|
+
const all = [...exact, ...wildcards];
|
|
311
|
+
const base = (entry) => entry.endsWith("/*") ? entry.slice(0, -2) : entry;
|
|
312
|
+
return all.filter((entry) => !all.some((other) => other !== entry && other.endsWith("/*") && covers(other, base(entry)))).sort();
|
|
231
313
|
}
|
|
232
314
|
function formatReport(report) {
|
|
233
315
|
const lines = [];
|
|
@@ -298,16 +380,25 @@ async function listPublicationPaths(options) {
|
|
|
298
380
|
|
|
299
381
|
// src/check-routes-cli.ts
|
|
300
382
|
var USAGE = `hyle-sdk-check-routes [--next-dir .next] [--base-url URL] [--json] [--print-reserved]
|
|
383
|
+
[--sync [--strict] [--no-check] [--host ID] [--build-id ID] [--allow-empty] [--allow-non-production]]
|
|
301
384
|
[--locales en,fr,es --default-locale en --locale-prefix as-needed|always|never] [--sections a,b] [--hyle-param hyle]
|
|
302
385
|
|
|
303
386
|
Run after \`next build\`. Reads the build's route manifests and hyle's read-only endpoints (mounts, and the published pages of each mount).
|
|
304
387
|
Credentials: HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN. The token is read from the environment only, never a flag.
|
|
305
388
|
(a) hyle pages a host static route shadows, (b) host dynamic routes that match hyle URLs, (c) mounts that are host static routes.
|
|
306
|
-
--print-reserved print the host's
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
389
|
+
--print-reserved print the host's routes in hyle's "Reserved paths" format and exit.
|
|
390
|
+
--sync report that list to hyle (ADR 0016) so nobody maintains it by hand, then run the check. Needs HYLE_CONTROL_TOKEN
|
|
391
|
+
(a hyle_tc_ control credential with hyle.workspace.manage; the read token cannot write), read from the environment only.
|
|
392
|
+
A failed sync only warns, so it never fails a deploy, unless --strict (exit 3). Skipped on a non-production Vercel
|
|
393
|
+
build (VERCEL_ENV) unless --allow-non-production. --no-check syncs without the collision check. The host id comes
|
|
394
|
+
from --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL; the build id from <next-dir>/BUILD_ID or --build-id.
|
|
395
|
+
An empty list is refused unless --allow-empty.
|
|
396
|
+
Exit: 0 no collision, 1 collision (a) or (c), 2 cannot run, 3 sync failed under --strict.`;
|
|
397
|
+
var FLAGS = /* @__PURE__ */ new Set(["--next-dir", "--base-url", "--locales", "--default-locale", "--locale-prefix", "--sections", "--hyle-param", "--host", "--build-id"]);
|
|
398
|
+
var BOOLEAN = /* @__PURE__ */ new Set(["--json", "--print-reserved", "--help", "--sync", "--strict", "--no-check", "--allow-empty", "--allow-non-production"]);
|
|
310
399
|
var CANNOT_RUN = 2;
|
|
400
|
+
var SYNC_FAILED = 3;
|
|
401
|
+
var MAX_SYNCED_PATHS = 512;
|
|
311
402
|
function parseArgs(argv) {
|
|
312
403
|
const args = /* @__PURE__ */ new Map();
|
|
313
404
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -319,6 +410,46 @@ function parseArgs(argv) {
|
|
|
319
410
|
return args;
|
|
320
411
|
}
|
|
321
412
|
var readJson = (file) => JSON.parse(readFileSync(file, "utf8"));
|
|
413
|
+
var SAFE_ID = /[^A-Za-z0-9._-]/g;
|
|
414
|
+
async function syncStep(args, io, ctx) {
|
|
415
|
+
const fail = (reason) => (io.err(`sync: ${printable(reason)}`), { status: "failed", reason });
|
|
416
|
+
const vercelEnv = io.env.VERCEL_ENV;
|
|
417
|
+
if (vercelEnv !== void 0 && vercelEnv !== "production" && !args.has("--allow-non-production")) {
|
|
418
|
+
io.err(`sync: skipped, this is a ${printable(vercelEnv)} build (a preview must not replace production's list; --allow-non-production overrides)`);
|
|
419
|
+
return { status: "skipped" };
|
|
420
|
+
}
|
|
421
|
+
const { baseUrl, mounts } = ctx.plan;
|
|
422
|
+
const token = io.env.HYLE_CONTROL_TOKEN;
|
|
423
|
+
if (!token) return fail("set HYLE_CONTROL_TOKEN (a hyle_tc_ control credential with hyle.workspace.manage; the read token cannot write)");
|
|
424
|
+
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");
|
|
425
|
+
const host = (args.get("--host") ?? io.env.HYLE_HOST_ID ?? io.env.VERCEL_PROJECT_PRODUCTION_URL)?.replace(SAFE_ID, "-").slice(0, 128);
|
|
426
|
+
if (!host) return fail("name this host with --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL");
|
|
427
|
+
let buildId = args.get("--build-id") ?? io.env.VERCEL_GIT_COMMIT_SHA;
|
|
428
|
+
try {
|
|
429
|
+
buildId = readFileSync(join(ctx.nextDir, "BUILD_ID"), "utf8").trim();
|
|
430
|
+
} catch {
|
|
431
|
+
}
|
|
432
|
+
buildId = buildId?.replace(SAFE_ID, "-").slice(0, 128);
|
|
433
|
+
if (!buildId) return fail("no build id: <next-dir>/BUILD_ID is missing; pass --build-id");
|
|
434
|
+
const rootMount = mounts.prefixes.includes("/");
|
|
435
|
+
const fromHost = reservedFor(ctx.hostRoutes, { ...ctx.locale ? { locale: ctx.locale } : {}, mounts: mounts.prefixes, hyleParam: ctx.hyleParam }).filter((p) => !(rootMount && p === "/"));
|
|
436
|
+
const reserved = [.../* @__PURE__ */ new Set([...fromHost, ...SDK_OWN_RESERVED])].sort();
|
|
437
|
+
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)");
|
|
438
|
+
if (reserved.length > MAX_SYNCED_PATHS) return fail(`${reserved.length} reserved paths exceed hyle's limit of ${MAX_SYNCED_PATHS}`);
|
|
439
|
+
try {
|
|
440
|
+
const result = await syncHostReserved({ baseUrl, token, workspaceId: mounts.workspaceId, paths: reserved, host, buildId, ...io.fetch ? { fetch: io.fetch } : {} });
|
|
441
|
+
if (!args.has("--json")) {
|
|
442
|
+
io.out(`sync: ${result.paths.length} reserved paths ${result.changed ? "updated" : "unchanged"} in hyle (host ${printable(host)}, build ${printable(buildId)})`);
|
|
443
|
+
if (result.conflicts.total > 0) {
|
|
444
|
+
io.out(`sync: ${result.conflicts.total} published hyle URL(s) are on paths this host owns (hyle unpublished nothing):`);
|
|
445
|
+
for (const path of result.conflicts.offenders) io.out(` ${printable(path)}`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return { status: "ok", result };
|
|
449
|
+
} catch (error) {
|
|
450
|
+
return fail(error instanceof Error ? `${error.name}: ${error.message}` : "unknown error");
|
|
451
|
+
}
|
|
452
|
+
}
|
|
322
453
|
async function runCli(argv, io) {
|
|
323
454
|
try {
|
|
324
455
|
const args = parseArgs(argv);
|
|
@@ -350,18 +481,35 @@ async function runCli(argv, io) {
|
|
|
350
481
|
const baseUrl = args.get("--base-url") ?? io.env.HYLE_TARGET_BASE_URL;
|
|
351
482
|
const token = io.env.HYLE_TARGET_TOKEN;
|
|
352
483
|
const client = baseUrl && token ? createHyleClient({ baseUrl, token, ...io.fetch ? { fetch: io.fetch } : {} }) : void 0;
|
|
353
|
-
|
|
484
|
+
let mounts;
|
|
485
|
+
let mountsError;
|
|
486
|
+
try {
|
|
487
|
+
mounts = client ? await client.mounts() : void 0;
|
|
488
|
+
} catch (error) {
|
|
489
|
+
if (!args.has("--sync")) throw error;
|
|
490
|
+
mountsError = error;
|
|
491
|
+
}
|
|
354
492
|
if (mounts?.kind === "disabled") {
|
|
355
493
|
io.err("CANNOT RUN: hyle's read surface is switched off (kind: disabled)");
|
|
356
494
|
return CANNOT_RUN;
|
|
357
495
|
}
|
|
358
496
|
const prefixes = mounts?.mounts.map((m) => m.prefix);
|
|
497
|
+
const strict = args.has("--strict");
|
|
498
|
+
let sync;
|
|
499
|
+
if (args.has("--sync")) {
|
|
500
|
+
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}` } : {} } });
|
|
501
|
+
if (args.has("--no-check")) {
|
|
502
|
+
if (args.has("--json")) io.out(JSON.stringify({ sync }));
|
|
503
|
+
return sync.status === "failed" && strict ? SYNC_FAILED : 0;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
359
506
|
if (args.has("--print-reserved")) {
|
|
360
|
-
const reserved = reservedFor(hostRoutes, { ...locale ? { locale } : {}, ...prefixes ? { mounts: prefixes } : {} });
|
|
507
|
+
const reserved = [.../* @__PURE__ */ new Set([...reservedFor(hostRoutes, { ...locale ? { locale } : {}, ...prefixes ? { mounts: prefixes } : {}, hyleParam }), ...SDK_OWN_RESERVED])].sort();
|
|
361
508
|
if (!prefixes) io.err("note: hyle was not reachable (set HYLE_TARGET_BASE_URL and HYLE_TARGET_TOKEN), so route groups are listed exactly, not collapsed to /x/*");
|
|
362
509
|
io.out(args.has("--json") ? JSON.stringify(reserved) : reserved.join("\n"));
|
|
363
510
|
return 0;
|
|
364
511
|
}
|
|
512
|
+
if (mountsError) throw mountsError;
|
|
365
513
|
if (!client || !mounts || mounts.kind !== "mounts") {
|
|
366
514
|
io.err("CANNOT RUN: set HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN");
|
|
367
515
|
return CANNOT_RUN;
|
|
@@ -377,8 +525,9 @@ async function runCli(argv, io) {
|
|
|
377
525
|
hylePaths.push(...listing.paths.map((p) => p.path));
|
|
378
526
|
}
|
|
379
527
|
const report = checkRoutes({ hostRoutes, mounts: mounts.mounts.map((m) => m.prefix), hylePaths, hyleParam, ...locale ? { locale } : {} });
|
|
380
|
-
io.out(args.has("--json") ? JSON.stringify(report, null, 2) : formatReport(report));
|
|
381
|
-
|
|
528
|
+
io.out(args.has("--json") ? JSON.stringify(sync ? { ...report, sync } : report, null, 2) : formatReport(report));
|
|
529
|
+
if (!report.ok) return 1;
|
|
530
|
+
return sync?.status === "failed" && strict ? SYNC_FAILED : 0;
|
|
382
531
|
} catch (error) {
|
|
383
532
|
io.err(`CANNOT RUN: ${error instanceof Error ? printable(`${error.name}: ${error.message}`) : "unknown error"}`);
|
|
384
533
|
return CANNOT_RUN;
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ASSET_FILE,
|
|
3
|
+
ASSET_RESERVED_PATH,
|
|
4
|
+
ASSET_ROUTE_PREFIX
|
|
5
|
+
} from "./chunk-67IOIAVW.js";
|
|
6
|
+
|
|
1
7
|
// src/errors.ts
|
|
2
8
|
var Cp1ClientError = class extends Error {
|
|
3
9
|
code;
|
|
@@ -43,16 +49,19 @@ function isMounts(data) {
|
|
|
43
49
|
const mounts = data.mounts;
|
|
44
50
|
return typeof data.workspace_id === "string" && isStrings(data.reserved) && isStrings(data.supported_locales) && Array.isArray(mounts) && mounts.every((m) => typeof m?.prefix === "string" && typeof m.default_section === "string");
|
|
45
51
|
}
|
|
46
|
-
function
|
|
52
|
+
function checkBaseUrl(baseUrl, allowInsecureHttp) {
|
|
47
53
|
let origin;
|
|
48
54
|
try {
|
|
49
|
-
origin = new URL(
|
|
55
|
+
origin = new URL(baseUrl);
|
|
50
56
|
} catch {
|
|
51
57
|
throw new TypeError("baseUrl must be an https origin");
|
|
52
58
|
}
|
|
53
|
-
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (
|
|
59
|
+
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
|
|
54
60
|
throw new TypeError("baseUrl must be https (http is allowed only for localhost, or with allowInsecureHttp)");
|
|
55
61
|
}
|
|
62
|
+
}
|
|
63
|
+
function createHyleClient(options) {
|
|
64
|
+
checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
|
|
56
65
|
if (!options.token) throw new TypeError("token is required");
|
|
57
66
|
const base = options.baseUrl.replace(/\/+$/, "");
|
|
58
67
|
const fetchImpl = options.fetch ?? fetch;
|
|
@@ -81,6 +90,7 @@ function createHyleClient(options) {
|
|
|
81
90
|
const query = new URLSearchParams({ path: opts.path });
|
|
82
91
|
if (opts.locale !== void 0) query.set("locale", opts.locale);
|
|
83
92
|
if (opts.format !== void 0) query.set("format", opts.format);
|
|
93
|
+
if (opts.nav !== void 0) query.set("nav", opts.nav);
|
|
84
94
|
if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
|
|
85
95
|
if (opts.limit !== void 0) query.set("limit", String(opts.limit));
|
|
86
96
|
const reply = await get("/cp1/read/resolve", query, opts.init);
|
|
@@ -95,7 +105,56 @@ function createHyleClient(options) {
|
|
|
95
105
|
if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
|
|
96
106
|
throw failure(reply);
|
|
97
107
|
}
|
|
98
|
-
|
|
108
|
+
async function asset(file, opts = {}) {
|
|
109
|
+
if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
|
|
110
|
+
const headers = new Headers({ authorization: `Bearer ${options.token}` });
|
|
111
|
+
for (const name of ["range", "if-range", "if-none-match"]) {
|
|
112
|
+
const value = opts.headers?.[name];
|
|
113
|
+
if (value) headers.set(name, value);
|
|
114
|
+
}
|
|
115
|
+
return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
|
|
116
|
+
}
|
|
117
|
+
return { resolve, mounts, asset };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/host-sync.ts
|
|
121
|
+
var CONTROL_TOKEN_PREFIX = "hyle_tc_";
|
|
122
|
+
var DEFAULT_TIMEOUT_MS2 = 1e4;
|
|
123
|
+
var MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
124
|
+
var PATH = "/cp1/control/workspace/host-reserved-paths";
|
|
125
|
+
async function syncHostReserved(input) {
|
|
126
|
+
checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
|
|
127
|
+
if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
|
|
128
|
+
throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
|
|
129
|
+
}
|
|
130
|
+
const fetchImpl = input.fetch ?? fetch;
|
|
131
|
+
const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
|
|
132
|
+
method: "PUT",
|
|
133
|
+
// redirect "error": the bearer token must never follow a redirect to another host.
|
|
134
|
+
redirect: "error",
|
|
135
|
+
signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
|
|
136
|
+
headers: {
|
|
137
|
+
authorization: `Bearer ${input.token}`,
|
|
138
|
+
"content-type": "application/json",
|
|
139
|
+
"cp-workspace": input.workspaceId,
|
|
140
|
+
"idempotency-key": `sync-${crypto.randomUUID()}`
|
|
141
|
+
},
|
|
142
|
+
body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
|
|
143
|
+
});
|
|
144
|
+
const text = await readCapped(res, MAX_RESPONSE_BYTES);
|
|
145
|
+
let parsed;
|
|
146
|
+
try {
|
|
147
|
+
parsed = JSON.parse(text);
|
|
148
|
+
} catch {
|
|
149
|
+
parsed = void 0;
|
|
150
|
+
}
|
|
151
|
+
const data = parsed?.data;
|
|
152
|
+
const conflicts = data?.conflicts;
|
|
153
|
+
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)) {
|
|
154
|
+
return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
|
|
155
|
+
}
|
|
156
|
+
const err = parsed?.error;
|
|
157
|
+
throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
|
|
99
158
|
}
|
|
100
159
|
|
|
101
160
|
// src/delivery-dedupe.ts
|
|
@@ -385,29 +444,50 @@ function checkRoutes(input) {
|
|
|
385
444
|
const shown = hostWins.length > 0 ? hostWins : matched;
|
|
386
445
|
dynamicOverlaps.push({ route, verdict: hostWins.length > 0 ? "host-wins" : "hyle-wins", matches: shown.length, examples: shown.slice(0, MAX_EXAMPLES) });
|
|
387
446
|
}
|
|
447
|
+
if (!routes.some((r) => r.startsWith(`${ASSET_ROUTE_PREFIX}/`))) {
|
|
448
|
+
notes.push(`no asset route (${ASSET_ROUTE_PREFIX}/[file], createAssetRoute) was found in the host routes: images, video and audio in hyle content will 404`);
|
|
449
|
+
}
|
|
388
450
|
if (catchAlls.length === 0) notes.push(`no hyle catch-all route (a "[...${hyleParam}]" or "[[...${hyleParam}]]" page) was found in the host routes`);
|
|
389
451
|
return { shadowedHylePaths, mountCollisions, dynamicOverlaps, notes, ok: shadowedHylePaths.length === 0 && mountCollisions.length === 0 };
|
|
390
452
|
}
|
|
453
|
+
var SDK_OWN_RESERVED = [ASSET_RESERVED_PATH];
|
|
454
|
+
var HASHED_METADATA_ROUTE = /^(opengraph-image|twitter-image|icon|apple-icon)-[a-z0-9]{5,8}$/;
|
|
455
|
+
var isHashedMetadataRoute = (route) => HASHED_METADATA_ROUTE.test(segmentsOf(route).at(-1) ?? "");
|
|
456
|
+
var covers = (entry, path) => {
|
|
457
|
+
if (!entry.endsWith("/*")) return entry === path;
|
|
458
|
+
const base = entry.slice(0, -2);
|
|
459
|
+
return path === base || path.startsWith(`${base}/`);
|
|
460
|
+
};
|
|
391
461
|
function reservedFor(hostRoutes, options = {}) {
|
|
392
462
|
const dropLocale = (route) => {
|
|
393
463
|
const [first, ...rest] = segmentsOf(route);
|
|
394
464
|
return options.locale && first === `[${LOCALE_PARAM}]` ? `/${rest.join("/")}` : route;
|
|
395
465
|
};
|
|
396
|
-
const
|
|
466
|
+
const hyleParam = options.hyleParam ?? "hyle";
|
|
467
|
+
const routes = hostRoutes.map(dropLocale).filter((r) => !isHashedMetadataRoute(r));
|
|
468
|
+
const exact = new Set(routes.filter((r) => !isDynamic(r)));
|
|
397
469
|
const mounts = options.mounts?.filter((m) => m !== "/");
|
|
470
|
+
const onMount = (segment) => mounts?.some((m) => m === `/${segment}` || m.startsWith(`/${segment}/`)) ?? true;
|
|
398
471
|
const groups = /* @__PURE__ */ new Map();
|
|
399
472
|
for (const route of exact) {
|
|
400
473
|
const [first, ...rest] = segmentsOf(route);
|
|
401
474
|
if (first !== void 0 && rest.length > 0) groups.set(first, [...groups.get(first) ?? [], route]);
|
|
402
475
|
}
|
|
476
|
+
const wildcards = /* @__PURE__ */ new Set();
|
|
403
477
|
for (const [first, members] of groups) {
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
478
|
+
if (members.length >= 2 && !onMount(first)) wildcards.add(`/${first}/*`);
|
|
479
|
+
}
|
|
480
|
+
for (const route of routes.filter(isDynamic)) {
|
|
481
|
+
const segments = parse(route);
|
|
482
|
+
const last = segments.at(-1);
|
|
483
|
+
if ((last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam) continue;
|
|
484
|
+
const dir = segments.slice(0, segments.findIndex((seg) => seg.kind !== "static")).map((seg) => seg.kind === "static" ? seg.value : "").join("/");
|
|
485
|
+
if (dir === "" || !mounts) continue;
|
|
486
|
+
if (!mounts.some((m) => m === `/${dir}` || m.startsWith(`/${dir}/`))) wildcards.add(`/${dir}/*`);
|
|
409
487
|
}
|
|
410
|
-
|
|
488
|
+
const all = [...exact, ...wildcards];
|
|
489
|
+
const base = (entry) => entry.endsWith("/*") ? entry.slice(0, -2) : entry;
|
|
490
|
+
return all.filter((entry) => !all.some((other) => other !== entry && other.endsWith("/*") && covers(other, base(entry)))).sort();
|
|
411
491
|
}
|
|
412
492
|
function formatReport(report) {
|
|
413
493
|
const lines = [];
|
|
@@ -439,6 +519,7 @@ var printable = (text) => {
|
|
|
439
519
|
export {
|
|
440
520
|
Cp1ClientError,
|
|
441
521
|
createHyleClient,
|
|
522
|
+
syncHostReserved,
|
|
442
523
|
DeliveryDedupe,
|
|
443
524
|
parseSignatureHeader,
|
|
444
525
|
verifyHyleSignature,
|
|
@@ -450,6 +531,7 @@ export {
|
|
|
450
531
|
hostRoutesFromManifests,
|
|
451
532
|
routeMatches,
|
|
452
533
|
checkRoutes,
|
|
534
|
+
SDK_OWN_RESERVED,
|
|
453
535
|
reservedFor,
|
|
454
536
|
formatReport
|
|
455
537
|
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// src/asset-path.ts
|
|
2
|
+
var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
|
|
3
|
+
var ASSET_RESERVED_PATH = "/api/hyle/*";
|
|
4
|
+
var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
|
5
|
+
var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg";
|
|
6
|
+
var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
|
|
7
|
+
var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
|
|
8
|
+
function hostAssetSrc(src) {
|
|
9
|
+
const file = HYLE_ASSET_URL.exec(src)?.[1];
|
|
10
|
+
return file ? `${ASSET_ROUTE_PREFIX}/${file.toLowerCase()}` : src;
|
|
11
|
+
}
|
|
12
|
+
function hostAssetHtml(html) {
|
|
13
|
+
return html.replace(new RegExp(`(\\ssrc=")(/assets/${UUID}(?:\\.(?:${EXTENSIONS}))?)(")`, "gi"), (_m, open, url, close) => `${open}${hostAssetSrc(url)}${close}`);
|
|
14
|
+
}
|
|
15
|
+
var ASSET_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
16
|
+
"image/png",
|
|
17
|
+
"image/jpeg",
|
|
18
|
+
"image/gif",
|
|
19
|
+
"image/webp",
|
|
20
|
+
"image/svg+xml",
|
|
21
|
+
"application/pdf",
|
|
22
|
+
"video/mp4",
|
|
23
|
+
"video/webm",
|
|
24
|
+
"audio/mpeg",
|
|
25
|
+
"audio/ogg"
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
export {
|
|
29
|
+
ASSET_ROUTE_PREFIX,
|
|
30
|
+
ASSET_RESERVED_PATH,
|
|
31
|
+
ASSET_FILE,
|
|
32
|
+
hostAssetSrc,
|
|
33
|
+
hostAssetHtml,
|
|
34
|
+
ASSET_CONTENT_TYPES
|
|
35
|
+
};
|