brease-client 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -15
- package/dist/chunk-ULU4ABCQ.js +222 -0
- package/dist/index.cjs +49 -0
- package/dist/index.d.cts +18 -1
- package/dist/index.d.ts +18 -1
- package/dist/index.js +2 -170
- package/dist/next.cjs +200 -0
- package/dist/next.d.cts +7 -1
- package/dist/next.d.ts +7 -1
- package/dist/next.js +13 -2
- package/package.json +1 -1
- package/dist/chunk-L7GXI4GK.js +0 -8
package/README.md
CHANGED
|
@@ -34,6 +34,7 @@ await brease.getRedirects() // [{ source, destination, status }]
|
|
|
34
34
|
await brease.resolve('/en/about') // { slug: 'about', locale: 'en' } | null
|
|
35
35
|
await brease.route(['en', 'about']) // the same from catch-all path segments; null for shared "_" pages
|
|
36
36
|
await brease.routes() // [{ path: ['en', 'about'] }, …]: static params for every published page
|
|
37
|
+
await brease.localeContext(['en', 'about']) // { locale, settings, alternates, homes } for BreaseLocaleProvider
|
|
37
38
|
await brease.sitemap('https://example.com') // [{ url, alternates }]
|
|
38
39
|
```
|
|
39
40
|
|
|
@@ -106,31 +107,41 @@ export default {
|
|
|
106
107
|
}
|
|
107
108
|
```
|
|
108
109
|
|
|
109
|
-
###
|
|
110
|
+
### Recommended structure (optional)
|
|
110
111
|
|
|
111
|
-
|
|
112
|
+
Brease works with any routing: `getPage()` and friends don't care how a site is built. This structure is what Brease recommends, and what its editor moves a site towards when the site follows Brease conventions. It makes locales a setting: adding one, or changing how URLs are prefixed, needs no code change.
|
|
112
113
|
|
|
113
114
|
```
|
|
114
115
|
app/
|
|
115
116
|
[[...path]]/
|
|
116
|
-
layout.tsx
|
|
117
|
-
page.tsx
|
|
117
|
+
layout.tsx root layout: <html lang>, the locale context for the page
|
|
118
|
+
page.tsx every page in every locale; the page's content picks its template
|
|
118
119
|
not-found.tsx
|
|
119
|
-
|
|
120
|
+
og/[[...path]]/route.tsx share images (image files can't sit inside an optional catch-all)
|
|
121
|
+
api/…, sitemap.ts, robots.ts, other route handlers unchanged: static routes win over the catch-all
|
|
122
|
+
brease/templates.tsx { home: …, article: … }, the site's own page templates
|
|
120
123
|
```
|
|
121
124
|
|
|
122
125
|
```tsx
|
|
123
126
|
// app/[[...path]]/layout.tsx (replaces app/layout.tsx)
|
|
124
127
|
import { brease } from '@/lib/brease'
|
|
128
|
+
import { LocaleProvider } from '@/components/locale' // the site's own React context around the value
|
|
125
129
|
|
|
126
130
|
type Props = { children: React.ReactNode; params: Promise<{ path?: string[] }> }
|
|
127
131
|
|
|
128
132
|
export default async function RootLayout({ children, params }: Props) {
|
|
129
|
-
const
|
|
130
|
-
const
|
|
133
|
+
const site = await brease.getSite()
|
|
134
|
+
const context = (await brease.localeContext((await params).path)) ?? {
|
|
135
|
+
locale: site.defaultLocale,
|
|
136
|
+
settings: site,
|
|
137
|
+
alternates: {},
|
|
138
|
+
homes: {}
|
|
139
|
+
}
|
|
131
140
|
return (
|
|
132
|
-
<html lang={locale}>
|
|
133
|
-
<body>
|
|
141
|
+
<html lang={context.locale}>
|
|
142
|
+
<body>
|
|
143
|
+
<LocaleProvider value={context}>{children}</LocaleProvider>
|
|
144
|
+
</body>
|
|
134
145
|
</html>
|
|
135
146
|
)
|
|
136
147
|
}
|
|
@@ -140,6 +151,7 @@ export default async function RootLayout({ children, params }: Props) {
|
|
|
140
151
|
// app/[[...path]]/page.tsx (replaces app/page.tsx and app/[slug]/page.tsx)
|
|
141
152
|
import { notFound } from 'next/navigation'
|
|
142
153
|
import { toMetadata } from 'brease-client/next'
|
|
154
|
+
import { templates } from '@/brease/templates'
|
|
143
155
|
import { brease } from '@/lib/brease'
|
|
144
156
|
|
|
145
157
|
export const revalidate = 60
|
|
@@ -149,7 +161,8 @@ type Props = { params: Promise<{ path?: string[] }> }
|
|
|
149
161
|
async function load(params: Props['params']) {
|
|
150
162
|
const route = await brease.route((await params).path)
|
|
151
163
|
const page = route && (await brease.getPage<Content>(route.slug, { locale: route.locale }))
|
|
152
|
-
|
|
164
|
+
const Template = page && templates[page.content.template]
|
|
165
|
+
return page && route && Template ? { page, locale: route.locale, Template } : null
|
|
153
166
|
}
|
|
154
167
|
|
|
155
168
|
export const generateStaticParams = () => brease.routes()
|
|
@@ -162,15 +175,28 @@ export async function generateMetadata({ params }: Props) {
|
|
|
162
175
|
export default async function Page({ params }: Props) {
|
|
163
176
|
const loaded = await load(params)
|
|
164
177
|
if (!loaded) notFound()
|
|
165
|
-
// Pass
|
|
166
|
-
return <Template page={loaded.page} locale={loaded.locale} />
|
|
178
|
+
// Pass the locale to everything else that reads Brease: navigations, shared "_" pages, site SEO.
|
|
179
|
+
return <loaded.Template page={loaded.page} locale={loaded.locale} />
|
|
167
180
|
}
|
|
168
181
|
```
|
|
169
182
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
183
|
+
The package stays framework-free: it gives the data and the logic, and the site renders them with its own framework.
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
import { localeHref, localeLinks } from 'brease-client'
|
|
187
|
+
|
|
188
|
+
const context = await brease.localeContext(path) // { locale, settings, alternates, homes }
|
|
189
|
+
localeLinks(context) // [{ locale: 'hu', label: 'Magyar', href: '/rolunk', current: true }, …]
|
|
190
|
+
localeHref(context.settings, 'about', 'de') // '/de/about'
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
A locale switcher is then a few lines in any framework: a list of `<a href={l.href} hreflang={l.locale}>{l.label}</a>`, with `aria-current` on the current one, hidden while `localeLinks()` returns fewer than two links. Share `context` with the components that need it the framework's own way (a React context, Astro props, a template variable).
|
|
194
|
+
|
|
195
|
+
- `localeLinks()` links each locale's version of the current page, else that locale's home page; locales without content yet are left out.
|
|
196
|
+
- Everything that read a fixed locale (`getPage(…, { locale: 'hu' })`, `getNavigation`, `site.seo.hu`) takes it from the route instead.
|
|
197
|
+
- Links inside content are already locale URLs. Build other internal links with `localeHref(settings, slug, locale)`.
|
|
173
198
|
- Text written into components (button labels, captions) stays as it is; moving it into Brease content is a separate change.
|
|
199
|
+
- `next.config`: `redirects: breaseRedirects()` (from `brease-client/next`) serves the redirects managed in Brease.
|
|
174
200
|
|
|
175
201
|
### Revalidation signature
|
|
176
202
|
|
|
@@ -0,0 +1,222 @@
|
|
|
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
|
+
|
|
76
|
+
// src/locales.ts
|
|
77
|
+
function localeLinks(context) {
|
|
78
|
+
const { settings, alternates, homes, locale: current } = context;
|
|
79
|
+
return settings.locales.flatMap((l) => {
|
|
80
|
+
const href = alternates[l] ?? homes[l] ?? (l === current ? buildPath(settings, "", l) : null);
|
|
81
|
+
return href ? [{ locale: l, label: nativeName(l), href, current: l === current }] : [];
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
function nativeName(locale) {
|
|
85
|
+
try {
|
|
86
|
+
const name = new Intl.DisplayNames([locale], { type: "language" }).of(locale) ?? locale;
|
|
87
|
+
return name.charAt(0).toLocaleUpperCase(locale) + name.slice(1);
|
|
88
|
+
} catch {
|
|
89
|
+
return locale;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
var localeHref = (settings, slug, locale) => buildPath(settings, slug, locale);
|
|
93
|
+
|
|
94
|
+
// src/index.ts
|
|
95
|
+
var RETRY_AFTER_CAP_MS = 1e4;
|
|
96
|
+
var SITE_TTL_MS = 6e4;
|
|
97
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
98
|
+
function createBrease(opts = {}) {
|
|
99
|
+
const apiUrl = (opts.apiUrl ?? env("BREASE_API_URL") ?? "https://api.brease.io").replace(/\/+$/, "");
|
|
100
|
+
const commit = opts.commit === false ? void 0 : opts.commit ?? env("VERCEL_GIT_COMMIT_SHA");
|
|
101
|
+
const retries = opts.retries ?? 2;
|
|
102
|
+
const baseMs = opts.retryBaseMs ?? 300;
|
|
103
|
+
const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
104
|
+
let site;
|
|
105
|
+
async function request(path, query = {}, nullOn404 = false) {
|
|
106
|
+
const token = opts.token ?? env("BREASE_TOKEN");
|
|
107
|
+
if (!token)
|
|
108
|
+
throw new BreaseError("unauthorized", "No Brease token: pass { token } or set BREASE_TOKEN", 401);
|
|
109
|
+
const params = new URLSearchParams();
|
|
110
|
+
for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, v);
|
|
111
|
+
const qs = params.toString();
|
|
112
|
+
const url = `${apiUrl}${path}${qs ? `?${qs}` : ""}`;
|
|
113
|
+
const headers = { authorization: `Bearer ${token}`, accept: "application/json" };
|
|
114
|
+
if (commit) headers["x-brease-commit"] = commit;
|
|
115
|
+
for (let attempt = 0; ; attempt++) {
|
|
116
|
+
let res;
|
|
117
|
+
try {
|
|
118
|
+
res = await doFetch(url, { method: "GET", headers });
|
|
119
|
+
} catch (err) {
|
|
120
|
+
if (attempt < retries) {
|
|
121
|
+
await sleep(backoff(attempt));
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
throw new BreaseError("network", `Request to ${url} failed: ${err.message}`, 0);
|
|
125
|
+
}
|
|
126
|
+
if (res.ok) return await res.json();
|
|
127
|
+
if (res.status === 404 && nullOn404) return null;
|
|
128
|
+
if ((res.status === 429 || res.status >= 500) && attempt < retries) {
|
|
129
|
+
const after = Number(res.headers.get("retry-after"));
|
|
130
|
+
await sleep(after > 0 ? Math.min(after * 1e3, RETRY_AFTER_CAP_MS) : backoff(attempt));
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
throw await BreaseError.fromResponse(res);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function backoff(attempt) {
|
|
137
|
+
return baseMs * 2 ** attempt + Math.random() * baseMs;
|
|
138
|
+
}
|
|
139
|
+
const client = {
|
|
140
|
+
getSite() {
|
|
141
|
+
if (!site || Date.now() - site.at > SITE_TTL_MS) {
|
|
142
|
+
const promise = request("/content-api/site").catch((err) => {
|
|
143
|
+
if (site?.promise === promise) site = void 0;
|
|
144
|
+
throw err;
|
|
145
|
+
});
|
|
146
|
+
site = { promise, at: Date.now() };
|
|
147
|
+
}
|
|
148
|
+
return site.promise;
|
|
149
|
+
},
|
|
150
|
+
getPage(slug, { locale }) {
|
|
151
|
+
return request("/content-api/page", { slug, locale }, true);
|
|
152
|
+
},
|
|
153
|
+
getPages(o = {}) {
|
|
154
|
+
return request("/content-api/pages", { locale: o.locale });
|
|
155
|
+
},
|
|
156
|
+
getNavigation(key, { locale }) {
|
|
157
|
+
return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
|
|
158
|
+
},
|
|
159
|
+
getRedirects() {
|
|
160
|
+
return request("/content-api/redirects");
|
|
161
|
+
},
|
|
162
|
+
getRelease() {
|
|
163
|
+
return request("/content-api/release");
|
|
164
|
+
},
|
|
165
|
+
async resolve(pathname) {
|
|
166
|
+
const site2 = await client.getSite();
|
|
167
|
+
const result = resolvePath(site2, pathname);
|
|
168
|
+
return site2.locales.includes(result.locale) ? result : null;
|
|
169
|
+
},
|
|
170
|
+
async route(path) {
|
|
171
|
+
const joined = Array.isArray(path) ? path.map((p) => decodeURIComponent(p)).join("/") : path ?? "";
|
|
172
|
+
const result = await client.resolve(`/${joined}`);
|
|
173
|
+
return result && !result.slug.split("/").some((part) => part.startsWith("_")) ? result : null;
|
|
174
|
+
},
|
|
175
|
+
async routes() {
|
|
176
|
+
const refs = await client.getPages();
|
|
177
|
+
return refs.filter((r) => !r.hidden && !r.slug.split("/").some((part) => part.startsWith("_"))).map((r) => ({ path: r.url.split("/").filter(Boolean) }));
|
|
178
|
+
},
|
|
179
|
+
async localeContext(path) {
|
|
180
|
+
const target = await client.route(path);
|
|
181
|
+
if (!target) return null;
|
|
182
|
+
const [site2, page, home] = await Promise.all([
|
|
183
|
+
client.getSite(),
|
|
184
|
+
client.getPage(target.slug, { locale: target.locale }),
|
|
185
|
+
client.getPage("", { locale: target.locale })
|
|
186
|
+
]);
|
|
187
|
+
const settings = {
|
|
188
|
+
locales: site2.locales,
|
|
189
|
+
defaultLocale: site2.defaultLocale,
|
|
190
|
+
localeStrategy: site2.localeStrategy,
|
|
191
|
+
urlTemplate: site2.urlTemplate
|
|
192
|
+
};
|
|
193
|
+
if (!page && !home) return null;
|
|
194
|
+
const alternates = {};
|
|
195
|
+
for (const [locale, url] of Object.entries(page?.alternates ?? {})) alternates[locale] = pathOf(url);
|
|
196
|
+
const homes = {};
|
|
197
|
+
for (const [locale, url] of Object.entries(home?.alternates ?? {})) homes[locale] = pathOf(url);
|
|
198
|
+
return { locale: target.locale, settings, alternates, homes };
|
|
199
|
+
},
|
|
200
|
+
async sitemap(baseUrl) {
|
|
201
|
+
const base = baseUrl.replace(/\/+$/, "");
|
|
202
|
+
const refs = (await client.getPages()).filter((r) => !r.hidden);
|
|
203
|
+
const byPage = /* @__PURE__ */ new Map();
|
|
204
|
+
for (const ref of refs) {
|
|
205
|
+
const alternates = byPage.get(ref.pageId) ?? {};
|
|
206
|
+
alternates[ref.locale] = `${base}${ref.url}`;
|
|
207
|
+
byPage.set(ref.pageId, alternates);
|
|
208
|
+
}
|
|
209
|
+
return refs.map((ref) => ({ url: `${base}${ref.url}`, alternates: byPage.get(ref.pageId) ?? {} }));
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
return client;
|
|
213
|
+
}
|
|
214
|
+
function pathOf(url) {
|
|
215
|
+
try {
|
|
216
|
+
return new URL(url, "http://localhost").pathname;
|
|
217
|
+
} catch {
|
|
218
|
+
return url;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export { BreaseError, buildPath, createBrease, env, localeHref, localeLinks, nativeName, normalizeSlug, resolvePath };
|
package/dist/index.cjs
CHANGED
|
@@ -77,6 +77,24 @@ function resolvePath(settings, pathname) {
|
|
|
77
77
|
return { slug: clean, locale: settings.defaultLocale };
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
+
// src/locales.ts
|
|
81
|
+
function localeLinks(context) {
|
|
82
|
+
const { settings, alternates, homes, locale: current } = context;
|
|
83
|
+
return settings.locales.flatMap((l) => {
|
|
84
|
+
const href = alternates[l] ?? homes[l] ?? (l === current ? buildPath(settings, "", l) : null);
|
|
85
|
+
return href ? [{ locale: l, label: nativeName(l), href, current: l === current }] : [];
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
function nativeName(locale) {
|
|
89
|
+
try {
|
|
90
|
+
const name = new Intl.DisplayNames([locale], { type: "language" }).of(locale) ?? locale;
|
|
91
|
+
return name.charAt(0).toLocaleUpperCase(locale) + name.slice(1);
|
|
92
|
+
} catch {
|
|
93
|
+
return locale;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
var localeHref = (settings, slug, locale) => buildPath(settings, slug, locale);
|
|
97
|
+
|
|
80
98
|
// src/index.ts
|
|
81
99
|
var RETRY_AFTER_CAP_MS = 1e4;
|
|
82
100
|
var SITE_TTL_MS = 6e4;
|
|
@@ -162,6 +180,27 @@ function createBrease(opts = {}) {
|
|
|
162
180
|
const refs = await client.getPages();
|
|
163
181
|
return refs.filter((r) => !r.hidden && !r.slug.split("/").some((part) => part.startsWith("_"))).map((r) => ({ path: r.url.split("/").filter(Boolean) }));
|
|
164
182
|
},
|
|
183
|
+
async localeContext(path) {
|
|
184
|
+
const target = await client.route(path);
|
|
185
|
+
if (!target) return null;
|
|
186
|
+
const [site2, page, home] = await Promise.all([
|
|
187
|
+
client.getSite(),
|
|
188
|
+
client.getPage(target.slug, { locale: target.locale }),
|
|
189
|
+
client.getPage("", { locale: target.locale })
|
|
190
|
+
]);
|
|
191
|
+
const settings = {
|
|
192
|
+
locales: site2.locales,
|
|
193
|
+
defaultLocale: site2.defaultLocale,
|
|
194
|
+
localeStrategy: site2.localeStrategy,
|
|
195
|
+
urlTemplate: site2.urlTemplate
|
|
196
|
+
};
|
|
197
|
+
if (!page && !home) return null;
|
|
198
|
+
const alternates = {};
|
|
199
|
+
for (const [locale, url] of Object.entries(page?.alternates ?? {})) alternates[locale] = pathOf(url);
|
|
200
|
+
const homes = {};
|
|
201
|
+
for (const [locale, url] of Object.entries(home?.alternates ?? {})) homes[locale] = pathOf(url);
|
|
202
|
+
return { locale: target.locale, settings, alternates, homes };
|
|
203
|
+
},
|
|
165
204
|
async sitemap(baseUrl) {
|
|
166
205
|
const base = baseUrl.replace(/\/+$/, "");
|
|
167
206
|
const refs = (await client.getPages()).filter((r) => !r.hidden);
|
|
@@ -176,9 +215,19 @@ function createBrease(opts = {}) {
|
|
|
176
215
|
};
|
|
177
216
|
return client;
|
|
178
217
|
}
|
|
218
|
+
function pathOf(url) {
|
|
219
|
+
try {
|
|
220
|
+
return new URL(url, "http://localhost").pathname;
|
|
221
|
+
} catch {
|
|
222
|
+
return url;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
179
225
|
|
|
180
226
|
exports.BreaseError = BreaseError;
|
|
181
227
|
exports.buildPath = buildPath;
|
|
182
228
|
exports.createBrease = createBrease;
|
|
229
|
+
exports.localeHref = localeHref;
|
|
230
|
+
exports.localeLinks = localeLinks;
|
|
231
|
+
exports.nativeName = nativeName;
|
|
183
232
|
exports.normalizeSlug = normalizeSlug;
|
|
184
233
|
exports.resolvePath = resolvePath;
|
package/dist/index.d.cts
CHANGED
|
@@ -11,6 +11,16 @@ declare class BreaseError extends Error {
|
|
|
11
11
|
static fromResponse(res: Response): Promise<BreaseError>;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
type LocaleLink = {
|
|
15
|
+
locale: string;
|
|
16
|
+
label: string;
|
|
17
|
+
href: string;
|
|
18
|
+
current: boolean;
|
|
19
|
+
};
|
|
20
|
+
declare function localeLinks(context: LocaleContext): LocaleLink[];
|
|
21
|
+
declare function nativeName(locale: string): string;
|
|
22
|
+
declare const localeHref: (settings: UrlSettings, slug: string, locale: string) => string;
|
|
23
|
+
|
|
14
24
|
declare function normalizeSlug(input: string): string;
|
|
15
25
|
declare function buildPath(settings: UrlSettings, slug: string, locale: string): string;
|
|
16
26
|
declare function resolvePath(settings: UrlSettings, pathname: string): {
|
|
@@ -18,6 +28,12 @@ declare function resolvePath(settings: UrlSettings, pathname: string): {
|
|
|
18
28
|
locale: string;
|
|
19
29
|
};
|
|
20
30
|
|
|
31
|
+
type LocaleContext = {
|
|
32
|
+
locale: string;
|
|
33
|
+
settings: UrlSettings;
|
|
34
|
+
alternates: Record<string, string>;
|
|
35
|
+
homes: Record<string, string>;
|
|
36
|
+
};
|
|
21
37
|
type BreaseOptions = {
|
|
22
38
|
token?: string;
|
|
23
39
|
apiUrl?: string;
|
|
@@ -50,8 +66,9 @@ interface Brease {
|
|
|
50
66
|
routes(): Promise<{
|
|
51
67
|
path: string[];
|
|
52
68
|
}[]>;
|
|
69
|
+
localeContext(path?: string | string[]): Promise<LocaleContext | null>;
|
|
53
70
|
sitemap(baseUrl: string): Promise<SitemapEntry[]>;
|
|
54
71
|
}
|
|
55
72
|
declare function createBrease(opts?: BreaseOptions): Brease;
|
|
56
73
|
|
|
57
|
-
export { type Brease, BreaseError, type BreaseOptions, Navigation, Page, PageRef, Redirect, Release, Site, SitemapEntry, UrlSettings, buildPath, createBrease, normalizeSlug, resolvePath };
|
|
74
|
+
export { type Brease, BreaseError, type BreaseOptions, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, Site, SitemapEntry, UrlSettings, buildPath, createBrease, localeHref, localeLinks, nativeName, normalizeSlug, resolvePath };
|
package/dist/index.d.ts
CHANGED
|
@@ -11,6 +11,16 @@ declare class BreaseError extends Error {
|
|
|
11
11
|
static fromResponse(res: Response): Promise<BreaseError>;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
type LocaleLink = {
|
|
15
|
+
locale: string;
|
|
16
|
+
label: string;
|
|
17
|
+
href: string;
|
|
18
|
+
current: boolean;
|
|
19
|
+
};
|
|
20
|
+
declare function localeLinks(context: LocaleContext): LocaleLink[];
|
|
21
|
+
declare function nativeName(locale: string): string;
|
|
22
|
+
declare const localeHref: (settings: UrlSettings, slug: string, locale: string) => string;
|
|
23
|
+
|
|
14
24
|
declare function normalizeSlug(input: string): string;
|
|
15
25
|
declare function buildPath(settings: UrlSettings, slug: string, locale: string): string;
|
|
16
26
|
declare function resolvePath(settings: UrlSettings, pathname: string): {
|
|
@@ -18,6 +28,12 @@ declare function resolvePath(settings: UrlSettings, pathname: string): {
|
|
|
18
28
|
locale: string;
|
|
19
29
|
};
|
|
20
30
|
|
|
31
|
+
type LocaleContext = {
|
|
32
|
+
locale: string;
|
|
33
|
+
settings: UrlSettings;
|
|
34
|
+
alternates: Record<string, string>;
|
|
35
|
+
homes: Record<string, string>;
|
|
36
|
+
};
|
|
21
37
|
type BreaseOptions = {
|
|
22
38
|
token?: string;
|
|
23
39
|
apiUrl?: string;
|
|
@@ -50,8 +66,9 @@ interface Brease {
|
|
|
50
66
|
routes(): Promise<{
|
|
51
67
|
path: string[];
|
|
52
68
|
}[]>;
|
|
69
|
+
localeContext(path?: string | string[]): Promise<LocaleContext | null>;
|
|
53
70
|
sitemap(baseUrl: string): Promise<SitemapEntry[]>;
|
|
54
71
|
}
|
|
55
72
|
declare function createBrease(opts?: BreaseOptions): Brease;
|
|
56
73
|
|
|
57
|
-
export { type Brease, BreaseError, type BreaseOptions, Navigation, Page, PageRef, Redirect, Release, Site, SitemapEntry, UrlSettings, buildPath, createBrease, normalizeSlug, resolvePath };
|
|
74
|
+
export { type Brease, BreaseError, type BreaseOptions, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, Site, SitemapEntry, UrlSettings, buildPath, createBrease, localeHref, localeLinks, nativeName, normalizeSlug, resolvePath };
|
package/dist/index.js
CHANGED
|
@@ -1,170 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
// src/errors.ts
|
|
5
|
-
var BreaseError = class _BreaseError extends Error {
|
|
6
|
-
constructor(code, message, status, requestId, details) {
|
|
7
|
-
super(message);
|
|
8
|
-
__publicField(this, "code", code);
|
|
9
|
-
__publicField(this, "status", status);
|
|
10
|
-
__publicField(this, "requestId", requestId);
|
|
11
|
-
__publicField(this, "details", details);
|
|
12
|
-
__publicField(this, "name", "BreaseError");
|
|
13
|
-
}
|
|
14
|
-
static async fromResponse(res) {
|
|
15
|
-
const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-vercel-id") ?? void 0;
|
|
16
|
-
let code = res.status === 429 ? "rate_limited" : res.status >= 500 ? "upstream" : "http_error";
|
|
17
|
-
let message = `Brease API responded ${res.status}`;
|
|
18
|
-
let details;
|
|
19
|
-
try {
|
|
20
|
-
const body = await res.json();
|
|
21
|
-
if (body?.error) {
|
|
22
|
-
code = body.error.code ?? code;
|
|
23
|
-
message = body.error.message ?? message;
|
|
24
|
-
details = body.error.details;
|
|
25
|
-
}
|
|
26
|
-
} catch {
|
|
27
|
-
}
|
|
28
|
-
return new _BreaseError(code, message, res.status, requestId ?? void 0, details);
|
|
29
|
-
}
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
// src/urls.ts
|
|
33
|
-
function normalizeSlug(input) {
|
|
34
|
-
return input.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
|
|
35
|
-
}
|
|
36
|
-
function buildPath(settings, slug, locale) {
|
|
37
|
-
const clean = normalizeSlug(slug);
|
|
38
|
-
if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
|
|
39
|
-
const path = settings.urlTemplate.replace("{locale}", locale).replace("{slug}", clean);
|
|
40
|
-
return `/${normalizeSlug(path)}`;
|
|
41
|
-
}
|
|
42
|
-
const prefixed = settings.localeStrategy === "PREFIX_ALL" || locale !== settings.defaultLocale;
|
|
43
|
-
const parts = [prefixed ? locale : "", clean].filter(Boolean);
|
|
44
|
-
return `/${parts.join("/")}`;
|
|
45
|
-
}
|
|
46
|
-
function resolvePath(settings, pathname) {
|
|
47
|
-
const clean = normalizeSlug(decodeURIComponent(pathname.split(/[?#]/)[0] ?? ""));
|
|
48
|
-
if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
|
|
49
|
-
const pattern = normalizeSlug(settings.urlTemplate).split(/(\{locale\}|\{slug\})/).map((part) => {
|
|
50
|
-
if (part === "{locale}") return "(?<locale>[^/]+)";
|
|
51
|
-
if (part === "{slug}") return "(?<slug>.*)";
|
|
52
|
-
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
53
|
-
}).join("");
|
|
54
|
-
const match = new RegExp(`^${pattern}$`).exec(clean);
|
|
55
|
-
if (match?.groups) {
|
|
56
|
-
return {
|
|
57
|
-
slug: normalizeSlug(match.groups.slug ?? ""),
|
|
58
|
-
locale: match.groups.locale ?? settings.defaultLocale
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
return { slug: clean, locale: settings.defaultLocale };
|
|
62
|
-
}
|
|
63
|
-
const [first, ...rest] = clean.split("/");
|
|
64
|
-
if (first && settings.locales.includes(first)) {
|
|
65
|
-
return { slug: rest.join("/"), locale: first };
|
|
66
|
-
}
|
|
67
|
-
return { slug: clean, locale: settings.defaultLocale };
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// src/index.ts
|
|
71
|
-
var RETRY_AFTER_CAP_MS = 1e4;
|
|
72
|
-
var SITE_TTL_MS = 6e4;
|
|
73
|
-
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
74
|
-
function createBrease(opts = {}) {
|
|
75
|
-
const apiUrl = (opts.apiUrl ?? env("BREASE_API_URL") ?? "https://api.brease.io").replace(/\/+$/, "");
|
|
76
|
-
const commit = opts.commit === false ? void 0 : opts.commit ?? env("VERCEL_GIT_COMMIT_SHA");
|
|
77
|
-
const retries = opts.retries ?? 2;
|
|
78
|
-
const baseMs = opts.retryBaseMs ?? 300;
|
|
79
|
-
const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
80
|
-
let site;
|
|
81
|
-
async function request(path, query = {}, nullOn404 = false) {
|
|
82
|
-
const token = opts.token ?? env("BREASE_TOKEN");
|
|
83
|
-
if (!token)
|
|
84
|
-
throw new BreaseError("unauthorized", "No Brease token: pass { token } or set BREASE_TOKEN", 401);
|
|
85
|
-
const params = new URLSearchParams();
|
|
86
|
-
for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, v);
|
|
87
|
-
const qs = params.toString();
|
|
88
|
-
const url = `${apiUrl}${path}${qs ? `?${qs}` : ""}`;
|
|
89
|
-
const headers = { authorization: `Bearer ${token}`, accept: "application/json" };
|
|
90
|
-
if (commit) headers["x-brease-commit"] = commit;
|
|
91
|
-
for (let attempt = 0; ; attempt++) {
|
|
92
|
-
let res;
|
|
93
|
-
try {
|
|
94
|
-
res = await doFetch(url, { method: "GET", headers });
|
|
95
|
-
} catch (err) {
|
|
96
|
-
if (attempt < retries) {
|
|
97
|
-
await sleep(backoff(attempt));
|
|
98
|
-
continue;
|
|
99
|
-
}
|
|
100
|
-
throw new BreaseError("network", `Request to ${url} failed: ${err.message}`, 0);
|
|
101
|
-
}
|
|
102
|
-
if (res.ok) return await res.json();
|
|
103
|
-
if (res.status === 404 && nullOn404) return null;
|
|
104
|
-
if ((res.status === 429 || res.status >= 500) && attempt < retries) {
|
|
105
|
-
const after = Number(res.headers.get("retry-after"));
|
|
106
|
-
await sleep(after > 0 ? Math.min(after * 1e3, RETRY_AFTER_CAP_MS) : backoff(attempt));
|
|
107
|
-
continue;
|
|
108
|
-
}
|
|
109
|
-
throw await BreaseError.fromResponse(res);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
function backoff(attempt) {
|
|
113
|
-
return baseMs * 2 ** attempt + Math.random() * baseMs;
|
|
114
|
-
}
|
|
115
|
-
const client = {
|
|
116
|
-
getSite() {
|
|
117
|
-
if (!site || Date.now() - site.at > SITE_TTL_MS) {
|
|
118
|
-
const promise = request("/content-api/site").catch((err) => {
|
|
119
|
-
if (site?.promise === promise) site = void 0;
|
|
120
|
-
throw err;
|
|
121
|
-
});
|
|
122
|
-
site = { promise, at: Date.now() };
|
|
123
|
-
}
|
|
124
|
-
return site.promise;
|
|
125
|
-
},
|
|
126
|
-
getPage(slug, { locale }) {
|
|
127
|
-
return request("/content-api/page", { slug, locale }, true);
|
|
128
|
-
},
|
|
129
|
-
getPages(o = {}) {
|
|
130
|
-
return request("/content-api/pages", { locale: o.locale });
|
|
131
|
-
},
|
|
132
|
-
getNavigation(key, { locale }) {
|
|
133
|
-
return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
|
|
134
|
-
},
|
|
135
|
-
getRedirects() {
|
|
136
|
-
return request("/content-api/redirects");
|
|
137
|
-
},
|
|
138
|
-
getRelease() {
|
|
139
|
-
return request("/content-api/release");
|
|
140
|
-
},
|
|
141
|
-
async resolve(pathname) {
|
|
142
|
-
const site2 = await client.getSite();
|
|
143
|
-
const result = resolvePath(site2, pathname);
|
|
144
|
-
return site2.locales.includes(result.locale) ? result : null;
|
|
145
|
-
},
|
|
146
|
-
async route(path) {
|
|
147
|
-
const joined = Array.isArray(path) ? path.map((p) => decodeURIComponent(p)).join("/") : path ?? "";
|
|
148
|
-
const result = await client.resolve(`/${joined}`);
|
|
149
|
-
return result && !result.slug.split("/").some((part) => part.startsWith("_")) ? result : null;
|
|
150
|
-
},
|
|
151
|
-
async routes() {
|
|
152
|
-
const refs = await client.getPages();
|
|
153
|
-
return refs.filter((r) => !r.hidden && !r.slug.split("/").some((part) => part.startsWith("_"))).map((r) => ({ path: r.url.split("/").filter(Boolean) }));
|
|
154
|
-
},
|
|
155
|
-
async sitemap(baseUrl) {
|
|
156
|
-
const base = baseUrl.replace(/\/+$/, "");
|
|
157
|
-
const refs = (await client.getPages()).filter((r) => !r.hidden);
|
|
158
|
-
const byPage = /* @__PURE__ */ new Map();
|
|
159
|
-
for (const ref of refs) {
|
|
160
|
-
const alternates = byPage.get(ref.pageId) ?? {};
|
|
161
|
-
alternates[ref.locale] = `${base}${ref.url}`;
|
|
162
|
-
byPage.set(ref.pageId, alternates);
|
|
163
|
-
}
|
|
164
|
-
return refs.map((ref) => ({ url: `${base}${ref.url}`, alternates: byPage.get(ref.pageId) ?? {} }));
|
|
165
|
-
}
|
|
166
|
-
};
|
|
167
|
-
return client;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
export { BreaseError, buildPath, createBrease, normalizeSlug, resolvePath };
|
|
1
|
+
export { BreaseError, buildPath, createBrease, localeHref, localeLinks, nativeName, normalizeSlug, resolvePath } from './chunk-ULU4ABCQ.js';
|
|
2
|
+
import './chunk-PKBMQBKP.js';
|
package/dist/next.cjs
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
5
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
6
|
+
|
|
3
7
|
// src/env.ts
|
|
4
8
|
function env(name) {
|
|
5
9
|
const proc = globalThis.process;
|
|
@@ -7,6 +11,190 @@ function env(name) {
|
|
|
7
11
|
return value === "" ? void 0 : value;
|
|
8
12
|
}
|
|
9
13
|
|
|
14
|
+
// src/errors.ts
|
|
15
|
+
var BreaseError = class _BreaseError extends Error {
|
|
16
|
+
constructor(code, message, status, requestId, details) {
|
|
17
|
+
super(message);
|
|
18
|
+
__publicField(this, "code", code);
|
|
19
|
+
__publicField(this, "status", status);
|
|
20
|
+
__publicField(this, "requestId", requestId);
|
|
21
|
+
__publicField(this, "details", details);
|
|
22
|
+
__publicField(this, "name", "BreaseError");
|
|
23
|
+
}
|
|
24
|
+
static async fromResponse(res) {
|
|
25
|
+
const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-vercel-id") ?? void 0;
|
|
26
|
+
let code = res.status === 429 ? "rate_limited" : res.status >= 500 ? "upstream" : "http_error";
|
|
27
|
+
let message = `Brease API responded ${res.status}`;
|
|
28
|
+
let details;
|
|
29
|
+
try {
|
|
30
|
+
const body = await res.json();
|
|
31
|
+
if (body?.error) {
|
|
32
|
+
code = body.error.code ?? code;
|
|
33
|
+
message = body.error.message ?? message;
|
|
34
|
+
details = body.error.details;
|
|
35
|
+
}
|
|
36
|
+
} catch {
|
|
37
|
+
}
|
|
38
|
+
return new _BreaseError(code, message, res.status, requestId ?? void 0, details);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// src/urls.ts
|
|
43
|
+
function normalizeSlug(input) {
|
|
44
|
+
return input.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
|
|
45
|
+
}
|
|
46
|
+
function resolvePath(settings, pathname) {
|
|
47
|
+
const clean = normalizeSlug(decodeURIComponent(pathname.split(/[?#]/)[0] ?? ""));
|
|
48
|
+
if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
|
|
49
|
+
const pattern = normalizeSlug(settings.urlTemplate).split(/(\{locale\}|\{slug\})/).map((part) => {
|
|
50
|
+
if (part === "{locale}") return "(?<locale>[^/]+)";
|
|
51
|
+
if (part === "{slug}") return "(?<slug>.*)";
|
|
52
|
+
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
53
|
+
}).join("");
|
|
54
|
+
const match = new RegExp(`^${pattern}$`).exec(clean);
|
|
55
|
+
if (match?.groups) {
|
|
56
|
+
return {
|
|
57
|
+
slug: normalizeSlug(match.groups.slug ?? ""),
|
|
58
|
+
locale: match.groups.locale ?? settings.defaultLocale
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
return { slug: clean, locale: settings.defaultLocale };
|
|
62
|
+
}
|
|
63
|
+
const [first, ...rest] = clean.split("/");
|
|
64
|
+
if (first && settings.locales.includes(first)) {
|
|
65
|
+
return { slug: rest.join("/"), locale: first };
|
|
66
|
+
}
|
|
67
|
+
return { slug: clean, locale: settings.defaultLocale };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// src/index.ts
|
|
71
|
+
var RETRY_AFTER_CAP_MS = 1e4;
|
|
72
|
+
var SITE_TTL_MS = 6e4;
|
|
73
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
74
|
+
function createBrease(opts = {}) {
|
|
75
|
+
const apiUrl = (opts.apiUrl ?? env("BREASE_API_URL") ?? "https://api.brease.io").replace(/\/+$/, "");
|
|
76
|
+
const commit = opts.commit === false ? void 0 : opts.commit ?? env("VERCEL_GIT_COMMIT_SHA");
|
|
77
|
+
const retries = opts.retries ?? 2;
|
|
78
|
+
const baseMs = opts.retryBaseMs ?? 300;
|
|
79
|
+
const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
80
|
+
let site;
|
|
81
|
+
async function request(path, query = {}, nullOn404 = false) {
|
|
82
|
+
const token = opts.token ?? env("BREASE_TOKEN");
|
|
83
|
+
if (!token)
|
|
84
|
+
throw new BreaseError("unauthorized", "No Brease token: pass { token } or set BREASE_TOKEN", 401);
|
|
85
|
+
const params = new URLSearchParams();
|
|
86
|
+
for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, v);
|
|
87
|
+
const qs = params.toString();
|
|
88
|
+
const url = `${apiUrl}${path}${qs ? `?${qs}` : ""}`;
|
|
89
|
+
const headers = { authorization: `Bearer ${token}`, accept: "application/json" };
|
|
90
|
+
if (commit) headers["x-brease-commit"] = commit;
|
|
91
|
+
for (let attempt = 0; ; attempt++) {
|
|
92
|
+
let res;
|
|
93
|
+
try {
|
|
94
|
+
res = await doFetch(url, { method: "GET", headers });
|
|
95
|
+
} catch (err) {
|
|
96
|
+
if (attempt < retries) {
|
|
97
|
+
await sleep(backoff(attempt));
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
throw new BreaseError("network", `Request to ${url} failed: ${err.message}`, 0);
|
|
101
|
+
}
|
|
102
|
+
if (res.ok) return await res.json();
|
|
103
|
+
if (res.status === 404 && nullOn404) return null;
|
|
104
|
+
if ((res.status === 429 || res.status >= 500) && attempt < retries) {
|
|
105
|
+
const after = Number(res.headers.get("retry-after"));
|
|
106
|
+
await sleep(after > 0 ? Math.min(after * 1e3, RETRY_AFTER_CAP_MS) : backoff(attempt));
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
throw await BreaseError.fromResponse(res);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function backoff(attempt) {
|
|
113
|
+
return baseMs * 2 ** attempt + Math.random() * baseMs;
|
|
114
|
+
}
|
|
115
|
+
const client = {
|
|
116
|
+
getSite() {
|
|
117
|
+
if (!site || Date.now() - site.at > SITE_TTL_MS) {
|
|
118
|
+
const promise = request("/content-api/site").catch((err) => {
|
|
119
|
+
if (site?.promise === promise) site = void 0;
|
|
120
|
+
throw err;
|
|
121
|
+
});
|
|
122
|
+
site = { promise, at: Date.now() };
|
|
123
|
+
}
|
|
124
|
+
return site.promise;
|
|
125
|
+
},
|
|
126
|
+
getPage(slug, { locale }) {
|
|
127
|
+
return request("/content-api/page", { slug, locale }, true);
|
|
128
|
+
},
|
|
129
|
+
getPages(o = {}) {
|
|
130
|
+
return request("/content-api/pages", { locale: o.locale });
|
|
131
|
+
},
|
|
132
|
+
getNavigation(key, { locale }) {
|
|
133
|
+
return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
|
|
134
|
+
},
|
|
135
|
+
getRedirects() {
|
|
136
|
+
return request("/content-api/redirects");
|
|
137
|
+
},
|
|
138
|
+
getRelease() {
|
|
139
|
+
return request("/content-api/release");
|
|
140
|
+
},
|
|
141
|
+
async resolve(pathname) {
|
|
142
|
+
const site2 = await client.getSite();
|
|
143
|
+
const result = resolvePath(site2, pathname);
|
|
144
|
+
return site2.locales.includes(result.locale) ? result : null;
|
|
145
|
+
},
|
|
146
|
+
async route(path) {
|
|
147
|
+
const joined = Array.isArray(path) ? path.map((p) => decodeURIComponent(p)).join("/") : path ?? "";
|
|
148
|
+
const result = await client.resolve(`/${joined}`);
|
|
149
|
+
return result && !result.slug.split("/").some((part) => part.startsWith("_")) ? result : null;
|
|
150
|
+
},
|
|
151
|
+
async routes() {
|
|
152
|
+
const refs = await client.getPages();
|
|
153
|
+
return refs.filter((r) => !r.hidden && !r.slug.split("/").some((part) => part.startsWith("_"))).map((r) => ({ path: r.url.split("/").filter(Boolean) }));
|
|
154
|
+
},
|
|
155
|
+
async localeContext(path) {
|
|
156
|
+
const target = await client.route(path);
|
|
157
|
+
if (!target) return null;
|
|
158
|
+
const [site2, page, home] = await Promise.all([
|
|
159
|
+
client.getSite(),
|
|
160
|
+
client.getPage(target.slug, { locale: target.locale }),
|
|
161
|
+
client.getPage("", { locale: target.locale })
|
|
162
|
+
]);
|
|
163
|
+
const settings = {
|
|
164
|
+
locales: site2.locales,
|
|
165
|
+
defaultLocale: site2.defaultLocale,
|
|
166
|
+
localeStrategy: site2.localeStrategy,
|
|
167
|
+
urlTemplate: site2.urlTemplate
|
|
168
|
+
};
|
|
169
|
+
if (!page && !home) return null;
|
|
170
|
+
const alternates = {};
|
|
171
|
+
for (const [locale, url] of Object.entries(page?.alternates ?? {})) alternates[locale] = pathOf(url);
|
|
172
|
+
const homes = {};
|
|
173
|
+
for (const [locale, url] of Object.entries(home?.alternates ?? {})) homes[locale] = pathOf(url);
|
|
174
|
+
return { locale: target.locale, settings, alternates, homes };
|
|
175
|
+
},
|
|
176
|
+
async sitemap(baseUrl) {
|
|
177
|
+
const base = baseUrl.replace(/\/+$/, "");
|
|
178
|
+
const refs = (await client.getPages()).filter((r) => !r.hidden);
|
|
179
|
+
const byPage = /* @__PURE__ */ new Map();
|
|
180
|
+
for (const ref of refs) {
|
|
181
|
+
const alternates = byPage.get(ref.pageId) ?? {};
|
|
182
|
+
alternates[ref.locale] = `${base}${ref.url}`;
|
|
183
|
+
byPage.set(ref.pageId, alternates);
|
|
184
|
+
}
|
|
185
|
+
return refs.map((ref) => ({ url: `${base}${ref.url}`, alternates: byPage.get(ref.pageId) ?? {} }));
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
return client;
|
|
189
|
+
}
|
|
190
|
+
function pathOf(url) {
|
|
191
|
+
try {
|
|
192
|
+
return new URL(url, "http://localhost").pathname;
|
|
193
|
+
} catch {
|
|
194
|
+
return url;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
10
198
|
// src/next.ts
|
|
11
199
|
var compact = (obj) => Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0));
|
|
12
200
|
function toMetadata(seo, opts = {}) {
|
|
@@ -100,8 +288,20 @@ async function hmacHex(secret, message) {
|
|
|
100
288
|
function json(status, data) {
|
|
101
289
|
return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });
|
|
102
290
|
}
|
|
291
|
+
function breaseRedirects(client = createBrease()) {
|
|
292
|
+
return async () => {
|
|
293
|
+
try {
|
|
294
|
+
const redirects = await client.getRedirects();
|
|
295
|
+
return redirects.map((r) => ({ source: r.source, destination: r.destination, statusCode: r.status }));
|
|
296
|
+
} catch (err) {
|
|
297
|
+
console.warn(`Brease redirects unavailable: ${err.message}`);
|
|
298
|
+
return [];
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
}
|
|
103
302
|
|
|
104
303
|
exports.breaseFetch = breaseFetch;
|
|
304
|
+
exports.breaseRedirects = breaseRedirects;
|
|
105
305
|
exports.hmacHex = hmacHex;
|
|
106
306
|
exports.revalidateHandler = revalidateHandler;
|
|
107
307
|
exports.toMetadata = toMetadata;
|
package/dist/next.d.cts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Brease } from './index.cjs';
|
|
1
2
|
import { R as ResolvedSeo } from './types-V0ELFvwy.cjs';
|
|
2
3
|
|
|
3
4
|
type BreaseMetadata = {
|
|
@@ -43,5 +44,10 @@ declare function breaseFetch(tags?: string[], revalidate?: number | false): type
|
|
|
43
44
|
declare function revalidateHandler(secret?: string): (req: Request) => Promise<Response>;
|
|
44
45
|
declare function verifySignature(body: string, timestamp: string | null, signature: string | null, secret: string, now?: number): Promise<boolean>;
|
|
45
46
|
declare function hmacHex(secret: string, message: string): Promise<string>;
|
|
47
|
+
declare function breaseRedirects(client?: Pick<Brease, 'getRedirects'>): () => Promise<{
|
|
48
|
+
source: string;
|
|
49
|
+
destination: string;
|
|
50
|
+
statusCode: 301 | 302 | 307 | 308;
|
|
51
|
+
}[]>;
|
|
46
52
|
|
|
47
|
-
export { type BreaseMetadata, breaseFetch, hmacHex, revalidateHandler, toMetadata, verifySignature };
|
|
53
|
+
export { type BreaseMetadata, breaseFetch, breaseRedirects, hmacHex, revalidateHandler, toMetadata, verifySignature };
|
package/dist/next.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Brease } from './index.js';
|
|
1
2
|
import { R as ResolvedSeo } from './types-V0ELFvwy.js';
|
|
2
3
|
|
|
3
4
|
type BreaseMetadata = {
|
|
@@ -43,5 +44,10 @@ declare function breaseFetch(tags?: string[], revalidate?: number | false): type
|
|
|
43
44
|
declare function revalidateHandler(secret?: string): (req: Request) => Promise<Response>;
|
|
44
45
|
declare function verifySignature(body: string, timestamp: string | null, signature: string | null, secret: string, now?: number): Promise<boolean>;
|
|
45
46
|
declare function hmacHex(secret: string, message: string): Promise<string>;
|
|
47
|
+
declare function breaseRedirects(client?: Pick<Brease, 'getRedirects'>): () => Promise<{
|
|
48
|
+
source: string;
|
|
49
|
+
destination: string;
|
|
50
|
+
statusCode: 301 | 302 | 307 | 308;
|
|
51
|
+
}[]>;
|
|
46
52
|
|
|
47
|
-
export { type BreaseMetadata, breaseFetch, hmacHex, revalidateHandler, toMetadata, verifySignature };
|
|
53
|
+
export { type BreaseMetadata, breaseFetch, breaseRedirects, hmacHex, revalidateHandler, toMetadata, verifySignature };
|
package/dist/next.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { env } from './chunk-
|
|
1
|
+
import { env, createBrease } from './chunk-ULU4ABCQ.js';
|
|
2
2
|
import './chunk-PKBMQBKP.js';
|
|
3
3
|
|
|
4
4
|
// src/next.ts
|
|
@@ -94,5 +94,16 @@ async function hmacHex(secret, message) {
|
|
|
94
94
|
function json(status, data) {
|
|
95
95
|
return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });
|
|
96
96
|
}
|
|
97
|
+
function breaseRedirects(client = createBrease()) {
|
|
98
|
+
return async () => {
|
|
99
|
+
try {
|
|
100
|
+
const redirects = await client.getRedirects();
|
|
101
|
+
return redirects.map((r) => ({ source: r.source, destination: r.destination, statusCode: r.status }));
|
|
102
|
+
} catch (err) {
|
|
103
|
+
console.warn(`Brease redirects unavailable: ${err.message}`);
|
|
104
|
+
return [];
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
97
108
|
|
|
98
|
-
export { breaseFetch, hmacHex, revalidateHandler, toMetadata, verifySignature };
|
|
109
|
+
export { breaseFetch, breaseRedirects, hmacHex, revalidateHandler, toMetadata, verifySignature };
|
package/package.json
CHANGED