@tdacorp/hyle-sdk 0.5.0 → 0.8.1

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/dist/index.cjs CHANGED
@@ -23,6 +23,7 @@ __export(src_exports, {
23
23
  CACHE_TAG_PATTERN: () => CACHE_TAG_PATTERN,
24
24
  Cp1ClientError: () => Cp1ClientError,
25
25
  DeliveryDedupe: () => DeliveryDedupe,
26
+ SDK_OWN_RESERVED: () => SDK_OWN_RESERVED,
26
27
  checkRoutes: () => checkRoutes,
27
28
  createHyleClient: () => createHyleClient,
28
29
  createRevalidationCallbackRoute: () => createRevalidationCallbackRoute,
@@ -34,10 +35,19 @@ __export(src_exports, {
34
35
  parseSignatureHeader: () => parseSignatureHeader,
35
36
  reservedFor: () => reservedFor,
36
37
  routeMatches: () => routeMatches,
38
+ syncHostReserved: () => syncHostReserved,
37
39
  verifyHyleSignature: () => verifyHyleSignature
38
40
  });
39
41
  module.exports = __toCommonJS(src_exports);
40
42
 
43
+ // src/asset-path.ts
44
+ var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
45
+ var ASSET_RESERVED_PATH = "/api/hyle/*";
46
+ var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
47
+ var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg";
48
+ var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
49
+ var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
50
+
41
51
  // src/errors.ts
42
52
  var Cp1ClientError = class extends Error {
43
53
  code;
@@ -83,16 +93,19 @@ function isMounts(data) {
83
93
  const mounts = data.mounts;
84
94
  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");
85
95
  }
86
- function createHyleClient(options) {
96
+ function checkBaseUrl(baseUrl, allowInsecureHttp) {
87
97
  let origin;
88
98
  try {
89
- origin = new URL(options.baseUrl);
99
+ origin = new URL(baseUrl);
90
100
  } catch {
91
101
  throw new TypeError("baseUrl must be an https origin");
92
102
  }
93
- if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (options.allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
103
+ if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
94
104
  throw new TypeError("baseUrl must be https (http is allowed only for localhost, or with allowInsecureHttp)");
95
105
  }
106
+ }
107
+ function createHyleClient(options) {
108
+ checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
96
109
  if (!options.token) throw new TypeError("token is required");
97
110
  const base = options.baseUrl.replace(/\/+$/, "");
98
111
  const fetchImpl = options.fetch ?? fetch;
@@ -135,7 +148,56 @@ function createHyleClient(options) {
135
148
  if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
136
149
  throw failure(reply);
137
150
  }
138
- return { resolve, mounts };
151
+ async function asset(file, opts = {}) {
152
+ if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
153
+ const headers = new Headers({ authorization: `Bearer ${options.token}` });
154
+ for (const name of ["range", "if-range", "if-none-match"]) {
155
+ const value = opts.headers?.[name];
156
+ if (value) headers.set(name, value);
157
+ }
158
+ return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
159
+ }
160
+ return { resolve, mounts, asset };
161
+ }
162
+
163
+ // src/host-sync.ts
164
+ var CONTROL_TOKEN_PREFIX = "hyle_tc_";
165
+ var DEFAULT_TIMEOUT_MS2 = 1e4;
166
+ var MAX_RESPONSE_BYTES = 1024 * 1024;
167
+ var PATH = "/cp1/control/workspace/host-reserved-paths";
168
+ async function syncHostReserved(input) {
169
+ checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
170
+ if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
171
+ throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
172
+ }
173
+ const fetchImpl = input.fetch ?? fetch;
174
+ const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
175
+ method: "PUT",
176
+ // redirect "error": the bearer token must never follow a redirect to another host.
177
+ redirect: "error",
178
+ signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
179
+ headers: {
180
+ authorization: `Bearer ${input.token}`,
181
+ "content-type": "application/json",
182
+ "cp-workspace": input.workspaceId,
183
+ "idempotency-key": `sync-${crypto.randomUUID()}`
184
+ },
185
+ body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
186
+ });
187
+ const text = await readCapped(res, MAX_RESPONSE_BYTES);
188
+ let parsed;
189
+ try {
190
+ parsed = JSON.parse(text);
191
+ } catch {
192
+ parsed = void 0;
193
+ }
194
+ const data = parsed?.data;
195
+ const conflicts = data?.conflicts;
196
+ 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)) {
197
+ return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
198
+ }
199
+ const err = parsed?.error;
200
+ throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
139
201
  }
140
202
 
141
203
  // src/delivery-dedupe.ts
