@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.
- package/README.md +135 -5
- package/bin/hyle-sdk-check-routes.mjs +3 -0
- package/dist/check-routes-bin.js +537 -0
- package/dist/chunk-67IOIAVW.js +35 -0
- package/dist/chunk-BUJFMR3M.js +38 -0
- package/dist/chunk-EBNIKRQH.js +536 -0
- package/dist/{chunk-EARQBSMF.js → chunk-LGW2KP4X.js} +109 -5
- package/dist/{chunk-7VCMJUPC.js → chunk-N4QYPO7S.js} +1 -1
- package/dist/diagram-viewer-DYX6R63Y.js +1132 -0
- package/dist/index.cjs +279 -23
- package/dist/index.d.cts +147 -3
- package/dist/index.d.ts +147 -3
- package/dist/index.js +18 -1
- package/dist/mermaid-diagram.cjs +1267 -16
- package/dist/mermaid-diagram.d.cts +39 -1
- package/dist/mermaid-diagram.d.ts +39 -1
- package/dist/mermaid-diagram.js +35 -5
- package/dist/next.cjs +385 -30
- package/dist/next.d.cts +93 -5
- package/dist/next.d.ts +93 -5
- package/dist/next.js +210 -5
- package/dist/react.cjs +118 -5
- package/dist/react.d.cts +44 -4
- package/dist/react.d.ts +44 -4
- package/dist/react.js +2 -1
- package/dist/{resolve-fMx2W8RR.d.ts → resolve-1rQntRBh.d.ts} +1 -1
- package/dist/{resolve-B_p0p4Zn.d.cts → resolve-36-Ng1H0.d.cts} +1 -1
- package/dist/styles.css +76 -0
- package/dist/{types-CBvLhUPr.d.ts → types-BoyBWF2F.d.ts} +1 -1
- package/dist/{types-DjXf6iPo.d.cts → types-CwBCPh6K.d.cts} +20 -1
- package/dist/{types-DjXf6iPo.d.ts → types-CwBCPh6K.d.ts} +20 -1
- package/dist/{types-D0qoLh4E.d.cts → types-DnPzhrFx.d.cts} +1 -1
- package/dist/use-cache.cjs +55 -23
- package/dist/use-cache.d.cts +2 -2
- package/dist/use-cache.d.ts +2 -2
- package/dist/use-cache.js +3 -2
- package/package.json +5 -1
- package/dist/chunk-HFUJRNFP.js +0 -290
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ASSET_FILE,
|
|
3
|
+
ASSET_RESERVED_PATH,
|
|
4
|
+
ASSET_ROUTE_PREFIX
|
|
5
|
+
} from "./chunk-67IOIAVW.js";
|
|
6
|
+
|
|
7
|
+
// src/errors.ts
|
|
8
|
+
var Cp1ClientError = class extends Error {
|
|
9
|
+
code;
|
|
10
|
+
status;
|
|
11
|
+
requestId;
|
|
12
|
+
details;
|
|
13
|
+
constructor(code, message, status, requestId, details) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.name = "Cp1ClientError";
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.requestId = requestId;
|
|
19
|
+
this.details = details;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
// src/client.ts
|
|
24
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
25
|
+
var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
|
|
26
|
+
var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
27
|
+
async function readCapped(res, max) {
|
|
28
|
+
const tooLarge = () => new Cp1ClientError("RESPONSE_TOO_LARGE", `hyle response exceeds ${max} bytes`, res.status, "");
|
|
29
|
+
if (Number(res.headers.get("content-length")) > max) throw tooLarge();
|
|
30
|
+
if (!res.body) return "";
|
|
31
|
+
const reader = res.body.getReader();
|
|
32
|
+
const chunks = [];
|
|
33
|
+
let total = 0;
|
|
34
|
+
for (; ; ) {
|
|
35
|
+
const { done, value } = await reader.read();
|
|
36
|
+
if (done) break;
|
|
37
|
+
total += value.byteLength;
|
|
38
|
+
if (total > max) {
|
|
39
|
+
await reader.cancel();
|
|
40
|
+
throw tooLarge();
|
|
41
|
+
}
|
|
42
|
+
chunks.push(value);
|
|
43
|
+
}
|
|
44
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
45
|
+
}
|
|
46
|
+
var KINDS = /* @__PURE__ */ new Set(["article", "list", "redirect", "notfound", "disabled"]);
|
|
47
|
+
var isStrings = (value) => Array.isArray(value) && value.every((v) => typeof v === "string");
|
|
48
|
+
function isMounts(data) {
|
|
49
|
+
const mounts = data.mounts;
|
|
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");
|
|
51
|
+
}
|
|
52
|
+
function checkBaseUrl(baseUrl, allowInsecureHttp) {
|
|
53
|
+
let origin;
|
|
54
|
+
try {
|
|
55
|
+
origin = new URL(baseUrl);
|
|
56
|
+
} catch {
|
|
57
|
+
throw new TypeError("baseUrl must be an https origin");
|
|
58
|
+
}
|
|
59
|
+
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
|
|
60
|
+
throw new TypeError("baseUrl must be https (http is allowed only for localhost, or with allowInsecureHttp)");
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function createHyleClient(options) {
|
|
64
|
+
checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
|
|
65
|
+
if (!options.token) throw new TypeError("token is required");
|
|
66
|
+
const base = options.baseUrl.replace(/\/+$/, "");
|
|
67
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
68
|
+
async function get(pathname, query, init) {
|
|
69
|
+
const url = new URL(`${base}${pathname}`);
|
|
70
|
+
url.search = query.toString();
|
|
71
|
+
const headers = new Headers(init?.headers);
|
|
72
|
+
headers.set("authorization", `Bearer ${options.token}`);
|
|
73
|
+
const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
74
|
+
const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
|
|
75
|
+
const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
|
|
76
|
+
const text = await readCapped(res, options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES);
|
|
77
|
+
let parsed;
|
|
78
|
+
try {
|
|
79
|
+
parsed = JSON.parse(text);
|
|
80
|
+
} catch {
|
|
81
|
+
parsed = void 0;
|
|
82
|
+
}
|
|
83
|
+
return { parsed, status: res.status };
|
|
84
|
+
}
|
|
85
|
+
const failure = ({ parsed, status }) => {
|
|
86
|
+
const err = parsed?.error;
|
|
87
|
+
return new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${status})`, status, err?.request_id ?? "", err?.details);
|
|
88
|
+
};
|
|
89
|
+
async function resolve(opts) {
|
|
90
|
+
const query = new URLSearchParams({ path: opts.path });
|
|
91
|
+
if (opts.locale !== void 0) query.set("locale", opts.locale);
|
|
92
|
+
if (opts.format !== void 0) query.set("format", opts.format);
|
|
93
|
+
if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
|
|
94
|
+
if (opts.limit !== void 0) query.set("limit", String(opts.limit));
|
|
95
|
+
const reply = await get("/cp1/read/resolve", query, opts.init);
|
|
96
|
+
const data = reply.parsed?.data;
|
|
97
|
+
if (data && data.cp === 1 && typeof data.kind === "string" && KINDS.has(data.kind)) return data;
|
|
98
|
+
throw failure(reply);
|
|
99
|
+
}
|
|
100
|
+
async function mounts(opts = {}) {
|
|
101
|
+
const reply = await get("/cp1/read/mounts", new URLSearchParams(), opts.init);
|
|
102
|
+
const data = reply.parsed?.data;
|
|
103
|
+
if (data?.cp === 1 && data.kind === "disabled") return data;
|
|
104
|
+
if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
|
|
105
|
+
throw failure(reply);
|
|
106
|
+
}
|
|
107
|
+
async function asset(file, opts = {}) {
|
|
108
|
+
if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
|
|
109
|
+
const headers = new Headers({ authorization: `Bearer ${options.token}` });
|
|
110
|
+
for (const name of ["range", "if-range", "if-none-match"]) {
|
|
111
|
+
const value = opts.headers?.[name];
|
|
112
|
+
if (value) headers.set(name, value);
|
|
113
|
+
}
|
|
114
|
+
return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
|
|
115
|
+
}
|
|
116
|
+
return { resolve, mounts, asset };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/host-sync.ts
|
|
120
|
+
var CONTROL_TOKEN_PREFIX = "hyle_tc_";
|
|
121
|
+
var DEFAULT_TIMEOUT_MS2 = 1e4;
|
|
122
|
+
var MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
123
|
+
var PATH = "/cp1/control/workspace/host-reserved-paths";
|
|
124
|
+
async function syncHostReserved(input) {
|
|
125
|
+
checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
|
|
126
|
+
if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
|
|
127
|
+
throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
|
|
128
|
+
}
|
|
129
|
+
const fetchImpl = input.fetch ?? fetch;
|
|
130
|
+
const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
|
|
131
|
+
method: "PUT",
|
|
132
|
+
// redirect "error": the bearer token must never follow a redirect to another host.
|
|
133
|
+
redirect: "error",
|
|
134
|
+
signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
|
|
135
|
+
headers: {
|
|
136
|
+
authorization: `Bearer ${input.token}`,
|
|
137
|
+
"content-type": "application/json",
|
|
138
|
+
"cp-workspace": input.workspaceId,
|
|
139
|
+
"idempotency-key": `sync-${crypto.randomUUID()}`
|
|
140
|
+
},
|
|
141
|
+
body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
|
|
142
|
+
});
|
|
143
|
+
const text = await readCapped(res, MAX_RESPONSE_BYTES);
|
|
144
|
+
let parsed;
|
|
145
|
+
try {
|
|
146
|
+
parsed = JSON.parse(text);
|
|
147
|
+
} catch {
|
|
148
|
+
parsed = void 0;
|
|
149
|
+
}
|
|
150
|
+
const data = parsed?.data;
|
|
151
|
+
const conflicts = data?.conflicts;
|
|
152
|
+
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)) {
|
|
153
|
+
return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
|
|
154
|
+
}
|
|
155
|
+
const err = parsed?.error;
|
|
156
|
+
throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// src/delivery-dedupe.ts
|
|
160
|
+
var DeliveryDedupe = class {
|
|
161
|
+
constructor(capacity = 1e3) {
|
|
162
|
+
this.capacity = capacity;
|
|
163
|
+
}
|
|
164
|
+
capacity;
|
|
165
|
+
seen = /* @__PURE__ */ new Map();
|
|
166
|
+
/** True if this id was already recorded (a duplicate delivery). */
|
|
167
|
+
has(deliveryId) {
|
|
168
|
+
return this.seen.has(deliveryId);
|
|
169
|
+
}
|
|
170
|
+
add(deliveryId) {
|
|
171
|
+
this.seen.delete(deliveryId);
|
|
172
|
+
this.seen.set(deliveryId, true);
|
|
173
|
+
if (this.seen.size > this.capacity) {
|
|
174
|
+
const oldest = this.seen.keys().next().value;
|
|
175
|
+
if (oldest !== void 0) this.seen.delete(oldest);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
// src/signature.ts
|
|
181
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
182
|
+
var SIGNATURE_HEX = /^[0-9a-f]{64}$/;
|
|
183
|
+
function parseSignatureHeader(header) {
|
|
184
|
+
let timestamp;
|
|
185
|
+
const signatures = [];
|
|
186
|
+
for (const part of header.split(",")) {
|
|
187
|
+
const [key, value] = part.split("=", 2);
|
|
188
|
+
if (key === "t" && value) {
|
|
189
|
+
const parsed = Number(value);
|
|
190
|
+
if (Number.isFinite(parsed)) timestamp = parsed;
|
|
191
|
+
} else if (key === "v1" && value && SIGNATURE_HEX.test(value)) {
|
|
192
|
+
signatures.push(value);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (timestamp === void 0 || signatures.length === 0) return void 0;
|
|
196
|
+
return { timestamp, signatures };
|
|
197
|
+
}
|
|
198
|
+
function computeSignature(secret, timestamp, rawBody) {
|
|
199
|
+
return createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest("hex");
|
|
200
|
+
}
|
|
201
|
+
function signaturesEqual(a, b) {
|
|
202
|
+
const bufA = Buffer.from(a, "hex");
|
|
203
|
+
const bufB = Buffer.from(b, "hex");
|
|
204
|
+
if (bufA.length !== bufB.length) return false;
|
|
205
|
+
return timingSafeEqual(bufA, bufB);
|
|
206
|
+
}
|
|
207
|
+
function verifyHyleSignature(params) {
|
|
208
|
+
const secrets = params.secrets.filter((s) => s !== "");
|
|
209
|
+
if (!params.header || secrets.length === 0) return false;
|
|
210
|
+
const parsed = parseSignatureHeader(params.header);
|
|
211
|
+
if (!parsed) return false;
|
|
212
|
+
const tolerance = params.toleranceSeconds ?? 300;
|
|
213
|
+
const now = (params.now ?? Date.now)() / 1e3;
|
|
214
|
+
if (Math.abs(now - parsed.timestamp) > tolerance) return false;
|
|
215
|
+
for (const secret of secrets) {
|
|
216
|
+
const expected = computeSignature(secret, parsed.timestamp, params.rawBody);
|
|
217
|
+
for (const candidate of parsed.signatures) {
|
|
218
|
+
if (signaturesEqual(candidate, expected)) return true;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// src/tag-validation.ts
|
|
225
|
+
var CACHE_TAG_PATTERN = /^hyle:1:(pub|doc|sec|link|ws):[0-9a-f-]{36}(:[\x21-\x7e]{1,200})?$/;
|
|
226
|
+
function isValidCacheTag(tag) {
|
|
227
|
+
return CACHE_TAG_PATTERN.test(tag);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// src/revalidation-callback.ts
|
|
231
|
+
var MAX_BODY_BYTES = 65536;
|
|
232
|
+
var MAX_TAGS = 1e3;
|
|
233
|
+
function createRevalidationCallbackRoute(options) {
|
|
234
|
+
const dedupe = new DeliveryDedupe(options.dedupeCapacity);
|
|
235
|
+
return {
|
|
236
|
+
async POST(req) {
|
|
237
|
+
const rawBody = await readCapped2(req);
|
|
238
|
+
if (rawBody === void 0) return new Response(null, { status: 413 });
|
|
239
|
+
const verified = verifyHyleSignature({
|
|
240
|
+
header: req.headers.get("hyle-signature"),
|
|
241
|
+
rawBody,
|
|
242
|
+
secrets: options.secrets,
|
|
243
|
+
...options.toleranceSeconds !== void 0 ? { toleranceSeconds: options.toleranceSeconds } : {},
|
|
244
|
+
...options.now !== void 0 ? { now: options.now } : {}
|
|
245
|
+
});
|
|
246
|
+
if (!verified) {
|
|
247
|
+
return new Response(null, { status: 401 });
|
|
248
|
+
}
|
|
249
|
+
let payload;
|
|
250
|
+
try {
|
|
251
|
+
payload = JSON.parse(rawBody);
|
|
252
|
+
} catch {
|
|
253
|
+
return new Response(null, { status: 400 });
|
|
254
|
+
}
|
|
255
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return new Response(null, { status: 400 });
|
|
256
|
+
const body = payload;
|
|
257
|
+
if (body.cp !== 1) {
|
|
258
|
+
return okResponse(0);
|
|
259
|
+
}
|
|
260
|
+
const tags = body.tags ?? [];
|
|
261
|
+
if (typeof body.workspace_id !== "string" || !Array.isArray(tags) || tags.length > MAX_TAGS || !tags.every((t) => typeof t === "string")) {
|
|
262
|
+
return new Response(null, { status: 400 });
|
|
263
|
+
}
|
|
264
|
+
if (body.workspace_id !== options.workspaceId) {
|
|
265
|
+
return okResponse(0);
|
|
266
|
+
}
|
|
267
|
+
const deliveryId = req.headers.get("hyle-delivery-id");
|
|
268
|
+
if (deliveryId && dedupe.has(deliveryId)) {
|
|
269
|
+
return okResponse(0);
|
|
270
|
+
}
|
|
271
|
+
let purged = 0;
|
|
272
|
+
try {
|
|
273
|
+
for (const tag of tags) {
|
|
274
|
+
if (!isValidCacheTag(tag)) continue;
|
|
275
|
+
options.revalidateTag(tag);
|
|
276
|
+
purged += 1;
|
|
277
|
+
}
|
|
278
|
+
} catch {
|
|
279
|
+
return new Response(null, { status: 500 });
|
|
280
|
+
}
|
|
281
|
+
if (deliveryId) dedupe.add(deliveryId);
|
|
282
|
+
return okResponse(purged);
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
async function readCapped2(req) {
|
|
287
|
+
const declared = Number(req.headers.get("content-length"));
|
|
288
|
+
if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) return void 0;
|
|
289
|
+
if (!req.body) return "";
|
|
290
|
+
const reader = req.body.getReader();
|
|
291
|
+
const chunks = [];
|
|
292
|
+
let total = 0;
|
|
293
|
+
for (; ; ) {
|
|
294
|
+
const { done, value } = await reader.read();
|
|
295
|
+
if (done) break;
|
|
296
|
+
total += value.byteLength;
|
|
297
|
+
if (total > MAX_BODY_BYTES) {
|
|
298
|
+
await reader.cancel();
|
|
299
|
+
return void 0;
|
|
300
|
+
}
|
|
301
|
+
chunks.push(value);
|
|
302
|
+
}
|
|
303
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
304
|
+
}
|
|
305
|
+
function okResponse(purged) {
|
|
306
|
+
return new Response(JSON.stringify({ ok: true, purged }), {
|
|
307
|
+
status: 200,
|
|
308
|
+
headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// src/sitemap.ts
|
|
313
|
+
var PAGE_LIMIT = 100;
|
|
314
|
+
var DEFAULT_MAX_PAGES = 20;
|
|
315
|
+
var SECTION_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
316
|
+
var UNSAFE_PATH = /[\\?#<>&"'\u0000- \u007f]/;
|
|
317
|
+
async function listPublicationPaths(options) {
|
|
318
|
+
const maxPages = options.maxPages ?? DEFAULT_MAX_PAGES;
|
|
319
|
+
const prefix = `${options.basePath}/`;
|
|
320
|
+
const indexes = [options.basePath || "/"];
|
|
321
|
+
for (const slug of options.sections ?? []) if (slug !== "posts" && SECTION_SLUG.test(slug)) indexes.push(`${options.basePath}/${slug}`);
|
|
322
|
+
const found = /* @__PURE__ */ new Map();
|
|
323
|
+
let complete = true;
|
|
324
|
+
try {
|
|
325
|
+
for (const index of new Set(indexes)) {
|
|
326
|
+
let cursor;
|
|
327
|
+
for (let page = 0; page < maxPages; page++) {
|
|
328
|
+
const result = await options.client.resolve({
|
|
329
|
+
path: index,
|
|
330
|
+
limit: PAGE_LIMIT,
|
|
331
|
+
...options.locale !== void 0 ? { locale: options.locale } : {},
|
|
332
|
+
...cursor !== void 0 ? { cursor } : {}
|
|
333
|
+
});
|
|
334
|
+
if (result.kind !== "list") {
|
|
335
|
+
complete = false;
|
|
336
|
+
break;
|
|
337
|
+
}
|
|
338
|
+
for (const item of result.items) {
|
|
339
|
+
if (item.canonical_path.startsWith(prefix) && !UNSAFE_PATH.test(item.canonical_path)) found.set(item.canonical_path, item.published_at);
|
|
340
|
+
}
|
|
341
|
+
if (!result.next_cursor) break;
|
|
342
|
+
if (page === maxPages - 1) complete = false;
|
|
343
|
+
cursor = result.next_cursor;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
} catch {
|
|
347
|
+
complete = false;
|
|
348
|
+
}
|
|
349
|
+
return { paths: [...found].map(([path, publishedAt]) => ({ path, publishedAt })), complete };
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// src/route-check.ts
|
|
353
|
+
var NOT_ROUTES = /* @__PURE__ */ new Set(["/_not-found", "/_global-error", "/_app", "/_error", "/_document", "/404", "/500"]);
|
|
354
|
+
var LOCALE_PARAM = "locale";
|
|
355
|
+
function normalizeRoute(key) {
|
|
356
|
+
const segments = key.replace(/\/(page|route)$/, "").split("/").filter((s) => s !== "");
|
|
357
|
+
if (segments.some((s) => s.startsWith("@") || /^\(\.{1,3}\)/.test(s))) return void 0;
|
|
358
|
+
const route = `/${segments.filter((s) => !/^\(.*\)$/.test(s)).join("/")}`;
|
|
359
|
+
return NOT_ROUTES.has(route) ? void 0 : route;
|
|
360
|
+
}
|
|
361
|
+
function hostRoutesFromManifests({ routesManifest, appPaths }) {
|
|
362
|
+
const keys = [...(routesManifest?.staticRoutes ?? []).map((r) => r.page), ...(routesManifest?.dynamicRoutes ?? []).map((r) => r.page), ...Object.keys(appPaths ?? {})];
|
|
363
|
+
return [...new Set(keys.map(normalizeRoute).filter((r) => r !== void 0))].sort();
|
|
364
|
+
}
|
|
365
|
+
var segmentsOf = (path) => path.split("/").filter((s) => s !== "");
|
|
366
|
+
function parse(route) {
|
|
367
|
+
return segmentsOf(route).map((value) => {
|
|
368
|
+
const optional = /^\[\[\.\.\.([^\]]+)\]\]$/.exec(value);
|
|
369
|
+
if (optional) return { kind: "optional-catch-all", name: optional[1] };
|
|
370
|
+
const rest = /^\[\.\.\.([^\]]+)\]$/.exec(value);
|
|
371
|
+
if (rest) return { kind: "catch-all", name: rest[1] };
|
|
372
|
+
const one = /^\[([^\]]+)\]$/.exec(value);
|
|
373
|
+
return one ? { kind: "dynamic", name: one[1] } : { kind: "static", value };
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
var isDynamic = (route) => parse(route).some((s) => s.kind !== "static");
|
|
377
|
+
function routeMatches(route, path) {
|
|
378
|
+
const pattern = parse(route);
|
|
379
|
+
const parts = segmentsOf(path);
|
|
380
|
+
for (const [i, seg] of pattern.entries()) {
|
|
381
|
+
if (seg.kind === "optional-catch-all") return i === pattern.length - 1;
|
|
382
|
+
if (seg.kind === "catch-all") return i === pattern.length - 1 && parts.length > i;
|
|
383
|
+
if (i >= parts.length || seg.kind === "static" && seg.value !== parts[i]) return false;
|
|
384
|
+
}
|
|
385
|
+
return parts.length === pattern.length;
|
|
386
|
+
}
|
|
387
|
+
var RANK = { static: 0, dynamic: 1, "catch-all": 2, "optional-catch-all": 3 };
|
|
388
|
+
function compareSpecificity(a, b) {
|
|
389
|
+
const [pa, pb] = [parse(a), parse(b)];
|
|
390
|
+
for (let i = 0; i < Math.min(pa.length, pb.length); i++) {
|
|
391
|
+
const d = RANK[pa[i].kind] - RANK[pb[i].kind];
|
|
392
|
+
if (d !== 0) return d;
|
|
393
|
+
}
|
|
394
|
+
return pa.length - pb.length;
|
|
395
|
+
}
|
|
396
|
+
function withLocale(path, locale) {
|
|
397
|
+
if (!locale) return [path];
|
|
398
|
+
const prefixed = (l) => path === "/" ? `/${l}` : `/${l}${path}`;
|
|
399
|
+
if (locale.prefix === "never") return [path];
|
|
400
|
+
return locale.locales.map((l) => locale.prefix === "as-needed" && l === locale.defaultLocale ? path : prefixed(l));
|
|
401
|
+
}
|
|
402
|
+
function expandLocale(route, locale) {
|
|
403
|
+
const [first, ...rest] = segmentsOf(route);
|
|
404
|
+
if (!locale || first !== `[${LOCALE_PARAM}]`) return [route];
|
|
405
|
+
return [...new Set(withLocale(`/${rest.join("/")}`, locale))];
|
|
406
|
+
}
|
|
407
|
+
var MAX_EXAMPLES = 5;
|
|
408
|
+
function checkRoutes(input) {
|
|
409
|
+
const { locale } = input;
|
|
410
|
+
const hyleParam = input.hyleParam ?? "hyle";
|
|
411
|
+
const routes = [...new Set(input.hostRoutes.flatMap((r) => expandLocale(r, locale)))];
|
|
412
|
+
const staticRoutes = new Set(routes.filter((r) => !isDynamic(r)));
|
|
413
|
+
const dynamicRoutes = routes.filter(isDynamic);
|
|
414
|
+
const catchAlls = dynamicRoutes.filter((r) => {
|
|
415
|
+
const last = parse(r).at(-1);
|
|
416
|
+
return (last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam;
|
|
417
|
+
});
|
|
418
|
+
const notes = [];
|
|
419
|
+
const shadowedHylePaths = input.hylePaths.flatMap(
|
|
420
|
+
(path) => withLocale(path, locale).filter((url) => staticRoutes.has(url)).map((url) => ({ path, url, route: url }))
|
|
421
|
+
);
|
|
422
|
+
const mountCollisions = [];
|
|
423
|
+
for (const prefix of input.mounts) {
|
|
424
|
+
if (prefix === "/") {
|
|
425
|
+
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)`);
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
for (const url of withLocale(prefix, locale)) if (staticRoutes.has(url)) mountCollisions.push({ prefix, url, route: url });
|
|
429
|
+
}
|
|
430
|
+
const urls = [...new Set([...input.hylePaths, ...input.mounts.filter((m) => m !== "/")].flatMap((p) => withLocale(p, locale)))];
|
|
431
|
+
const dynamicOverlaps = [];
|
|
432
|
+
for (const route of dynamicRoutes) {
|
|
433
|
+
const matched = urls.filter((u) => routeMatches(route, u));
|
|
434
|
+
if (catchAlls.includes(route)) {
|
|
435
|
+
dynamicOverlaps.push({ route, verdict: "hyle-catch-all", matches: matched.length, examples: matched.slice(0, MAX_EXAMPLES) });
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
const hostWins = matched.filter((u) => {
|
|
439
|
+
const best = catchAlls.filter((c) => routeMatches(c, u)).sort(compareSpecificity)[0];
|
|
440
|
+
return best === void 0 || compareSpecificity(route, best) <= 0;
|
|
441
|
+
});
|
|
442
|
+
if (matched.length === 0) continue;
|
|
443
|
+
const shown = hostWins.length > 0 ? hostWins : matched;
|
|
444
|
+
dynamicOverlaps.push({ route, verdict: hostWins.length > 0 ? "host-wins" : "hyle-wins", matches: shown.length, examples: shown.slice(0, MAX_EXAMPLES) });
|
|
445
|
+
}
|
|
446
|
+
if (!routes.some((r) => r.startsWith(`${ASSET_ROUTE_PREFIX}/`))) {
|
|
447
|
+
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`);
|
|
448
|
+
}
|
|
449
|
+
if (catchAlls.length === 0) notes.push(`no hyle catch-all route (a "[...${hyleParam}]" or "[[...${hyleParam}]]" page) was found in the host routes`);
|
|
450
|
+
return { shadowedHylePaths, mountCollisions, dynamicOverlaps, notes, ok: shadowedHylePaths.length === 0 && mountCollisions.length === 0 };
|
|
451
|
+
}
|
|
452
|
+
var SDK_OWN_RESERVED = [ASSET_RESERVED_PATH];
|
|
453
|
+
var HASHED_METADATA_ROUTE = /^(opengraph-image|twitter-image|icon|apple-icon)-[a-z0-9]{5,8}$/;
|
|
454
|
+
var isHashedMetadataRoute = (route) => HASHED_METADATA_ROUTE.test(segmentsOf(route).at(-1) ?? "");
|
|
455
|
+
var covers = (entry, path) => {
|
|
456
|
+
if (!entry.endsWith("/*")) return entry === path;
|
|
457
|
+
const base = entry.slice(0, -2);
|
|
458
|
+
return path === base || path.startsWith(`${base}/`);
|
|
459
|
+
};
|
|
460
|
+
function reservedFor(hostRoutes, options = {}) {
|
|
461
|
+
const dropLocale = (route) => {
|
|
462
|
+
const [first, ...rest] = segmentsOf(route);
|
|
463
|
+
return options.locale && first === `[${LOCALE_PARAM}]` ? `/${rest.join("/")}` : route;
|
|
464
|
+
};
|
|
465
|
+
const hyleParam = options.hyleParam ?? "hyle";
|
|
466
|
+
const routes = hostRoutes.map(dropLocale).filter((r) => !isHashedMetadataRoute(r));
|
|
467
|
+
const exact = new Set(routes.filter((r) => !isDynamic(r)));
|
|
468
|
+
const mounts = options.mounts?.filter((m) => m !== "/");
|
|
469
|
+
const onMount = (segment) => mounts?.some((m) => m === `/${segment}` || m.startsWith(`/${segment}/`)) ?? true;
|
|
470
|
+
const groups = /* @__PURE__ */ new Map();
|
|
471
|
+
for (const route of exact) {
|
|
472
|
+
const [first, ...rest] = segmentsOf(route);
|
|
473
|
+
if (first !== void 0 && rest.length > 0) groups.set(first, [...groups.get(first) ?? [], route]);
|
|
474
|
+
}
|
|
475
|
+
const wildcards = /* @__PURE__ */ new Set();
|
|
476
|
+
for (const [first, members] of groups) {
|
|
477
|
+
if (members.length >= 2 && !onMount(first)) wildcards.add(`/${first}/*`);
|
|
478
|
+
}
|
|
479
|
+
for (const route of routes.filter(isDynamic)) {
|
|
480
|
+
const segments = parse(route);
|
|
481
|
+
const last = segments.at(-1);
|
|
482
|
+
if ((last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam) continue;
|
|
483
|
+
const dir = segments.slice(0, segments.findIndex((seg) => seg.kind !== "static")).map((seg) => seg.kind === "static" ? seg.value : "").join("/");
|
|
484
|
+
if (dir === "" || !mounts) continue;
|
|
485
|
+
if (!mounts.some((m) => m === `/${dir}` || m.startsWith(`/${dir}/`))) wildcards.add(`/${dir}/*`);
|
|
486
|
+
}
|
|
487
|
+
const all = [...exact, ...wildcards];
|
|
488
|
+
const base = (entry) => entry.endsWith("/*") ? entry.slice(0, -2) : entry;
|
|
489
|
+
return all.filter((entry) => !all.some((other) => other !== entry && other.endsWith("/*") && covers(other, base(entry)))).sort();
|
|
490
|
+
}
|
|
491
|
+
function formatReport(report) {
|
|
492
|
+
const lines = [];
|
|
493
|
+
const section = (title, rows, empty) => lines.push(`${title}`, ...rows.length ? rows.map((r) => ` ${printable(r)}`) : [` ${empty}`], "");
|
|
494
|
+
section(
|
|
495
|
+
"(a) hyle paths shadowed by host static routes (the hyle page is never served):",
|
|
496
|
+
report.shadowedHylePaths.map((s) => `${s.url} (hyle path ${s.path})`),
|
|
497
|
+
"none"
|
|
498
|
+
);
|
|
499
|
+
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");
|
|
500
|
+
section(
|
|
501
|
+
"(b) host dynamic routes matching hyle URLs:",
|
|
502
|
+
report.dynamicOverlaps.map((d) => {
|
|
503
|
+
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];
|
|
504
|
+
return `${d.route} ${label} (${d.matches} URLs, e.g. ${d.examples.join(", ") || "-"})`;
|
|
505
|
+
}),
|
|
506
|
+
"none"
|
|
507
|
+
);
|
|
508
|
+
if (report.notes.length) section("notes:", report.notes, "");
|
|
509
|
+
lines.push(report.ok ? "RESULT: no collisions" : "RESULT: collisions found");
|
|
510
|
+
return lines.join("\n");
|
|
511
|
+
}
|
|
512
|
+
var MAX_PRINTED = 200;
|
|
513
|
+
var printable = (text) => {
|
|
514
|
+
const clean = text.replace(/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|.)?/g, "").replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
|
|
515
|
+
return clean.length > MAX_PRINTED ? `${clean.slice(0, MAX_PRINTED)}...` : clean;
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
export {
|
|
519
|
+
Cp1ClientError,
|
|
520
|
+
createHyleClient,
|
|
521
|
+
syncHostReserved,
|
|
522
|
+
DeliveryDedupe,
|
|
523
|
+
parseSignatureHeader,
|
|
524
|
+
verifyHyleSignature,
|
|
525
|
+
CACHE_TAG_PATTERN,
|
|
526
|
+
isValidCacheTag,
|
|
527
|
+
createRevalidationCallbackRoute,
|
|
528
|
+
listPublicationPaths,
|
|
529
|
+
normalizeRoute,
|
|
530
|
+
hostRoutesFromManifests,
|
|
531
|
+
routeMatches,
|
|
532
|
+
checkRoutes,
|
|
533
|
+
SDK_OWN_RESERVED,
|
|
534
|
+
reservedFor,
|
|
535
|
+
formatReport
|
|
536
|
+
};
|