brease-client 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,383 +0,0 @@
1
- import { __publicField } from './chunk-PKBMQBKP.js';
2
-
3
- // src/env.ts
4
- function env(name) {
5
- const proc = globalThis.process;
6
- const value = proc?.env?.[name];
7
- return value === "" ? void 0 : value;
8
- }
9
-
10
- // src/errors.ts
11
- var BreaseError = class _BreaseError extends Error {
12
- constructor(code, message, status, requestId, details) {
13
- super(message);
14
- __publicField(this, "code", code);
15
- __publicField(this, "status", status);
16
- __publicField(this, "requestId", requestId);
17
- __publicField(this, "details", details);
18
- __publicField(this, "name", "BreaseError");
19
- }
20
- static async fromResponse(res) {
21
- const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-vercel-id") ?? void 0;
22
- let code = res.status === 429 ? "rate_limited" : res.status >= 500 ? "upstream" : "http_error";
23
- let message = `Brease API responded ${res.status}`;
24
- let details;
25
- try {
26
- const body = await res.json();
27
- if (body?.error) {
28
- code = body.error.code ?? code;
29
- message = body.error.message ?? message;
30
- details = body.error.details;
31
- }
32
- } catch {
33
- }
34
- return new _BreaseError(code, message, res.status, requestId ?? void 0, details);
35
- }
36
- };
37
-
38
- // src/urls.ts
39
- function normalizeSlug(input) {
40
- return input.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
41
- }
42
- function buildPath(settings, slug, locale) {
43
- const clean = normalizeSlug(slug);
44
- if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
45
- const path = settings.urlTemplate.replace("{locale}", locale).replace("{slug}", clean);
46
- return `/${normalizeSlug(path)}`;
47
- }
48
- const prefixed = settings.localeStrategy === "PREFIX_ALL" || locale !== settings.defaultLocale;
49
- const parts = [prefixed ? locale : "", clean].filter(Boolean);
50
- return `/${parts.join("/")}`;
51
- }
52
- function resolvePath(settings, pathname) {
53
- const clean = normalizeSlug(decodeURIComponent(pathname.split(/[?#]/)[0] ?? ""));
54
- if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
55
- const pattern = normalizeSlug(settings.urlTemplate).split(/(\{locale\}|\{slug\})/).map((part) => {
56
- if (part === "{locale}") return "(?<locale>[^/]+)";
57
- if (part === "{slug}") return "(?<slug>.*)";
58
- return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
59
- }).join("");
60
- const match = new RegExp(`^${pattern}$`).exec(clean);
61
- if (match?.groups) {
62
- return {
63
- slug: normalizeSlug(match.groups.slug ?? ""),
64
- locale: match.groups.locale ?? settings.defaultLocale
65
- };
66
- }
67
- return { slug: clean, locale: settings.defaultLocale };
68
- }
69
- const [first, ...rest] = clean.split("/");
70
- if (first && settings.locales.includes(first)) {
71
- return { slug: rest.join("/"), locale: first };
72
- }
73
- return { slug: clean, locale: settings.defaultLocale };
74
- }
75
- function canonicalPath(settings, pathname) {
76
- const path = pathname.split(/[?#]/)[0] ?? "";
77
- const { slug, locale } = resolvePath(settings, path);
78
- const canonical = buildPath(settings, slug, locale);
79
- const trim = (p) => p.length > 1 ? p.replace(/\/+$/, "") : p;
80
- return trim(decodeURIComponent(path)) === trim(canonical) ? null : canonical;
81
- }
82
-
83
- // src/analytics.ts
84
- var MEASUREMENT_ID = /^G-[A-Z0-9]+$/;
85
- function ga4Tag(site) {
86
- const id = site.analytics?.ga4;
87
- if (!id || !MEASUREMENT_ID.test(id)) return null;
88
- const inline = [
89
- "window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}",
90
- "gtag('consent','default',{ad_storage:'denied',ad_user_data:'denied',ad_personalization:'denied',analytics_storage:'denied',wait_for_update:500});",
91
- "gtag('js',new Date());",
92
- `gtag('config','${id}');`
93
- ].join("");
94
- return { id, src: `https://www.googletagmanager.com/gtag/js?id=${id}`, inline };
95
- }
96
- function ga4Html(site) {
97
- const tag = ga4Tag(site);
98
- return tag ? `<script async src="${tag.src}"></script>
99
- <script>${tag.inline}</script>` : "";
100
- }
101
- function grantAnalytics(granted = true) {
102
- const gtag = globalThis.gtag;
103
- gtag?.("consent", "update", { analytics_storage: granted ? "granted" : "denied" });
104
- }
105
-
106
- // src/custom-code.ts
107
- function customTags(seo) {
108
- return [seo.customHead, seo.customCode].flatMap((html) => html ? parseTags(html) : []);
109
- }
110
- function parseTags(html) {
111
- const out = [];
112
- const re = /<(script|style|noscript)\b([^>]*)>([\s\S]*?)<\/\1\s*>|<(meta|link)\b([^>]*?)\/?>/gi;
113
- for (const m of html.matchAll(re)) {
114
- if (m[1]) {
115
- const tag = m[1].toLowerCase();
116
- out.push({ tag, attrs: attrsOf(m[2] ?? ""), ...m[3]?.trim() ? { content: m[3] } : {} });
117
- } else if (m[4])
118
- out.push({ tag: m[4].toLowerCase(), attrs: attrsOf(m[5] ?? "") });
119
- }
120
- return out;
121
- }
122
- function attrsOf(source) {
123
- const attrs = {};
124
- for (const m of source.matchAll(/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g))
125
- attrs[m[1].toLowerCase()] = m[2] ?? m[3] ?? m[4] ?? "";
126
- return attrs;
127
- }
128
-
129
- // src/locales.ts
130
- function localeLinks(context) {
131
- const { settings, alternates, homes, locale: current } = context;
132
- return settings.locales.flatMap((l) => {
133
- const href = alternates[l] ?? homes[l] ?? (l === current ? buildPath(settings, "", l) : null);
134
- return href ? [{ locale: l, label: nativeName(l), href, current: l === current }] : [];
135
- });
136
- }
137
- function nativeName(locale) {
138
- try {
139
- const name = new Intl.DisplayNames([locale], { type: "language" }).of(locale) ?? locale;
140
- return name.charAt(0).toLocaleUpperCase(locale) + name.slice(1);
141
- } catch {
142
- return locale;
143
- }
144
- }
145
- var localeHref = (settings, slug, locale) => buildPath(settings, slug, locale);
146
-
147
- // src/markers.ts
148
- function fieldPath(path, pageId) {
149
- return pageId ? `${pageId}:${path}` : path;
150
- }
151
- function navPath(key) {
152
- return `nav:${key}`;
153
- }
154
-
155
- // src/redirects.ts
156
- function matchRedirect(redirects, pathname) {
157
- const path = normalize(pathname);
158
- for (const r of redirects) {
159
- const params = matchSource(normalize(r.source), path);
160
- if (!params) continue;
161
- const destination = r.destination.replace(
162
- /:([A-Za-z_][A-Za-z0-9_]*)\*?/g,
163
- (whole, name) => name in params ? params[name] : whole
164
- );
165
- if (normalize(destination) === path) continue;
166
- return { destination, status: r.status };
167
- }
168
- return null;
169
- }
170
- var normalize = (p) => (p.length > 1 ? p.replace(/\/+$/, "") : p) || "/";
171
- function matchSource(source, path) {
172
- const want = source.split("/").filter(Boolean);
173
- const have = path.split("/").filter(Boolean);
174
- const params = {};
175
- for (let i = 0; i < want.length; i++) {
176
- const seg = want[i];
177
- const rest = /^:([A-Za-z_][A-Za-z0-9_]*)\*$/.exec(seg);
178
- if (rest) {
179
- params[rest[1]] = have.slice(i).join("/");
180
- return params;
181
- }
182
- const value = have[i];
183
- if (value === void 0) return null;
184
- const param = /^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(seg);
185
- if (param) params[param[1]] = value;
186
- else if (decodeURIComponent(value) !== decodeURIComponent(seg)) return null;
187
- }
188
- return want.length === have.length ? params : null;
189
- }
190
-
191
- // src/signature.ts
192
- var MAX_SKEW_MS = 5 * 6e4;
193
- async function hmacHex(secret, message) {
194
- const enc = new TextEncoder();
195
- const key = await crypto.subtle.importKey(
196
- "raw",
197
- enc.encode(secret),
198
- { name: "HMAC", hash: "SHA-256" },
199
- false,
200
- ["sign"]
201
- );
202
- const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(message)));
203
- return Array.from(sig, (b) => b.toString(16).padStart(2, "0")).join("");
204
- }
205
- async function verifySignature(body, timestamp, signature, secret, now = Date.now()) {
206
- if (!timestamp || !signature) return false;
207
- if (!Number.isFinite(Number(timestamp)) || Math.abs(now - Number(timestamp)) > MAX_SKEW_MS) return false;
208
- const expected = await hmacHex(secret, `${timestamp}.${body}`);
209
- if (expected.length !== signature.length) return false;
210
- let diff = 0;
211
- for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
212
- return diff === 0;
213
- }
214
- async function verifyRevalidate(req, secret) {
215
- const raw = await req.text();
216
- const ok = await verifySignature(
217
- raw,
218
- req.headers.get("x-brease-timestamp"),
219
- req.headers.get("x-brease-signature"),
220
- secret
221
- );
222
- if (!ok) return { ok: false, reason: "signature" };
223
- let body;
224
- try {
225
- body = JSON.parse(raw || "{}");
226
- } catch {
227
- return { ok: false, reason: "body" };
228
- }
229
- const paths = new Set(body.paths ?? []);
230
- for (const url of body.urls ?? []) {
231
- try {
232
- paths.add(new URL(url, "http://localhost").pathname);
233
- } catch {
234
- }
235
- }
236
- return { ok: true, paths: [...paths], tags: ["brease", ...body.tags ?? []], body };
237
- }
238
-
239
- // src/index.ts
240
- var RETRY_AFTER_CAP_MS = 1e4;
241
- var SITE_TTL_MS = 6e4;
242
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
243
- function createBrease(opts = {}) {
244
- const apiUrl = (opts.apiUrl ?? env("BREASE_API_URL") ?? "https://api.brease.io").replace(/\/+$/, "");
245
- const commit = opts.commit === false ? void 0 : opts.commit ?? env("VERCEL_GIT_COMMIT_SHA");
246
- const retries = opts.retries ?? 2;
247
- const baseMs = opts.retryBaseMs ?? 300;
248
- const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
249
- let site;
250
- let redirects;
251
- async function request(path, query = {}, nullOn404 = false) {
252
- const token = opts.token ?? env("BREASE_TOKEN");
253
- if (!token)
254
- throw new BreaseError("unauthorized", "No Brease token: pass { token } or set BREASE_TOKEN", 401);
255
- const params = new URLSearchParams();
256
- for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, v);
257
- const qs = params.toString();
258
- const url = `${apiUrl}${path}${qs ? `?${qs}` : ""}`;
259
- const headers = { authorization: `Bearer ${token}`, accept: "application/json" };
260
- if (commit) headers["x-brease-commit"] = commit;
261
- for (let attempt = 0; ; attempt++) {
262
- let res;
263
- try {
264
- res = await doFetch(url, { method: "GET", headers });
265
- } catch (err) {
266
- if (attempt < retries) {
267
- await sleep(backoff(attempt));
268
- continue;
269
- }
270
- throw new BreaseError("network", `Request to ${url} failed: ${err.message}`, 0);
271
- }
272
- if (res.ok) return await res.json();
273
- if (res.status === 404 && nullOn404) return null;
274
- if ((res.status === 429 || res.status >= 500) && attempt < retries) {
275
- const after = Number(res.headers.get("retry-after"));
276
- await sleep(after > 0 ? Math.min(after * 1e3, RETRY_AFTER_CAP_MS) : backoff(attempt));
277
- continue;
278
- }
279
- throw await BreaseError.fromResponse(res);
280
- }
281
- }
282
- function backoff(attempt) {
283
- return baseMs * 2 ** attempt + Math.random() * baseMs;
284
- }
285
- const client = {
286
- getSite() {
287
- if (!site || Date.now() - site.at > SITE_TTL_MS) {
288
- const promise = request("/content-api/site").catch((err) => {
289
- if (site?.promise === promise) site = void 0;
290
- throw err;
291
- });
292
- site = { promise, at: Date.now() };
293
- }
294
- return site.promise;
295
- },
296
- getPage(slug, { locale }) {
297
- return request("/content-api/page", { slug, locale }, true);
298
- },
299
- getPages(o = {}) {
300
- return request("/content-api/pages", {
301
- locale: o.locale,
302
- parentId: o.parentId,
303
- template: o.template,
304
- withContent: o.withContent ? "1" : void 0
305
- });
306
- },
307
- getNavigation(key, { locale }) {
308
- return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
309
- },
310
- // Cached for a minute, like the site: a proxy applies redirects per request (matchRedirect).
311
- getRedirects() {
312
- if (!redirects || Date.now() - redirects.at > SITE_TTL_MS) {
313
- const promise = request("/content-api/redirects").catch((err) => {
314
- if (redirects?.promise === promise) redirects = void 0;
315
- throw err;
316
- });
317
- redirects = { promise, at: Date.now() };
318
- }
319
- return redirects.promise;
320
- },
321
- getRelease() {
322
- return request("/content-api/release");
323
- },
324
- async resolve(pathname) {
325
- const site2 = await client.getSite();
326
- const result = resolvePath(site2, pathname);
327
- return site2.locales.includes(result.locale) ? result : null;
328
- },
329
- async route(path) {
330
- const joined = Array.isArray(path) ? path.map((p) => decodeURIComponent(p)).join("/") : path ?? "";
331
- const result = await client.resolve(`/${joined}`);
332
- return result && !result.slug.split("/").some((part) => part.startsWith("_")) ? result : null;
333
- },
334
- async routes() {
335
- const refs = await client.getPages();
336
- return refs.filter((r) => !r.hidden && !r.slug.split("/").some((part) => part.startsWith("_"))).map((r) => ({ path: r.url.split("/").filter(Boolean) }));
337
- },
338
- async localeContext(path) {
339
- const target = await client.route(path);
340
- if (!target) return null;
341
- const [site2, page, home] = await Promise.all([
342
- client.getSite(),
343
- client.getPage(target.slug, { locale: target.locale }),
344
- client.getPage("", { locale: target.locale })
345
- ]);
346
- const settings = {
347
- locales: site2.locales,
348
- defaultLocale: site2.defaultLocale,
349
- localeStrategy: site2.localeStrategy,
350
- urlTemplate: site2.urlTemplate
351
- };
352
- if (!page && !home) return null;
353
- const alternates = {};
354
- for (const [locale, url] of Object.entries(page?.alternates ?? {})) alternates[locale] = pathOf(url);
355
- const homes = {};
356
- for (const [locale, url] of Object.entries(home?.alternates ?? {})) homes[locale] = pathOf(url);
357
- return { locale: target.locale, settings, alternates, homes };
358
- },
359
- async sitemap(baseUrl) {
360
- const base = baseUrl.replace(/\/+$/, "");
361
- const refs = (await client.getPages()).filter(
362
- (r) => !r.hidden && r.index !== false && !r.slug.split("/").some((part) => part.startsWith("_"))
363
- );
364
- const byPage = /* @__PURE__ */ new Map();
365
- for (const ref of refs) {
366
- const alternates = byPage.get(ref.pageId) ?? {};
367
- alternates[ref.locale] = `${base}${ref.url}`;
368
- byPage.set(ref.pageId, alternates);
369
- }
370
- return refs.map((ref) => ({ url: `${base}${ref.url}`, alternates: byPage.get(ref.pageId) ?? {} }));
371
- }
372
- };
373
- return client;
374
- }
375
- function pathOf(url) {
376
- try {
377
- return new URL(url, "http://localhost").pathname;
378
- } catch {
379
- return url;
380
- }
381
- }
382
-
383
- export { BreaseError, buildPath, canonicalPath, createBrease, customTags, env, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, resolvePath, verifyRevalidate, verifySignature };
@@ -1,10 +0,0 @@
1
- // src/structured-data.ts
2
- var jsonLdText = (data) => JSON.stringify(data).replace(/</g, "\\u003c");
3
- function jsonLd(seo) {
4
- return (seo.structuredData ?? []).map((data) => ({ data, json: jsonLdText(data) }));
5
- }
6
- function jsonLdHtml(seo) {
7
- return jsonLd(seo).map((d) => `<script type="application/ld+json">${d.json}</script>`).join("\n");
8
- }
9
-
10
- export { jsonLd, jsonLdHtml };