@@ -425,29 +487,50 @@ function checkRoutes(input) {
425
487
  const shown = hostWins.length > 0 ? hostWins : matched;
426
488
  dynamicOverlaps.push({ route, verdict: hostWins.length > 0 ? "host-wins" : "hyle-wins", matches: shown.length, examples: shown.slice(0, MAX_EXAMPLES) });
427
489
  }
490
+ if (!routes.some((r) => r.startsWith(`${ASSET_ROUTE_PREFIX}/`))) {
491
+ 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`);
492
+ }
428
493
  if (catchAlls.length === 0) notes.push(`no hyle catch-all route (a "[...${hyleParam}]" or "[[...${hyleParam}]]" page) was found in the host routes`);
429
494
  return { shadowedHylePaths, mountCollisions, dynamicOverlaps, notes, ok: shadowedHylePaths.length === 0 && mountCollisions.length === 0 };
430
495
  }
496
+ var SDK_OWN_RESERVED = [ASSET_RESERVED_PATH];
497
+ var HASHED_METADATA_ROUTE = /^(opengraph-image|twitter-image|icon|apple-icon)-[a-z0-9]{5,8}$/;
498
+ var isHashedMetadataRoute = (route) => HASHED_METADATA_ROUTE.test(segmentsOf(route).at(-1) ?? "");
499
+ var covers = (entry, path) => {
500
+ if (!entry.endsWith("/*")) return entry === path;
501
+ const base = entry.slice(0, -2);
502
+ return path === base || path.startsWith(`${base}/`);
503
+ };
431
504
  function reservedFor(hostRoutes, options = {}) {
432
505
  const dropLocale = (route) => {
433
506
  const [first, ...rest] = segmentsOf(route);
434
507
  return options.locale && first === `[${LOCALE_PARAM}]` ? `/${rest.join("/")}` : route;
435
508
  };
436
- const exact = new Set(hostRoutes.map(dropLocale).filter((r) => !isDynamic(r)));
509
+ const hyleParam = options.hyleParam ?? "hyle";
510
+ const routes = hostRoutes.map(dropLocale).filter((r) => !isHashedMetadataRoute(r));
511
+ const exact = new Set(routes.filter((r) => !isDynamic(r)));
437
512
  const mounts = options.mounts?.filter((m) => m !== "/");
513
+ const onMount = (segment) => mounts?.some((m) => m === `/${segment}` || m.startsWith(`/${segment}/`)) ?? true;
438
514
  const groups = /* @__PURE__ */ new Map();
439
515
  for (const route of exact) {
440
516
  const [first, ...rest] = segmentsOf(route);
441
517
  if (first !== void 0 && rest.length > 0) groups.set(first, [...groups.get(first) ?? [], route]);
442
518
  }
519
+ const wildcards = /* @__PURE__ */ new Set();
443
520
  for (const [first, members] of groups) {
444
- const onMount = mounts?.some((m) => m === `/${first}` || m.startsWith(`/${first}/`)) ?? true;
445
- if (members.length < 2 || onMount) continue;
446
- for (const m of members) exact.delete(m);
447
- exact.delete(`/${first}`);
448
- exact.add(`/${first}/*`);
521
+ if (members.length >= 2 && !onMount(first)) wildcards.add(`/${first}/*`);
522
+ }
523
+ for (const route of routes.filter(isDynamic)) {
524
+ const segments = parse(route);
525
+ const last = segments.at(-1);
526
+ if ((last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam) continue;
527
+ const dir = segments.slice(0, segments.findIndex((seg) => seg.kind !== "static")).map((seg) => seg.kind === "static" ? seg.value : "").join("/");
528
+ if (dir === "" || !mounts) continue;
529
+ if (!mounts.some((m) => m === `/${dir}` || m.startsWith(`/${dir}/`))) wildcards.add(`/${dir}/*`);
449
530
  }
450
- return [...exact].sort();
531
+ const all = [...exact, ...wildcards];
532
+ const base = (entry) => entry.endsWith("/*") ? entry.slice(0, -2) : entry;
533
+ return all.filter((entry) => !all.some((other) => other !== entry && other.endsWith("/*") && covers(other, base(entry)))).sort();
451
534
  }
452
535
  function formatReport(report) {
453
536
  const lines = [];
@@ -480,6 +563,7 @@ var printable = (text) => {
480
563
  CACHE_TAG_PATTERN,
481
564
  Cp1ClientError,
482
565
  DeliveryDedupe,
566
+ SDK_OWN_RESERVED,
483
567
  checkRoutes,
484
568
  createHyleClient,
485
569
  createRevalidationCallbackRoute,
@@ -491,5 +575,6 @@ var printable = (text) => {
491
575
  parseSignatureHeader,
492
576
  reservedFor,
493
577
  routeMatches,
578
+ syncHostReserved,
494
579
  verifyHyleSignature
495
580
  });
package/dist/index.d.cts CHANGED
@@ -37,9 +37,20 @@ interface MountsOptions {
37
37
  /** Extra fetch options (for example Next's `next: { tags, revalidate }`). Method, body and the auth header cannot be overridden. */
38
38
  readonly init?: HyleRequestInit;
39
39
  }
