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.
package/dist/cli.cjs CHANGED
@@ -3,50 +3,177 @@
3
3
 
4
4
  var fs = require('fs');
5
5
  var path = require('path');
6
+ var http = require('http');
7
+
8
+ var __defProp = Object.defineProperty;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
11
+
12
+ // src/env.ts
13
+ function env(name) {
14
+ const proc = globalThis.process;
15
+ const value = proc?.env?.[name];
16
+ return value === "" ? void 0 : value;
17
+ }
18
+
19
+ // src/errors.ts
20
+ var BreaseError = class _BreaseError extends Error {
21
+ constructor(code, message, status, requestId, details) {
22
+ super(message);
23
+ __publicField(this, "code", code);
24
+ __publicField(this, "status", status);
25
+ __publicField(this, "requestId", requestId);
26
+ __publicField(this, "details", details);
27
+ __publicField(this, "name", "BreaseError");
28
+ }
29
+ static async fromResponse(res) {
30
+ const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-vercel-id") ?? void 0;
31
+ let code = res.status === 429 ? "rate_limited" : res.status >= 500 ? "upstream" : "http_error";
32
+ let message = `Brease API responded ${res.status}`;
33
+ let details;
34
+ try {
35
+ const body = await res.json();
36
+ if (body?.error) {
37
+ code = body.error.code ?? code;
38
+ message = body.error.message ?? message;
39
+ details = body.error.details;
40
+ }
41
+ } catch {
42
+ }
43
+ return new _BreaseError(code, message, res.status, requestId ?? void 0, details);
44
+ }
45
+ };
46
+
47
+ // src/urls.ts
48
+ function normalizeSlug(input) {
49
+ return input.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
50
+ }
51
+ function customPattern(template) {
52
+ const parts = normalizeSlug(template).split(/(\{locale\}|\{slug\})/);
53
+ const slashBefore = (i) => parts[i] === "{slug}" && !!parts[i - 1]?.endsWith("/");
54
+ const slashAfter = (i) => parts[i] === "{slug}" && !slashBefore(i) && !!parts[i + 1]?.startsWith("/");
55
+ const pattern = parts.map((part, i) => {
56
+ if (part === "{locale}") return "(?<locale>[^/]+)";
57
+ if (part === "{slug}") {
58
+ if (slashBefore(i)) return "(?:/(?<slug>.*))?";
59
+ if (slashAfter(i)) return "(?:(?<slug>.*)/)?";
60
+ return "(?<slug>.*)";
61
+ }
62
+ let text = part;
63
+ if (slashBefore(i + 1)) text = text.slice(0, -1);
64
+ if (slashAfter(i - 1)) text = text.slice(1);
65
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
66
+ }).join("");
67
+ return new RegExp(`^${pattern}$`);
68
+ }
69
+ function safeDecode(value) {
70
+ try {
71
+ return decodeURIComponent(value);
72
+ } catch {
73
+ return value;
74
+ }
75
+ }
76
+ function resolvePath(settings, pathname) {
77
+ const clean = normalizeSlug(safeDecode(pathname.split(/[?#]/)[0] ?? ""));
78
+ if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
79
+ const match = customPattern(settings.urlTemplate).exec(clean);
80
+ if (match?.groups) {
81
+ return {
82
+ slug: normalizeSlug(match.groups.slug ?? ""),
83
+ locale: match.groups.locale ?? settings.defaultLocale
84
+ };
85
+ }
86
+ return { slug: clean, locale: settings.defaultLocale };
87
+ }
88
+ const [first, ...rest] = clean.split("/");
89
+ if (first && settings.locales.includes(first)) {
90
+ return { slug: rest.join("/"), locale: first };
91
+ }
92
+ return { slug: clean, locale: settings.defaultLocale };
93
+ }
94
+
95
+ // src/redirects.ts
96
+ function matchRedirect(redirects, pathname) {
97
+ const path = normalize(pathname);
98
+ for (const r of redirects) {
99
+ const params = matchSource(normalize(r.source), path);
100
+ if (!params) continue;
101
+ const destination = r.destination.replace(
102
+ /:([A-Za-z_][A-Za-z0-9_]*)\*?/g,
103
+ (whole, name) => name in params ? params[name] : whole
104
+ );
105
+ if (normalize(destination) === path) continue;
106
+ return { destination, status: r.status };
107
+ }
108
+ return null;
109
+ }
110
+ var normalize = (p) => (p.length > 1 ? p.replace(/\/+$/, "") : p) || "/";
111
+ function matchSource(source, path) {
112
+ const want = source.split("/").filter(Boolean);
113
+ const have = path.split("/").filter(Boolean);
114
+ const params = {};
115
+ for (let i = 0; i < want.length; i++) {
116
+ const seg = want[i];
117
+ const rest = /^:([A-Za-z_][A-Za-z0-9_]*)\*$/.exec(seg);
118
+ if (rest) {
119
+ params[rest[1]] = have.slice(i).join("/");
120
+ return params;
121
+ }
122
+ const value = have[i];
123
+ if (value === void 0) return null;
124
+ const param = /^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(seg);
125
+ if (param) params[param[1]] = value;
126
+ else if (safeDecode(value) !== safeDecode(seg)) return null;
127
+ }
128
+ return want.length === have.length ? params : null;
129
+ }
6
130
 
7
131
  // src/sections.ts
8
132
  var SECTION_FOLDERS = ["src/brease/sections", "brease/sections"];
9
133
  var TYPE_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
10
- function checkSections(files2, pages = {}) {
11
- const warnings2 = [];
12
- const folder2 = SECTION_FOLDERS.find((f) => Object.keys(files2).some((p) => p.startsWith(`${f}/`)));
13
- if (!folder2) return warnings2;
14
- const inFolder = Object.entries(files2).map(([p, text]) => [p.slice(folder2.length + 1), text]);
134
+ var MAP_FILE = /^(index|sections)\.(astro|vue|svelte|[cm]?[jt]sx?)$/i;
135
+ function checkSections(files, pages = {}) {
136
+ const warnings = [];
137
+ const folder = SECTION_FOLDERS.find((f) => Object.keys(files).some((p) => p.startsWith(`${f}/`)));
138
+ if (!folder) return warnings;
139
+ const inFolder = Object.entries(files).map(([p, text]) => [p.slice(folder.length + 1), text]);
15
140
  const types = [
16
141
  ...new Set(
17
142
  inFolder.map(([p]) => p.split("/")).filter((s) => s.length > 1).map((s) => s[0])
18
143
  )
19
144
  ];
20
- const map = inFolder.find(([p]) => /^index\.[cm]?[jt]sx?$/.test(p));
145
+ const map = inFolder.find(([p]) => MAP_FILE.test(p));
21
146
  if (!map)
22
- warnings2.push(`${folder2} has no map file (index.tsx, index.ts or index.js) rendering the section types`);
147
+ warnings.push(
148
+ `${folder} has no map file (index.tsx, index.ts, Sections.astro or the like) rendering the section types`
149
+ );
23
150
  const marked = inFolder.some(
24
151
  ([, text]) => text.includes("data-brease-section") || text.includes("sectionAttrs(")
25
152
  );
26
153
  if (!marked)
27
- warnings2.push(
28
- `No component in ${folder2} renders data-brease-section (or sectionAttrs), so editors can't add sections`
154
+ warnings.push(
155
+ `No component in ${folder} renders data-brease-section (or sectionAttrs), so editors can't add sections`
29
156
  );
30
157
  for (const type of types) {
31
158
  if (!TYPE_NAME.test(type)) {
32
- warnings2.push(`${folder2}/${type}: use lowercase letters, numbers and - in section folder names`);
159
+ warnings.push(`${folder}/${type}: use lowercase letters, numbers and - in section folder names`);
33
160
  continue;
34
161
  }
35
- const json = files2[`${folder2}/${type}/section.json`];
162
+ const json = files[`${folder}/${type}/section.json`];
36
163
  if (json === void 0) {
37
- warnings2.push(`${folder2}/${type} has no section.json`);
164
+ warnings.push(`${folder}/${type} has no section.json`);
38
165
  continue;
39
166
  }
40
167
  try {
41
168
  const meta = JSON.parse(json);
42
169
  if (typeof meta.name !== "string" || !meta.name.trim())
43
- warnings2.push(`${folder2}/${type}/section.json has no name`);
170
+ warnings.push(`${folder}/${type}/section.json has no name`);
44
171
  if (meta.fields !== void 0 && (typeof meta.fields !== "object" || meta.fields === null))
45
- warnings2.push(`${folder2}/${type}/section.json: fields must be a JSON Schema object`);
172
+ warnings.push(`${folder}/${type}/section.json: fields must be a JSON Schema object`);
46
173
  } catch {
47
- warnings2.push(`${folder2}/${type}/section.json is not valid JSON`);
174
+ warnings.push(`${folder}/${type}/section.json is not valid JSON`);
48
175
  }
49
- if (map && !map[1].includes(type)) warnings2.push(`${type} is in ${folder2} but not in its map file`);
176
+ if (map && !map[1].includes(type)) warnings.push(`${type} is in ${folder} but not in its map file`);
50
177
  }
51
178
  const known = new Set(types);
52
179
  for (const [pageId, locales] of Object.entries(pages)) {
@@ -55,27 +182,706 @@ function checkSections(files2, pages = {}) {
55
182
  const list = file.content?.sections;
56
183
  if (list === void 0) continue;
57
184
  if (!Array.isArray(list)) {
58
- warnings2.push(`${pageId} (${locale}): sections is not a list`);
185
+ warnings.push(`${pageId} (${locale}): sections is not a list`);
59
186
  continue;
60
187
  }
61
188
  const ids = /* @__PURE__ */ new Set();
62
189
  for (const item of list) {
63
190
  if (typeof item?.id !== "string" || typeof item.type !== "string") {
64
- warnings2.push(`${pageId} (${locale}): a section has no id or type`);
191
+ warnings.push(`${pageId} (${locale}): a section has no id or type`);
65
192
  continue;
66
193
  }
67
- if (ids.has(item.id)) warnings2.push(`${pageId} (${locale}): section ${item.id} appears twice`);
194
+ if (ids.has(item.id)) warnings.push(`${pageId} (${locale}): section ${item.id} appears twice`);
68
195
  ids.add(item.id);
69
196
  if (!known.has(item.type))
70
- warnings2.push(`${pageId} (${locale}): section type "${item.type}" has no folder`);
197
+ warnings.push(`${pageId} (${locale}): section type "${item.type}" has no folder`);
71
198
  }
72
199
  const shape = list.map((s) => `${s?.id}:${s?.type}`).join(",");
73
200
  if (reference === null) reference = shape;
74
201
  else if (shape !== reference)
75
- warnings2.push(`${pageId}: the sections in ${locale} differ from the other locales`);
202
+ warnings.push(`${pageId}: the sections in ${locale} differ from the other locales`);
76
203
  }
77
204
  }
78
- return warnings2;
205
+ return warnings;
206
+ }
207
+
208
+ // src/structured-data.ts
209
+ var jsonLdText = (data) => JSON.stringify(data).replace(/</g, "\\u003c");
210
+ function jsonLd(seo) {
211
+ return (seo.structuredData ?? []).map((data) => ({ data, json: jsonLdText(data) }));
212
+ }
213
+
214
+ // src/html.ts
215
+ function headTagList(seo, opts = {}) {
216
+ const tags = [{ tag: "title", attrs: {}, content: seo.title }];
217
+ const meta = (key, name, value) => {
218
+ if (value) tags.push({ tag: "meta", attrs: { [key]: name, content: value } });
219
+ };
220
+ meta("name", "description", seo.description);
221
+ if (seo.canonical) tags.push({ tag: "link", attrs: { rel: "canonical", href: seo.canonical } });
222
+ meta(
223
+ "name",
224
+ "robots",
225
+ `${seo.robots.index ? "index" : "noindex"}, ${seo.robots.follow ? "follow" : "nofollow"}`
226
+ );
227
+ for (const [lang, href] of Object.entries(seo.alternates)) {
228
+ tags.push({ tag: "link", attrs: { rel: "alternate", hreflang: lang, href } });
229
+ }
230
+ if (opts.xDefault) {
231
+ tags.push({ tag: "link", attrs: { rel: "alternate", hreflang: "x-default", href: opts.xDefault } });
232
+ }
233
+ const og = seo.openGraph;
234
+ meta("property", "og:type", og.type);
235
+ meta("property", "og:title", og.title);
236
+ meta("property", "og:description", og.description);
237
+ meta("property", "og:image", og.image);
238
+ meta("property", "og:url", og.url);
239
+ meta("property", "og:site_name", og.siteName);
240
+ const tw = seo.twitter;
241
+ meta("name", "twitter:card", tw.card);
242
+ meta("name", "twitter:site", tw.site);
243
+ meta("name", "twitter:creator", tw.creator);
244
+ meta("name", "twitter:title", tw.title);
245
+ meta("name", "twitter:description", tw.description);
246
+ meta("name", "twitter:image", tw.image);
247
+ if (seo.favicon) tags.push({ tag: "link", attrs: { rel: "icon", href: seo.favicon } });
248
+ for (const item of jsonLd(seo)) {
249
+ tags.push({ tag: "script", attrs: { type: "application/ld+json" }, content: item.json });
250
+ }
251
+ return tags;
252
+ }
253
+ var escapeHtml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
254
+ function renderTag(t) {
255
+ const attrs = Object.entries(t.attrs).map(([k, v]) => ` ${k}="${escapeHtml(v)}"`).join("");
256
+ if (t.tag === "meta" || t.tag === "link") return `<${t.tag}${attrs}>`;
257
+ const content = t.tag === "script" ? t.content ?? "" : escapeHtml(t.content ?? "");
258
+ return `<${t.tag}${attrs}>${content}</${t.tag}>`;
259
+ }
260
+ function headTags(seo, opts = {}) {
261
+ const parts = headTagList(seo, opts).map(renderTag);
262
+ if (opts.includeCustom !== false) {
263
+ if (seo.customHead) parts.push(seo.customHead);
264
+ if (seo.customCode) parts.push(seo.customCode);
265
+ }
266
+ return parts.join("\n");
267
+ }
268
+
269
+ // src/template.ts
270
+ var VOID = /* @__PURE__ */ new Set([
271
+ "area",
272
+ "base",
273
+ "br",
274
+ "col",
275
+ "embed",
276
+ "hr",
277
+ "img",
278
+ "input",
279
+ "link",
280
+ "meta",
281
+ "source",
282
+ "track",
283
+ "wbr"
284
+ ]);
285
+ var RAW_TEXT = /* @__PURE__ */ new Set(["script", "style", "textarea", "title"]);
286
+ var ATTR = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
287
+ function parseAttrs(source) {
288
+ const attrs = [];
289
+ for (const m of source.matchAll(ATTR)) {
290
+ attrs.push({ name: m[1], value: m[2] ?? m[3] ?? m[4] ?? null });
291
+ }
292
+ return attrs;
293
+ }
294
+ function parseHtml(html) {
295
+ const root = { kind: "el", tag: "#root", attrs: [], children: [], selfClosing: false, void: false };
296
+ const stack = [root];
297
+ const top = () => stack[stack.length - 1];
298
+ let i = 0;
299
+ const text = (t) => {
300
+ if (t) top().children.push({ kind: "raw", text: t });
301
+ };
302
+ while (i < html.length) {
303
+ const lt = html.indexOf("<", i);
304
+ if (lt === -1) {
305
+ text(html.slice(i));
306
+ break;
307
+ }
308
+ text(html.slice(i, lt));
309
+ if (html.startsWith("<!--", lt)) {
310
+ const end = html.indexOf("-->", lt + 4);
311
+ const stop = end === -1 ? html.length : end + 3;
312
+ text(html.slice(lt, stop));
313
+ i = stop;
314
+ continue;
315
+ }
316
+ if (html[lt + 1] === "!" || html[lt + 1] === "?") {
317
+ const end = html.indexOf(">", lt);
318
+ const stop = end === -1 ? html.length : end + 1;
319
+ text(html.slice(lt, stop));
320
+ i = stop;
321
+ continue;
322
+ }
323
+ const close = /^<\/([a-zA-Z][\w:-]*)\s*>/.exec(html.slice(lt));
324
+ if (close) {
325
+ const name = close[1].toLowerCase();
326
+ const at = stack.map((e) => e.tag).lastIndexOf(name);
327
+ if (at > 0) stack.length = at;
328
+ i = lt + close[0].length;
329
+ continue;
330
+ }
331
+ const open = /^<([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>/.exec(
332
+ html.slice(lt)
333
+ );
334
+ if (!open) {
335
+ text("<");
336
+ i = lt + 1;
337
+ continue;
338
+ }
339
+ const tag = open[1].toLowerCase();
340
+ const el = {
341
+ kind: "el",
342
+ tag,
343
+ attrs: parseAttrs(open[2] ?? ""),
344
+ children: [],
345
+ selfClosing: open[3] === "/",
346
+ void: VOID.has(tag)
347
+ };
348
+ top().children.push(el);
349
+ i = lt + open[0].length;
350
+ if (el.void || el.selfClosing) continue;
351
+ if (RAW_TEXT.has(tag)) {
352
+ const end = html.toLowerCase().indexOf(`</${tag}`, i);
353
+ const stop = end === -1 ? html.length : end;
354
+ if (stop > i) el.children.push({ kind: "raw", text: html.slice(i, stop) });
355
+ const gt = end === -1 ? html.length : html.indexOf(">", end);
356
+ i = gt === -1 ? html.length : gt + 1;
357
+ continue;
358
+ }
359
+ stack.push(el);
360
+ }
361
+ return root.children;
362
+ }
363
+ var escapeText = (v) => v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
364
+ var escapeAttr = (v) => escapeText(v).replace(/"/g, "&quot;");
365
+ function serializeHtml(nodes) {
366
+ return nodes.map((n) => {
367
+ if (n.kind === "raw") return n.text;
368
+ const attrs = n.attrs.map(
369
+ (a) => a.value === null ? ` ${a.name}` : ` ${a.name}="${escapeAttr(a.value)}"`
370
+ );
371
+ const open = `<${n.tag}${attrs.join("")}${n.selfClosing ? " /" : ""}>`;
372
+ if (n.void || n.selfClosing) return open;
373
+ return `${open}${serializeHtml(n.children)}</${n.tag}>`;
374
+ }).join("");
375
+ }
376
+ var attr = (el, name) => el.attrs.find((a) => a.name === name);
377
+ function setAttr(el, name, value) {
378
+ const found = attr(el, name);
379
+ if (found) found.value = value;
380
+ else el.attrs.push({ name, value });
381
+ }
382
+ var removeAttr = (el, name) => {
383
+ el.attrs = el.attrs.filter((a) => a.name !== name);
384
+ };
385
+ var elements = (nodes) => nodes.filter((n) => n.kind === "el");
386
+ function valueAt(source, path) {
387
+ let current = source;
388
+ for (const key of path.split(".")) {
389
+ if (current === null || typeof current !== "object") return void 0;
390
+ current = current[key];
391
+ }
392
+ return current;
393
+ }
394
+ var isImage = (v) => !!v && typeof v === "object" && typeof v.url === "string" && !("href" in v);
395
+ var isLink = (v) => !!v && typeof v === "object" && typeof v.href === "string";
396
+ var looksLikeHtml = (v) => /<[a-z][\s\S]*>/i.test(v);
397
+ function setText(el, value, html) {
398
+ el.children = [{ kind: "raw", text: html ? value : escapeText(value) }];
399
+ }
400
+ function renumber(nodes, listPath, index) {
401
+ const from = `${listPath}.0.`;
402
+ const to = `${listPath}.${index}.`;
403
+ for (const el of elements(nodes)) {
404
+ const marker = attr(el, "data-brease");
405
+ if (marker?.value?.includes(from)) marker.value = marker.value.replace(from, to);
406
+ renumber(el.children, listPath, index);
407
+ }
408
+ }
409
+ var clone = (value) => JSON.parse(JSON.stringify(value));
410
+ function itemTemplate(el) {
411
+ const children = elements(el.children);
412
+ const template = children.find((c) => attr(c, "data-brease-item"));
413
+ return template ?? null;
414
+ }
415
+ function renderNavItem(template, item) {
416
+ const copy = clone(template);
417
+ const labels = [];
418
+ const links = [];
419
+ const walk2 = (el) => {
420
+ if (attr(el, "data-brease-label")) labels.push(el);
421
+ if (el.tag === "a") links.push(el);
422
+ for (const c of elements(el.children)) walk2(c);
423
+ };
424
+ walk2(copy);
425
+ const link = copy.tag === "a" ? copy : links[0];
426
+ if (link) {
427
+ setAttr(link, "href", item.url);
428
+ if (item.target === "_blank") setAttr(link, "target", "_blank");
429
+ if (!labels.length && !elements(link.children).length) setText(link, item.label, false);
430
+ }
431
+ for (const label of labels) setText(label, item.label, false);
432
+ return copy;
433
+ }
434
+ function renderTemplate(template, data) {
435
+ const nodes = parseHtml(template);
436
+ const head = headTags(data.page.resolvedSeo);
437
+ const resolve = (ref) => {
438
+ const at = ref.indexOf(":");
439
+ if (at === -1) return { value: valueAt(data.page.content, ref), marker: ref };
440
+ const owner = ref.slice(0, at);
441
+ const path = ref.slice(at + 1);
442
+ if (owner === "_global") {
443
+ const global = data.global;
444
+ return {
445
+ value: global ? valueAt(global.content, path) : void 0,
446
+ marker: global ? `${global.pageId}:${path}` : ref
447
+ };
448
+ }
449
+ return { value: void 0, marker: ref };
450
+ };
451
+ const fill = (el) => {
452
+ const marker = attr(el, "data-brease");
453
+ const ref = marker?.value;
454
+ if (marker && ref?.startsWith("nav:")) {
455
+ const items = data.navigations?.[ref.slice(4)]?.items;
456
+ const template2 = itemTemplate(el);
457
+ if (items && template2) {
458
+ const rendered = items.map((item) => renderNavItem(template2, item));
459
+ el.children = el.children.flatMap(
460
+ (c) => c === template2 ? rendered : c.kind === "el" && attr(c, "data-brease-item") ? [] : [c]
461
+ );
462
+ }
463
+ return;
464
+ }
465
+ if (marker && ref) {
466
+ const { value, marker: written } = resolve(ref);
467
+ marker.value = written;
468
+ if (Array.isArray(value)) {
469
+ const template2 = itemTemplate(el);
470
+ if (template2) {
471
+ const listPath = written;
472
+ const rendered = value.map((_, index) => {
473
+ const copy = clone(template2);
474
+ if (index > 0) renumber([copy], listPath, index);
475
+ return copy;
476
+ });
477
+ el.children = el.children.flatMap(
478
+ (c) => c === template2 ? rendered : c.kind === "el" && attr(c, "data-brease-item") ? [] : [c]
479
+ );
480
+ }
481
+ } else if (isImage(value)) {
482
+ if (el.tag === "img" || el.tag === "source") {
483
+ setAttr(el, el.tag === "source" ? "srcset" : "src", value.url);
484
+ if (el.tag === "img") {
485
+ removeAttr(el, "srcset");
486
+ if (value.alt !== void 0) setAttr(el, "alt", value.alt);
487
+ if (value.width) setAttr(el, "width", String(value.width));
488
+ if (value.height) setAttr(el, "height", String(value.height));
489
+ }
490
+ } else {
491
+ const style = (attr(el, "style")?.value ?? "").replace(/background-image\s*:[^;]*;?/i, "").trim();
492
+ setAttr(
493
+ el,
494
+ "style",
495
+ `${style ? `${style.replace(/;?$/, ";")} ` : ""}background-image: url('${value.url}')`
496
+ );
497
+ }
498
+ } else if (isLink(value)) {
499
+ if (el.tag === "a") {
500
+ setAttr(el, "href", value.href);
501
+ if (value.target === "_blank") setAttr(el, "target", "_blank");
502
+ }
503
+ if (value.label !== void 0 && !elements(el.children).length) setText(el, value.label, false);
504
+ } else if (typeof value === "string" || typeof value === "number") {
505
+ const text = String(value);
506
+ setText(el, text, attr(el, "data-brease-html") !== void 0 || looksLikeHtml(text));
507
+ return;
508
+ }
509
+ }
510
+ for (const child of elements(el.children)) fill(child);
511
+ };
512
+ const walk2 = (list) => {
513
+ for (let i = 0; i < list.length; i++) {
514
+ const n = list[i];
515
+ if (n.kind === "raw") {
516
+ if (n.text.includes("<!-- brease:head -->")) n.text = n.text.replace("<!-- brease:head -->", head);
517
+ continue;
518
+ }
519
+ if (n.tag === "html") setAttr(n, "lang", data.page.locale);
520
+ if (n.tag === "script" || n.tag === "style") continue;
521
+ if (attr(n, "data-brease")) fill(n);
522
+ else walk2(n.children);
523
+ }
524
+ };
525
+ walk2(nodes);
526
+ return serializeHtml(nodes);
527
+ }
528
+
529
+ // src/index.ts
530
+ var RETRY_AFTER_CAP_MS = 1e4;
531
+ var SITE_TTL_MS = 6e4;
532
+ var DRAFT_BRANCH_PREFIX = "brease/draft/";
533
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
534
+ var HOST_GIT_ENV = [
535
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
536
+ ["WORKERS_CI_COMMIT_SHA", "WORKERS_CI_BRANCH"],
537
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"]
538
+ ];
539
+ function hostGit() {
540
+ for (const [commit, branch] of HOST_GIT_ENV) {
541
+ const sha = env(commit);
542
+ if (sha) return { commit: sha, branch: env(branch) };
543
+ }
544
+ return {};
545
+ }
546
+ var cacheGeneration = 0;
547
+ function createBrease(opts = {}) {
548
+ const apiUrl = (opts.apiUrl ?? env("BREASE_API_URL") ?? "https://api.brease.io").replace(/\/+$/, "");
549
+ const host = hostGit();
550
+ const commit = opts.commit === false ? void 0 : opts.commit ?? host.commit;
551
+ const branch = opts.branch === false ? void 0 : opts.branch ?? host.branch;
552
+ const draftBranch = branch?.startsWith(DRAFT_BRANCH_PREFIX) ? branch : void 0;
553
+ const retries = opts.retries ?? 2;
554
+ const baseMs = opts.retryBaseMs ?? 300;
555
+ const timeoutMs = opts.timeoutMs ?? 5e3;
556
+ const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
557
+ function cached(path) {
558
+ let entry;
559
+ let last;
560
+ return () => {
561
+ if (!entry || Date.now() - entry.at > SITE_TTL_MS || entry.generation !== cacheGeneration || env("BREASE_PREVIEW")) {
562
+ const promise = request(path).then(
563
+ (value) => {
564
+ last = { value };
565
+ return value;
566
+ },
567
+ (err) => {
568
+ if (last) return last.value;
569
+ if (entry?.promise === promise) entry = void 0;
570
+ throw err;
571
+ }
572
+ );
573
+ entry = { promise, at: Date.now(), generation: cacheGeneration };
574
+ }
575
+ return entry.promise;
576
+ };
577
+ }
578
+ async function request(path, query = {}, nullOn404 = false) {
579
+ const token = opts.token ?? env("BREASE_TOKEN");
580
+ if (!token)
581
+ throw new BreaseError("unauthorized", "No Brease token: pass { token } or set BREASE_TOKEN", 401);
582
+ const params = new URLSearchParams();
583
+ for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, v);
584
+ const qs = params.toString();
585
+ const url = `${apiUrl}${path}${qs ? `?${qs}` : ""}`;
586
+ const headers = { authorization: `Bearer ${token}`, accept: "application/json" };
587
+ if (commit) headers["x-brease-commit"] = commit;
588
+ if (draftBranch) headers["x-brease-branch"] = draftBranch;
589
+ for (let attempt = 0; ; attempt++) {
590
+ let res;
591
+ try {
592
+ res = await doFetch(url, { method: "GET", headers, signal: AbortSignal.timeout(timeoutMs) });
593
+ } catch (err) {
594
+ const timedOut = err.name === "TimeoutError";
595
+ if (attempt < retries && !timedOut) {
596
+ await sleep(backoff(attempt));
597
+ continue;
598
+ }
599
+ throw new BreaseError("network", `Request to ${url} failed: ${err.message}`, 0);
600
+ }
601
+ if (res.ok) return await res.json();
602
+ if (res.status === 404 && nullOn404) return null;
603
+ if ((res.status === 429 || res.status >= 500) && attempt < retries) {
604
+ const after = Number(res.headers.get("retry-after"));
605
+ await sleep(after > 0 ? Math.min(after * 1e3, RETRY_AFTER_CAP_MS) : backoff(attempt));
606
+ continue;
607
+ }
608
+ throw await BreaseError.fromResponse(res);
609
+ }
610
+ }
611
+ function backoff(attempt) {
612
+ return baseMs * 2 ** attempt + Math.random() * baseMs;
613
+ }
614
+ const cachedSite = cached("/content-api/site");
615
+ const cachedRedirects = cached("/content-api/redirects");
616
+ const client = {
617
+ getSite: cachedSite,
618
+ getPage(slug, { locale }) {
619
+ return request("/content-api/page", { slug, locale }, true);
620
+ },
621
+ getPages(o = {}) {
622
+ return request("/content-api/pages", {
623
+ locale: o.locale,
624
+ parentId: o.parentId === null ? "" : o.parentId,
625
+ template: o.template,
626
+ withContent: o.withContent ? "1" : void 0
627
+ });
628
+ },
629
+ getNavigation(key, { locale }) {
630
+ return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
631
+ },
632
+ // Cached for a minute, like the site: a proxy applies redirects per request (matchRedirect).
633
+ getRedirects: cachedRedirects,
634
+ getRelease() {
635
+ return request("/content-api/release");
636
+ },
637
+ async resolve(pathname) {
638
+ const site = await client.getSite();
639
+ const result = resolvePath(site, pathname);
640
+ return site.locales.includes(result.locale) ? result : null;
641
+ },
642
+ async route(path) {
643
+ const joined = Array.isArray(path) ? path.join("/") : path ?? "";
644
+ const result = await client.resolve(`/${joined}`);
645
+ return result && !result.slug.split("/").some((part) => part.startsWith("_")) ? result : null;
646
+ },
647
+ async routes() {
648
+ const refs = await client.getPages();
649
+ return refs.filter((r) => !r.hidden && !r.slug.split("/").some((part) => part.startsWith("_"))).map((r) => ({ path: r.url.split("/").filter(Boolean) }));
650
+ },
651
+ async localeContext(path) {
652
+ const target = await client.route(path);
653
+ if (!target) return null;
654
+ const [site, page, home] = await Promise.all([
655
+ client.getSite(),
656
+ client.getPage(target.slug, { locale: target.locale }),
657
+ client.getPage("", { locale: target.locale })
658
+ ]);
659
+ const settings = {
660
+ locales: site.locales,
661
+ defaultLocale: site.defaultLocale,
662
+ localeStrategy: site.localeStrategy,
663
+ urlTemplate: site.urlTemplate
664
+ };
665
+ if (!page && !home) return null;
666
+ const alternates = {};
667
+ for (const [locale, url] of Object.entries(page?.alternates ?? {})) alternates[locale] = pathOf(url);
668
+ const homes = {};
669
+ for (const [locale, url] of Object.entries(home?.alternates ?? {})) homes[locale] = pathOf(url);
670
+ return { locale: target.locale, settings, alternates, homes };
671
+ },
672
+ async sitemap(baseUrl) {
673
+ const base = baseUrl.replace(/\/+$/, "");
674
+ const refs = (await client.getPages()).filter(
675
+ (r) => !r.hidden && r.index !== false && !r.slug.split("/").some((part) => part.startsWith("_"))
676
+ );
677
+ const byPage = /* @__PURE__ */ new Map();
678
+ for (const ref of refs) {
679
+ const alternates = byPage.get(ref.pageId) ?? {};
680
+ alternates[ref.locale] = `${base}${ref.url}`;
681
+ byPage.set(ref.pageId, alternates);
682
+ }
683
+ return refs.map((ref) => ({ url: `${base}${ref.url}`, alternates: byPage.get(ref.pageId) ?? {} }));
684
+ }
685
+ };
686
+ return client;
687
+ }
688
+ function pathOf(url) {
689
+ try {
690
+ return new URL(url, "http://localhost").pathname;
691
+ } catch {
692
+ return url;
693
+ }
694
+ }
695
+ var TEMPLATES_DIR = "templates";
696
+ var NOT_ASSETS = /* @__PURE__ */ new Set([
697
+ TEMPLATES_DIR,
698
+ "dist",
699
+ "node_modules",
700
+ "scripts",
701
+ ".brease",
702
+ "brease-seed",
703
+ ".git",
704
+ ".vercel",
705
+ ".github",
706
+ "package.json",
707
+ "package-lock.json",
708
+ "pnpm-lock.yaml",
709
+ "yarn.lock",
710
+ "bun.lock",
711
+ "BREASE.md",
712
+ "README.md",
713
+ "vercel.json",
714
+ "wrangler.toml",
715
+ "wrangler.jsonc"
716
+ ]);
717
+ var MIME = {
718
+ ".html": "text/html; charset=utf-8",
719
+ ".css": "text/css",
720
+ ".js": "text/javascript",
721
+ ".mjs": "text/javascript",
722
+ ".json": "application/json",
723
+ ".svg": "image/svg+xml",
724
+ ".png": "image/png",
725
+ ".jpg": "image/jpeg",
726
+ ".jpeg": "image/jpeg",
727
+ ".webp": "image/webp",
728
+ ".avif": "image/avif",
729
+ ".gif": "image/gif",
730
+ ".ico": "image/x-icon",
731
+ ".woff": "font/woff",
732
+ ".woff2": "font/woff2",
733
+ ".txt": "text/plain",
734
+ ".xml": "application/xml",
735
+ ".pdf": "application/pdf",
736
+ ".mp4": "video/mp4",
737
+ ".webm": "video/webm"
738
+ };
739
+ function templateFor(root, page) {
740
+ const dir = path.join(root, TEMPLATES_DIR);
741
+ const candidates = [
742
+ page.template ? `${page.template}.html` : null,
743
+ page.slug === "" ? "home.html" : null,
744
+ "page.html"
745
+ ].filter((c) => !!c);
746
+ for (const name of candidates) if (fs.existsSync(path.join(dir, name))) return path.join(dir, name);
747
+ return null;
748
+ }
749
+ var navigationKeys = (html) => [
750
+ ...new Set([...html.matchAll(/data-brease="nav:([^"]+)"/g)].map((m) => m[1]))
751
+ ];
752
+ async function renderPage(brease, root, slug, locale) {
753
+ const page = await brease.getPage(slug, { locale });
754
+ if (!page) return null;
755
+ const file = templateFor(root, {
756
+ slug,
757
+ template: page.content.template ?? page.template
758
+ });
759
+ if (!file) throw new Error(`No template for "${slug || "home"}": add ${TEMPLATES_DIR}/page.html`);
760
+ const template = fs.readFileSync(file, "utf8");
761
+ const [global, navigations] = await Promise.all([
762
+ template.includes("_global:") ? brease.getPage("_global", { locale }).catch(() => null) : null,
763
+ Promise.all(
764
+ navigationKeys(template).map(async (key) => [
765
+ key,
766
+ await brease.getNavigation(key, { locale }).catch(() => null)
767
+ ])
768
+ )
769
+ ]);
770
+ return renderTemplate(template, {
771
+ page,
772
+ global,
773
+ navigations: Object.fromEntries(navigations)
774
+ });
775
+ }
776
+ var outFile = (out, path$1) => path.join(out, ...path$1, "index.html");
777
+ function copyAssets(root, out) {
778
+ for (const name of fs.readdirSync(root)) {
779
+ if (NOT_ASSETS.has(name) || name.startsWith(".env")) continue;
780
+ if (name.endsWith(".html") && fs.statSync(path.join(root, name)).isFile()) continue;
781
+ fs.cpSync(path.join(root, name), path.join(out, name), { recursive: true });
782
+ }
783
+ }
784
+ async function build(brease, opts = {}) {
785
+ const root = opts.root ?? process.cwd();
786
+ const out = path.join(root, opts.out ?? "dist");
787
+ fs.rmSync(out, { recursive: true, force: true });
788
+ fs.mkdirSync(out, { recursive: true });
789
+ copyAssets(root, out);
790
+ const pages = [];
791
+ for (const { path: path$1 } of await brease.routes()) {
792
+ const route = await brease.route(path$1);
793
+ if (!route) continue;
794
+ const html = await renderPage(brease, root, route.slug, route.locale);
795
+ if (!html) continue;
796
+ const file = outFile(out, path$1);
797
+ fs.mkdirSync(path.dirname(file), { recursive: true });
798
+ fs.writeFileSync(file, html);
799
+ pages.push(`/${path$1.join("/")}`);
800
+ }
801
+ await writeHostOutput(await brease.getRedirects().catch(() => []), out, opts.host ?? detectHost());
802
+ return { pages, out };
803
+ }
804
+ var detectHost = () => process.env.VERCEL ? "vercel" : process.env.CF_PAGES || process.env.WORKERS_CI ? "cloudflare" : null;
805
+ async function writeHostOutput(redirects, out, host) {
806
+ const lines = redirects.map((r) => `${r.source} ${r.destination} ${r.status}`);
807
+ fs.writeFileSync(path.join(out, "_redirects"), lines.length ? `${lines.join("\n")}
808
+ ` : "");
809
+ if (host !== "vercel") return;
810
+ const vercel = path.join(path.dirname(out), ".vercel", "output");
811
+ fs.rmSync(vercel, { recursive: true, force: true });
812
+ fs.mkdirSync(vercel, { recursive: true });
813
+ fs.cpSync(out, path.join(vercel, "static"), { recursive: true });
814
+ const routes = redirects.map((r) => ({
815
+ src: `^${vercelSource(r.source)}/?$`,
816
+ headers: { Location: r.destination.replace(/:(\w+)\*?/g, "$$$1") },
817
+ status: r.status
818
+ }));
819
+ fs.writeFileSync(
820
+ path.join(vercel, "config.json"),
821
+ JSON.stringify({ version: 3, routes: [...routes, { handle: "filesystem" }] }, null, 2)
822
+ );
823
+ }
824
+ var vercelSource = (source) => source.split(/(:\w+\*?)/).map(
825
+ (part) => part.startsWith(":") ? part.endsWith("*") ? `(?<${part.slice(1, -1)}>.*)` : `(?<${part.slice(1)}>[^/]+)` : part.replace(/[.+?^${}()|[\]\\*]/g, "\\$&")
826
+ ).join("");
827
+ function serve(brease, opts = {}) {
828
+ const root = opts.root ?? process.cwd();
829
+ const server = http.createServer(async (req, res) => {
830
+ try {
831
+ const url = new URL(req.url ?? "/", "http://localhost");
832
+ const pathname = decodeURIComponent(url.pathname);
833
+ const asset = path.join(root, pathname);
834
+ const inRoot = !path.relative(root, asset).startsWith("..");
835
+ const top = pathname.split("/")[1] ?? "";
836
+ if (inRoot && !NOT_ASSETS.has(top) && fs.existsSync(asset) && fs.statSync(asset).isFile() && !asset.endsWith(".html")) {
837
+ res.writeHead(200, {
838
+ "content-type": MIME[path.extname(asset).toLowerCase()] ?? "application/octet-stream"
839
+ });
840
+ res.end(fs.readFileSync(asset));
841
+ return;
842
+ }
843
+ const hit = matchRedirect(await brease.getRedirects().catch(() => []), pathname);
844
+ if (hit) {
845
+ res.writeHead(hit.status, { location: hit.destination });
846
+ res.end();
847
+ return;
848
+ }
849
+ const route = await brease.route(pathname.split("/").filter(Boolean));
850
+ const html = route && await renderPage(brease, root, route.slug, route.locale);
851
+ res.writeHead(html ? 200 : 404, { "content-type": MIME[".html"] });
852
+ res.end(html ?? "Not found");
853
+ } catch (err) {
854
+ res.writeHead(500, { "content-type": "text/plain" });
855
+ res.end(`Brease couldn't render this page: ${err.message}`);
856
+ }
857
+ });
858
+ server.listen(opts.port ?? Number(process.env.PORT ?? 3e3));
859
+ return server;
860
+ }
861
+ async function exportContent(brease, navigationKeys2 = []) {
862
+ const site = await brease.getSite();
863
+ const pages = {};
864
+ const navigations = {};
865
+ const global = {};
866
+ for (const locale of site.locales) {
867
+ pages[locale] = {};
868
+ for (const ref of await brease.getPages({ locale })) {
869
+ const page = await brease.getPage(ref.slug, { locale });
870
+ if (page) pages[locale][ref.slug] = page;
871
+ }
872
+ navigations[locale] = Object.fromEntries(
873
+ await Promise.all(
874
+ navigationKeys2.map(async (k) => [k, await brease.getNavigation(k, { locale }).catch(() => null)])
875
+ )
876
+ );
877
+ global[locale] = await brease.getPage("_global", { locale }).catch(() => null);
878
+ }
879
+ return { site, pages, navigations, global, redirects: await brease.getRedirects().catch(() => []) };
880
+ }
881
+ function writeJson(file, value) {
882
+ fs.mkdirSync(path.dirname(file), { recursive: true });
883
+ fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}
884
+ `);
79
885
  }
80
886
 
81
887
  // src/cli.ts
@@ -105,22 +911,69 @@ function pagesIn(root) {
105
911
  }
106
912
  return pages;
107
913
  }
108
- var [command] = process.argv.slice(2);
109
- if (command !== "check") {
110
- console.log("Usage: brease-client check");
914
+ var USAGE = `Usage:
915
+ brease-client check the sections convention
916
+ brease-client build [--out dist] render every page from templates/ into dist/ (sites without a framework)
917
+ brease-client serve the same pages, rendered per request on $PORT (the editor's preview)
918
+ brease-client output <dir> write Brease's redirects for the host next to built files in <dir>
919
+ brease-client content <file.json> [--nav main,footer] [--watch]
920
+ the content a browser-only app imports at build time`;
921
+ var [command, ...args] = process.argv.slice(2);
922
+ var flag = (name) => {
923
+ const at = args.indexOf(`--${name}`);
924
+ return at === -1 ? void 0 : args[at + 1] ?? "";
925
+ };
926
+ function check() {
927
+ const cwd = process.cwd();
928
+ const folder = SECTION_FOLDERS.find((f) => fs.existsSync(path.join(cwd, f)));
929
+ if (!folder) {
930
+ console.log("No sections folder (src/brease/sections or brease/sections): nothing to check.");
931
+ process.exit(0);
932
+ }
933
+ const files = Object.fromEntries(
934
+ walk(path.join(cwd, folder)).map((p) => [path.relative(cwd, p).split("\\").join("/"), fs.readFileSync(p, "utf8")])
935
+ );
936
+ const content = ["brease-seed", ".brease"].map((d) => path.join(cwd, d)).find((d) => fs.existsSync(d));
937
+ const warnings = checkSections(files, content ? pagesIn(content) : {});
938
+ for (const w of warnings) console.log(`warning: ${w}`);
939
+ console.log(warnings.length ? `${warnings.length} warning(s)` : "Sections look right.");
940
+ process.exit(warnings.length ? 1 : 0);
941
+ }
942
+ async function main() {
943
+ if (command === "check") return check();
944
+ if (command === "build") {
945
+ const { pages, out } = await build(createBrease(), { out: flag("out") });
946
+ console.log(`Rendered ${pages.length} page(s) into ${path.relative(process.cwd(), out) || "."}`);
947
+ return;
948
+ }
949
+ if (command === "serve") {
950
+ serve(createBrease());
951
+ console.log(`Serving on port ${process.env.PORT ?? 3e3}`);
952
+ return;
953
+ }
954
+ if (command === "output" && args[0]) {
955
+ await writeHostOutput(await createBrease().getRedirects(), path.join(process.cwd(), args[0]), detectHost());
956
+ return;
957
+ }
958
+ if (command === "content" && args[0]) {
959
+ const file = path.join(process.cwd(), args[0]);
960
+ const keys = (flag("nav") ?? "").split(",").filter(Boolean);
961
+ const brease = createBrease();
962
+ let last = "";
963
+ const write = async () => {
964
+ const json = JSON.stringify(await exportContent(brease, keys));
965
+ if (json === last) return;
966
+ last = json;
967
+ writeJson(file, JSON.parse(json));
968
+ };
969
+ await write();
970
+ if (args.includes("--watch")) setInterval(() => void write().catch((e) => console.warn(e.message)), 2e3);
971
+ return;
972
+ }
973
+ console.log(USAGE);
111
974
  process.exit(command ? 1 : 0);
112
975
  }
113
- var cwd = process.cwd();
114
- var folder = SECTION_FOLDERS.find((f) => fs.existsSync(path.join(cwd, f)));
115
- if (!folder) {
116
- console.log("No sections folder (src/brease/sections or brease/sections): nothing to check.");
117
- process.exit(0);
118
- }
119
- var files = Object.fromEntries(
120
- walk(path.join(cwd, folder)).map((p) => [path.relative(cwd, p).split("\\").join("/"), fs.readFileSync(p, "utf8")])
121
- );
122
- var content = ["brease-seed", ".brease"].map((d) => path.join(cwd, d)).find((d) => fs.existsSync(d));
123
- var warnings = checkSections(files, content ? pagesIn(content) : {});
124
- for (const w of warnings) console.log(`warning: ${w}`);
125
- console.log(warnings.length ? `${warnings.length} warning(s)` : "Sections look right.");
126
- process.exit(warnings.length ? 1 : 0);
976
+ main().catch((err) => {
977
+ console.error(err instanceof Error ? err.message : err);
978
+ process.exit(1);
979
+ });