@tdacorp/hyle-sdk 0.3.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.
Files changed (38) hide show
  1. package/README.md +135 -5
  2. package/bin/hyle-sdk-check-routes.mjs +3 -0
  3. package/dist/check-routes-bin.js +537 -0
  4. package/dist/chunk-67IOIAVW.js +35 -0
  5. package/dist/chunk-BUJFMR3M.js +38 -0
  6. package/dist/chunk-EBNIKRQH.js +536 -0
  7. package/dist/{chunk-EARQBSMF.js → chunk-LGW2KP4X.js} +109 -5
  8. package/dist/{chunk-7VCMJUPC.js → chunk-N4QYPO7S.js} +1 -1
  9. package/dist/diagram-viewer-DYX6R63Y.js +1132 -0
  10. package/dist/index.cjs +279 -23
  11. package/dist/index.d.cts +147 -3
  12. package/dist/index.d.ts +147 -3
  13. package/dist/index.js +18 -1
  14. package/dist/mermaid-diagram.cjs +1267 -16
  15. package/dist/mermaid-diagram.d.cts +39 -1
  16. package/dist/mermaid-diagram.d.ts +39 -1
  17. package/dist/mermaid-diagram.js +35 -5
  18. package/dist/next.cjs +385 -30
  19. package/dist/next.d.cts +93 -5
  20. package/dist/next.d.ts +93 -5
  21. package/dist/next.js +210 -5
  22. package/dist/react.cjs +118 -5
  23. package/dist/react.d.cts +44 -4
  24. package/dist/react.d.ts +44 -4
  25. package/dist/react.js +2 -1
  26. package/dist/{resolve-fMx2W8RR.d.ts → resolve-1rQntRBh.d.ts} +1 -1
  27. package/dist/{resolve-B_p0p4Zn.d.cts → resolve-36-Ng1H0.d.cts} +1 -1
  28. package/dist/styles.css +76 -0
  29. package/dist/{types-CBvLhUPr.d.ts → types-BoyBWF2F.d.ts} +1 -1
  30. package/dist/{types-DjXf6iPo.d.cts → types-CwBCPh6K.d.cts} +20 -1
  31. package/dist/{types-DjXf6iPo.d.ts → types-CwBCPh6K.d.ts} +20 -1
  32. package/dist/{types-D0qoLh4E.d.cts → types-DnPzhrFx.d.cts} +1 -1
  33. package/dist/use-cache.cjs +55 -23
  34. package/dist/use-cache.d.cts +2 -2
  35. package/dist/use-cache.d.ts +2 -2
  36. package/dist/use-cache.js +3 -2
  37. package/package.json +5 -1
  38. package/dist/chunk-HFUJRNFP.js +0 -290