40
+ interface AssetOptions {
41
+ /** Only these request headers are sent upstream: a browser's own cache validators and byte range. Everything else is dropped. */
42
+ readonly headers?: {
43
+ readonly range?: string | null;
44
+ readonly "if-range"?: string | null;
45
+ readonly "if-none-match"?: string | null;
46
+ };
47
+ /** Abort after this many milliseconds, body included. Default: the client's `timeoutMs`. */
48
+ readonly timeoutMs?: number;
49
+ }
40
50
  declare function createHyleClient(options: HyleClientOptions): {
41
51
  resolve: (opts: ResolveOptions) => Promise<Resolved>;
42
52
  mounts: (opts?: MountsOptions) => Promise<MountsResult>;
53
+ asset: (file: string, opts?: AssetOptions) => Promise<Response>;
43
54
  };
44
55
  type HyleClient = ReturnType<typeof createHyleClient>;
45
56
 
@@ -51,6 +62,41 @@ declare class Cp1ClientError extends Error {
51
62
  constructor(code: string, message: string, status: number, requestId: string, details?: Record<string, unknown>);
52
63
  }
53
64
 
65
+ interface HostSyncInput {
66
+ /** hyle's origin. */
67
+ readonly baseUrl: string;
68
+ /** A CONTROL credential (hyle_tc_...) holding hyle.workspace.manage on the workspace. Never a target (read) token. */
69
+ readonly token: string;
70
+ /** The workspace to write, from `client.mounts()`; the credential must be granted on it. */
71
+ readonly workspaceId: string;
72
+ /** The host's complete list of reserved paths (a replace). */
73
+ readonly paths: readonly string[];
74
+ readonly host: string;
75
+ readonly buildId: string;
76
+ readonly fetch?: typeof fetch;
77
+ readonly timeoutMs?: number;
78
+ readonly allowInsecureHttp?: boolean;
79
+ }
80
+ interface HostSyncResult {
81
+ /** What hyle stored: sorted, de-duplicated. */
82
+ readonly paths: readonly string[];
83
+ /** False when hyle already held exactly this list. */
84
+ readonly changed: boolean;
85
+ readonly syncedAt: string;
86
+ /** Published hyle URLs the list now covers. hyle unpublishes nothing; the host decides what to do. */
87
+ readonly conflicts: {
88
+ readonly total: number;
89
+ readonly offenders: readonly string[];
90
+ };
91
+ }
92
+ /**
93
+ * Reports the host's reserved paths to hyle (ADR 0016): `PUT /cp1/control/workspace/host-reserved-paths`. Idempotent (resending the
94
+ * same list changes nothing), so a retry or a repeated deploy is safe; the random Idempotency-Key only satisfies the control
95
+ * surface's mutation rule. Throws `TypeError` before any request for a wrong token kind or an insecure URL, and `Cp1ClientError`
96
+ * for anything hyle answers or the network does.
97
+ */
98
+ declare function syncHostReserved(input: HostSyncInput): Promise<HostSyncResult>;
99
+
54
100
  /**
55
101
  * docs/cp1-spec.md section 5.2: `Hyle-Signature: t=<unix seconds>,v1=<hex>,v1=<hex>`.
56
102
  * Multiple v1= values support dual-secret rotation with no receiver-side
@@ -207,17 +253,23 @@ interface RouteCheckReport {
207
253
  readonly ok: boolean;
208
254
  }
209
255
  declare function checkRoutes(input: RouteCheckInput): RouteCheckReport;
256
+ /** Paths the SDK's own components serve inside a host app, always reserved on top of the host's routes: the asset route (ADR 0015). */
257
+ declare const SDK_OWN_RESERVED: readonly string[];
210
258
  /**
211
- * The host's static routes in hyle's Reserved paths format: exact paths, and "/x/*" for a segment with two or more routes under it
212
- * (route groups such as "/api/*"). A segment is NOT collapsed when a non-root mount prefix lies on it, so "/learn/about" stays exact
213
- * while a mount serves "/learn/notes". Without `mounts` (hyle unreachable) nothing is collapsed. The leading locale segment is dropped
214
- * because hyle's paths carry no host locale prefix.
259
+ * The host's routes in hyle's Reserved paths format. Static routes are exact paths, and "/x/*" for a segment with two or more
260
+ * routes under it (route groups such as "/api/*"). A dynamic route ("/shop/[id]", "/docs/[...slug]") becomes the wildcard on its
261
+ * static prefix ("/shop/*", "/docs/*"); one with no static prefix, and hyle's own catch-all (`hyleParam`, default "hyle"), are
262
+ * skipped. A segment is NOT collapsed, and a wildcard is not made, when a non-root mount prefix lies on it, so "/learn/about" stays
263
+ * exact while a mount serves "/learn/notes". Without `mounts` (hyle unreachable) nothing is collapsed. The leading locale segment
264
+ * is dropped because hyle's paths carry no host locale prefix. Per-build hashed metadata routes are omitted, an entry another
265
+ * wildcard already covers is dropped, and the result is sorted.
215
266
  */
