@bettercms-ai/next 0.36.3 → 0.39.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.js CHANGED
@@ -1,6 +1,25 @@
1
+ // src/node-builtins.ts
2
+ function builtin(id) {
3
+ const proc = globalThis.process;
4
+ if (typeof proc?.getBuiltinModule !== "function") {
5
+ throw new Error(`@bettercms-ai/next: ${id} is read on the server only, through process.getBuiltinModule (Node 20.16+ or 22.3+).`);
6
+ }
7
+ return proc.getBuiltinModule(id);
8
+ }
9
+ var nodeFs = () => builtin("node:fs");
10
+ var nodePath = () => builtin("node:path");
11
+ var readText = (path) => nodeFs().readFileSync(nodePath().resolve(path), "utf8");
12
+ function readTextOrNull(path) {
13
+ const fs = nodeFs();
14
+ const file = nodePath().resolve(path);
15
+ try {
16
+ return fs.readFileSync(file, "utf8");
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+
1
22
  // src/client.ts
2
- import { readFileSync } from "fs";
3
- import { resolve } from "path";
4
23
  import { resolveBcmsConfig } from "@bettercms-ai/sdk/config";
5
24
  import { BRANCH_SIGNATURE_HEADER } from "@bettercms-ai/sdk/draft";
6
25
 
@@ -37,20 +56,23 @@ function mapEntry(raw) {
37
56
  updatedAt: raw.updatedAt ?? null
38
57
  };
39
58
  }
40
- function configFromSite(config) {
59
+ function siteConfig(options = {}) {
41
60
  const env = typeof process !== "undefined" ? process.env : {};
42
- const { config: site, missing } = resolveBcmsConfig({
43
- options: { workspace: config.workspace, projectId: config.projectId },
61
+ return resolveBcmsConfig({
62
+ options,
44
63
  env,
45
64
  prefixes: ["NEXT_PUBLIC_", ""],
46
65
  snapshot: () => {
47
66
  try {
48
- return JSON.parse(readFileSync(resolve(env.BCMS_CONTENT_FILE || "bcms-content.json"), "utf8"));
67
+ return JSON.parse(readText(env.BCMS_CONTENT_FILE || "bcms-content.json"));
49
68
  } catch {
50
69
  return {};
51
70
  }
52
71
  }
53
72
  });
73
+ }
74
+ function configFromSite(config) {
75
+ const { config: site, missing } = siteConfig({ workspace: config.workspace, projectId: config.projectId });
54
76
  if (missing.includes("workspace")) {
55
77
  throw new Error(
56
78
  "[@bettercms-ai/next] No workspace: pass createBetterCMS({ workspace }), set NEXT_PUBLIC_BCMS_WORKSPACE, or run `bettercms pull-content` before the build so bcms-content.json is present."
@@ -221,7 +243,7 @@ function createBetterCMS(options = {}) {
221
243
  }
222
244
 
223
245
  // src/metadata.ts
224
- import { resolveSeo } from "@bettercms-ai/sdk";
246
+ import { resolveSeo } from "@bettercms-ai/sdk/seo";
225
247
  function withSiteUrlFallback(page, location) {
226
248
  const siteUrl = location.siteUrl || (typeof process !== "undefined" ? process.env.BETTERCMS_SITE_URL : void 0);
227
249
  const slugPath2 = page.slug ? page.slug === "home" ? "/" : `/${page.slug.replace(/^\/+/, "")}` : void 0;
@@ -312,11 +334,9 @@ function entryField(entry, path, opts) {
312
334
  }
313
335
 
314
336
  // src/index.ts
315
- import { resolveSeo as resolveSeo2 } from "@bettercms-ai/sdk";
337
+ import { resolveSeo as resolveSeo2 } from "@bettercms-ai/sdk/seo";
316
338
 
317
339
  // src/snapshot.ts
318
- import { readFileSync as readFileSync2, writeFileSync, mkdirSync } from "fs";
319
- import { dirname, resolve as resolve2 } from "path";
320
340
  var SNAPSHOT_VERSION = 1;
321
341
  var DEFAULT_SNAPSHOT_FILE = "bcms-content.json";
322
342
  function serializeSnapshot(snapshot) {
@@ -362,20 +382,20 @@ function isPlatformSnapshot(parsed) {
362
382
  return typeof snap?.$schema === "string" && snap.$schema.startsWith("bcms-content/") && typeof snap.collections === "object" && snap.collections !== null;
363
383
  }
364
384
  function writeSnapshot(path, snapshot) {
365
- const out = resolve2(process.cwd(), path);
385
+ const out = nodePath().resolve(path);
366
386
  try {
367
- if (isPlatformSnapshot(JSON.parse(readFileSync2(out, "utf8")))) return false;
387
+ if (isPlatformSnapshot(JSON.parse(readText(out)))) return false;
368
388
  } catch {
369
389
  }
370
- mkdirSync(dirname(out), { recursive: true });
371
- writeFileSync(out, serializeSnapshot(snapshot), "utf8");
390
+ const fs = nodeFs();
391
+ fs.mkdirSync(nodePath().dirname(out), { recursive: true });
392
+ fs.writeFileSync(out, serializeSnapshot(snapshot), "utf8");
372
393
  return true;
373
394
  }
374
395
  function readSnapshot(path) {
375
- const out = resolve2(process.cwd(), path);
376
396
  let json;
377
397
  try {
378
- json = readFileSync2(out, "utf8");
398
+ json = readText(path);
379
399
  } catch (err) {
380
400
  if (err?.code === "ENOENT") return null;
381
401
  throw err;
@@ -428,7 +448,7 @@ function getContent(config, opts = {}) {
428
448
  listEntries: (model) => live.listEntries(model, { revalidate: false })
429
449
  };
430
450
  }
431
- const resolved = resolve2(process.cwd(), path);
451
+ const resolved = nodePath().resolve(path);
432
452
  function load() {
433
453
  const cached = snapshotCache.get(resolved);
434
454
  if (cached) return cached;
@@ -633,15 +653,9 @@ import {
633
653
  } from "@bettercms-ai/image-url";
634
654
 
635
655
  // src/forms-read.ts
636
- import { readFileSync as readFileSync3 } from "fs";
637
- import { resolve as resolve3 } from "path";
638
656
  function readForms(path = process.env.BCMS_CONTENT_FILE || "bcms-content.json") {
639
- let raw;
640
- try {
641
- raw = readFileSync3(resolve3(process.cwd(), path), "utf8");
642
- } catch {
643
- return { forms: [], turnstileSiteKey: null };
644
- }
657
+ const raw = readTextOrNull(path);
658
+ if (raw === null) return { forms: [], turnstileSiteKey: null };
645
659
  const snap = JSON.parse(raw);
646
660
  return { forms: snap.forms ?? [], turnstileSiteKey: snap.turnstileSiteKey ?? null };
647
661
  }
@@ -650,15 +664,9 @@ function getForm(idOrName, path) {
650
664
  }
651
665
 
652
666
  // src/pages-read.ts
653
- import { readFileSync as readFileSync4 } from "fs";
654
- import { resolve as resolve4 } from "path";
655
667
  function readPages(path = process.env.BCMS_CONTENT_FILE || "bcms-content.json") {
656
- let raw;
657
- try {
658
- raw = readFileSync4(resolve4(process.cwd(), path), "utf8");
659
- } catch {
660
- return [];
661
- }
668
+ const raw = readTextOrNull(path);
669
+ if (raw === null) return [];
662
670
  const snap = JSON.parse(raw);
663
671
  return snap.pages ?? [];
664
672
  }
@@ -666,16 +674,84 @@ function getPage(slug, path) {
666
674
  return readPages(path).find((p) => p.slug === slug);
667
675
  }
668
676
 
677
+ // src/page-content.ts
678
+ import { readPublishedContent } from "@bettercms-ai/sdk/read";
679
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
680
+ var valuesOf = (row) => {
681
+ const { $html: _authored, ...values } = isRecord(row.data) ? row.data : {};
682
+ return { ...values, slug: row.slug };
683
+ };
684
+ var pageTags = (workspace, slug) => [
685
+ `bcms:${workspace}:all`,
686
+ `bcms:${workspace}:entry:${slug}`,
687
+ `bcms:${workspace}:page:${slug}`
688
+ ];
689
+ function pageFromContent(content, slug, stub = {}) {
690
+ const collections = isRecord(content) && isRecord(content.collections) ? content.collections : {};
691
+ const rows = Object.values(collections).flatMap((r) => Array.isArray(r) ? r : []).filter((r) => isRecord(r) && typeof r.slug === "string");
692
+ const html = (row) => isRecord(row.$html) ? { $html: row.$html } : {};
693
+ const entries = {};
694
+ for (const row of rows) {
695
+ if (row.slug in entries || isRecord(row._meta) && row._meta.page === true) continue;
696
+ entries[row.slug] = isRecord(row.data) ? { ...valuesOf(row), ...html(row) } : row;
697
+ }
698
+ const own = rows.find((r) => r.slug === slug);
699
+ const withHtml = rows.find((r) => r.slug === slug && isRecord(r.$html));
700
+ const base = own ? isRecord(own.data) ? { ...valuesOf(own), ...withHtml ? html(withHtml) : {} } : own : null;
701
+ const values = base ? "entries" in base ? base : { ...base, entries } : Object.keys(entries).length ? { slug, entries } : null;
702
+ const listed = isRecord(content) && Array.isArray(content.pages) ? content.pages : [];
703
+ const page = listed.find((p) => isRecord(p) && p.slug === slug);
704
+ let out = values;
705
+ if (page && isRecord(page.fieldStyles)) out = { ...out ?? { slug }, fieldStyles: page.fieldStyles };
706
+ if (page && "blocks" in stub && Array.isArray(page.blocks)) out = { ...out ?? { slug }, blocks: page.blocks };
707
+ return out;
708
+ }
709
+ function overlay(row, snapshot) {
710
+ const { entries, fieldStyles, blocks } = snapshot;
711
+ return { ...valuesOf(row), ...entries ? { entries } : {}, ...fieldStyles ? { fieldStyles } : {}, ...blocks ? { blocks } : {} };
712
+ }
713
+ async function readRow(url, init, draft) {
714
+ const res = await fetch(url, { ...init, headers: { Accept: "application/json" } });
715
+ if (!res.ok) return null;
716
+ const body = await res.json();
717
+ const row = draft ? body.data : body;
718
+ return isRecord(row) && isRecord(row.data) ? row : null;
719
+ }
720
+ var fellBack = /* @__PURE__ */ new Set();
721
+ function sayFellBack(slug, snapshot) {
722
+ if (typeof process === "undefined" || process.env.NODE_ENV !== "production" || fellBack.has(slug)) return;
723
+ fellBack.add(slug);
724
+ const stub = Object.entries(snapshot).every(([key, v]) => key === "slug" || key === "blocks" && Array.isArray(v) && v.length === 0);
725
+ console.warn(
726
+ stub ? `[bcms] CONTENT_STUB ${slug}: the build has no published content for this page; it renders the source's copy` : `[bcms] CONTENT_SNAPSHOT ${slug}: no live or published content could be read; it renders the snapshot it was built with`
727
+ );
728
+ }
729
+ async function bcmsPage(slug, snapshot = {}, opts = {}) {
730
+ const { config } = siteConfig(opts);
731
+ if (config.apiUrl && config.workspace) {
732
+ try {
733
+ const token = await isDraftEnabled() ? await getPreviewToken() : null;
734
+ const project = config.projectId ? `?projectId=${encodeURIComponent(config.projectId)}` : "";
735
+ const row = token ? await readRow(`${config.apiUrl}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`, { cache: "no-store" }, true) : await readRow(
736
+ `${config.apiUrl}/api/v1/delivery/${encodeURIComponent(config.workspace)}/content-entries/${encodeURIComponent(slug)}${project}`,
737
+ { next: { revalidate: false, tags: pageTags(config.workspace, slug) } },
738
+ false
739
+ );
740
+ if (row) return overlay(row, snapshot);
741
+ } catch (err) {
742
+ if (isRecord(err) && "digest" in err) throw err;
743
+ }
744
+ }
745
+ const published = pageFromContent(readPublishedContent(), slug, snapshot);
746
+ if (published) return published;
747
+ sayFellBack(slug, snapshot);
748
+ return snapshot;
749
+ }
750
+
669
751
  // src/components-read.ts
670
- import { readFileSync as readFileSync5 } from "fs";
671
- import { resolve as resolve5 } from "path";
672
752
  function readComponents(path = process.env.BCMS_CONTENT_FILE || "bcms-content.json") {
673
- let raw;
674
- try {
675
- raw = readFileSync5(resolve5(process.cwd(), path), "utf8");
676
- } catch {
677
- return [];
678
- }
753
+ const raw = readTextOrNull(path);
754
+ if (raw === null) return [];
679
755
  const snap = JSON.parse(raw);
680
756
  return snap.components ?? [];
681
757
  }
@@ -686,22 +762,43 @@ function getComponent(idOrSlug, path) {
686
762
  }
687
763
 
688
764
  // src/sections-read.ts
689
- import { readPublishedContent } from "@bettercms-ai/sdk";
765
+ import { readPublishedContent as readPublishedContent2 } from "@bettercms-ai/sdk/read";
690
766
  function pageRow(pages, page, read) {
691
767
  const rows = (Array.isArray(pages) ? pages : []).filter((p) => p?.slug === page);
692
768
  const template = rows.find((row) => row.template === true);
693
769
  return read?.template ? template : rows.find((row) => row.template !== true) ?? rows[0];
694
770
  }
771
+ function idsUnder(value, key, into = /* @__PURE__ */ new Set()) {
772
+ if (Array.isArray(value)) for (const item of value) idsUnder(item, key, into);
773
+ else if (value && typeof value === "object") {
774
+ for (const [k, v] of Object.entries(value)) {
775
+ if (k === key && typeof v === "string") into.add(v);
776
+ else idsUnder(v, key, into);
777
+ }
778
+ }
779
+ return into;
780
+ }
781
+ function referencedComponents(blocks, components) {
782
+ const byId = new Map(components.map((c) => [c.id, c]));
783
+ const reached = /* @__PURE__ */ new Set();
784
+ const queue = [...idsUnder(blocks, "componentId")];
785
+ for (let id = queue.pop(); id !== void 0; id = queue.pop()) {
786
+ const def = byId.get(id);
787
+ if (!def || reached.has(id)) continue;
788
+ reached.add(id);
789
+ queue.push(...idsUnder(def, "componentId"));
790
+ }
791
+ return components.filter((c) => reached.has(c.id));
792
+ }
793
+ var listOf = (value) => Array.isArray(value) ? value : [];
695
794
  function sectionsFor(page, read) {
696
- const snapshot = readPublishedContent();
795
+ const snapshot = readPublishedContent2();
697
796
  const row = pageRow(snapshot?.pages, page, read);
698
- const blocks = row?.blocks ?? row?.blockJson;
699
- return {
700
- page,
701
- blocks: Array.isArray(blocks) ? blocks : null,
702
- components: Array.isArray(snapshot?.components) ? snapshot.components : [],
703
- forms: Array.isArray(snapshot?.forms) ? snapshot.forms : []
704
- };
797
+ const listed = row?.blocks ?? row?.blockJson;
798
+ const blocks = Array.isArray(listed) ? listed : null;
799
+ const components = referencedComponents(blocks ?? [], listOf(snapshot?.components));
800
+ const formIds = idsUnder([blocks, components], "formId");
801
+ return { page, blocks, components, forms: listOf(snapshot?.forms).filter((f) => formIds.has(f.id)) };
705
802
  }
706
803
  function sectionsStaticProps(page, own, read) {
707
804
  return async (context) => {
@@ -766,9 +863,29 @@ function BcmsButton({ path, value, className }) {
766
863
  );
767
864
  }
768
865
 
866
+ // src/icon.tsx
867
+ import { iconSrc } from "@bettercms-ai/types";
868
+ import { ICON_MARKUP as ICON_MARKUP2, ICON_VIEWBOX as ICON_VIEWBOX2 } from "@bettercms-ai/icons/markup";
869
+ import { jsx as jsx3 } from "react/jsx-runtime";
870
+ function BcmsIcon({ value, className }) {
871
+ const src = iconSrc(value);
872
+ if (!src) return null;
873
+ const a11y = src.label ? { role: "img", "aria-label": src.label } : { "aria-hidden": true };
874
+ if ("name" in src) {
875
+ const markup = ICON_MARKUP2[src.name];
876
+ if (!markup) return null;
877
+ return /* @__PURE__ */ jsx3("svg", { "data-bcms-icon": src.name, className, viewBox: ICON_VIEWBOX2, width: "1em", height: "1em", fill: "none", focusable: "false", ...a11y, dangerouslySetInnerHTML: { __html: markup } });
878
+ }
879
+ if (src.followsText) {
880
+ const mask = `url(${JSON.stringify(src.url)}) center / contain no-repeat`;
881
+ return /* @__PURE__ */ jsx3("span", { "data-bcms-icon-url": src.url, className, style: { display: "inline-block", width: "1em", height: "1em", backgroundColor: "currentColor", mask, WebkitMask: mask }, ...a11y });
882
+ }
883
+ return /* @__PURE__ */ jsx3("img", { src: src.url, alt: src.label ?? "", className, width: 16, height: 16, style: { width: "1em", height: "1em", objectFit: "contain" } });
884
+ }
885
+
769
886
  // src/image.tsx
770
887
  import { imageCore } from "@bettercms-ai/sdk/bindings";
771
- import { jsx as jsx3 } from "react/jsx-runtime";
888
+ import { jsx as jsx4 } from "react/jsx-runtime";
772
889
  function BcmsImage({
773
890
  src,
774
891
  path,
@@ -788,7 +905,7 @@ function BcmsImage({
788
905
  }) {
789
906
  const { src: src1x, srcset: srcSet, alt: resolvedAlt, css } = imageCore(src, { alt, width, height, format, quality, fit, sizes, focalX, focalY, baseUrl });
790
907
  const merged = { ...css, ...style };
791
- return /* @__PURE__ */ jsx3(
908
+ return /* @__PURE__ */ jsx4(
792
909
  "img",
793
910
  {
794
911
  src: src1x,
@@ -813,11 +930,13 @@ function defineBetterCMSLive(config) {
813
930
  }
814
931
 
815
932
  // src/revalidate-route.ts
816
- import { createHmac, timingSafeEqual } from "crypto";
817
- function safeEqual(a, b) {
818
- const ab = Buffer.from(a);
819
- const bb = Buffer.from(b);
820
- return ab.length === bb.length && timingSafeEqual(ab, bb);
933
+ async function signatureValid(secret, body, header) {
934
+ const hex = /^sha256=([0-9a-f]{64})$/.exec(header)?.[1];
935
+ if (!hex) return false;
936
+ const utf8 = new TextEncoder();
937
+ const key = await crypto.subtle.importKey("raw", utf8.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
938
+ const signature = Uint8Array.from(hex.match(/../g), (byte) => parseInt(byte, 16));
939
+ return crypto.subtle.verify("HMAC", key, signature, utf8.encode(body));
821
940
  }
822
941
  function slugPath(slug) {
823
942
  if (slug.startsWith("//") || /[\s?#\\]/.test(slug)) return null;
@@ -829,9 +948,8 @@ function createRevalidateRoute(config = {}) {
829
948
  const body = await request.text();
830
949
  const secret = config.secret ?? process.env.BCMS_REVALIDATE_SECRET;
831
950
  if (secret) {
832
- const provided = request.headers.get("x-bettercms-signature") ?? "";
833
- const expected = `sha256=${createHmac("sha256", secret).update(body).digest("hex")}`;
834
- if (!safeEqual(provided, expected)) {
951
+ const header = request.headers.get("x-bettercms-signature") ?? request.headers.get("x-bcms-signature") ?? "";
952
+ if (!await signatureValid(secret, body, header)) {
835
953
  return new Response("Invalid signature", { status: 401 });
836
954
  }
837
955
  }
@@ -842,13 +960,16 @@ function createRevalidateRoute(config = {}) {
842
960
  return new Response("Invalid JSON", { status: 400 });
843
961
  }
844
962
  const strings = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
845
- const tags = strings(payload.data?.tags);
846
- const paths = [...new Set(strings(payload.data?.slugs).map(slugPath).filter((p) => p !== null))];
963
+ const tags = [.../* @__PURE__ */ new Set([...strings(payload.data?.tags), ...strings(payload.tags)])];
964
+ const changed = [...strings(payload.data?.slugs), ...strings(payload.paths)];
965
+ const paths = [...new Set(changed.map(slugPath).filter((p) => p !== null))];
966
+ const everything = payload.event === "revalidate" && changed.length === 0 && tags.length === 0;
847
967
  const { revalidateTag, revalidatePath } = await import("next/cache");
848
968
  const tag = revalidateTag;
849
969
  for (const t of tags) tag(t, { expire: 0 });
850
970
  for (const p of paths) revalidatePath(p);
851
- return Response.json({ revalidated: true, tags, paths });
971
+ if (everything) revalidatePath("/", "layout");
972
+ return Response.json({ revalidated: true, tags, paths: everything ? ["/"] : paths });
852
973
  }
853
974
  return { POST };
854
975
  }
@@ -857,12 +978,14 @@ export {
857
978
  BcmsDraftMarker,
858
979
  BcmsEmbedScripts,
859
980
  BcmsField,
981
+ BcmsIcon,
860
982
  BcmsImage,
861
983
  BetterCMSError,
862
984
  DEFAULT_SNAPSHOT_FILE,
863
985
  PREVIEW_TOKEN_COOKIE,
864
986
  RESPONSIVE_CSS,
865
987
  SNAPSHOT_VERSION,
988
+ bcmsPage,
866
989
  buildMetadata,
867
990
  buildSnapshot,
868
991
  createBetterCMS,