@@ -0,0 +1,537 @@
1
+ // src/check-routes-cli.ts
2
+ import { readFileSync } from "fs";
3
+ import { join } from "path";
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
+
13
+ // src/errors.ts
14
+ var Cp1ClientError = class extends Error {
15
+ code;
16
+ status;
17
+ requestId;
18
+ details;
19
+ constructor(code, message, status, requestId, details) {
20
+ super(message);
21
+ this.name = "Cp1ClientError";
22
+ this.code = code;
23
+ this.status = status;
24
+ this.requestId = requestId;
25
+ this.details = details;
26
+ }
27
+ };
28
+
29
+ // src/client.ts
30
+ var DEFAULT_TIMEOUT_MS = 1e4;
31
+ var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
32
+ var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
33
+ async function readCapped(res, max) {
34
+ const tooLarge = () => new Cp1ClientError("RESPONSE_TOO_LARGE", `hyle response exceeds ${max} bytes`, res.status, "");
35
+ if (Number(res.headers.get("content-length")) > max) throw tooLarge();
36
+ if (!res.body) return "";
37
+ const reader = res.body.getReader();
38
+ const chunks = [];
39
+ let total = 0;
40
+ for (; ; ) {
41
+ const { done, value } = await reader.read();
42
+ if (done) break;
43
+ total += value.byteLength;
44
+ if (total > max) {
45
+ await reader.cancel();
46
+ throw tooLarge();
47
+ }
48
+ chunks.push(value);
49
+ }
50
+ return Buffer.concat(chunks).toString("utf8");
51
+ }
52
+ var KINDS = /* @__PURE__ */ new Set(["article", "list", "redirect", "notfound", "disabled"]);
53
+ var isStrings = (value) => Array.isArray(value) && value.every((v) => typeof v === "string");
54
+ function isMounts(data) {
55
+ const mounts = data.mounts;
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");
57
+ }
58
+ function checkBaseUrl(baseUrl, allowInsecureHttp) {
59
+ let origin;
60
+ try {
61
+ origin = new URL(baseUrl);
62
+ } catch {
63
+ throw new TypeError("baseUrl must be an https origin");
64
+ }
65
+ if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
66
+ throw new TypeError("baseUrl must be https (http is allowed only for localhost, or with allowInsecureHttp)");
67
+ }
68
+ }
69
+ function createHyleClient(options) {
70
+ checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
71
+ if (!options.token) throw new TypeError("token is required");
72
+ const base = options.baseUrl.replace(/\/+$/, "");
73
+ const fetchImpl = options.fetch ?? fetch;
74
+ async function get(pathname, query, init) {
75
+ const url = new URL(`${base}${pathname}`);
76
+ url.search = query.toString();
77
+ const headers = new Headers(init?.headers);
78
+ headers.set("authorization", `Bearer ${options.token}`);
79
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
80
+ const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
81
+ const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
82
+ const text = await readCapped(res, options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES);
83
+ let parsed;
84
+ try {
85
+ parsed = JSON.parse(text);
86
+ } catch {
87
+ parsed = void 0;
88
+ }
89
+ return { parsed, status: res.status };
90
+ }
91
+ const failure = ({ parsed, status }) => {
92
+ const err = parsed?.error;
93
+ return new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${status})`, status, err?.request_id ?? "", err?.details);
94
+ };
95
+ async function resolve(opts) {
96
+ const query = new URLSearchParams({ path: opts.path });
97
+ if (opts.locale !== void 0) query.set("locale", opts.locale);
98
+ if (opts.format !== void 0) query.set("format", opts.format);
99
+ if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
100
+ if (opts.limit !== void 0) query.set("limit", String(opts.limit));
101
+ const reply = await get("/cp1/read/resolve", query, opts.init);
102
+ const data = reply.parsed?.data;
103
+ if (data && data.cp === 1 && typeof data.kind === "string" && KINDS.has(data.kind)) return data;
104
+ throw failure(reply);
105
+ }
106
+ async function mounts(opts = {}) {
107
+ const reply = await get("/cp1/read/mounts", new URLSearchParams(), opts.init);
108
+ const data = reply.parsed?.data;
109
+ if (data?.cp === 1 && data.kind === "disabled") return data;
110
+ if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
111
+ throw failure(reply);
112
+ }
113
+ async function asset(file, opts = {}) {
114
+ if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
115
+ const headers = new Headers({ authorization: `Bearer ${options.token}` });
116
+ for (const name of ["range", "if-range", "if-none-match"]) {
117
+ const value = opts.headers?.[name];
118
+ if (value) headers.set(name, value);
119
+ }
120
+ return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
121
+ }
122
+ return { resolve, mounts, asset };
123
+ }
124
+
125
+ // src/host-sync.ts
126
+ var CONTROL_TOKEN_PREFIX = "hyle_tc_";
127
+ var DEFAULT_TIMEOUT_MS2 = 1e4;
128
+ var MAX_RESPONSE_BYTES = 1024 * 1024;
129
+ var PATH = "/cp1/control/workspace/host-reserved-paths";
130
+ async function syncHostReserved(input) {
131
+ checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
132
+ if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
133
+ throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
134
+ }
135
+ const fetchImpl = input.fetch ?? fetch;
136
+ const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
137
+ method: "PUT",
138
+ // redirect "error": the bearer token must never follow a redirect to another host.
139
+ redirect: "error",
140
+ signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
141
+ headers: {
142
+ authorization: `Bearer ${input.token}`,
143
+ "content-type": "application/json",
144
+ "cp-workspace": input.workspaceId,
145
+ "idempotency-key": `sync-${crypto.randomUUID()}`
146
+ },
147
+ body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
148
+ });
149
+ const text = await readCapped(res, MAX_RESPONSE_BYTES);
150
+ let parsed;
151
+ try {
152
+ parsed = JSON.parse(text);
153
+ } catch {
154
+ parsed = void 0;
155
+ }
156
+ const data = parsed?.data;
157
+ const conflicts = data?.conflicts;
158
+ 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)) {
159
+ return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
160
+ }
161
+ const err = parsed?.error;
162
+ throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
163
+ }
164
+
165
+ // src/next/paths.ts
166
+ function normalizeBasePath(basePath) {
167
+ const raw = basePath ?? "";
168
+ const value = raw === "/" ? "" : raw.replace(/\/$/, "");
169
+ if (value === "") return "";
170
+ if (!/^\/[^\s?#\\]+$/.test(value) || raw.includes("//")) throw new TypeError(`basePath must look like "/learn", got "${basePath}"`);
171
+ return value;
172
+ }
173
+
174
+ // src/route-check.ts
175
+ var NOT_ROUTES = /* @__PURE__ */ new Set(["/_not-found", "/_global-error", "/_app", "/_error", "/_document", "/404", "/500"]);
176
+ var LOCALE_PARAM = "locale";
177
+ function normalizeRoute(key) {
178
+ const segments = key.replace(/\/(page|route)$/, "").split("/").filter((s) => s !== "");
179
+ if (segments.some((s) => s.startsWith("@") || /^\(\.{1,3}\)/.test(s))) return void 0;
180
+ const route = `/${segments.filter((s) => !/^\(.*\)$/.test(s)).join("/")}`;
181
+ return NOT_ROUTES.has(route) ? void 0 : route;
182
+ }
183
+ function hostRoutesFromManifests({ routesManifest, appPaths }) {
184
+ const keys = [...(routesManifest?.staticRoutes ?? []).map((r) => r.page), ...(routesManifest?.dynamicRoutes ?? []).map((r) => r.page), ...Object.keys(appPaths ?? {})];
185
+ return [...new Set(keys.map(normalizeRoute).filter((r) => r !== void 0))].sort();
186
+ }
187
+ var segmentsOf = (path) => path.split("/").filter((s) => s !== "");
188
+ function parse(route) {
189
+ return segmentsOf(route).map((value) => {
190
+ const optional = /^\[\[\.\.\.([^\]]+)\]\]$/.exec(value);
191
+ if (optional) return { kind: "optional-catch-all", name: optional[1] };
192
+ const rest = /^\[\.\.\.([^\]]+)\]$/.exec(value);
193
+ if (rest) return { kind: "catch-all", name: rest[1] };
194
+ const one = /^\[([^\]]+)\]$/.exec(value);
195
+ return one ? { kind: "dynamic", name: one[1] } : { kind: "static", value };
196
+ });
197
+ }
198
+ var isDynamic = (route) => parse(route).some((s) => s.kind !== "static");
199
+ function routeMatches(route, path) {
200
+ const pattern = parse(route);
201
+ const parts = segmentsOf(path);
202
+ for (const [i, seg] of pattern.entries()) {
203
+ if (seg.kind === "optional-catch-all") return i === pattern.length - 1;
204
+ if (seg.kind === "catch-all") return i === pattern.length - 1 && parts.length > i;
205
+ if (i >= parts.length || seg.kind === "static" && seg.value !== parts[i]) return false;
206
+ }
207
+ return parts.length === pattern.length;
208
+ }
209
+ var RANK = { static: 0, dynamic: 1, "catch-all": 2, "optional-catch-all": 3 };
210
+ function compareSpecificity(a, b) {
211
+ const [pa, pb] = [parse(a), parse(b)];
212
+ for (let i = 0; i < Math.min(pa.length, pb.length); i++) {
213
+ const d = RANK[pa[i].kind] - RANK[pb[i].kind];
214
+ if (d !== 0) return d;
215
+ }
216
+ return pa.length - pb.length;
217
+ }
218
+ function withLocale(path, locale) {
219
+ if (!locale) return [path];
220
+ const prefixed = (l) => path === "/" ? `/${l}` : `/${l}${path}`;
221
+ if (locale.prefix === "never") return [path];
222
+ return locale.locales.map((l) => locale.prefix === "as-needed" && l === locale.defaultLocale ? path : prefixed(l));
223
+ }
224
+ function expandLocale(route, locale) {
225
+ const [first, ...rest] = segmentsOf(route);
226
+ if (!locale || first !== `[${LOCALE_PARAM}]`) return [route];
227
+ return [...new Set(withLocale(`/${rest.join("/")}`, locale))];
228
+ }
229
+ var MAX_EXAMPLES = 5;
230
+ function checkRoutes(input) {
231
+ const { locale } = input;
232
+ const hyleParam = input.hyleParam ?? "hyle";
233
+ const routes = [...new Set(input.hostRoutes.flatMap((r) => expandLocale(r, locale)))];
234
+ const staticRoutes = new Set(routes.filter((r) => !isDynamic(r)));
235
+ const dynamicRoutes = routes.filter(isDynamic);
236
+ const catchAlls = dynamicRoutes.filter((r) => {
237
+ const last = parse(r).at(-1);
238
+ return (last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam;
239
+ });
240
+ const notes = [];
241
+ const shadowedHylePaths = input.hylePaths.flatMap(
242
+ (path) => withLocale(path, locale).filter((url) => staticRoutes.has(url)).map((url) => ({ path, url, route: url }))
243
+ );
244
+ const mountCollisions = [];
245
+ for (const prefix of input.mounts) {
246
+ if (prefix === "/") {
247
+ if (staticRoutes.has("/")) notes.push(`root mount: the host's own home page owns "/", so hyle's index page is not served there (pages below it are)`);
248
+ continue;
249
+ }
250
+ for (const url of withLocale(prefix, locale)) if (staticRoutes.has(url)) mountCollisions.push({ prefix, url, route: url });
251
+ }
252
+ const urls = [...new Set([...input.hylePaths, ...input.mounts.filter((m) => m !== "/")].flatMap((p) => withLocale(p, locale)))];
253
+ const dynamicOverlaps = [];
254
+ for (const route of dynamicRoutes) {
255
+ const matched = urls.filter((u) => routeMatches(route, u));
256
+ if (catchAlls.includes(route)) {
257
+ dynamicOverlaps.push({ route, verdict: "hyle-catch-all", matches: matched.length, examples: matched.slice(0, MAX_EXAMPLES) });
258
+ continue;
259
+ }
260
+ const hostWins = matched.filter((u) => {
261
+ const best = catchAlls.filter((c) => routeMatches(c, u)).sort(compareSpecificity)[0];
262
+ return best === void 0 || compareSpecificity(route, best) <= 0;
263
+ });
264
+ if (matched.length === 0) continue;
265
+ const shown = hostWins.length > 0 ? hostWins : matched;
266
+ dynamicOverlaps.push({ route, verdict: hostWins.length > 0 ? "host-wins" : "hyle-wins", matches: shown.length, examples: shown.slice(0, MAX_EXAMPLES) });
267
+ }
268
+ if (!routes.some((r) => r.startsWith(`${ASSET_ROUTE_PREFIX}/`))) {
269
+ 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`);
270
+ }
271
+ if (catchAlls.length === 0) notes.push(`no hyle catch-all route (a "[...${hyleParam}]" or "[[...${hyleParam}]]" page) was found in the host routes`);
272
+ return { shadowedHylePaths, mountCollisions, dynamicOverlaps, notes, ok: shadowedHylePaths.length === 0 && mountCollisions.length === 0 };
273
+ }
274
+ var SDK_OWN_RESERVED = [ASSET_RESERVED_PATH];
275
+ var HASHED_METADATA_ROUTE = /^(opengraph-image|twitter-image|icon|apple-icon)-[a-z0-9]{5,8}$/;
276
+ var isHashedMetadataRoute = (route) => HASHED_METADATA_ROUTE.test(segmentsOf(route).at(-1) ?? "");
277
+ var covers = (entry, path) => {
278
+ if (!entry.endsWith("/*")) return entry === path;
279
+ const base = entry.slice(0, -2);
280
+ return path === base || path.startsWith(`${base}/`);
281
+ };
282
+ function reservedFor(hostRoutes, options = {}) {
283
+ const dropLocale = (route) => {
284
+ const [first, ...rest] = segmentsOf(route);
285
+ return options.locale && first === `[${LOCALE_PARAM}]` ? `/${rest.join("/")}` : route;
286
+ };
287
+ const hyleParam = options.hyleParam ?? "hyle";
288
+ const routes = hostRoutes.map(dropLocale).filter((r) => !isHashedMetadataRoute(r));
289
+ const exact = new Set(routes.filter((r) => !isDynamic(r)));
290
+ const mounts = options.mounts?.filter((m) => m !== "/");
291
+ const onMount = (segment) => mounts?.some((m) => m === `/${segment}` || m.startsWith(`/${segment}/`)) ?? true;
292
+ const groups = /* @__PURE__ */ new Map();
293
+ for (const route of exact) {
294
+ const [first, ...rest] = segmentsOf(route);
295
+ if (first !== void 0 && rest.length > 0) groups.set(first, [...groups.get(first) ?? [], route]);
296
+ }
297
+ const wildcards = /* @__PURE__ */ new Set();
298
+ for (const [first, members] of groups) {
299
+ if (members.length >= 2 && !onMount(first)) wildcards.add(`/${first}/*`);
300
+ }
301
+ for (const route of routes.filter(isDynamic)) {
302
+ const segments = parse(route);
303
+ const last = segments.at(-1);
304
+ if ((last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam) continue;
305
+ const dir = segments.slice(0, segments.findIndex((seg) => seg.kind !== "static")).map((seg) => seg.kind === "static" ? seg.value : "").join("/");
306
+ if (dir === "" || !mounts) continue;
307
+ if (!mounts.some((m) => m === `/${dir}` || m.startsWith(`/${dir}/`))) wildcards.add(`/${dir}/*`);
308
+ }
309
+ const all = [...exact, ...wildcards];
310
+ const base = (entry) => entry.endsWith("/*") ? entry.slice(0, -2) : entry;
311
+ return all.filter((entry) => !all.some((other) => other !== entry && other.endsWith("/*") && covers(other, base(entry)))).sort();
312
+ }
313
+ function formatReport(report) {
314
+ const lines = [];
315
+ const section = (title, rows, empty) => lines.push(`${title}`, ...rows.length ? rows.map((r) => ` ${printable(r)}`) : [` ${empty}`], "");
316
+ section(
317
+ "(a) hyle paths shadowed by host static routes (the hyle page is never served):",
318
+ report.shadowedHylePaths.map((s) => `${s.url} (hyle path ${s.path})`),
319
+ "none"
320
+ );
321
+ section("(c) mounts whose prefix is a host static route (the mount's index page is never served):", report.mountCollisions.map((m) => `${m.url} (mount ${m.prefix})`), "none");
322
+ section(
323
+ "(b) host dynamic routes matching hyle URLs:",
324
+ report.dynamicOverlaps.map((d) => {
325
+ const label = { "hyle-catch-all": "OK: this is hyle's catch-all", "hyle-wins": "OK: hyle's catch-all is more specific", "host-wins": "WARN: the host route is served, hyle content is hidden" }[d.verdict];
326
+ return `${d.route} ${label} (${d.matches} URLs, e.g. ${d.examples.join(", ") || "-"})`;
327
+ }),
328
+ "none"
329
+ );
330
+ if (report.notes.length) section("notes:", report.notes, "");
331
+ lines.push(report.ok ? "RESULT: no collisions" : "RESULT: collisions found");
332
+ return lines.join("\n");
333
+ }
334
+ var MAX_PRINTED = 200;
335
+ var printable = (text) => {
336
+ const clean = text.replace(/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|.)?/g, "").replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
337
+ return clean.length > MAX_PRINTED ? `${clean.slice(0, MAX_PRINTED)}...` : clean;
338
+ };
339
+
340
+ // src/sitemap.ts
341
+ var PAGE_LIMIT = 100;
342
+ var DEFAULT_MAX_PAGES = 20;
343
+ var SECTION_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
344
+ var UNSAFE_PATH = /[\\?#<>&"'\u0000- \u007f]/;
345
+ async function listPublicationPaths(options) {
346
+ const maxPages = options.maxPages ?? DEFAULT_MAX_PAGES;
347
+ const prefix = `${options.basePath}/`;
348
+ const indexes = [options.basePath || "/"];
349
+ for (const slug of options.sections ?? []) if (slug !== "posts" && SECTION_SLUG.test(slug)) indexes.push(`${options.basePath}/${slug}`);
350
+ const found = /* @__PURE__ */ new Map();
351
+ let complete = true;
352
+ try {
353
+ for (const index of new Set(indexes)) {
354
+ let cursor;
355
+ for (let page = 0; page < maxPages; page++) {
356
+ const result = await options.client.resolve({
357
+ path: index,
358
+ limit: PAGE_LIMIT,
359
+ ...options.locale !== void 0 ? { locale: options.locale } : {},
360
+ ...cursor !== void 0 ? { cursor } : {}
361
+ });
362
+ if (result.kind !== "list") {
363
+ complete = false;
364
+ break;
365
+ }
366
+ for (const item of result.items) {
367
+ if (item.canonical_path.startsWith(prefix) && !UNSAFE_PATH.test(item.canonical_path)) found.set(item.canonical_path, item.published_at);
368
+ }
369
+ if (!result.next_cursor) break;
370
+ if (page === maxPages - 1) complete = false;
371
+ cursor = result.next_cursor;
372
+ }
373
+ }
374
+ } catch {
375
+ complete = false;
376
+ }
377
+ return { paths: [...found].map(([path, publishedAt]) => ({ path, publishedAt })), complete };
378
+ }
379
+
380
+ // src/check-routes-cli.ts
381
+ var USAGE = `hyle-sdk-check-routes [--next-dir .next] [--base-url URL] [--json] [--print-reserved]
382
+ [--sync [--strict] [--no-check] [--host ID] [--build-id ID] [--allow-empty] [--allow-non-production]]
383
+ [--locales en,fr,es --default-locale en --locale-prefix as-needed|always|never] [--sections a,b] [--hyle-param hyle]
384
+
385
+ Run after \`next build\`. Reads the build's route manifests and hyle's read-only endpoints (mounts, and the published pages of each mount).
386
+ Credentials: HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN. The token is read from the environment only, never a flag.
387
+ (a) hyle pages a host static route shadows, (b) host dynamic routes that match hyle URLs, (c) mounts that are host static routes.
388
+ --print-reserved print the host's routes in hyle's "Reserved paths" format and exit.
389
+ --sync report that list to hyle (ADR 0016) so nobody maintains it by hand, then run the check. Needs HYLE_CONTROL_TOKEN
390
+ (a hyle_tc_ control credential with hyle.workspace.manage; the read token cannot write), read from the environment only.
391
+ A failed sync only warns, so it never fails a deploy, unless --strict (exit 3). Skipped on a non-production Vercel
392
+ build (VERCEL_ENV) unless --allow-non-production. --no-check syncs without the collision check. The host id comes
393
+ from --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL; the build id from <next-dir>/BUILD_ID or --build-id.
394
+ An empty list is refused unless --allow-empty.
395
+ Exit: 0 no collision, 1 collision (a) or (c), 2 cannot run, 3 sync failed under --strict.`;
396
+ var FLAGS = /* @__PURE__ */ new Set(["--next-dir", "--base-url", "--locales", "--default-locale", "--locale-prefix", "--sections", "--hyle-param", "--host", "--build-id"]);
397
+ var BOOLEAN = /* @__PURE__ */ new Set(["--json", "--print-reserved", "--help", "--sync", "--strict", "--no-check", "--allow-empty", "--allow-non-production"]);
398
+ var CANNOT_RUN = 2;
399
+ var SYNC_FAILED = 3;
400
+ var MAX_SYNCED_PATHS = 512;
401
+ function parseArgs(argv) {
402
+ const args = /* @__PURE__ */ new Map();
403
+ for (let i = 0; i < argv.length; i++) {
404
+ const flag = argv[i];
405
+ if (BOOLEAN.has(flag)) args.set(flag, "true");
406
+ else if (FLAGS.has(flag) && argv[i + 1] !== void 0) args.set(flag, argv[++i]);
407
+ else throw new Error(`unknown or incomplete option ${flag}`);
408
+ }
409
+ return args;
410
+ }
411
+ var readJson = (file) => JSON.parse(readFileSync(file, "utf8"));
412
+ var SAFE_ID = /[^A-Za-z0-9._-]/g;
413
+ async function syncStep(args, io, ctx) {
414
+ const fail = (reason) => (io.err(`sync: ${printable(reason)}`), { status: "failed", reason });
415
+ const vercelEnv = io.env.VERCEL_ENV;
416
+ if (vercelEnv !== void 0 && vercelEnv !== "production" && !args.has("--allow-non-production")) {
417
+ io.err(`sync: skipped, this is a ${printable(vercelEnv)} build (a preview must not replace production's list; --allow-non-production overrides)`);
418
+ return { status: "skipped" };
419
+ }
420
+ const { baseUrl, mounts } = ctx.plan;
421
+ const token = io.env.HYLE_CONTROL_TOKEN;
422
+ if (!token) return fail("set HYLE_CONTROL_TOKEN (a hyle_tc_ control credential with hyle.workspace.manage; the read token cannot write)");
423
+ 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");
424
+ const host = (args.get("--host") ?? io.env.HYLE_HOST_ID ?? io.env.VERCEL_PROJECT_PRODUCTION_URL)?.replace(SAFE_ID, "-").slice(0, 128);
425
+ if (!host) return fail("name this host with --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL");
426
+ let buildId = args.get("--build-id") ?? io.env.VERCEL_GIT_COMMIT_SHA;
427
+ try {
428
+ buildId = readFileSync(join(ctx.nextDir, "BUILD_ID"), "utf8").trim();
429
+ } catch {
430
+ }
431
+ buildId = buildId?.replace(SAFE_ID, "-").slice(0, 128);
432
+ if (!buildId) return fail("no build id: <next-dir>/BUILD_ID is missing; pass --build-id");
433
+ const rootMount = mounts.prefixes.includes("/");
434
+ const fromHost = reservedFor(ctx.hostRoutes, { ...ctx.locale ? { locale: ctx.locale } : {}, mounts: mounts.prefixes, hyleParam: ctx.hyleParam }).filter((p) => !(rootMount && p === "/"));
435
+ const reserved = [.../* @__PURE__ */ new Set([...fromHost, ...SDK_OWN_RESERVED])].sort();
436
+ 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)");
437
+ if (reserved.length > MAX_SYNCED_PATHS) return fail(`${reserved.length} reserved paths exceed hyle's limit of ${MAX_SYNCED_PATHS}`);
438
+ try {
439
+ const result = await syncHostReserved({ baseUrl, token, workspaceId: mounts.workspaceId, paths: reserved, host, buildId, ...io.fetch ? { fetch: io.fetch } : {} });
440
+ if (!args.has("--json")) {
441
+ io.out(`sync: ${result.paths.length} reserved paths ${result.changed ? "updated" : "unchanged"} in hyle (host ${printable(host)}, build ${printable(buildId)})`);
442
+ if (result.conflicts.total > 0) {
443
+ io.out(`sync: ${result.conflicts.total} published hyle URL(s) are on paths this host owns (hyle unpublished nothing):`);
444
+ for (const path of result.conflicts.offenders) io.out(` ${printable(path)}`);
445
+ }
446
+ }
447
+ return { status: "ok", result };
448
+ } catch (error) {
449
+ return fail(error instanceof Error ? `${error.name}: ${error.message}` : "unknown error");
450
+ }
451
+ }
452
+ async function runCli(argv, io) {
453
+ try {
454
+ const args = parseArgs(argv);
455
+ if (args.has("--help")) return io.out(USAGE), 0;
456
+ const nextDir = args.get("--next-dir") ?? ".next";
457
+ const hyleParam = args.get("--hyle-param") ?? "hyle";
458
+ let locale;
459
+ if (args.has("--locales")) {
460
+ const prefix = args.get("--locale-prefix") ?? "as-needed";
461
+ const locales = args.get("--locales").split(",").filter(Boolean);
462
+ const defaultLocale = args.get("--default-locale") ?? locales[0];
463
+ if (!["as-needed", "always", "never"].includes(prefix) || !defaultLocale || !locales.includes(defaultLocale)) throw new Error("--locales needs --default-locale among them and --locale-prefix as-needed|always|never");
464
+ locale = { locales, defaultLocale, prefix };
465
+ }
466
+ let hostRoutes;
467
+ try {
468
+ const appPaths = (() => {
469
+ try {
470
+ return readJson(join(nextDir, "server", "app-paths-manifest.json"));
471
+ } catch {
472
+ return void 0;
473
+ }
474
+ })();
475
+ hostRoutes = hostRoutesFromManifests({ routesManifest: readJson(join(nextDir, "routes-manifest.json")), ...appPaths ? { appPaths } : {} });
476
+ } catch {
477
+ io.err(`CANNOT RUN: no readable ${join(nextDir, "routes-manifest.json")} (run \`next build\` first, or pass --next-dir)`);
478
+ return CANNOT_RUN;
479
+ }
480
+ const baseUrl = args.get("--base-url") ?? io.env.HYLE_TARGET_BASE_URL;
481
+ const token = io.env.HYLE_TARGET_TOKEN;
482
+ const client = baseUrl && token ? createHyleClient({ baseUrl, token, ...io.fetch ? { fetch: io.fetch } : {} }) : void 0;
483
+ let mounts;
484
+ let mountsError;
485
+ try {
486
+ mounts = client ? await client.mounts() : void 0;
487
+ } catch (error) {
488
+ if (!args.has("--sync")) throw error;
489
+ mountsError = error;
490
+ }
491
+ if (mounts?.kind === "disabled") {
492
+ io.err("CANNOT RUN: hyle's read surface is switched off (kind: disabled)");
493
+ return CANNOT_RUN;
494
+ }
495
+ const prefixes = mounts?.mounts.map((m) => m.prefix);
496
+ const strict = args.has("--strict");
497
+ let sync;
498
+ if (args.has("--sync")) {
499
+ 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}` } : {} } });
500
+ if (args.has("--no-check")) {
501
+ if (args.has("--json")) io.out(JSON.stringify({ sync }));
502
+ return sync.status === "failed" && strict ? SYNC_FAILED : 0;
503
+ }
504
+ }
505
+ if (args.has("--print-reserved")) {
506
+ const reserved = [.../* @__PURE__ */ new Set([...reservedFor(hostRoutes, { ...locale ? { locale } : {}, ...prefixes ? { mounts: prefixes } : {}, hyleParam }), ...SDK_OWN_RESERVED])].sort();
507
+ 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/*");
508
+ io.out(args.has("--json") ? JSON.stringify(reserved) : reserved.join("\n"));
509
+ return 0;
510
+ }
511
+ if (mountsError) throw mountsError;
512
+ if (!client || !mounts || mounts.kind !== "mounts") {
513
+ io.err("CANNOT RUN: set HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN");
514
+ return CANNOT_RUN;
515
+ }
516
+ const sections = args.get("--sections")?.split(",").filter(Boolean);
517
+ const hylePaths = [];
518
+ for (const { prefix } of mounts.mounts) {
519
+ const listing = await listPublicationPaths({ client, basePath: normalizeBasePath(prefix), maxPages: 100, ...sections ? { sections } : {} });
520
+ if (!listing.complete) {
521
+ io.err(`CANNOT RUN: hyle's pages under ${printable(prefix)} could not be listed completely, so a collision could be missed`);
522
+ return CANNOT_RUN;
523
+ }
524
+ hylePaths.push(...listing.paths.map((p) => p.path));
525
+ }
526
+ const report = checkRoutes({ hostRoutes, mounts: mounts.mounts.map((m) => m.prefix), hylePaths, hyleParam, ...locale ? { locale } : {} });
527
+ io.out(args.has("--json") ? JSON.stringify(sync ? { ...report, sync } : report, null, 2) : formatReport(report));
528
+ if (!report.ok) return 1;
529
+ return sync?.status === "failed" && strict ? SYNC_FAILED : 0;
530
+ } catch (error) {
531
+ io.err(`CANNOT RUN: ${error instanceof Error ? printable(`${error.name}: ${error.message}`) : "unknown error"}`);
532
+ return CANNOT_RUN;
533
+ }
534
+ }
535
+
536
+ // src/check-routes-bin.ts
537
+ process.exitCode = await runCli(process.argv.slice(2), { env: process.env, out: (l) => console.log(l), err: (l) => console.error(l) });
@@ -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
+ };
@@ -0,0 +1,38 @@
1
+ // src/react/viewer/labels.ts
2
+ var VIEWER_LABELS_EN = {
3
+ expand: "Expand diagram",
4
+ expandHint: "Expand",
5
+ viewer: "Diagram viewer",
6
+ close: "Close",
7
+ zoomIn: "Zoom in",
8
+ zoomOut: "Zoom out",
9
+ fit: "Fit to window",
10
+ actual: "Actual size",
11
+ search: "Find in diagram",
12
+ searchPlaceholder: "Find",
13
+ noMatch: "No match",
14
+ matchOf: "{n} of {total}",
15
+ copySource: "Copy diagram source",
16
+ downloadSvg: "Download SVG",
17
+ downloadPng: "Download PNG",
18
+ copyImage: "Copy as image",
19
+ pngScale: "PNG scale",
20
+ fullscreen: "Fullscreen",
21
+ exitFullscreen: "Exit fullscreen",
22
+ copied: "Copied",
23
+ saved: "Saved",
24
+ unavailable: "Not available here",
25
+ hint: "Scroll to zoom, drag to pan, click a node to trace its paths, press / to search",
26
+ legendSelected: "Selected",
27
+ legendUpstream: "Upstream",
28
+ legendDownstream: "Downstream",
29
+ outgoing: "outgoing",
30
+ tracing: "{label}: {up} upstream, {down} downstream",
31
+ map: "Overview map"
32
+ };
33
+ var fill = (template, values) => template.replace(/\{(\w+)\}/g, (m, k) => k in values ? String(values[k]) : m);
34
+
35
+ export {
36
+ VIEWER_LABELS_EN,
37
+ fill
38
+ };