216
267
  declare function reservedFor(hostRoutes: readonly string[], options?: {
217
268
  readonly locale?: LocaleOptions;
218
269
  readonly mounts?: readonly string[];
270
+ readonly hyleParam?: string;
219
271
  }): string[];
220
272
  /** The human report. */
221
273
  declare function formatReport(report: RouteCheckReport): string;
222
274
 
223
- export { CACHE_TAG_PATTERN, Cp1ClientError, DeliveryDedupe, type DynamicOverlap, type HyleClient, type HyleClientOptions, type HyleRequestInit, type ListPublicationPathsOptions, type LocaleOptions, type LocalePrefix, type MountsOptions, MountsResult, type NextManifests, type ParsedSignatureHeader, type PublicationPath, type PublicationPaths, type ResolveOptions, Resolved, type RouteCheckInput, type RouteCheckReport, type VerifySignatureParams, checkRoutes, createHyleClient, formatReport, hostRoutesFromManifests, isValidCacheTag, listPublicationPaths, normalizeRoute, parseSignatureHeader, reservedFor, routeMatches, verifyHyleSignature };
275
+ export { type AssetOptions, CACHE_TAG_PATTERN, Cp1ClientError, DeliveryDedupe, type DynamicOverlap, type HostSyncInput, type HostSyncResult, type HyleClient, type HyleClientOptions, type HyleRequestInit, type ListPublicationPathsOptions, type LocaleOptions, type LocalePrefix, type MountsOptions, MountsResult, type NextManifests, type ParsedSignatureHeader, type PublicationPath, type PublicationPaths, type ResolveOptions, Resolved, type RouteCheckInput, type RouteCheckReport, SDK_OWN_RESERVED, type VerifySignatureParams, checkRoutes, createHyleClient, formatReport, hostRoutesFromManifests, isValidCacheTag, listPublicationPaths, normalizeRoute, parseSignatureHeader, reservedFor, routeMatches, syncHostReserved, verifyHyleSignature };
package/dist/index.d.ts CHANGED
@@ -37,9 +37,20 @@ interface MountsOptions {
37
37
  /** Extra fetch options (for example Next's `next: { tags, revalidate }`). Method, body and the auth header cannot be overridden. */
38
38
  readonly init?: HyleRequestInit;
39
39
  }
40
+ interface AssetOptions {
41
+ /** Only these request headers are sent upstream: a browser's own cache validators and byte range. Everything else is dropped. */
42
+ readonly headers?: {
43
+ readonly range?: string | null;
44
+ readonly "if-range"?: string | null;
45
+ readonly "if-none-match"?: string | null;
46
+ };
47
+ /** Abort after this many milliseconds, body included. Default: the client's `timeoutMs`. */
48
+ readonly timeoutMs?: number;
49
+ }
40
50
  declare function createHyleClient(options: HyleClientOptions): {
41
51
  resolve: (opts: ResolveOptions) => Promise<Resolved>;
42
52
  mounts: (opts?: MountsOptions) => Promise<MountsResult>;
53
+ asset: (file: string, opts?: AssetOptions) => Promise<Response>;
43
54
  };
44
55
  type HyleClient = ReturnType<typeof createHyleClient>;
45
56
 
@@ -51,6 +62,41 @@ declare class Cp1ClientError extends Error {
51
62
  constructor(code: string, message: string, status: number, requestId: string, details?: Record<string, unknown>);
52
63
  }
53
64
 
