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/index.cjs CHANGED
@@ -53,15 +53,35 @@ function buildPath(settings, slug, locale) {
53
53
  const parts = [prefixed ? locale : "", clean].filter(Boolean);
54
54
  return `/${parts.join("/")}`;
55
55
  }
56
+ function customPattern(template) {
57
+ const parts = normalizeSlug(template).split(/(\{locale\}|\{slug\})/);
58
+ const slashBefore = (i) => parts[i] === "{slug}" && !!parts[i - 1]?.endsWith("/");
59
+ const slashAfter = (i) => parts[i] === "{slug}" && !slashBefore(i) && !!parts[i + 1]?.startsWith("/");
60
+ const pattern = parts.map((part, i) => {
61
+ if (part === "{locale}") return "(?<locale>[^/]+)";
62
+ if (part === "{slug}") {
63
+ if (slashBefore(i)) return "(?:/(?<slug>.*))?";
64
+ if (slashAfter(i)) return "(?:(?<slug>.*)/)?";
65
+ return "(?<slug>.*)";
66
+ }
67
+ let text = part;
68
+ if (slashBefore(i + 1)) text = text.slice(0, -1);
69
+ if (slashAfter(i - 1)) text = text.slice(1);
70
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
71
+ }).join("");
72
+ return new RegExp(`^${pattern}$`);
73
+ }
74
+ function safeDecode(value) {
75
+ try {
76
+ return decodeURIComponent(value);
77
+ } catch {
78
+ return value;
79
+ }
80
+ }
56
81
  function resolvePath(settings, pathname) {
57
- const clean = normalizeSlug(decodeURIComponent(pathname.split(/[?#]/)[0] ?? ""));
82
+ const clean = normalizeSlug(safeDecode(pathname.split(/[?#]/)[0] ?? ""));
58
83
  if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
59
- const pattern = normalizeSlug(settings.urlTemplate).split(/(\{locale\}|\{slug\})/).map((part) => {
60
- if (part === "{locale}") return "(?<locale>[^/]+)";
61
- if (part === "{slug}") return "(?<slug>.*)";
62
- return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
63
- }).join("");
64
- const match = new RegExp(`^${pattern}$`).exec(clean);
84
+ const match = customPattern(settings.urlTemplate).exec(clean);
65
85
  if (match?.groups) {
66
86
  return {
67
87
  slug: normalizeSlug(match.groups.slug ?? ""),
@@ -81,7 +101,7 @@ function canonicalPath(settings, pathname) {
81
101
  const { slug, locale } = resolvePath(settings, path);
82
102
  const canonical = buildPath(settings, slug, locale);
83
103
  const trim = (p) => p.length > 1 ? p.replace(/\/+$/, "") : p;
84
- return trim(decodeURIComponent(path)) === trim(canonical) ? null : canonical;
104
+ return trim(safeDecode(path)) === trim(canonical) ? null : canonical;
85
105
  }
86
106
 
87
107
  // src/analytics.ts
@@ -187,7 +207,7 @@ function matchSource(source, path) {
187
207
  if (value === void 0) return null;
188
208
  const param = /^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(seg);
189
209
  if (param) params[param[1]] = value;
190
- else if (decodeURIComponent(value) !== decodeURIComponent(seg)) return null;
210
+ else if (safeDecode(value) !== safeDecode(seg)) return null;
191
211
  }
192
212
  return want.length === have.length ? params : null;
193
213
  }
@@ -199,6 +219,7 @@ function sectionAttrs(section) {
199
219
  }
200
220
  var SECTION_FOLDERS = ["src/brease/sections", "brease/sections"];
201
221
  var TYPE_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
222
+ var MAP_FILE = /^(index|sections)\.(astro|vue|svelte|[cm]?[jt]sx?)$/i;
202
223
  function checkSections(files, pages = {}) {
203
224
  const warnings = [];
204
225
  const folder = SECTION_FOLDERS.find((f) => Object.keys(files).some((p) => p.startsWith(`${f}/`)));
@@ -209,9 +230,11 @@ function checkSections(files, pages = {}) {
209
230
  inFolder.map(([p]) => p.split("/")).filter((s) => s.length > 1).map((s) => s[0])
210
231
  )
211
232
  ];
212
- const map = inFolder.find(([p]) => /^index\.[cm]?[jt]sx?$/.test(p));
233
+ const map = inFolder.find(([p]) => MAP_FILE.test(p));
213
234
  if (!map)
214
- warnings.push(`${folder} has no map file (index.tsx, index.ts or index.js) rendering the section types`);
235
+ warnings.push(
236
+ `${folder} has no map file (index.tsx, index.ts, Sections.astro or the like) rendering the section types`
237
+ );
215
238
  const marked = inFolder.some(
216
239
  ([, text]) => text.includes("data-brease-section") || text.includes("sectionAttrs(")
217
240
  );
@@ -327,18 +350,373 @@ function jsonLdHtml(seo) {
327
350
  return jsonLd(seo).map((d) => `<script type="application/ld+json">${d.json}</script>`).join("\n");
328
351
  }
329
352
 
353
+ // src/html.ts
354
+ function headTagList(seo, opts = {}) {
355
+ const tags = [{ tag: "title", attrs: {}, content: seo.title }];
356
+ const meta = (key, name, value) => {
357
+ if (value) tags.push({ tag: "meta", attrs: { [key]: name, content: value } });
358
+ };
359
+ meta("name", "description", seo.description);
360
+ if (seo.canonical) tags.push({ tag: "link", attrs: { rel: "canonical", href: seo.canonical } });
361
+ meta(
362
+ "name",
363
+ "robots",
364
+ `${seo.robots.index ? "index" : "noindex"}, ${seo.robots.follow ? "follow" : "nofollow"}`
365
+ );
366
+ for (const [lang, href] of Object.entries(seo.alternates)) {
367
+ tags.push({ tag: "link", attrs: { rel: "alternate", hreflang: lang, href } });
368
+ }
369
+ if (opts.xDefault) {
370
+ tags.push({ tag: "link", attrs: { rel: "alternate", hreflang: "x-default", href: opts.xDefault } });
371
+ }
372
+ const og = seo.openGraph;
373
+ meta("property", "og:type", og.type);
374
+ meta("property", "og:title", og.title);
375
+ meta("property", "og:description", og.description);
376
+ meta("property", "og:image", og.image);
377
+ meta("property", "og:url", og.url);
378
+ meta("property", "og:site_name", og.siteName);
379
+ const tw = seo.twitter;
380
+ meta("name", "twitter:card", tw.card);
381
+ meta("name", "twitter:site", tw.site);
382
+ meta("name", "twitter:creator", tw.creator);
383
+ meta("name", "twitter:title", tw.title);
384
+ meta("name", "twitter:description", tw.description);
385
+ meta("name", "twitter:image", tw.image);
386
+ if (seo.favicon) tags.push({ tag: "link", attrs: { rel: "icon", href: seo.favicon } });
387
+ for (const item of jsonLd(seo)) {
388
+ tags.push({ tag: "script", attrs: { type: "application/ld+json" }, content: item.json });
389
+ }
390
+ return tags;
391
+ }
392
+ var escapeHtml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
393
+ function renderTag(t) {
394
+ const attrs = Object.entries(t.attrs).map(([k, v]) => ` ${k}="${escapeHtml(v)}"`).join("");
395
+ if (t.tag === "meta" || t.tag === "link") return `<${t.tag}${attrs}>`;
396
+ const content = t.tag === "script" ? t.content ?? "" : escapeHtml(t.content ?? "");
397
+ return `<${t.tag}${attrs}>${content}</${t.tag}>`;
398
+ }
399
+ function headTags(seo, opts = {}) {
400
+ const parts = headTagList(seo, opts).map(renderTag);
401
+ if (opts.includeCustom !== false) {
402
+ if (seo.customHead) parts.push(seo.customHead);
403
+ if (seo.customCode) parts.push(seo.customCode);
404
+ }
405
+ return parts.join("\n");
406
+ }
407
+
408
+ // src/template.ts
409
+ var VOID = /* @__PURE__ */ new Set([
410
+ "area",
411
+ "base",
412
+ "br",
413
+ "col",
414
+ "embed",
415
+ "hr",
416
+ "img",
417
+ "input",
418
+ "link",
419
+ "meta",
420
+ "source",
421
+ "track",
422
+ "wbr"
423
+ ]);
424
+ var RAW_TEXT = /* @__PURE__ */ new Set(["script", "style", "textarea", "title"]);
425
+ var ATTR = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
426
+ function parseAttrs(source) {
427
+ const attrs = [];
428
+ for (const m of source.matchAll(ATTR)) {
429
+ attrs.push({ name: m[1], value: m[2] ?? m[3] ?? m[4] ?? null });
430
+ }
431
+ return attrs;
432
+ }
433
+ function parseHtml(html) {
434
+ const root = { kind: "el", tag: "#root", attrs: [], children: [], selfClosing: false, void: false };
435
+ const stack = [root];
436
+ const top = () => stack[stack.length - 1];
437
+ let i = 0;
438
+ const text = (t) => {
439
+ if (t) top().children.push({ kind: "raw", text: t });
440
+ };
441
+ while (i < html.length) {
442
+ const lt = html.indexOf("<", i);
443
+ if (lt === -1) {
444
+ text(html.slice(i));
445
+ break;
446
+ }
447
+ text(html.slice(i, lt));
448
+ if (html.startsWith("<!--", lt)) {
449
+ const end = html.indexOf("-->", lt + 4);
450
+ const stop = end === -1 ? html.length : end + 3;
451
+ text(html.slice(lt, stop));
452
+ i = stop;
453
+ continue;
454
+ }
455
+ if (html[lt + 1] === "!" || html[lt + 1] === "?") {
456
+ const end = html.indexOf(">", lt);
457
+ const stop = end === -1 ? html.length : end + 1;
458
+ text(html.slice(lt, stop));
459
+ i = stop;
460
+ continue;
461
+ }
462
+ const close = /^<\/([a-zA-Z][\w:-]*)\s*>/.exec(html.slice(lt));
463
+ if (close) {
464
+ const name = close[1].toLowerCase();
465
+ const at = stack.map((e) => e.tag).lastIndexOf(name);
466
+ if (at > 0) stack.length = at;
467
+ i = lt + close[0].length;
468
+ continue;
469
+ }
470
+ const open = /^<([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>/.exec(
471
+ html.slice(lt)
472
+ );
473
+ if (!open) {
474
+ text("<");
475
+ i = lt + 1;
476
+ continue;
477
+ }
478
+ const tag = open[1].toLowerCase();
479
+ const el = {
480
+ kind: "el",
481
+ tag,
482
+ attrs: parseAttrs(open[2] ?? ""),
483
+ children: [],
484
+ selfClosing: open[3] === "/",
485
+ void: VOID.has(tag)
486
+ };
487
+ top().children.push(el);
488
+ i = lt + open[0].length;
489
+ if (el.void || el.selfClosing) continue;
490
+ if (RAW_TEXT.has(tag)) {
491
+ const end = html.toLowerCase().indexOf(`</${tag}`, i);
492
+ const stop = end === -1 ? html.length : end;
493
+ if (stop > i) el.children.push({ kind: "raw", text: html.slice(i, stop) });
494
+ const gt = end === -1 ? html.length : html.indexOf(">", end);
495
+ i = gt === -1 ? html.length : gt + 1;
496
+ continue;
497
+ }
498
+ stack.push(el);
499
+ }
500
+ return root.children;
501
+ }
502
+ var escapeText = (v) => v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
503
+ var escapeAttr = (v) => escapeText(v).replace(/"/g, "&quot;");
504
+ function serializeHtml(nodes) {
505
+ return nodes.map((n) => {
506
+ if (n.kind === "raw") return n.text;
507
+ const attrs = n.attrs.map(
508
+ (a) => a.value === null ? ` ${a.name}` : ` ${a.name}="${escapeAttr(a.value)}"`
509
+ );
510
+ const open = `<${n.tag}${attrs.join("")}${n.selfClosing ? " /" : ""}>`;
511
+ if (n.void || n.selfClosing) return open;
512
+ return `${open}${serializeHtml(n.children)}</${n.tag}>`;
513
+ }).join("");
514
+ }
515
+ var attr = (el, name) => el.attrs.find((a) => a.name === name);
516
+ function setAttr(el, name, value) {
517
+ const found = attr(el, name);
518
+ if (found) found.value = value;
519
+ else el.attrs.push({ name, value });
520
+ }
521
+ var removeAttr = (el, name) => {
522
+ el.attrs = el.attrs.filter((a) => a.name !== name);
523
+ };
524
+ var elements = (nodes) => nodes.filter((n) => n.kind === "el");
525
+ function valueAt(source, path) {
526
+ let current = source;
527
+ for (const key of path.split(".")) {
528
+ if (current === null || typeof current !== "object") return void 0;
529
+ current = current[key];
530
+ }
531
+ return current;
532
+ }
533
+ var isImage = (v) => !!v && typeof v === "object" && typeof v.url === "string" && !("href" in v);
534
+ var isLink = (v) => !!v && typeof v === "object" && typeof v.href === "string";
535
+ var looksLikeHtml = (v) => /<[a-z][\s\S]*>/i.test(v);
536
+ function setText(el, value, html) {
537
+ el.children = [{ kind: "raw", text: html ? value : escapeText(value) }];
538
+ }
539
+ function renumber(nodes, listPath, index) {
540
+ const from = `${listPath}.0.`;
541
+ const to = `${listPath}.${index}.`;
542
+ for (const el of elements(nodes)) {
543
+ const marker = attr(el, "data-brease");
544
+ if (marker?.value?.includes(from)) marker.value = marker.value.replace(from, to);
545
+ renumber(el.children, listPath, index);
546
+ }
547
+ }
548
+ var clone = (value) => JSON.parse(JSON.stringify(value));
549
+ function itemTemplate(el) {
550
+ const children = elements(el.children);
551
+ const template = children.find((c) => attr(c, "data-brease-item"));
552
+ return template ?? null;
553
+ }
554
+ function renderNavItem(template, item) {
555
+ const copy = clone(template);
556
+ const labels = [];
557
+ const links = [];
558
+ const walk = (el) => {
559
+ if (attr(el, "data-brease-label")) labels.push(el);
560
+ if (el.tag === "a") links.push(el);
561
+ for (const c of elements(el.children)) walk(c);
562
+ };
563
+ walk(copy);
564
+ const link = copy.tag === "a" ? copy : links[0];
565
+ if (link) {
566
+ setAttr(link, "href", item.url);
567
+ if (item.target === "_blank") setAttr(link, "target", "_blank");
568
+ if (!labels.length && !elements(link.children).length) setText(link, item.label, false);
569
+ }
570
+ for (const label of labels) setText(label, item.label, false);
571
+ return copy;
572
+ }
573
+ function renderTemplate(template, data) {
574
+ const nodes = parseHtml(template);
575
+ const head = headTags(data.page.resolvedSeo);
576
+ const resolve = (ref) => {
577
+ const at = ref.indexOf(":");
578
+ if (at === -1) return { value: valueAt(data.page.content, ref), marker: ref };
579
+ const owner = ref.slice(0, at);
580
+ const path = ref.slice(at + 1);
581
+ if (owner === "_global") {
582
+ const global = data.global;
583
+ return {
584
+ value: global ? valueAt(global.content, path) : void 0,
585
+ marker: global ? `${global.pageId}:${path}` : ref
586
+ };
587
+ }
588
+ return { value: void 0, marker: ref };
589
+ };
590
+ const fill = (el) => {
591
+ const marker = attr(el, "data-brease");
592
+ const ref = marker?.value;
593
+ if (marker && ref?.startsWith("nav:")) {
594
+ const items = data.navigations?.[ref.slice(4)]?.items;
595
+ const template2 = itemTemplate(el);
596
+ if (items && template2) {
597
+ const rendered = items.map((item) => renderNavItem(template2, item));
598
+ el.children = el.children.flatMap(
599
+ (c) => c === template2 ? rendered : c.kind === "el" && attr(c, "data-brease-item") ? [] : [c]
600
+ );
601
+ }
602
+ return;
603
+ }
604
+ if (marker && ref) {
605
+ const { value, marker: written } = resolve(ref);
606
+ marker.value = written;
607
+ if (Array.isArray(value)) {
608
+ const template2 = itemTemplate(el);
609
+ if (template2) {
610
+ const listPath = written;
611
+ const rendered = value.map((_, index) => {
612
+ const copy = clone(template2);
613
+ if (index > 0) renumber([copy], listPath, index);
614
+ return copy;
615
+ });
616
+ el.children = el.children.flatMap(
617
+ (c) => c === template2 ? rendered : c.kind === "el" && attr(c, "data-brease-item") ? [] : [c]
618
+ );
619
+ }
620
+ } else if (isImage(value)) {
621
+ if (el.tag === "img" || el.tag === "source") {
622
+ setAttr(el, el.tag === "source" ? "srcset" : "src", value.url);
623
+ if (el.tag === "img") {
624
+ removeAttr(el, "srcset");
625
+ if (value.alt !== void 0) setAttr(el, "alt", value.alt);
626
+ if (value.width) setAttr(el, "width", String(value.width));
627
+ if (value.height) setAttr(el, "height", String(value.height));
628
+ }
629
+ } else {
630
+ const style = (attr(el, "style")?.value ?? "").replace(/background-image\s*:[^;]*;?/i, "").trim();
631
+ setAttr(
632
+ el,
633
+ "style",
634
+ `${style ? `${style.replace(/;?$/, ";")} ` : ""}background-image: url('${value.url}')`
635
+ );
636
+ }
637
+ } else if (isLink(value)) {
638
+ if (el.tag === "a") {
639
+ setAttr(el, "href", value.href);
640
+ if (value.target === "_blank") setAttr(el, "target", "_blank");
641
+ }
642
+ if (value.label !== void 0 && !elements(el.children).length) setText(el, value.label, false);
643
+ } else if (typeof value === "string" || typeof value === "number") {
644
+ const text = String(value);
645
+ setText(el, text, attr(el, "data-brease-html") !== void 0 || looksLikeHtml(text));
646
+ return;
647
+ }
648
+ }
649
+ for (const child of elements(el.children)) fill(child);
650
+ };
651
+ const walk = (list) => {
652
+ for (let i = 0; i < list.length; i++) {
653
+ const n = list[i];
654
+ if (n.kind === "raw") {
655
+ if (n.text.includes("<!-- brease:head -->")) n.text = n.text.replace("<!-- brease:head -->", head);
656
+ continue;
657
+ }
658
+ if (n.tag === "html") setAttr(n, "lang", data.page.locale);
659
+ if (n.tag === "script" || n.tag === "style") continue;
660
+ if (attr(n, "data-brease")) fill(n);
661
+ else walk(n.children);
662
+ }
663
+ };
664
+ walk(nodes);
665
+ return serializeHtml(nodes);
666
+ }
667
+
330
668
  // src/index.ts
331
669
  var RETRY_AFTER_CAP_MS = 1e4;
332
670
  var SITE_TTL_MS = 6e4;
671
+ var DRAFT_BRANCH_PREFIX = "brease/draft/";
333
672
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
673
+ var HOST_GIT_ENV = [
674
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
675
+ ["WORKERS_CI_COMMIT_SHA", "WORKERS_CI_BRANCH"],
676
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"]
677
+ ];
678
+ function hostGit() {
679
+ for (const [commit, branch] of HOST_GIT_ENV) {
680
+ const sha = env(commit);
681
+ if (sha) return { commit: sha, branch: env(branch) };
682
+ }
683
+ return {};
684
+ }
685
+ var cacheGeneration = 0;
686
+ function clearBreaseCache() {
687
+ cacheGeneration++;
688
+ }
334
689
  function createBrease(opts = {}) {
335
690
  const apiUrl = (opts.apiUrl ?? env("BREASE_API_URL") ?? "https://api.brease.io").replace(/\/+$/, "");
336
- const commit = opts.commit === false ? void 0 : opts.commit ?? env("VERCEL_GIT_COMMIT_SHA");
691
+ const host = hostGit();
692
+ const commit = opts.commit === false ? void 0 : opts.commit ?? host.commit;
693
+ const branch = opts.branch === false ? void 0 : opts.branch ?? host.branch;
694
+ const draftBranch = branch?.startsWith(DRAFT_BRANCH_PREFIX) ? branch : void 0;
337
695
  const retries = opts.retries ?? 2;
338
696
  const baseMs = opts.retryBaseMs ?? 300;
697
+ const timeoutMs = opts.timeoutMs ?? 5e3;
339
698
  const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
340
- let site;
341
- let redirects;
699
+ function cached(path) {
700
+ let entry;
701
+ let last;
702
+ return () => {
703
+ if (!entry || Date.now() - entry.at > SITE_TTL_MS || entry.generation !== cacheGeneration || env("BREASE_PREVIEW")) {
704
+ const promise = request(path).then(
705
+ (value) => {
706
+ last = { value };
707
+ return value;
708
+ },
709
+ (err) => {
710
+ if (last) return last.value;
711
+ if (entry?.promise === promise) entry = void 0;
712
+ throw err;
713
+ }
714
+ );
715
+ entry = { promise, at: Date.now(), generation: cacheGeneration };
716
+ }
717
+ return entry.promise;
718
+ };
719
+ }
342
720
  async function request(path, query = {}, nullOn404 = false) {
343
721
  const token = opts.token ?? env("BREASE_TOKEN");
344
722
  if (!token)
@@ -349,12 +727,14 @@ function createBrease(opts = {}) {
349
727
  const url = `${apiUrl}${path}${qs ? `?${qs}` : ""}`;
350
728
  const headers = { authorization: `Bearer ${token}`, accept: "application/json" };
351
729
  if (commit) headers["x-brease-commit"] = commit;
730
+ if (draftBranch) headers["x-brease-branch"] = draftBranch;
352
731
  for (let attempt = 0; ; attempt++) {
353
732
  let res;
354
733
  try {
355
- res = await doFetch(url, { method: "GET", headers });
734
+ res = await doFetch(url, { method: "GET", headers, signal: AbortSignal.timeout(timeoutMs) });
356
735
  } catch (err) {
357
- if (attempt < retries) {
736
+ const timedOut = err.name === "TimeoutError";
737
+ if (attempt < retries && !timedOut) {
358
738
  await sleep(backoff(attempt));
359
739
  continue;
360
740
  }
@@ -373,24 +753,17 @@ function createBrease(opts = {}) {
373
753
  function backoff(attempt) {
374
754
  return baseMs * 2 ** attempt + Math.random() * baseMs;
375
755
  }
756
+ const cachedSite = cached("/content-api/site");
757
+ const cachedRedirects = cached("/content-api/redirects");
376
758
  const client = {
377
- getSite() {
378
- if (!site || Date.now() - site.at > SITE_TTL_MS) {
379
- const promise = request("/content-api/site").catch((err) => {
380
- if (site?.promise === promise) site = void 0;
381
- throw err;
382
- });
383
- site = { promise, at: Date.now() };
384
- }
385
- return site.promise;
386
- },
759
+ getSite: cachedSite,
387
760
  getPage(slug, { locale }) {
388
761
  return request("/content-api/page", { slug, locale }, true);
389
762
  },
390
763
  getPages(o = {}) {
391
764
  return request("/content-api/pages", {
392
765
  locale: o.locale,
393
- parentId: o.parentId,
766
+ parentId: o.parentId === null ? "" : o.parentId,
394
767
  template: o.template,
395
768
  withContent: o.withContent ? "1" : void 0
396
769
  });
@@ -399,26 +772,17 @@ function createBrease(opts = {}) {
399
772
  return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
400
773
  },
401
774
  // Cached for a minute, like the site: a proxy applies redirects per request (matchRedirect).
402
- getRedirects() {
403
- if (!redirects || Date.now() - redirects.at > SITE_TTL_MS) {
404
- const promise = request("/content-api/redirects").catch((err) => {
405
- if (redirects?.promise === promise) redirects = void 0;
406
- throw err;
407
- });
408
- redirects = { promise, at: Date.now() };
409
- }
410
- return redirects.promise;
411
- },
775
+ getRedirects: cachedRedirects,
412
776
  getRelease() {
413
777
  return request("/content-api/release");
414
778
  },
415
779
  async resolve(pathname) {
416
- const site2 = await client.getSite();
417
- const result = resolvePath(site2, pathname);
418
- return site2.locales.includes(result.locale) ? result : null;
780
+ const site = await client.getSite();
781
+ const result = resolvePath(site, pathname);
782
+ return site.locales.includes(result.locale) ? result : null;
419
783
  },
420
784
  async route(path) {
421
- const joined = Array.isArray(path) ? path.map((p) => decodeURIComponent(p)).join("/") : path ?? "";
785
+ const joined = Array.isArray(path) ? path.join("/") : path ?? "";
422
786
  const result = await client.resolve(`/${joined}`);
423
787
  return result && !result.slug.split("/").some((part) => part.startsWith("_")) ? result : null;
424
788
  },
@@ -429,16 +793,16 @@ function createBrease(opts = {}) {
429
793
  async localeContext(path) {
430
794
  const target = await client.route(path);
431
795
  if (!target) return null;
432
- const [site2, page, home] = await Promise.all([
796
+ const [site, page, home] = await Promise.all([
433
797
  client.getSite(),
434
798
  client.getPage(target.slug, { locale: target.locale }),
435
799
  client.getPage("", { locale: target.locale })
436
800
  ]);
437
801
  const settings = {
438
- locales: site2.locales,
439
- defaultLocale: site2.defaultLocale,
440
- localeStrategy: site2.localeStrategy,
441
- urlTemplate: site2.urlTemplate
802
+ locales: site.locales,
803
+ defaultLocale: site.defaultLocale,
804
+ localeStrategy: site.localeStrategy,
805
+ urlTemplate: site.urlTemplate
442
806
  };
443
807
  if (!page && !home) return null;
444
808
  const alternates = {};
@@ -475,6 +839,7 @@ exports.BreaseError = BreaseError;
475
839
  exports.buildPath = buildPath;
476
840
  exports.canonicalPath = canonicalPath;
477
841
  exports.checkSections = checkSections;
842
+ exports.clearBreaseCache = clearBreaseCache;
478
843
  exports.createBrease = createBrease;
479
844
  exports.customTags = customTags;
480
845
  exports.fieldPath = fieldPath;
@@ -490,6 +855,7 @@ exports.matchRedirect = matchRedirect;
490
855
  exports.nativeName = nativeName;
491
856
  exports.navPath = navPath;
492
857
  exports.normalizeSlug = normalizeSlug;
858
+ exports.renderTemplate = renderTemplate;
493
859
  exports.resolvePath = resolvePath;
494
860
  exports.sectionAttrs = sectionAttrs;
495
861
  exports.sectionsAttrs = sectionsAttrs;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { S as Site, R as ResolvedSeo, U as UrlSettings, a as Redirect, P as Page, b as PageRef, N as Navigation, c as Release, d as SitemapEntry } from './types-D5mwpqAP.cjs';
1
+ import { S as Site, R as ResolvedSeo, U as UrlSettings, a as Redirect, P as Page, N as Navigation, b as PageRef, c as Release, d as SitemapEntry } from './types-D5mwpqAP.cjs';
2
2
  export { B as BreaseImage, e as BreaseLink, L as LocaleStrategy, f as NavigationItem, O as OpenGraph, g as PageSeo, h as Robots, i as SiteSeo, T as Twitter } from './types-D5mwpqAP.cjs';
3
3
 
4
4
  type Ga4Tag = {
@@ -96,6 +96,13 @@ type JsonLd = {
96
96
  declare function jsonLd(seo: Pick<ResolvedSeo, 'structuredData'>): JsonLd[];
97
97
  declare function jsonLdHtml(seo: Pick<ResolvedSeo, 'structuredData'>): string;
98
98
 
99
+ type TemplateData = {
100
+ page: Pick<Page, 'pageId' | 'locale' | 'content' | 'resolvedSeo'>;
101
+ global?: Pick<Page, 'pageId' | 'content'> | null;
102
+ navigations?: Record<string, Navigation | null>;
103
+ };
104
+ declare function renderTemplate(template: string, data: TemplateData): string;
105
+
99
106
  declare function normalizeSlug(input: string): string;
100
107
  declare function buildPath(settings: UrlSettings, slug: string, locale: string): string;
101
108
  declare function resolvePath(settings: UrlSettings, pathname: string): {
@@ -114,9 +121,11 @@ type BreaseOptions = {
114
121
  token?: string;
115
122
  apiUrl?: string;
116
123
  commit?: string | false;
124
+ branch?: string | false;
117
125
  fetch?: typeof fetch;
118
126
  retries?: number;
119
127
  retryBaseMs?: number;
128
+ timeoutMs?: number;
120
129
  };
121
130
  interface Brease {
122
131
  getSite(): Promise<Site>;
@@ -125,7 +134,7 @@ interface Brease {
125
134
  }): Promise<Page<T> | null>;
126
135
  getPages<T = Record<string, unknown>>(opts?: {
127
136
  locale?: string;
128
- parentId?: string;
137
+ parentId?: string | null;
129
138
  template?: string;
130
139
  withContent?: boolean;
131
140
  }): Promise<PageRef<T>[]>;
@@ -148,6 +157,7 @@ interface Brease {
148
157
  localeContext(path?: string | string[]): Promise<LocaleContext | null>;
149
158
  sitemap(baseUrl: string): Promise<SitemapEntry[]>;
150
159
  }
160
+ declare function clearBreaseCache(): void;
151
161
  declare function createBrease(opts?: BreaseOptions): Brease;
152
162
 
153
- export { type Brease, BreaseError, type BreaseOptions, type BreaseSection, type CustomTag, type Ga4Tag, type JsonLd, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, ResolvedSeo, type RevalidateBody, type RevalidateTarget, Site, SitemapEntry, UrlSettings, buildPath, canonicalPath, checkSections, createBrease, customTags, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, jsonLd, jsonLdHtml, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, resolvePath, sectionAttrs, sectionsAttrs, verifyRevalidate, verifySignature };
163
+ export { type Brease, BreaseError, type BreaseOptions, type BreaseSection, type CustomTag, type Ga4Tag, type JsonLd, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, ResolvedSeo, type RevalidateBody, type RevalidateTarget, Site, SitemapEntry, type TemplateData, UrlSettings, buildPath, canonicalPath, checkSections, clearBreaseCache, createBrease, customTags, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, jsonLd, jsonLdHtml, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, renderTemplate, resolvePath, sectionAttrs, sectionsAttrs, verifyRevalidate, verifySignature };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { S as Site, R as ResolvedSeo, U as UrlSettings, a as Redirect, P as Page, b as PageRef, N as Navigation, c as Release, d as SitemapEntry } from './types-D5mwpqAP.js';
1
+ import { S as Site, R as ResolvedSeo, U as UrlSettings, a as Redirect, P as Page, N as Navigation, b as PageRef, c as Release, d as SitemapEntry } from './types-D5mwpqAP.js';
2
2
  export { B as BreaseImage, e as BreaseLink, L as LocaleStrategy, f as NavigationItem, O as OpenGraph, g as PageSeo, h as Robots, i as SiteSeo, T as Twitter } from './types-D5mwpqAP.js';
3
3
 
4
4
  type Ga4Tag = {
@@ -96,6 +96,13 @@ type JsonLd = {
96
96
  declare function jsonLd(seo: Pick<ResolvedSeo, 'structuredData'>): JsonLd[];
97
97
  declare function jsonLdHtml(seo: Pick<ResolvedSeo, 'structuredData'>): string;
98
98
 
99
+ type TemplateData = {
100
+ page: Pick<Page, 'pageId' | 'locale' | 'content' | 'resolvedSeo'>;
101
+ global?: Pick<Page, 'pageId' | 'content'> | null;
102
+ navigations?: Record<string, Navigation | null>;
103
+ };
104
+ declare function renderTemplate(template: string, data: TemplateData): string;
105
+
99
106
  declare function normalizeSlug(input: string): string;
100
107
  declare function buildPath(settings: UrlSettings, slug: string, locale: string): string;
101
108
  declare function resolvePath(settings: UrlSettings, pathname: string): {
@@ -114,9 +121,11 @@ type BreaseOptions = {
114
121
  token?: string;
115
122
  apiUrl?: string;
116
123
  commit?: string | false;
124
+ branch?: string | false;
117
125
  fetch?: typeof fetch;
118
126
  retries?: number;
119
127
  retryBaseMs?: number;
128
+ timeoutMs?: number;
120
129
  };
121
130
  interface Brease {
122
131
  getSite(): Promise<Site>;
@@ -125,7 +134,7 @@ interface Brease {
125
134
  }): Promise<Page<T> | null>;
126
135
  getPages<T = Record<string, unknown>>(opts?: {
127
136
  locale?: string;
128
- parentId?: string;
137
+ parentId?: string | null;
129
138
  template?: string;
130
139
  withContent?: boolean;
131
140
  }): Promise<PageRef<T>[]>;
@@ -148,6 +157,7 @@ interface Brease {
148
157
  localeContext(path?: string | string[]): Promise<LocaleContext | null>;
149
158
  sitemap(baseUrl: string): Promise<SitemapEntry[]>;
150
159
  }
160
+ declare function clearBreaseCache(): void;
151
161
  declare function createBrease(opts?: BreaseOptions): Brease;
152
162
 
153
- export { type Brease, BreaseError, type BreaseOptions, type BreaseSection, type CustomTag, type Ga4Tag, type JsonLd, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, ResolvedSeo, type RevalidateBody, type RevalidateTarget, Site, SitemapEntry, UrlSettings, buildPath, canonicalPath, checkSections, createBrease, customTags, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, jsonLd, jsonLdHtml, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, resolvePath, sectionAttrs, sectionsAttrs, verifyRevalidate, verifySignature };
163
+ export { type Brease, BreaseError, type BreaseOptions, type BreaseSection, type CustomTag, type Ga4Tag, type JsonLd, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, ResolvedSeo, type RevalidateBody, type RevalidateTarget, Site, SitemapEntry, type TemplateData, UrlSettings, buildPath, canonicalPath, checkSections, clearBreaseCache, createBrease, customTags, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, jsonLd, jsonLdHtml, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, renderTemplate, resolvePath, sectionAttrs, sectionsAttrs, verifyRevalidate, verifySignature };
package/dist/index.js CHANGED
@@ -1,4 +1,3 @@
1
- export { BreaseError, buildPath, canonicalPath, createBrease, customTags, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, resolvePath, verifyRevalidate, verifySignature } from './chunk-MWTYINWA.js';
2
- export { checkSections, sectionAttrs, sectionsAttrs } from './chunk-CQZLTZGN.js';
3
- export { jsonLd, jsonLdHtml } from './chunk-N3QOL5EU.js';
1
+ export { BreaseError, buildPath, canonicalPath, checkSections, clearBreaseCache, createBrease, customTags, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, renderTemplate, resolvePath, sectionAttrs, sectionsAttrs, verifyRevalidate, verifySignature } from './chunk-ES4KMYDH.js';
2
+ export { jsonLd, jsonLdHtml } from './chunk-VQGKMILO.js';
4
3
  import './chunk-PKBMQBKP.js';