65
+ interface HostSyncInput {
66
+ /** hyle's origin. */
67
+ readonly baseUrl: string;
68
+ /** A CONTROL credential (hyle_tc_...) holding hyle.workspace.manage on the workspace. Never a target (read) token. */
69
+ readonly token: string;
70
+ /** The workspace to write, from `client.mounts()`; the credential must be granted on it. */
71
+ readonly workspaceId: string;
72
+ /** The host's complete list of reserved paths (a replace). */
73
+ readonly paths: readonly string[];
74
+ readonly host: string;
75
+ readonly buildId: string;
76
+ readonly fetch?: typeof fetch;
77
+ readonly timeoutMs?: number;
78
+ readonly allowInsecureHttp?: boolean;
79
+ }
80
+ interface HostSyncResult {
81
+ /** What hyle stored: sorted, de-duplicated. */
82
+ readonly paths: readonly string[];
83
+ /** False when hyle already held exactly this list. */
84
+ readonly changed: boolean;
85
+ readonly syncedAt: string;
86
+ /** Published hyle URLs the list now covers. hyle unpublishes nothing; the host decides what to do. */
87
+ readonly conflicts: {
88
+ readonly total: number;
89
+ readonly offenders: readonly string[];
90
+ };
91
+ }
92
+ /**
93
+ * Reports the host's reserved paths to hyle (ADR 0016): `PUT /cp1/control/workspace/host-reserved-paths`. Idempotent (resending the
94
+ * same list changes nothing), so a retry or a repeated deploy is safe; the random Idempotency-Key only satisfies the control
95
+ * surface's mutation rule. Throws `TypeError` before any request for a wrong token kind or an insecure URL, and `Cp1ClientError`
96
+ * for anything hyle answers or the network does.
97
+ */
98
+ declare function syncHostReserved(input: HostSyncInput): Promise<HostSyncResult>;
99
+
54
100
  /**
55
101
  * docs/cp1-spec.md section 5.2: `Hyle-Signature: t=<unix seconds>,v1=<hex>,v1=<hex>`.
56
102
  * Multiple v1= values support dual-secret rotation with no receiver-side
@@ -207,17 +253,23 @@ interface RouteCheckReport {
207
253
  readonly ok: boolean;
208
254
  }
209
255
  declare function checkRoutes(input: RouteCheckInput): RouteCheckReport;
256
+ /** Paths the SDK's own components serve inside a host app, always reserved on top of the host's routes: the asset route (ADR 0015). */
257
+ declare const SDK_OWN_RESERVED: readonly string[];
210
258
  /**
211
- * The host's static routes in hyle's Reserved paths format: exact paths, and "/x/*" for a segment with two or more routes under it
212
- * (route groups such as "/api/*"). A segment is NOT collapsed when a non-root mount prefix lies on it, so "/learn/about" stays exact
213
- * while a mount serves "/learn/notes". Without `mounts` (hyle unreachable) nothing is collapsed. The leading locale segment is dropped
214
- * because hyle's paths carry no host locale prefix.
259
+ * The host's routes in hyle's Reserved paths format. Static routes are exact paths, and "/x/*" for a segment with two or more
260
+ * routes under it (route groups such as "/api/*"). A dynamic route ("/shop/[id]", "/docs/[...slug]") becomes the wildcard on its
261
+ * static prefix ("/shop/*", "/docs/*"); one with no static prefix, and hyle's own catch-all (`hyleParam`, default "hyle"), are
262
+ * skipped. A segment is NOT collapsed, and a wildcard is not made, when a non-root mount prefix lies on it, so "/learn/about" stays
263
+ * exact while a mount serves "/learn/notes". Without `mounts` (hyle unreachable) nothing is collapsed. The leading locale segment
264
+ * is dropped because hyle's paths carry no host locale prefix. Per-build hashed metadata routes are omitted, an entry another
265
+ * wildcard already covers is dropped, and the result is sorted.
215
266
  */
216
267
  declare function reservedFor(hostRoutes: readonly string[], options?: {
217
268
  readonly locale?: LocaleOptions;
218
269
  readonly mounts?: readonly string[];
270
+ readonly hyleParam?: string;
219
271
  }): string[];
220
272
  /** The human report. */
221
273
  declare function formatReport(report: RouteCheckReport): string;
222
274
 
223
- export { CACHE_TAG_PATTERN, Cp1ClientError, DeliveryDedupe, type DynamicOverlap, type HyleClient, type HyleClientOptions, type HyleRequestInit, type ListPublicationPathsOptions, type LocaleOptions, type LocalePrefix, type MountsOptions, MountsResult, type NextManifests, type ParsedSignatureHeader, type PublicationPath, type PublicationPaths, type ResolveOptions, Resolved, type RouteCheckInput, type RouteCheckReport, type VerifySignatureParams, checkRoutes, createHyleClient, formatReport, hostRoutesFromManifests, isValidCacheTag, listPublicationPaths, normalizeRoute, parseSignatureHeader, reservedFor, routeMatches, verifyHyleSignature };
275
+ export { type AssetOptions, CACHE_TAG_PATTERN, Cp1ClientError, DeliveryDedupe, type DynamicOverlap, type HostSyncInput, type HostSyncResult, type HyleClient, type HyleClientOptions, type HyleRequestInit, type ListPublicationPathsOptions, type LocaleOptions, type LocalePrefix, type MountsOptions, MountsResult, type NextManifests, type ParsedSignatureHeader, type PublicationPath, type PublicationPaths, type ResolveOptions, Resolved, type RouteCheckInput, type RouteCheckReport, SDK_OWN_RESERVED, type VerifySignatureParams, checkRoutes, createHyleClient, formatReport, hostRoutesFromManifests, isValidCacheTag, listPublicationPaths, normalizeRoute, parseSignatureHeader, reservedFor, routeMatches, syncHostReserved, verifyHyleSignature };
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@ import {
2
2
  CACHE_TAG_PATTERN,
3
3
  Cp1ClientError,
4
4
  DeliveryDedupe,
5
+ SDK_OWN_RESERVED,
5
6
  checkRoutes,
6
7
  createHyleClient,
7
8
  createRevalidationCallbackRoute,
@@ -13,12 +14,15 @@ import {
13
14
  parseSignatureHeader,
14
15
  reservedFor,
15
16
  routeMatches,
17
+ syncHostReserved,
16
18
  verifyHyleSignature
17
- } from "./chunk-4OB77ZOD.js";
19
+ } from "./chunk-EBNIKRQH.js";
20
+ import "./chunk-67IOIAVW.js";
18
21
  export {
19
22
  CACHE_TAG_PATTERN,
20
23
  Cp1ClientError,
21
24
  DeliveryDedupe,
25
+ SDK_OWN_RESERVED,
22
26
  checkRoutes,
23
27
  createHyleClient,
24
28
  createRevalidationCallbackRoute,
@@ -30,5 +34,6 @@ export {
30
34
  parseSignatureHeader,
31
35
  reservedFor,
32
36
  routeMatches,
37
+ syncHostReserved,
33
38
  verifyHyleSignature
34
39
  };
package/dist/next.cjs CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var next_exports = {};
22
22
  __export(next_exports, {
23
23
  MOUNTS_MAX_STALE_MS: () => MOUNTS_MAX_STALE_MS,
24
+ createAssetRoute: () => createAssetRoute,
24
25
  createRevalidateRoute: () => createRevalidateRoute,
25
26
  fetchResolver: () => fetchResolver,
26
27
  hyleMetadata: () => hyleMetadata,
@@ -36,6 +37,32 @@ module.exports = __toCommonJS(next_exports);
36
37
  // src/next/page.tsx
37
38
  var import_navigation2 = require("next/navigation");
38
39
 
40
+ // src/asset-path.ts
41
+ var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
42
+ var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
43
+ var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg";
44
+ var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
45
+ var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
46
+ function hostAssetSrc(src) {
47
+ const file = HYLE_ASSET_URL.exec(src)?.[1];
48
+ return file ? `${ASSET_ROUTE_PREFIX}/${file.toLowerCase()}` : src;
49
+ }
50
+ function hostAssetHtml(html) {
51
+ return html.replace(new RegExp(`(\\ssrc=")(/assets/${UUID}(?:\\.(?:${EXTENSIONS}))?)(")`, "gi"), (_m, open, url, close) => `${open}${hostAssetSrc(url)}${close}`);
52
+ }
53
+ var ASSET_CONTENT_TYPES = /* @__PURE__ */ new Set([
54
+ "image/png",
55
+ "image/jpeg",
56
+ "image/gif",
57
+ "image/webp",
58
+ "image/svg+xml",
59
+ "application/pdf",
60
+ "video/mp4",
61
+ "video/webm",
62
+ "audio/mpeg",
63
+ "audio/ogg"
64
+ ]);
65
+
39
66
  // src/errors.ts
40
67
  var Cp1ClientError = class extends Error {
41
68
  code;
@@ -81,16 +108,19 @@ function isMounts(data) {
81
108
  const mounts = data.mounts;
82
109
  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");
83
110
  }
84
- function createHyleClient(options) {
111
+ function checkBaseUrl(baseUrl, allowInsecureHttp) {
85
112
  let origin;
86
113
  try {
87
- origin = new URL(options.baseUrl);
114
+ origin = new URL(baseUrl);
88
115
  } catch {
89
116
  throw new TypeError("baseUrl must be an https origin");
90
117
  }
91
- if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (options.allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
118
+ if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
92
119
  throw new TypeError("baseUrl must be https (http is allowed only for localhost, or with allowInsecureHttp)");
93
120
  }
121
+ }
122
+ function createHyleClient(options) {
123
+ checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
94
124
  if (!options.token) throw new TypeError("token is required");
95
125
  const base = options.baseUrl.replace(/\/+$/, "");
96
126
  const fetchImpl = options.fetch ?? fetch;
@@ -133,7 +163,16 @@ function createHyleClient(options) {
133
163
  if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
134
164
  throw failure(reply);
135
165
  }
136
- return { resolve, mounts };
166
+ async function asset(file, opts = {}) {
167
+ if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
168
+ const headers = new Headers({ authorization: `Bearer ${options.token}` });
169
+ for (const name of ["range", "if-range", "if-none-match"]) {
170
+ const value = opts.headers?.[name];
171
+ if (value) headers.set(name, value);
172
+ }
173
+ return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
174
+ }
175
+ return { resolve, mounts, asset };
137
176
  }
138
177
 
139
178
  // src/delivery-dedupe.ts
@@ -525,6 +564,7 @@ function clean(node, depth, ctx2, budget) {
525
564
  if (Object.hasOwn(rules, key) && rules[key](value, inner)) properties[key] = value;
526
565
  }
527
566
  }
567
+ if ((tag === "img" || tag === "video" || tag === "audio") && typeof properties.src === "string") properties.src = hostAssetSrc(properties.src);
528
568
  if (tag === "iframe") {
529
569
  if (properties.sandbox === void 0 || properties.srcdoc === void 0) return [];
530
570
  properties.sandbox = "allow-scripts";
@@ -872,7 +912,7 @@ function HastContent({ tree, title, components = {}, locale }) {
872
912
  });
873
913
  }
874
914
  function TrustedServerHtml({ html }) {
875
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { dangerouslySetInnerHTML: { __html: html } });
915
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { dangerouslySetInnerHTML: { __html: hostAssetHtml(html) } });
876
916
  }
877
917
 
878
918
  // src/react/index.ts
@@ -1452,9 +1492,84 @@ async function hyleRootSitemap(options, sitemap) {
1452
1492
  }
1453
1493
  return [...entries.values()];
1454
1494
  }
1495
+
1496
+ // src/next/asset.ts
1497
+ var DEFAULT_MAX_BYTES = 16 * 1024 * 1024;
1498
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
1499
+ var CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400";
1500
+ var PARTIAL_CACHE_CONTROL = "no-store";
1501
+ var SAFE_HEADERS = { "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" };
1502
+ var empty = (status, headers = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers } });
1503
+ var isSwitchedOff2 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
1504
+ function capped(body, max) {
1505
+ let seen = 0;
1506
+ return body.pipeThrough(
1507
+ new TransformStream({
1508
+ transform(chunk, controller) {
1509
+ seen += chunk.byteLength;
1510
+ if (seen > max) return controller.error(new Error("asset too large"));
1511
+ controller.enqueue(chunk);
1512
+ }
1513
+ })
1514
+ );
1515
+ }
1516
+ function createAssetRoute(options) {
1517
+ let client;
1518
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
1519
+ async function serve(req, ctx2, head) {
1520
+ if (isSwitchedOff2((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return empty(404);
1521
+ const file = (await ctx2.params).file;
1522
+ if (typeof file !== "string" || !ASSET_FILE.test(file)) return empty(404);
1523
+ try {
1524
+ client ??= createHyleClient({ baseUrl: options.baseUrl?.trim() ?? "", token: options.token?.trim() ?? "", ...options.fetch ? { fetch: options.fetch } : {} });
1525
+ } catch {
1526
+ return empty(404);
1527
+ }
1528
+ let upstream;
1529
+ try {
1530
+ upstream = await client.asset(file, {
1531
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS2,
1532
+ headers: { range: req.headers.get("range"), "if-range": req.headers.get("if-range"), "if-none-match": req.headers.get("if-none-match") }
1533
+ });
1534
+ } catch {
1535
+ return empty(502);
1536
+ }
1537
+ const drop = () => void upstream.body?.cancel().catch(() => {
1538
+ });
1539
+ const etag = upstream.headers.get("etag");
1540
+ if (upstream.status === 304) {
1541
+ drop();
1542
+ return new Response(null, { status: 304, headers: { "Cache-Control": CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS, ...etag ? { ETag: etag } : {} } });
1543
+ }
1544
+ if (upstream.status === 404 || upstream.status === 416) {
1545
+ drop();
1546
+ const range = upstream.status === 416 ? upstream.headers.get("content-range") : null;
1547
+ return empty(upstream.status, range ? { "Content-Range": range } : {});
1548
+ }
1549
+ const type = upstream.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
1550
+ const length = Number(upstream.headers.get("content-length"));
1551
+ const expectedStatus = upstream.status === 200 || upstream.status === 206;
1552
+ if (!expectedStatus || !upstream.body || !type || !ASSET_CONTENT_TYPES.has(type) || Number.isFinite(length) && length > maxBytes) {
1553
+ drop();
1554
+ return empty(502);
1555
+ }
1556
+ const headers = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
1557
+ if (etag) headers.set("ETag", etag);
1558
+ const contentRange = upstream.headers.get("content-range");
1559
+ if (upstream.status === 206 && contentRange) headers.set("Content-Range", contentRange);
1560
+ if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers.set("Content-Length", String(length));
1561
+ if (head) {
1562
+ drop();
1563
+ return new Response(null, { status: upstream.status, headers });
1564
+ }
1565
+ return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
1566
+ }
1567
+ return { GET: (req, ctx2) => serve(req, ctx2, false), HEAD: (req, ctx2) => serve(req, ctx2, true) };
1568
+ }
1455
1569
  // Annotate the CommonJS export names for ESM import in node:
1456
1570
  0 && (module.exports = {
1457
1571
  MOUNTS_MAX_STALE_MS,
1572
+ createAssetRoute,
1458
1573
  createRevalidateRoute,
1459
1574
  fetchResolver,
1460
1575
  hyleMetadata,
package/dist/next.d.cts CHANGED
@@ -185,4 +185,46 @@ interface HyleRootSitemapOptions {
185
185
  */
186
186
  declare function hyleRootSitemap(options: Configs, sitemap: HyleRootSitemapOptions): Promise<MetadataRoute.Sitemap>;
187
187
 
188
- export { FetchResolverOptions, type HyleNextOptions, HyleResolver, type HyleRootConfig, type HyleRootSitemapOptions, type HyleSitemapOptions, MOUNTS_MAX_STALE_MS, type PageProps, type RevalidateRouteOptions, type RouteParams, createRevalidateRoute, hyleMetadata, hylePage, hyleRootMetadata, hyleRootPage, hyleRootSitemap, hyleSitemap };
188
+ interface AssetRouteOptions {
189
+ /** hyle's origin (HYLE_TARGET_BASE_URL). */
190
+ readonly baseUrl: string | undefined;
191
+ /** This workspace's target credential (HYLE_TARGET_TOKEN). Used only server-side; it never reaches the browser. */
192
+ readonly token: string | undefined;
193
+ /** Environment to read the site switch from. Default process.env. */
194
+ readonly env?: Readonly<Record<string, string | undefined>>;
195
+ /** Refuse (502) an asset larger than this many bytes. Default 16 MiB; hyle's own upload limit is 4 MiB. */
196
+ readonly maxBytes?: number;
197
+ /** Abort the upstream request, body included, after this many milliseconds. Default 30000. */
198
+ readonly timeoutMs?: number;
199
+ /** Injectable for tests. */
200
+ readonly fetch?: typeof fetch;
201
+ }
202
+ interface AssetRoute {
203
+ GET(req: Request, ctx: {
204
+ params: Promise<{
205
+ file?: string;
206
+ }>;
207
+ }): Promise<Response>;
208
+ HEAD(req: Request, ctx: {
209
+ params: Promise<{
210
+ file?: string;
211
+ }>;
212
+ }): Promise<Response>;
213
+ }
214
+ /**
215
+ * `export const { GET, HEAD } = createAssetRoute({ ... })` in `app/api/hyle/assets/[file]/route.ts` (ADR 0015).
216
+ *
217
+ * The SDK rewrites hyle's `/assets/<uuid>.<ext>` in rendered content to `/api/hyle/assets/<uuid>.<ext>`; this route answers it by
218
+ * asking hyle for exactly that file with the target credential and streaming the bytes back, same-origin, so a strict
219
+ * `img-src 'self'` (and `media-src 'self'`) CSP needs no change. hyle serves only assets that a currently published page of this
220
+ * workspace references, so an unpublished or other workspace's asset is a 404 here too.
221
+ *
222
+ * Safety: the only input is the `file` segment, matched against `<uuid>[.<ext>]` before anything is sent, so this is not an open
223
+ * proxy. The browser's cookies and authorization header are never forwarded; only `Range`, `If-Range` and `If-None-Match` are.
224
+ * The response headers are built here (no upstream header is copied blindly), the content type must be on the asset allowlist,
225
+ * the body is size-capped and time-bounded, and every failure is an empty 404 or 502 that says nothing about hyle.
226
+ * The site switch `HYLE_CONTENT_ENABLED=0`/`false`, or missing configuration, answers 404.
227
+ */
228
+ declare function createAssetRoute(options: AssetRouteOptions): AssetRoute;
229
+
230
+ export { type AssetRoute, type AssetRouteOptions, FetchResolverOptions, type HyleNextOptions, HyleResolver, type HyleRootConfig, type HyleRootSitemapOptions, type HyleSitemapOptions, MOUNTS_MAX_STALE_MS, type PageProps, type RevalidateRouteOptions, type RouteParams, createAssetRoute, createRevalidateRoute, hyleMetadata, hylePage, hyleRootMetadata, hyleRootPage, hyleRootSitemap, hyleSitemap };