@bettercms-ai/codegen 0.5.0 → 0.6.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 +96 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/cli.js +0 -501
- package/dist/cli.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -16,6 +16,60 @@ export type RichText = {
|
|
|
16
16
|
readonly html?: string;
|
|
17
17
|
};
|
|
18
18
|
|
|
19
|
+
/**
|
|
20
|
+
* A field that may arrive as EITHER shape.
|
|
21
|
+
*
|
|
22
|
+
* Switching a field between \`text\` and \`richtext\` in the CMS switches what Delivery
|
|
23
|
+
* returns for it \u2014 a bare string becomes \`{ format, value, html }\`. Type author-editable
|
|
24
|
+
* text with this and read it through \`plain()\`/\`rich()\` below, and that switch stops being
|
|
25
|
+
* a site-breaking change. Interpolating the value directly renders \`[object Object]\`.
|
|
26
|
+
*/
|
|
27
|
+
export type TextOrRich = string | RichText | null | undefined;
|
|
28
|
+
|
|
29
|
+
/** True when the value is a rich-text envelope rather than a bare string. */
|
|
30
|
+
export function isRichText(value: unknown): value is RichText {
|
|
31
|
+
return (
|
|
32
|
+
typeof value === "object" && value !== null && !Array.isArray(value) &&
|
|
33
|
+
("html" in value || "format" in value)
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Plain text for attribute contexts \u2014 \`<title>\`, meta description, JSON-LD, \`alt\`. */
|
|
38
|
+
export function plain(value: TextOrRich): string {
|
|
39
|
+
if (typeof value === "string") return value;
|
|
40
|
+
if (!isRichText(value) || typeof value.html !== "string") return "";
|
|
41
|
+
return decodeEntities(value.html.replace(/<[^>]+>/g, "")).trim();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Renderable HTML, for \`set:html\` / \`dangerouslySetInnerHTML\`. Rich text keeps its inline
|
|
46
|
+
* marks (the server sanitizes \`html\` on write); a bare string is escaped, so a plain field
|
|
47
|
+
* can never inject markup. A LONE wrapping block is unwrapped \u2014 a field switched from
|
|
48
|
+
* \`text\` stores \`<p>\u2026</p>\`, and \`<h1><p>\u2026</p></h1>\` is invalid HTML (the parser closes the
|
|
49
|
+
* heading early, dropping the text out of it). Real block structure is left alone.
|
|
50
|
+
*/
|
|
51
|
+
export function rich(value: TextOrRich, fallback = ""): string {
|
|
52
|
+
const html = (
|
|
53
|
+
typeof value === "string" ? escapeHtml(value) : isRichText(value) ? (value.html ?? "") : ""
|
|
54
|
+
).trim();
|
|
55
|
+
return html ? unwrapLoneBlock(html) : escapeHtml(fallback);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function unwrapLoneBlock(html: string): string {
|
|
59
|
+
const m = html.match(/^<(p|div|h[1-6])(?:\\s[^>]*)?>([\\s\\S]*)<\\/\\1>$/i);
|
|
60
|
+
return m && !new RegExp(\`</\${m[1]}>\`, "i").test(m[2]) ? m[2] : html;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function escapeHtml(s: string): string {
|
|
64
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function decodeEntities(s: string): string {
|
|
68
|
+
return s
|
|
69
|
+
.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"')
|
|
70
|
+
.replace(/�?39;/g, "'").replace(/ /g, " ").replace(/&/g, "&");
|
|
71
|
+
}
|
|
72
|
+
|
|
19
73
|
/**
|
|
20
74
|
* Image / media field value as stored and returned verbatim by the Delivery API
|
|
21
75
|
* (server-normalized on write to the canonical shape). \`url\` is always present; an
|
|
@@ -31,6 +85,26 @@ export interface BetterCMSImage {
|
|
|
31
85
|
readonly height?: number;
|
|
32
86
|
}
|
|
33
87
|
|
|
88
|
+
/**
|
|
89
|
+
* A component slot's value, as stored and delivered.
|
|
90
|
+
*
|
|
91
|
+
* \`componentId\` points at a component definition; \`overrides\` are the author's values,
|
|
92
|
+
* keyed by the component's declared prop keys.
|
|
93
|
+
*
|
|
94
|
+
* \`resolved\` is the SNAPSHOT: at publish time the component is resolved (its block tree
|
|
95
|
+
* with the overrides applied) and frozen onto the published value. That is why editing a
|
|
96
|
+
* component does not silently rewrite entries that were already published \u2014 a published
|
|
97
|
+
* entry carries what it was published with until it is published again.
|
|
98
|
+
*
|
|
99
|
+
* Read \`resolved\` when it is there; it is absent on draft-perspective reads, where you
|
|
100
|
+
* should resolve \`componentId\` yourself against the components endpoint.
|
|
101
|
+
*/
|
|
102
|
+
export interface BetterCMSComponentRef {
|
|
103
|
+
readonly componentId: string;
|
|
104
|
+
readonly overrides?: Readonly<Record<string, unknown>>;
|
|
105
|
+
readonly resolved?: readonly unknown[];
|
|
106
|
+
}
|
|
107
|
+
|
|
34
108
|
/**
|
|
35
109
|
* Delivery envelope around a model's typed \`data\`. \`getEntry\`/\`listEntries\` in the
|
|
36
110
|
* Next adapter return this shape, with \`fields\` typed by the model.
|
|
@@ -78,7 +152,12 @@ function scalarType(field) {
|
|
|
78
152
|
case "reference":
|
|
79
153
|
return "string";
|
|
80
154
|
// referenced entry id
|
|
155
|
+
// Both spellings are live (see ContentModelFieldType). Template- and Webflow-seeded
|
|
156
|
+
// models carry the camelCase one; until it was handled here it fell through to the
|
|
157
|
+
// exhaustiveness default, so generated types for every template-created collection
|
|
158
|
+
// typed this field as `unknown` instead of `string[]`.
|
|
81
159
|
case "multi-reference":
|
|
160
|
+
case "multiReference":
|
|
82
161
|
return "string[]";
|
|
83
162
|
// referenced entry ids
|
|
84
163
|
case "array": {
|
|
@@ -86,6 +165,23 @@ function scalarType(field) {
|
|
|
86
165
|
const inner = itemType === "number" ? "number" : "string";
|
|
87
166
|
return `${inner}[]`;
|
|
88
167
|
}
|
|
168
|
+
// ── Builder scalars ────────────────────────────────────────────────────────
|
|
169
|
+
// All string-shaped on the wire; each is value-validated on write (see
|
|
170
|
+
// src/lib/content/reference-validation.ts), so the generated type is the
|
|
171
|
+
// narrowest thing that is actually true of the stored value.
|
|
172
|
+
case "longtext":
|
|
173
|
+
case "slug":
|
|
174
|
+
case "email":
|
|
175
|
+
case "phone":
|
|
176
|
+
case "link":
|
|
177
|
+
case "color":
|
|
178
|
+
return "string";
|
|
179
|
+
case "json":
|
|
180
|
+
return "unknown";
|
|
181
|
+
case "component-ref":
|
|
182
|
+
return "BetterCMSComponentRef";
|
|
183
|
+
case "file":
|
|
184
|
+
return "BetterCMSImage";
|
|
89
185
|
default: {
|
|
90
186
|
const _exhaustive = t;
|
|
91
187
|
return "unknown";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generate.ts","../src/bindings.ts","../src/components.ts","../src/fetch-models.ts"],"sourcesContent":["/**\n * @bettercms-ai/codegen — schema → TypeScript generator (the single source of truth).\n *\n * Both the dashboard schema builder and the MCP `create_model`/`add_field` tools write\n * the SAME `content_models.fields` (an array of `ContentModelField`). This generator maps\n * that one array into TypeScript. Because there is exactly one schema representation, the\n * generated types can never drift from the editor or the agent — they are the same source.\n *\n * Pure + deterministic: same models in → identical string out (stable ordering, no clock,\n * no I/O). That makes it trivially testable and safe to commit + diff in a customer repo.\n */\n\nimport type { ContentModelField, ContentModelFieldType } from \"@bettercms-ai/types\";\n\n/** Minimal model shape the generator needs — a subset of the Management API model row. */\nexport interface GeneratableModel {\n /** Machine-safe slug, e.g. \"blog\" or \"case-study\". Used for the schema-map key. */\n slug: string;\n /** Human name, used only for the JSDoc header. */\n name?: string;\n description?: string | null;\n fields: ContentModelField[];\n}\n\nexport interface GenerateOptions {\n /** Generator version stamped into the header (defaults to the package version). */\n version?: string;\n /** Override the banner timestamp source — omitted by default so output is deterministic. */\n bannerComment?: string;\n}\n\n/** Helper types emitted once at the top of every generated file (self-contained, zero-dep). */\nconst PREAMBLE = `/**\n * Rich-text field value returned by the Delivery API.\n *\n * - \\`format\\`/\\`value\\`: the portable, editor-agnostic payload (Lexical EditorState) —\n * render it with your editor's serializer for full fidelity.\n * - \\`html\\`: server-rendered, sanitized HTML (computed render-on-write). Present on\n * Delivery reads; the simplest path for non-React consumers — safe to inject directly\n * (e.g. \\`dangerouslySetInnerHTML\\`). Optional: legacy/un-normalized values may omit it.\n *\n * The \\`{ format, value }\\` contract is unchanged; \\`html\\` is additive.\n */\nexport type RichText = {\n readonly format: string;\n readonly value: unknown;\n readonly html?: string;\n};\n\n/**\n * Image / media field value as stored and returned verbatim by the Delivery API\n * (server-normalized on write to the canonical shape). \\`url\\` is always present; an\n * unresolved/external value may carry only \\`url\\`. \\`altText\\` is the accessibility text\n * for \\`<img alt>\\`.\n */\nexport interface BetterCMSImage {\n readonly id?: string;\n readonly url: string;\n readonly name?: string;\n readonly altText?: string | null;\n readonly width?: number;\n readonly height?: number;\n}\n\n/**\n * Delivery envelope around a model's typed \\`data\\`. \\`getEntry\\`/\\`listEntries\\` in the\n * Next adapter return this shape, with \\`fields\\` typed by the model.\n */\nexport interface BetterCMSEntry<TFields> {\n readonly slug: string;\n readonly status: \"draft\" | \"published\";\n readonly fields: TFields;\n readonly updatedAt: string;\n}\n`;\n\n/** PascalCase an identifier from a slug: \"case-study\" → \"CaseStudy\". */\nfunction pascalCase(slug: string): string {\n const parts = slug.split(/[-_\\s]+/).filter(Boolean);\n const pascal = parts\n .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n .join(\"\");\n // Guard against an identifier that starts with a digit (invalid TS type name).\n return /^[0-9]/.test(pascal) ? `Model${pascal}` : pascal || \"Model\";\n}\n\n/**\n * Make a string safe to embed inside a `/** ... */` JSDoc comment. A field label\n * (free-text, author/agent-controlled) could contain `*/` — which closes the comment\n * early and injects the remainder as code — or a newline, which breaks the single-line\n * comment. Both are neutralized here. Without this, hostile content produces non-\n * compiling (or worse, code-injected) output.\n */\nfunction escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"* /\").replace(/[\\r\\n]+/g, \" \").trim();\n}\n\nconst VALID_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * Render a field key as a TS property name. Field keys are author/agent-controlled and\n * not guaranteed to be valid identifiers (e.g. \"my-field\", \"1title\", \"\"), so anything\n * that isn't a bare identifier is emitted as a quoted property name — always valid TS.\n */\nfunction propName(key: string): string {\n return VALID_IDENT.test(key) ? key : JSON.stringify(key);\n}\n\n/** A scalar/primitive field maps to a TS type expression (no nesting). */\nfunction scalarType(field: ContentModelField): string {\n const t: ContentModelFieldType = field.type;\n switch (t) {\n case \"text\":\n return \"string\";\n case \"richtext\":\n return \"RichText\";\n case \"image\":\n return \"BetterCMSImage\";\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"date\":\n case \"datetime\":\n return \"string\"; // ISO 8601\n case \"select\": {\n const opts = field.options?.filter((o) => typeof o === \"string\") ?? [];\n return opts.length > 0\n ? opts.map((o) => JSON.stringify(o)).join(\" | \")\n : \"string\";\n }\n case \"reference\":\n return \"string\"; // referenced entry id\n case \"multi-reference\":\n return \"string[]\"; // referenced entry ids\n case \"array\": {\n // Zoned arrays (config.zones) are expanded by fieldsToBody before reaching here;\n // this branch handles only the primitive list form (config.itemType).\n const itemType = field.config?.itemType ?? \"text\";\n const inner =\n itemType === \"number\" ? \"number\" : \"string\"; // text | date → string\n return `${inner}[]`;\n }\n default: {\n // Exhaustiveness guard: if a new field type is added to the union and not\n // mapped here, this line becomes a compile error in the codegen build.\n const _exhaustive: never = t;\n return \"unknown\";\n }\n }\n}\n\n/**\n * Render the TS type for a zoned `array` field: an object with optional\n * `nonRepeatable` (a fixed block) and/or `repeatable` (a list of blocks). Recurses\n * through zone fields, so a zone field that is itself a zoned `array` nests naturally.\n */\nfunction arrayZoneType(field: ContentModelField, indent: string): string {\n const zones = field.config?.zones;\n const parts: string[] = [];\n if (zones?.nonRepeatable?.length) {\n const nested = fieldsToBody(zones.nonRepeatable, indent + \" \");\n parts.push(`${indent} readonly nonRepeatable?: {\\n${nested}\\n${indent} };`);\n }\n if (zones?.repeatable?.fields?.length) {\n const nested = fieldsToBody(zones.repeatable.fields, indent + \" \");\n parts.push(`${indent} readonly repeatable?: Array<{\\n${nested}\\n${indent} }>;`);\n }\n if (parts.length === 0) return \"Record<string, unknown>\"; // zoned array with no fields yet\n return `{\\n${parts.join(\"\\n\")}\\n${indent}}`;\n}\n\n/** Render the body of an object type from a field list, recursing into zones. */\nfunction fieldsToBody(fields: ContentModelField[], indent: string): string {\n const lines: string[] = [];\n for (const field of fields) {\n const optional = field.required ? \"\" : \"?\";\n let typeExpr: string;\n\n if (field.type === \"array\" && field.config?.zones) {\n typeExpr = arrayZoneType(field, indent);\n } else {\n typeExpr = scalarType(field);\n }\n\n const safeLabel = field.label ? escapeJsDoc(field.label) : \"\";\n if (safeLabel && safeLabel !== field.key) {\n lines.push(`${indent}/** ${safeLabel} */`);\n }\n lines.push(`${indent}readonly ${propName(field.key)}${optional}: ${typeExpr};`);\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate a complete `.ts` module from a set of content models.\n * Deterministic: models are sorted by slug; field order is preserved as authored.\n */\nexport function generateTypes(\n models: GeneratableModel[],\n opts: GenerateOptions = {},\n): string {\n const version = opts.version ?? \"0.1.0\";\n // Code-unit sort (NOT localeCompare): locale/ICU-independent so the generated\n // file is byte-identical on every machine — committed output diffs cleanly.\n const sorted = [...models].sort((a, b) =>\n a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0,\n );\n\n const header = `// ⚠️ AUTO-GENERATED by @bettercms-ai/codegen v${version} — DO NOT EDIT.\n// Regenerate with: npx @bettercms-ai/codegen\n// Source of truth: your BetterCMS content models (the same schema the dashboard\n// builder and the MCP tools write). Re-run codegen after any schema change.\n${opts.bannerComment ? `// ${opts.bannerComment}\\n` : \"\"}`;\n\n const interfaces: string[] = [];\n const mapEntries: string[] = [];\n // Different slugs can PascalCase to the same base name (e.g. \"case-study\" and\n // \"case_study\" → \"CaseStudy\"). Emitting two identical interfaces would silently\n // declaration-merge into one wrong type, so disambiguate with a numeric suffix.\n const usedNames = new Set<string>();\n\n for (const model of sorted) {\n const base = `${pascalCase(model.slug)}Fields`;\n let typeName = base;\n for (let n = 2; usedNames.has(typeName); n++) typeName = `${base}_${n}`;\n usedNames.add(typeName);\n\n const name = model.name ? escapeJsDoc(model.name) : \"\";\n const desc = model.description ? escapeJsDoc(model.description) : \"\";\n const doc = name\n ? `/**\\n * ${name}${desc ? ` — ${desc}` : \"\"}\\n * Model slug: \\`${model.slug}\\`\\n */\\n`\n : \"\";\n const body = model.fields.length\n ? fieldsToBody(model.fields, \" \")\n : \" // (no fields defined yet)\";\n interfaces.push(`${doc}export interface ${typeName} {\\n${body}\\n}`);\n mapEntries.push(` readonly ${JSON.stringify(model.slug)}: ${typeName};`);\n }\n\n const schemaMap = `/**\n * Registry mapping each model slug to its typed fields. The Next adapter uses this to\n * type \\`getEntry(\"blog\", ...)\\` by slug — autocomplete and exhaustiveness for free.\n */\nexport interface BetterCMSSchema {\n${mapEntries.join(\"\\n\") || \" // (no models defined yet)\"}\n}\n\n/** Union of all model slugs. */\nexport type BetterCMSModelSlug = keyof BetterCMSSchema;`;\n\n return [header, PREAMBLE, interfaces.join(\"\\n\\n\"), schemaMap, \"\"].join(\"\\n\");\n}\n","/**\n * @bettercms-ai/codegen — schema → Live Preview binding helper generator.\n *\n * Companion to {@link generateTypes}. Where that emits the *types*, this emits a\n * tiny, schema-derived runtime that stamps `data-bcms-field` / `data-bcms-kind`\n * attributes onto the elements a site author binds to CMS content. Those\n * attributes are what the dashboard's Live Preview editor reads to turn the real,\n * running site into an editable canvas (the parent maps `data-bcms-field` → its\n * internal `data-node-id` on frame load).\n *\n * Why a helper and not auto-injection: BetterCMS never renders the customer's DOM\n * — the site does. So binding is opt-in per element via a spread:\n *\n * import { bcms } from \"./bettercms.bindings.generated\";\n *\n * <h1 {...bcms.blog.title}>{entry.fields.title}</h1> // scalar\n * <li {...bcms.blog.tags.value(i)}>{tag}</li> // primitive-array item\n * <article {...bcms.blog.features.$(i)}> // array item root\n * <h3 {...bcms.blog.features.label(i)}>{f.label}</h3> // array item sub-field\n * </article>\n *\n * The attributes only appear when the site is built with `BCMS_ANNOTATE` set\n * (preview builds); a normal production build ships zero extra attributes, because\n * `bcmsField` returns `{}`. Same generated file, both builds — no separate mode.\n *\n * Pure + deterministic, exactly like the type generator: same models in → identical\n * string out (slug-sorted, field order preserved, no clock, no I/O). Field keys are\n * author/agent-controlled, so every embedded key is emitted as an escaped string\n * literal (never interpolated into code) — hostile input can't break the output.\n *\n * Grammar — mirrors what the editor's `fieldPathToNodeId` resolves:\n * `title` · `hero.heroTitle` · `hero.primaryCta.label` (group leaves, any depth)\n * `features[0]` · `features[0].label` · `intro.facts[0].label` (repeaters, one index)\n * Group (non-repeatable) zones recurse into nested binding objects; a repeater is an\n * object with `$(i)` (item root) + one accessor per scalar sub-field. Arrays nested\n * inside a repeater item (a second index) are still beyond what the editor can\n * address, so they are intentionally omitted rather than emitted as dead paths.\n */\n\nimport type { ContentModelField, ContentModelFieldType } from \"@bettercms-ai/types\";\nimport type { GeneratableModel, GenerateOptions } from \"./generate.js\";\n\nconst VALID_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * Render a field key as an object property name. Keys aren't guaranteed to be valid\n * identifiers (e.g. \"my-field\", \"1title\"), so anything that isn't a bare identifier\n * is quoted — always valid TS. (Mirrors the same helper in `generate.ts`.)\n */\nfunction propName(key: string): string {\n return VALID_IDENT.test(key) ? key : JSON.stringify(key);\n}\n\n/**\n * The kind label written to `data-bcms-kind`, mapped to the editor's closed field-type\n * set (matches the dashboard adapter's `toEditorFieldType`): API-only types that have\n * no on-canvas control collapse to \"text\". Informational today — the editor derives the\n * authoritative kind from the loaded model — but kept truthful for debugging/forward use.\n */\nfunction bindingKind(t: ContentModelFieldType): string {\n switch (t) {\n case \"text\":\n case \"richtext\":\n case \"image\":\n case \"boolean\":\n case \"number\":\n case \"select\":\n case \"array\":\n return t;\n // reference / multi-reference / date / datetime → plain text in the editor v1.\n default:\n return \"text\";\n }\n}\n\n/**\n * Build a runtime path expression for an array element: a string literal split around\n * the index so it concatenates at call time. Both halves are JSON-escaped, so an\n * author-controlled key can never inject code. e.g. (\"features[\", \"].label\") →\n * `\"features[\" + i + \"].label\"`.\n */\nfunction indexedPath(prefix: string, suffix: string): string {\n return `${JSON.stringify(prefix)} + i + ${JSON.stringify(suffix)}`;\n}\n\n/** Render a repeater binding object: `$(i)` item root + one accessor per scalar\n * sub-field. `path` is the repeater's full (possibly dotted) field path. */\nfunction repeaterBinding(\n itemFields: ContentModelField[],\n path: string,\n indent: string,\n): string {\n const lines: string[] = [\n `${indent} $: (i: number) => bcmsField(${indexedPath(`${path}[`, \"]\")}, \"array\"),`,\n ];\n for (const sub of itemFields) {\n // A sub-field that is itself an array would need a second index the editor\n // can't address yet — skip it rather than emit a path that won't bind.\n if (sub.type === \"array\") continue;\n lines.push(\n `${indent} ${propName(sub.key)}: (i: number) => bcmsField(${indexedPath(`${path}[`, `].${sub.key}`)}, ${JSON.stringify(bindingKind(sub.type))}),`,\n );\n }\n return `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n}\n\n/** Render the binding for one field at `path`, recursing into group zones. */\nfunction fieldBinding(\n field: ContentModelField,\n prefix: string,\n indent: string,\n): string {\n const path = prefix ? `${prefix}.${field.key}` : field.key;\n const name = propName(field.key);\n\n if (field.type !== \"array\") {\n return `${indent}${name}: bcmsField(${JSON.stringify(path)}, ${JSON.stringify(bindingKind(field.type))}),`;\n }\n\n const zones = field.config?.zones;\n // Group (non-repeatable) → a nested object of dotted-path leaf bindings.\n if (zones?.nonRepeatable?.length) {\n const body = zones.nonRepeatable\n .map((child) => fieldBinding(child, path, `${indent} `))\n .join(\"\\n\");\n return `${indent}${name}: {\\n${body}\\n${indent}},`;\n }\n // Repeater → `$(i)` + scalar sub-field accessors.\n if (zones?.repeatable?.fields?.length) {\n return `${indent}${name}: ${repeaterBinding(zones.repeatable.fields, path, indent)},`;\n }\n // Primitive list (`config.itemType` or bare) → `$(i)` + synthetic `value(i)`.\n const lines = [\n `${indent} $: (i: number) => bcmsField(${indexedPath(`${path}[`, \"]\")}, \"array\"),`,\n `${indent} value: (i: number) => bcmsField(${indexedPath(`${path}[`, \"].value\")}, \"text\"),`,\n ];\n return `${indent}${name}: {\\n${lines.join(\"\\n\")}\\n${indent}},`;\n}\n\n/** Render the binding entries for one model's fields (field order preserved). */\nfunction fieldsToBindings(fields: ContentModelField[], indent: string): string {\n return fields.map((field) => fieldBinding(field, \"\", indent)).join(\"\\n\");\n}\n\n/** The self-contained runtime emitted once at the top of every bindings file. */\nconst PREAMBLE = `/**\n * True when this site is built for Live Preview annotation. Set \\`BCMS_ANNOTATE=1\\`\n * in the preview build only; unset (the default) ships zero binding attributes.\n * Read defensively so the module is safe in any runtime (browser, Node, edge).\n */\nconst BCMS_ANNOTATE: boolean = (() => {\n try {\n const v = (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env?.BCMS_ANNOTATE;\n return v != null && v !== \"\" && v !== \"0\" && v !== \"false\";\n } catch {\n return false;\n }\n})();\n\n/**\n * Binding attributes for a CMS-bound element. Spread onto the element that renders a\n * field: \\`<h1 {...bcmsField(\"title\", \"text\")}>\\`. Returns \\`{}\\` unless BCMS_ANNOTATE\n * is set, so production markup is untouched.\n */\nexport function bcmsField(path: string, kind: string): Record<string, string> {\n return BCMS_ANNOTATE ? { \"data-bcms-field\": path, \"data-bcms-kind\": kind } : {};\n}\n`;\n\n/**\n * Generate the Live Preview bindings module from a set of content models.\n * Deterministic: models are sorted by slug; field order is preserved as authored.\n */\nexport function generateBindings(\n models: GeneratableModel[],\n opts: GenerateOptions = {},\n): string {\n const version = opts.version ?? \"0.1.0\";\n // Code-unit sort (NOT localeCompare) so output is byte-identical on every machine.\n const sorted = [...models].sort((a, b) =>\n a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0,\n );\n\n const header = `// ⚠️ AUTO-GENERATED by @bettercms-ai/codegen v${version} — DO NOT EDIT.\n// Live Preview field bindings. Regenerate with: npx @bettercms-ai/codegen --bindings-out <path>\n// Spread these onto the elements that render your content; they emit\n// data-bcms-field/data-bcms-kind only when the site is built with BCMS_ANNOTATE set.\n${opts.bannerComment ? `// ${opts.bannerComment}\\n` : \"\"}`;\n\n const entries = sorted.map((model) => {\n const body = model.fields.length\n ? `\\n${fieldsToBindings(model.fields, \" \")}\\n `\n : \"\";\n return ` ${JSON.stringify(model.slug)}: {${body}},`;\n });\n\n const bcms = `/**\n * Field bindings keyed by model slug. Spread a binding onto the element that renders\n * that field. Arrays expose \\`$(i)\\` for the item element and one accessor per\n * (one-level) sub-field; primitive arrays expose \\`value(i)\\` for the item's scalar.\n */\nexport const bcms = {\n${entries.join(\"\\n\") || \" // (no models defined yet)\"}\n} as const;`;\n\n return [header, PREAMBLE, bcms, \"\"].join(\"\\n\");\n}\n","/**\n * @bettercms-ai/codegen — schema → typed React render components generator.\n *\n * Companion to {@link generateTypes} (types) and {@link generateBindings} (Live\n * Preview attributes). This emits a small, self-contained `.tsx` module with two\n * components that render the canonical Delivery field shapes CORRECTLY, so authors\n * never hand-roll the rendering that produces the classic bugs:\n *\n * - <RichText> renders the server-sanitized `html` via `dangerouslySetInnerHTML`,\n * instead of interpolating the value as a JSX child (which React escapes, so the\n * page shows literal `<p>…</p>` tags — the #6 escaped-richtext bug).\n * - <Image> reads the normalized image object's `.url`/`.altText`, instead of\n * treating the object as a string.\n *\n * The emitted module is intentionally generic (not per-model) and dependency-free\n * beyond React, so it is a drop-in: point codegen at a path and import the two\n * components. It is deterministic (no clock, no I/O) like the sibling generators.\n *\n * Security: `html` is the Delivery API's server-rendered, DOMPurify-sanitized output\n * (see the RichText type docs). `<RichText>` injects exactly that field. If a caller\n * passes HTML from another, untrusted source they must sanitize it themselves.\n */\n\nimport type { GenerateOptions } from \"./generate.js\";\n\n/**\n * Generate the `bettercms.components.tsx` module: typed `<RichText>` and `<Image>`\n * components for the canonical Delivery field shapes. Deterministic — same options\n * in, identical string out.\n */\nexport function generateComponents(opts: GenerateOptions = {}): string {\n const version = opts.version ?? \"0.1.0\";\n const header = `// ⚠️ AUTO-GENERATED by @bettercms-ai/codegen v${version} — DO NOT EDIT.\n// Regenerate with: npx @bettercms-ai/codegen --components-out <path>\n// Typed render components for BetterCMS field shapes. Use these instead of\n// hand-rendering richtext/image values — they render the canonical shapes correctly.\n${opts.bannerComment ? `// ${opts.bannerComment}\\n` : \"\"}`;\n\n const body = `import * as React from \"react\";\n\n/** Rich-text value from the Delivery API. \\`html\\` is server-rendered + sanitized. */\nexport type RichTextValue = {\n readonly format: string;\n readonly value: unknown;\n readonly html?: string;\n};\n\n/** Normalized image/media value from the Delivery API. */\nexport interface BetterCMSImageValue {\n readonly url: string;\n readonly altText?: string | null;\n readonly width?: number;\n readonly height?: number;\n}\n\ntype RichTextProps = {\n /** The richtext field value (\\`entry.fields.someRichText\\`). */\n field?: RichTextValue | null;\n /** Element/component to render as. Default: \\`\"div\"\\`. */\n as?: React.ElementType;\n} & Omit<React.HTMLAttributes<HTMLElement>, \"dangerouslySetInnerHTML\" | \"children\">;\n\n/**\n * Render a richtext field as HTML. Uses the server-sanitized \\`html\\` via\n * \\`dangerouslySetInnerHTML\\` — NEVER interpolate a richtext value as a JSX child\n * (React escapes it, so the page shows literal tags). Renders nothing when unset.\n */\nexport function RichText({ field, as: Tag = \"div\", ...rest }: RichTextProps) {\n if (!field || !field.html) return null;\n return <Tag {...rest} dangerouslySetInnerHTML={{ __html: field.html }} />;\n}\n\ntype ImageProps = {\n /** The image field value (\\`entry.fields.someImage\\`). */\n field?: BetterCMSImageValue | null;\n /** Alt text override; defaults to the field's \\`altText\\`, then \\`\"\"\\`. */\n alt?: string;\n} & Omit<React.ImgHTMLAttributes<HTMLImageElement>, \"src\">;\n\n/**\n * Render an image field as an \\`<img>\\` from its normalized \\`.url\\`/\\`.altText\\`.\n * Renders nothing when unset. Pass \\`alt\\` to override the stored alt text.\n */\nexport function Image({ field, alt, ...rest }: ImageProps) {\n if (!field || !field.url) return null;\n return (\n <img\n src={field.url}\n alt={alt ?? field.altText ?? \"\"}\n width={field.width}\n height={field.height}\n {...rest}\n />\n );\n}\n`;\n\n return [header, body].join(\"\\n\");\n}\n","/**\n * Fetches content models from the BetterCMS Management API so the CLI can generate\n * types against a live project. Kept dependency-free (plain fetch) so the generated\n * artifact and this fetcher can run anywhere — a GitHub Action, a postinstall, a script.\n */\n\nimport type { GeneratableModel } from \"./generate.js\";\n\nexport interface FetchModelsOptions {\n /** Management API base, e.g. \"https://api.bettercms.ai/api/v1\". */\n apiUrl: string;\n /** A management-scoped key (content:manage) or device-minted token. */\n apiKey: string;\n /** Optional fetch override (testing / custom runtime). */\n fetchImpl?: typeof fetch;\n}\n\ninterface ManagedModelRow {\n slug: string;\n name?: string;\n description?: string | null;\n fields: GeneratableModel[\"fields\"];\n}\n\n/**\n * GET /management/content/models — returns the project's models (the key is\n * project-scoped server-side, so this is exactly the schema for this site).\n */\nexport async function fetchModels(\n opts: FetchModelsOptions,\n): Promise<GeneratableModel[]> {\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n const base = opts.apiUrl.replace(/\\/+$/, \"\");\n const url = `${base}/management/content/models`;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n // No Content-Type: this is a bodyless GET; the header is incorrect here and\n // strict edge runtimes/proxies may reject it.\n headers: { Authorization: `Bearer ${opts.apiKey}`, Accept: \"application/json\" },\n });\n } catch (err) {\n throw new Error(\n `Could not reach the BetterCMS Management API at ${url}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n\n if (!res.ok) {\n const hint =\n res.status === 401 || res.status === 403\n ? \" — check your management API key (it must have the content:manage scope).\"\n : \"\";\n throw new Error(`Management API returned ${res.status} ${res.statusText}${hint}`);\n }\n\n const body = (await res.json()) as { data?: ManagedModelRow[] };\n const rows = body.data ?? [];\n return rows.map((r) => ({\n slug: r.slug,\n name: r.name,\n description: r.description ?? null,\n fields: r.fields ?? [],\n }));\n}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ACtEA,eAAsB,YACpB,MAC6B;AAC7B,QAAM,UAAU,KAAK,aAAa,WAAW;AAC7C,QAAM,OAAO,KAAK,OAAO,QAAQ,QAAQ,EAAE;AAC3C,QAAM,MAAM,GAAG,IAAI;AAEnB,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,QAAQ,KAAK;AAAA;AAAA;AAAA,MAGvB,SAAS,EAAE,eAAe,UAAU,KAAK,MAAM,IAAI,QAAQ,mBAAmB;AAAA,IAChF,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,UAAM,IAAI;AAAA,MACR,mDAAmD,GAAG,KACpD,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CACjD;AAAA,IACF;AAAA,EACF;AAEA,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,OACJ,IAAI,WAAW,OAAO,IAAI,WAAW,MACjC,mFACA;AACN,UAAM,IAAI,MAAM,2BAA2B,IAAI,MAAM,IAAI,IAAI,UAAU,GAAG,IAAI,EAAE;AAAA,EAClF;AAEA,QAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,QAAM,OAAO,KAAK,QAAQ,CAAC;AAC3B,SAAO,KAAK,IAAI,CAAC,OAAO;AAAA,IACtB,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,IACR,aAAa,EAAE,eAAe;AAAA,IAC9B,QAAQ,EAAE,UAAU,CAAC;AAAA,EACvB,EAAE;AACJ;","names":["VALID_IDENT","propName","PREAMBLE"]}
|
|
1
|
+
{"version":3,"sources":["../src/generate.ts","../src/bindings.ts","../src/components.ts","../src/fetch-models.ts"],"sourcesContent":["/**\n * @bettercms-ai/codegen — schema → TypeScript generator (the single source of truth).\n *\n * Both the dashboard schema builder and the MCP `create_model`/`add_field` tools write\n * the SAME `content_models.fields` (an array of `ContentModelField`). This generator maps\n * that one array into TypeScript. Because there is exactly one schema representation, the\n * generated types can never drift from the editor or the agent — they are the same source.\n *\n * Pure + deterministic: same models in → identical string out (stable ordering, no clock,\n * no I/O). That makes it trivially testable and safe to commit + diff in a customer repo.\n */\n\nimport type { ContentModelField, ContentModelFieldType } from \"@bettercms-ai/types\";\n\n/** Minimal model shape the generator needs — a subset of the Management API model row. */\nexport interface GeneratableModel {\n /** Machine-safe slug, e.g. \"blog\" or \"case-study\". Used for the schema-map key. */\n slug: string;\n /** Human name, used only for the JSDoc header. */\n name?: string;\n description?: string | null;\n fields: ContentModelField[];\n}\n\nexport interface GenerateOptions {\n /** Generator version stamped into the header (defaults to the package version). */\n version?: string;\n /** Override the banner timestamp source — omitted by default so output is deterministic. */\n bannerComment?: string;\n}\n\n/** Helper types emitted once at the top of every generated file (self-contained, zero-dep). */\nconst PREAMBLE = `/**\n * Rich-text field value returned by the Delivery API.\n *\n * - \\`format\\`/\\`value\\`: the portable, editor-agnostic payload (Lexical EditorState) —\n * render it with your editor's serializer for full fidelity.\n * - \\`html\\`: server-rendered, sanitized HTML (computed render-on-write). Present on\n * Delivery reads; the simplest path for non-React consumers — safe to inject directly\n * (e.g. \\`dangerouslySetInnerHTML\\`). Optional: legacy/un-normalized values may omit it.\n *\n * The \\`{ format, value }\\` contract is unchanged; \\`html\\` is additive.\n */\nexport type RichText = {\n readonly format: string;\n readonly value: unknown;\n readonly html?: string;\n};\n\n/**\n * A field that may arrive as EITHER shape.\n *\n * Switching a field between \\`text\\` and \\`richtext\\` in the CMS switches what Delivery\n * returns for it — a bare string becomes \\`{ format, value, html }\\`. Type author-editable\n * text with this and read it through \\`plain()\\`/\\`rich()\\` below, and that switch stops being\n * a site-breaking change. Interpolating the value directly renders \\`[object Object]\\`.\n */\nexport type TextOrRich = string | RichText | null | undefined;\n\n/** True when the value is a rich-text envelope rather than a bare string. */\nexport function isRichText(value: unknown): value is RichText {\n return (\n typeof value === \"object\" && value !== null && !Array.isArray(value) &&\n (\"html\" in value || \"format\" in value)\n );\n}\n\n/** Plain text for attribute contexts — \\`<title>\\`, meta description, JSON-LD, \\`alt\\`. */\nexport function plain(value: TextOrRich): string {\n if (typeof value === \"string\") return value;\n if (!isRichText(value) || typeof value.html !== \"string\") return \"\";\n return decodeEntities(value.html.replace(/<[^>]+>/g, \"\")).trim();\n}\n\n/**\n * Renderable HTML, for \\`set:html\\` / \\`dangerouslySetInnerHTML\\`. Rich text keeps its inline\n * marks (the server sanitizes \\`html\\` on write); a bare string is escaped, so a plain field\n * can never inject markup. A LONE wrapping block is unwrapped — a field switched from\n * \\`text\\` stores \\`<p>…</p>\\`, and \\`<h1><p>…</p></h1>\\` is invalid HTML (the parser closes the\n * heading early, dropping the text out of it). Real block structure is left alone.\n */\nexport function rich(value: TextOrRich, fallback = \"\"): string {\n const html = (\n typeof value === \"string\" ? escapeHtml(value) : isRichText(value) ? (value.html ?? \"\") : \"\"\n ).trim();\n return html ? unwrapLoneBlock(html) : escapeHtml(fallback);\n}\n\nfunction unwrapLoneBlock(html: string): string {\n const m = html.match(/^<(p|div|h[1-6])(?:\\\\s[^>]*)?>([\\\\s\\\\S]*)<\\\\/\\\\1>$/i);\n return m && !new RegExp(\\`</\\${m[1]}>\\`, \"i\").test(m[2]) ? m[2] : html;\n}\n\nfunction escapeHtml(s: string): string {\n return s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n}\n\nfunction decodeEntities(s: string): string {\n return s\n .replace(/</g, \"<\").replace(/>/g, \">\").replace(/"/g, '\"')\n .replace(/�?39;/g, \"'\").replace(/ /g, \" \").replace(/&/g, \"&\");\n}\n\n/**\n * Image / media field value as stored and returned verbatim by the Delivery API\n * (server-normalized on write to the canonical shape). \\`url\\` is always present; an\n * unresolved/external value may carry only \\`url\\`. \\`altText\\` is the accessibility text\n * for \\`<img alt>\\`.\n */\nexport interface BetterCMSImage {\n readonly id?: string;\n readonly url: string;\n readonly name?: string;\n readonly altText?: string | null;\n readonly width?: number;\n readonly height?: number;\n}\n\n/**\n * A component slot's value, as stored and delivered.\n *\n * \\`componentId\\` points at a component definition; \\`overrides\\` are the author's values,\n * keyed by the component's declared prop keys.\n *\n * \\`resolved\\` is the SNAPSHOT: at publish time the component is resolved (its block tree\n * with the overrides applied) and frozen onto the published value. That is why editing a\n * component does not silently rewrite entries that were already published — a published\n * entry carries what it was published with until it is published again.\n *\n * Read \\`resolved\\` when it is there; it is absent on draft-perspective reads, where you\n * should resolve \\`componentId\\` yourself against the components endpoint.\n */\nexport interface BetterCMSComponentRef {\n readonly componentId: string;\n readonly overrides?: Readonly<Record<string, unknown>>;\n readonly resolved?: readonly unknown[];\n}\n\n/**\n * Delivery envelope around a model's typed \\`data\\`. \\`getEntry\\`/\\`listEntries\\` in the\n * Next adapter return this shape, with \\`fields\\` typed by the model.\n */\nexport interface BetterCMSEntry<TFields> {\n readonly slug: string;\n readonly status: \"draft\" | \"published\";\n readonly fields: TFields;\n readonly updatedAt: string;\n}\n`;\n\n/** PascalCase an identifier from a slug: \"case-study\" → \"CaseStudy\". */\nfunction pascalCase(slug: string): string {\n const parts = slug.split(/[-_\\s]+/).filter(Boolean);\n const pascal = parts\n .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n .join(\"\");\n // Guard against an identifier that starts with a digit (invalid TS type name).\n return /^[0-9]/.test(pascal) ? `Model${pascal}` : pascal || \"Model\";\n}\n\n/**\n * Make a string safe to embed inside a `/** ... */` JSDoc comment. A field label\n * (free-text, author/agent-controlled) could contain `*/` — which closes the comment\n * early and injects the remainder as code — or a newline, which breaks the single-line\n * comment. Both are neutralized here. Without this, hostile content produces non-\n * compiling (or worse, code-injected) output.\n */\nfunction escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"* /\").replace(/[\\r\\n]+/g, \" \").trim();\n}\n\nconst VALID_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * Render a field key as a TS property name. Field keys are author/agent-controlled and\n * not guaranteed to be valid identifiers (e.g. \"my-field\", \"1title\", \"\"), so anything\n * that isn't a bare identifier is emitted as a quoted property name — always valid TS.\n */\nfunction propName(key: string): string {\n return VALID_IDENT.test(key) ? key : JSON.stringify(key);\n}\n\n/** A scalar/primitive field maps to a TS type expression (no nesting). */\nfunction scalarType(field: ContentModelField): string {\n const t: ContentModelFieldType = field.type;\n switch (t) {\n case \"text\":\n return \"string\";\n case \"richtext\":\n return \"RichText\";\n case \"image\":\n return \"BetterCMSImage\";\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"date\":\n case \"datetime\":\n return \"string\"; // ISO 8601\n case \"select\": {\n const opts = field.options?.filter((o) => typeof o === \"string\") ?? [];\n return opts.length > 0\n ? opts.map((o) => JSON.stringify(o)).join(\" | \")\n : \"string\";\n }\n case \"reference\":\n return \"string\"; // referenced entry id\n // Both spellings are live (see ContentModelFieldType). Template- and Webflow-seeded\n // models carry the camelCase one; until it was handled here it fell through to the\n // exhaustiveness default, so generated types for every template-created collection\n // typed this field as `unknown` instead of `string[]`.\n case \"multi-reference\":\n case \"multiReference\":\n return \"string[]\"; // referenced entry ids\n case \"array\": {\n // Zoned arrays (config.zones) are expanded by fieldsToBody before reaching here;\n // this branch handles only the primitive list form (config.itemType).\n const itemType = field.config?.itemType ?? \"text\";\n const inner =\n itemType === \"number\" ? \"number\" : \"string\"; // text | date → string\n return `${inner}[]`;\n }\n // ── Builder scalars ────────────────────────────────────────────────────────\n // All string-shaped on the wire; each is value-validated on write (see\n // src/lib/content/reference-validation.ts), so the generated type is the\n // narrowest thing that is actually true of the stored value.\n case \"longtext\":\n case \"slug\":\n case \"email\":\n case \"phone\":\n case \"link\":\n case \"color\":\n return \"string\";\n case \"json\":\n // Arbitrary author-supplied JSON — object or parseable string. `unknown`\n // forces the consumer to narrow, which is correct: we genuinely don't know.\n return \"unknown\";\n case \"component-ref\":\n // The delivered value is the reference plus, on published reads, its frozen tree.\n return \"BetterCMSComponentRef\";\n case \"file\":\n // The file envelope is the image envelope minus the pixel dimensions\n // ({ url, name?, ... }), and BetterCMSImage's width/height are optional — so\n // every file value is already a valid BetterCMSImage. Reused rather than\n // emitting a second near-identical public type into every generated SDK.\n return \"BetterCMSImage\";\n default: {\n // Exhaustiveness guard: if a new field type is added to the union and not\n // mapped here, this line becomes a compile error in the codegen build.\n const _exhaustive: never = t;\n return \"unknown\";\n }\n }\n}\n\n/**\n * Render the TS type for a zoned `array` field: an object with optional\n * `nonRepeatable` (a fixed block) and/or `repeatable` (a list of blocks). Recurses\n * through zone fields, so a zone field that is itself a zoned `array` nests naturally.\n */\nfunction arrayZoneType(field: ContentModelField, indent: string): string {\n const zones = field.config?.zones;\n const parts: string[] = [];\n if (zones?.nonRepeatable?.length) {\n const nested = fieldsToBody(zones.nonRepeatable, indent + \" \");\n parts.push(`${indent} readonly nonRepeatable?: {\\n${nested}\\n${indent} };`);\n }\n if (zones?.repeatable?.fields?.length) {\n const nested = fieldsToBody(zones.repeatable.fields, indent + \" \");\n parts.push(`${indent} readonly repeatable?: Array<{\\n${nested}\\n${indent} }>;`);\n }\n if (parts.length === 0) return \"Record<string, unknown>\"; // zoned array with no fields yet\n return `{\\n${parts.join(\"\\n\")}\\n${indent}}`;\n}\n\n/** Render the body of an object type from a field list, recursing into zones. */\nfunction fieldsToBody(fields: ContentModelField[], indent: string): string {\n const lines: string[] = [];\n for (const field of fields) {\n const optional = field.required ? \"\" : \"?\";\n let typeExpr: string;\n\n if (field.type === \"array\" && field.config?.zones) {\n typeExpr = arrayZoneType(field, indent);\n } else {\n typeExpr = scalarType(field);\n }\n\n const safeLabel = field.label ? escapeJsDoc(field.label) : \"\";\n if (safeLabel && safeLabel !== field.key) {\n lines.push(`${indent}/** ${safeLabel} */`);\n }\n lines.push(`${indent}readonly ${propName(field.key)}${optional}: ${typeExpr};`);\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate a complete `.ts` module from a set of content models.\n * Deterministic: models are sorted by slug; field order is preserved as authored.\n */\nexport function generateTypes(\n models: GeneratableModel[],\n opts: GenerateOptions = {},\n): string {\n const version = opts.version ?? \"0.1.0\";\n // Code-unit sort (NOT localeCompare): locale/ICU-independent so the generated\n // file is byte-identical on every machine — committed output diffs cleanly.\n const sorted = [...models].sort((a, b) =>\n a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0,\n );\n\n const header = `// ⚠️ AUTO-GENERATED by @bettercms-ai/codegen v${version} — DO NOT EDIT.\n// Regenerate with: npx @bettercms-ai/codegen\n// Source of truth: your BetterCMS content models (the same schema the dashboard\n// builder and the MCP tools write). Re-run codegen after any schema change.\n${opts.bannerComment ? `// ${opts.bannerComment}\\n` : \"\"}`;\n\n const interfaces: string[] = [];\n const mapEntries: string[] = [];\n // Different slugs can PascalCase to the same base name (e.g. \"case-study\" and\n // \"case_study\" → \"CaseStudy\"). Emitting two identical interfaces would silently\n // declaration-merge into one wrong type, so disambiguate with a numeric suffix.\n const usedNames = new Set<string>();\n\n for (const model of sorted) {\n const base = `${pascalCase(model.slug)}Fields`;\n let typeName = base;\n for (let n = 2; usedNames.has(typeName); n++) typeName = `${base}_${n}`;\n usedNames.add(typeName);\n\n const name = model.name ? escapeJsDoc(model.name) : \"\";\n const desc = model.description ? escapeJsDoc(model.description) : \"\";\n const doc = name\n ? `/**\\n * ${name}${desc ? ` — ${desc}` : \"\"}\\n * Model slug: \\`${model.slug}\\`\\n */\\n`\n : \"\";\n const body = model.fields.length\n ? fieldsToBody(model.fields, \" \")\n : \" // (no fields defined yet)\";\n interfaces.push(`${doc}export interface ${typeName} {\\n${body}\\n}`);\n mapEntries.push(` readonly ${JSON.stringify(model.slug)}: ${typeName};`);\n }\n\n const schemaMap = `/**\n * Registry mapping each model slug to its typed fields. The Next adapter uses this to\n * type \\`getEntry(\"blog\", ...)\\` by slug — autocomplete and exhaustiveness for free.\n */\nexport interface BetterCMSSchema {\n${mapEntries.join(\"\\n\") || \" // (no models defined yet)\"}\n}\n\n/** Union of all model slugs. */\nexport type BetterCMSModelSlug = keyof BetterCMSSchema;`;\n\n return [header, PREAMBLE, interfaces.join(\"\\n\\n\"), schemaMap, \"\"].join(\"\\n\");\n}\n","/**\n * @bettercms-ai/codegen — schema → Live Preview binding helper generator.\n *\n * Companion to {@link generateTypes}. Where that emits the *types*, this emits a\n * tiny, schema-derived runtime that stamps `data-bcms-field` / `data-bcms-kind`\n * attributes onto the elements a site author binds to CMS content. Those\n * attributes are what the dashboard's Live Preview editor reads to turn the real,\n * running site into an editable canvas (the parent maps `data-bcms-field` → its\n * internal `data-node-id` on frame load).\n *\n * Why a helper and not auto-injection: BetterCMS never renders the customer's DOM\n * — the site does. So binding is opt-in per element via a spread:\n *\n * import { bcms } from \"./bettercms.bindings.generated\";\n *\n * <h1 {...bcms.blog.title}>{entry.fields.title}</h1> // scalar\n * <li {...bcms.blog.tags.value(i)}>{tag}</li> // primitive-array item\n * <article {...bcms.blog.features.$(i)}> // array item root\n * <h3 {...bcms.blog.features.label(i)}>{f.label}</h3> // array item sub-field\n * </article>\n *\n * The attributes only appear when the site is built with `BCMS_ANNOTATE` set\n * (preview builds); a normal production build ships zero extra attributes, because\n * `bcmsField` returns `{}`. Same generated file, both builds — no separate mode.\n *\n * Pure + deterministic, exactly like the type generator: same models in → identical\n * string out (slug-sorted, field order preserved, no clock, no I/O). Field keys are\n * author/agent-controlled, so every embedded key is emitted as an escaped string\n * literal (never interpolated into code) — hostile input can't break the output.\n *\n * Grammar — mirrors what the editor's `fieldPathToNodeId` resolves:\n * `title` · `hero.heroTitle` · `hero.primaryCta.label` (group leaves, any depth)\n * `features[0]` · `features[0].label` · `intro.facts[0].label` (repeaters, one index)\n * Group (non-repeatable) zones recurse into nested binding objects; a repeater is an\n * object with `$(i)` (item root) + one accessor per scalar sub-field. Arrays nested\n * inside a repeater item (a second index) are still beyond what the editor can\n * address, so they are intentionally omitted rather than emitted as dead paths.\n */\n\nimport type { ContentModelField, ContentModelFieldType } from \"@bettercms-ai/types\";\nimport type { GeneratableModel, GenerateOptions } from \"./generate.js\";\n\nconst VALID_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * Render a field key as an object property name. Keys aren't guaranteed to be valid\n * identifiers (e.g. \"my-field\", \"1title\"), so anything that isn't a bare identifier\n * is quoted — always valid TS. (Mirrors the same helper in `generate.ts`.)\n */\nfunction propName(key: string): string {\n return VALID_IDENT.test(key) ? key : JSON.stringify(key);\n}\n\n/**\n * The kind label written to `data-bcms-kind`, mapped to the editor's closed field-type\n * set (matches the dashboard adapter's `toEditorFieldType`): API-only types that have\n * no on-canvas control collapse to \"text\". Informational today — the editor derives the\n * authoritative kind from the loaded model — but kept truthful for debugging/forward use.\n */\nfunction bindingKind(t: ContentModelFieldType): string {\n switch (t) {\n case \"text\":\n case \"richtext\":\n case \"image\":\n case \"boolean\":\n case \"number\":\n case \"select\":\n case \"array\":\n return t;\n // reference / multi-reference / date / datetime → plain text in the editor v1.\n default:\n return \"text\";\n }\n}\n\n/**\n * Build a runtime path expression for an array element: a string literal split around\n * the index so it concatenates at call time. Both halves are JSON-escaped, so an\n * author-controlled key can never inject code. e.g. (\"features[\", \"].label\") →\n * `\"features[\" + i + \"].label\"`.\n */\nfunction indexedPath(prefix: string, suffix: string): string {\n return `${JSON.stringify(prefix)} + i + ${JSON.stringify(suffix)}`;\n}\n\n/** Render a repeater binding object: `$(i)` item root + one accessor per scalar\n * sub-field. `path` is the repeater's full (possibly dotted) field path. */\nfunction repeaterBinding(\n itemFields: ContentModelField[],\n path: string,\n indent: string,\n): string {\n const lines: string[] = [\n `${indent} $: (i: number) => bcmsField(${indexedPath(`${path}[`, \"]\")}, \"array\"),`,\n ];\n for (const sub of itemFields) {\n // A sub-field that is itself an array would need a second index the editor\n // can't address yet — skip it rather than emit a path that won't bind.\n if (sub.type === \"array\") continue;\n lines.push(\n `${indent} ${propName(sub.key)}: (i: number) => bcmsField(${indexedPath(`${path}[`, `].${sub.key}`)}, ${JSON.stringify(bindingKind(sub.type))}),`,\n );\n }\n return `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n}\n\n/** Render the binding for one field at `path`, recursing into group zones. */\nfunction fieldBinding(\n field: ContentModelField,\n prefix: string,\n indent: string,\n): string {\n const path = prefix ? `${prefix}.${field.key}` : field.key;\n const name = propName(field.key);\n\n if (field.type !== \"array\") {\n return `${indent}${name}: bcmsField(${JSON.stringify(path)}, ${JSON.stringify(bindingKind(field.type))}),`;\n }\n\n const zones = field.config?.zones;\n // Group (non-repeatable) → a nested object of dotted-path leaf bindings.\n if (zones?.nonRepeatable?.length) {\n const body = zones.nonRepeatable\n .map((child) => fieldBinding(child, path, `${indent} `))\n .join(\"\\n\");\n return `${indent}${name}: {\\n${body}\\n${indent}},`;\n }\n // Repeater → `$(i)` + scalar sub-field accessors.\n if (zones?.repeatable?.fields?.length) {\n return `${indent}${name}: ${repeaterBinding(zones.repeatable.fields, path, indent)},`;\n }\n // Primitive list (`config.itemType` or bare) → `$(i)` + synthetic `value(i)`.\n const lines = [\n `${indent} $: (i: number) => bcmsField(${indexedPath(`${path}[`, \"]\")}, \"array\"),`,\n `${indent} value: (i: number) => bcmsField(${indexedPath(`${path}[`, \"].value\")}, \"text\"),`,\n ];\n return `${indent}${name}: {\\n${lines.join(\"\\n\")}\\n${indent}},`;\n}\n\n/** Render the binding entries for one model's fields (field order preserved). */\nfunction fieldsToBindings(fields: ContentModelField[], indent: string): string {\n return fields.map((field) => fieldBinding(field, \"\", indent)).join(\"\\n\");\n}\n\n/** The self-contained runtime emitted once at the top of every bindings file. */\nconst PREAMBLE = `/**\n * True when this site is built for Live Preview annotation. Set \\`BCMS_ANNOTATE=1\\`\n * in the preview build only; unset (the default) ships zero binding attributes.\n * Read defensively so the module is safe in any runtime (browser, Node, edge).\n */\nconst BCMS_ANNOTATE: boolean = (() => {\n try {\n const v = (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env?.BCMS_ANNOTATE;\n return v != null && v !== \"\" && v !== \"0\" && v !== \"false\";\n } catch {\n return false;\n }\n})();\n\n/**\n * Binding attributes for a CMS-bound element. Spread onto the element that renders a\n * field: \\`<h1 {...bcmsField(\"title\", \"text\")}>\\`. Returns \\`{}\\` unless BCMS_ANNOTATE\n * is set, so production markup is untouched.\n */\nexport function bcmsField(path: string, kind: string): Record<string, string> {\n return BCMS_ANNOTATE ? { \"data-bcms-field\": path, \"data-bcms-kind\": kind } : {};\n}\n`;\n\n/**\n * Generate the Live Preview bindings module from a set of content models.\n * Deterministic: models are sorted by slug; field order is preserved as authored.\n */\nexport function generateBindings(\n models: GeneratableModel[],\n opts: GenerateOptions = {},\n): string {\n const version = opts.version ?? \"0.1.0\";\n // Code-unit sort (NOT localeCompare) so output is byte-identical on every machine.\n const sorted = [...models].sort((a, b) =>\n a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0,\n );\n\n const header = `// ⚠️ AUTO-GENERATED by @bettercms-ai/codegen v${version} — DO NOT EDIT.\n// Live Preview field bindings. Regenerate with: npx @bettercms-ai/codegen --bindings-out <path>\n// Spread these onto the elements that render your content; they emit\n// data-bcms-field/data-bcms-kind only when the site is built with BCMS_ANNOTATE set.\n${opts.bannerComment ? `// ${opts.bannerComment}\\n` : \"\"}`;\n\n const entries = sorted.map((model) => {\n const body = model.fields.length\n ? `\\n${fieldsToBindings(model.fields, \" \")}\\n `\n : \"\";\n return ` ${JSON.stringify(model.slug)}: {${body}},`;\n });\n\n const bcms = `/**\n * Field bindings keyed by model slug. Spread a binding onto the element that renders\n * that field. Arrays expose \\`$(i)\\` for the item element and one accessor per\n * (one-level) sub-field; primitive arrays expose \\`value(i)\\` for the item's scalar.\n */\nexport const bcms = {\n${entries.join(\"\\n\") || \" // (no models defined yet)\"}\n} as const;`;\n\n return [header, PREAMBLE, bcms, \"\"].join(\"\\n\");\n}\n","/**\n * @bettercms-ai/codegen — schema → typed React render components generator.\n *\n * Companion to {@link generateTypes} (types) and {@link generateBindings} (Live\n * Preview attributes). This emits a small, self-contained `.tsx` module with two\n * components that render the canonical Delivery field shapes CORRECTLY, so authors\n * never hand-roll the rendering that produces the classic bugs:\n *\n * - <RichText> renders the server-sanitized `html` via `dangerouslySetInnerHTML`,\n * instead of interpolating the value as a JSX child (which React escapes, so the\n * page shows literal `<p>…</p>` tags — the #6 escaped-richtext bug).\n * - <Image> reads the normalized image object's `.url`/`.altText`, instead of\n * treating the object as a string.\n *\n * The emitted module is intentionally generic (not per-model) and dependency-free\n * beyond React, so it is a drop-in: point codegen at a path and import the two\n * components. It is deterministic (no clock, no I/O) like the sibling generators.\n *\n * Security: `html` is the Delivery API's server-rendered, DOMPurify-sanitized output\n * (see the RichText type docs). `<RichText>` injects exactly that field. If a caller\n * passes HTML from another, untrusted source they must sanitize it themselves.\n */\n\nimport type { GenerateOptions } from \"./generate.js\";\n\n/**\n * Generate the `bettercms.components.tsx` module: typed `<RichText>` and `<Image>`\n * components for the canonical Delivery field shapes. Deterministic — same options\n * in, identical string out.\n */\nexport function generateComponents(opts: GenerateOptions = {}): string {\n const version = opts.version ?? \"0.1.0\";\n const header = `// ⚠️ AUTO-GENERATED by @bettercms-ai/codegen v${version} — DO NOT EDIT.\n// Regenerate with: npx @bettercms-ai/codegen --components-out <path>\n// Typed render components for BetterCMS field shapes. Use these instead of\n// hand-rendering richtext/image values — they render the canonical shapes correctly.\n${opts.bannerComment ? `// ${opts.bannerComment}\\n` : \"\"}`;\n\n const body = `import * as React from \"react\";\n\n/** Rich-text value from the Delivery API. \\`html\\` is server-rendered + sanitized. */\nexport type RichTextValue = {\n readonly format: string;\n readonly value: unknown;\n readonly html?: string;\n};\n\n/** Normalized image/media value from the Delivery API. */\nexport interface BetterCMSImageValue {\n readonly url: string;\n readonly altText?: string | null;\n readonly width?: number;\n readonly height?: number;\n}\n\ntype RichTextProps = {\n /** The richtext field value (\\`entry.fields.someRichText\\`). */\n field?: RichTextValue | null;\n /** Element/component to render as. Default: \\`\"div\"\\`. */\n as?: React.ElementType;\n} & Omit<React.HTMLAttributes<HTMLElement>, \"dangerouslySetInnerHTML\" | \"children\">;\n\n/**\n * Render a richtext field as HTML. Uses the server-sanitized \\`html\\` via\n * \\`dangerouslySetInnerHTML\\` — NEVER interpolate a richtext value as a JSX child\n * (React escapes it, so the page shows literal tags). Renders nothing when unset.\n */\nexport function RichText({ field, as: Tag = \"div\", ...rest }: RichTextProps) {\n if (!field || !field.html) return null;\n return <Tag {...rest} dangerouslySetInnerHTML={{ __html: field.html }} />;\n}\n\ntype ImageProps = {\n /** The image field value (\\`entry.fields.someImage\\`). */\n field?: BetterCMSImageValue | null;\n /** Alt text override; defaults to the field's \\`altText\\`, then \\`\"\"\\`. */\n alt?: string;\n} & Omit<React.ImgHTMLAttributes<HTMLImageElement>, \"src\">;\n\n/**\n * Render an image field as an \\`<img>\\` from its normalized \\`.url\\`/\\`.altText\\`.\n * Renders nothing when unset. Pass \\`alt\\` to override the stored alt text.\n */\nexport function Image({ field, alt, ...rest }: ImageProps) {\n if (!field || !field.url) return null;\n return (\n <img\n src={field.url}\n alt={alt ?? field.altText ?? \"\"}\n width={field.width}\n height={field.height}\n {...rest}\n />\n );\n}\n`;\n\n return [header, body].join(\"\\n\");\n}\n","/**\n * Fetches content models from the BetterCMS Management API so the CLI can generate\n * types against a live project. Kept dependency-free (plain fetch) so the generated\n * artifact and this fetcher can run anywhere — a GitHub Action, a postinstall, a script.\n */\n\nimport type { GeneratableModel } from \"./generate.js\";\n\nexport interface FetchModelsOptions {\n /** Management API base, e.g. \"https://api.bettercms.ai/api/v1\". */\n apiUrl: string;\n /** A management-scoped key (content:manage) or device-minted token. */\n apiKey: string;\n /** Optional fetch override (testing / custom runtime). */\n fetchImpl?: typeof fetch;\n}\n\ninterface ManagedModelRow {\n slug: string;\n name?: string;\n description?: string | null;\n fields: GeneratableModel[\"fields\"];\n}\n\n/**\n * GET /management/content/models — returns the project's models (the key is\n * project-scoped server-side, so this is exactly the schema for this site).\n */\nexport async function fetchModels(\n opts: FetchModelsOptions,\n): Promise<GeneratableModel[]> {\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n const base = opts.apiUrl.replace(/\\/+$/, \"\");\n const url = `${base}/management/content/models`;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n // No Content-Type: this is a bodyless GET; the header is incorrect here and\n // strict edge runtimes/proxies may reject it.\n headers: { Authorization: `Bearer ${opts.apiKey}`, Accept: \"application/json\" },\n });\n } catch (err) {\n throw new Error(\n `Could not reach the BetterCMS Management API at ${url}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n\n if (!res.ok) {\n const hint =\n res.status === 401 || res.status === 403\n ? \" — check your management API key (it must have the content:manage scope).\"\n : \"\";\n throw new Error(`Management API returned ${res.status} ${res.statusText}${hint}`);\n }\n\n const body = (await res.json()) as { data?: ManagedModelRow[] };\n const rows = body.data ?? [];\n return rows.map((r) => ({\n slug: r.slug,\n name: r.name,\n description: r.description ?? null,\n fields: r.fields ?? [],\n }));\n}\n"],"mappings":";AAgCA,IAAM,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuHjB,SAAS,WAAW,MAAsB;AACxC,QAAM,QAAQ,KAAK,MAAM,SAAS,E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,KAAK,OAAO,QAAQ,QAAQ,EAAE;AAC3C,QAAM,MAAM,GAAG,IAAI;AAEnB,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,QAAQ,KAAK;AAAA;AAAA;AAAA,MAGvB,SAAS,EAAE,eAAe,UAAU,KAAK,MAAM,IAAI,QAAQ,mBAAmB;AAAA,IAChF,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,UAAM,IAAI;AAAA,MACR,mDAAmD,GAAG,KACpD,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CACjD;AAAA,IACF;AAAA,EACF;AAEA,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,OACJ,IAAI,WAAW,OAAO,IAAI,WAAW,MACjC,mFACA;AACN,UAAM,IAAI,MAAM,2BAA2B,IAAI,MAAM,IAAI,IAAI,UAAU,GAAG,IAAI,EAAE;AAAA,EAClF;AAEA,QAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,QAAM,OAAO,KAAK,QAAQ,CAAC;AAC3B,SAAO,KAAK,IAAI,CAAC,OAAO;AAAA,IACtB,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,IACR,aAAa,EAAE,eAAe;AAAA,IAC9B,QAAQ,EAAE,UAAU,CAAC;AAAA,EACvB,EAAE;AACJ;","names":["VALID_IDENT","propName","PREAMBLE"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bettercms-ai/codegen",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Generate TypeScript types from your BetterCMS content schema — the single source of truth shared by the dashboard builder and the MCP tools.",
|
|
6
6
|
"bin": {
|
package/dist/cli.js
DELETED
|
@@ -1,501 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// src/cli.ts
|
|
4
|
-
import { writeFile, mkdir } from "fs/promises";
|
|
5
|
-
import { dirname, resolve } from "path";
|
|
6
|
-
|
|
7
|
-
// src/fetch-models.ts
|
|
8
|
-
async function fetchModels(opts) {
|
|
9
|
-
const doFetch = opts.fetchImpl ?? globalThis.fetch;
|
|
10
|
-
const base = opts.apiUrl.replace(/\/+$/, "");
|
|
11
|
-
const url = `${base}/management/content/models`;
|
|
12
|
-
let res;
|
|
13
|
-
try {
|
|
14
|
-
res = await doFetch(url, {
|
|
15
|
-
// No Content-Type: this is a bodyless GET; the header is incorrect here and
|
|
16
|
-
// strict edge runtimes/proxies may reject it.
|
|
17
|
-
headers: { Authorization: `Bearer ${opts.apiKey}`, Accept: "application/json" }
|
|
18
|
-
});
|
|
19
|
-
} catch (err) {
|
|
20
|
-
throw new Error(
|
|
21
|
-
`Could not reach the BetterCMS Management API at ${url}: ${err instanceof Error ? err.message : String(err)}`
|
|
22
|
-
);
|
|
23
|
-
}
|
|
24
|
-
if (!res.ok) {
|
|
25
|
-
const hint = res.status === 401 || res.status === 403 ? " \u2014 check your management API key (it must have the content:manage scope)." : "";
|
|
26
|
-
throw new Error(`Management API returned ${res.status} ${res.statusText}${hint}`);
|
|
27
|
-
}
|
|
28
|
-
const body = await res.json();
|
|
29
|
-
const rows = body.data ?? [];
|
|
30
|
-
return rows.map((r) => ({
|
|
31
|
-
slug: r.slug,
|
|
32
|
-
name: r.name,
|
|
33
|
-
description: r.description ?? null,
|
|
34
|
-
fields: r.fields ?? []
|
|
35
|
-
}));
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// src/generate.ts
|
|
39
|
-
var PREAMBLE = `/**
|
|
40
|
-
* Rich-text field value returned by the Delivery API.
|
|
41
|
-
*
|
|
42
|
-
* - \`format\`/\`value\`: the portable, editor-agnostic payload (Lexical EditorState) \u2014
|
|
43
|
-
* render it with your editor's serializer for full fidelity.
|
|
44
|
-
* - \`html\`: server-rendered, sanitized HTML (computed render-on-write). Present on
|
|
45
|
-
* Delivery reads; the simplest path for non-React consumers \u2014 safe to inject directly
|
|
46
|
-
* (e.g. \`dangerouslySetInnerHTML\`). Optional: legacy/un-normalized values may omit it.
|
|
47
|
-
*
|
|
48
|
-
* The \`{ format, value }\` contract is unchanged; \`html\` is additive.
|
|
49
|
-
*/
|
|
50
|
-
export type RichText = {
|
|
51
|
-
readonly format: string;
|
|
52
|
-
readonly value: unknown;
|
|
53
|
-
readonly html?: string;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Image / media field value as stored and returned verbatim by the Delivery API
|
|
58
|
-
* (server-normalized on write to the canonical shape). \`url\` is always present; an
|
|
59
|
-
* unresolved/external value may carry only \`url\`. \`altText\` is the accessibility text
|
|
60
|
-
* for \`<img alt>\`.
|
|
61
|
-
*/
|
|
62
|
-
export interface BetterCMSImage {
|
|
63
|
-
readonly id?: string;
|
|
64
|
-
readonly url: string;
|
|
65
|
-
readonly name?: string;
|
|
66
|
-
readonly altText?: string | null;
|
|
67
|
-
readonly width?: number;
|
|
68
|
-
readonly height?: number;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Delivery envelope around a model's typed \`data\`. \`getEntry\`/\`listEntries\` in the
|
|
73
|
-
* Next adapter return this shape, with \`fields\` typed by the model.
|
|
74
|
-
*/
|
|
75
|
-
export interface BetterCMSEntry<TFields> {
|
|
76
|
-
readonly slug: string;
|
|
77
|
-
readonly status: "draft" | "published";
|
|
78
|
-
readonly fields: TFields;
|
|
79
|
-
readonly updatedAt: string;
|
|
80
|
-
}
|
|
81
|
-
`;
|
|
82
|
-
function pascalCase(slug) {
|
|
83
|
-
const parts = slug.split(/[-_\s]+/).filter(Boolean);
|
|
84
|
-
const pascal = parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
|
|
85
|
-
return /^[0-9]/.test(pascal) ? `Model${pascal}` : pascal || "Model";
|
|
86
|
-
}
|
|
87
|
-
function escapeJsDoc(text) {
|
|
88
|
-
return text.replace(/\*\//g, "* /").replace(/[\r\n]+/g, " ").trim();
|
|
89
|
-
}
|
|
90
|
-
var VALID_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
91
|
-
function propName(key) {
|
|
92
|
-
return VALID_IDENT.test(key) ? key : JSON.stringify(key);
|
|
93
|
-
}
|
|
94
|
-
function scalarType(field) {
|
|
95
|
-
const t = field.type;
|
|
96
|
-
switch (t) {
|
|
97
|
-
case "text":
|
|
98
|
-
return "string";
|
|
99
|
-
case "richtext":
|
|
100
|
-
return "RichText";
|
|
101
|
-
case "image":
|
|
102
|
-
return "BetterCMSImage";
|
|
103
|
-
case "boolean":
|
|
104
|
-
return "boolean";
|
|
105
|
-
case "number":
|
|
106
|
-
return "number";
|
|
107
|
-
case "date":
|
|
108
|
-
case "datetime":
|
|
109
|
-
return "string";
|
|
110
|
-
// ISO 8601
|
|
111
|
-
case "select": {
|
|
112
|
-
const opts = field.options?.filter((o) => typeof o === "string") ?? [];
|
|
113
|
-
return opts.length > 0 ? opts.map((o) => JSON.stringify(o)).join(" | ") : "string";
|
|
114
|
-
}
|
|
115
|
-
case "reference":
|
|
116
|
-
return "string";
|
|
117
|
-
// referenced entry id
|
|
118
|
-
case "multi-reference":
|
|
119
|
-
return "string[]";
|
|
120
|
-
// referenced entry ids
|
|
121
|
-
case "array": {
|
|
122
|
-
const itemType = field.config?.itemType ?? "text";
|
|
123
|
-
const inner = itemType === "number" ? "number" : "string";
|
|
124
|
-
return `${inner}[]`;
|
|
125
|
-
}
|
|
126
|
-
default: {
|
|
127
|
-
const _exhaustive = t;
|
|
128
|
-
return "unknown";
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
function arrayZoneType(field, indent) {
|
|
133
|
-
const zones = field.config?.zones;
|
|
134
|
-
const parts = [];
|
|
135
|
-
if (zones?.nonRepeatable?.length) {
|
|
136
|
-
const nested = fieldsToBody(zones.nonRepeatable, indent + " ");
|
|
137
|
-
parts.push(`${indent} readonly nonRepeatable?: {
|
|
138
|
-
${nested}
|
|
139
|
-
${indent} };`);
|
|
140
|
-
}
|
|
141
|
-
if (zones?.repeatable?.fields?.length) {
|
|
142
|
-
const nested = fieldsToBody(zones.repeatable.fields, indent + " ");
|
|
143
|
-
parts.push(`${indent} readonly repeatable?: Array<{
|
|
144
|
-
${nested}
|
|
145
|
-
${indent} }>;`);
|
|
146
|
-
}
|
|
147
|
-
if (parts.length === 0) return "Record<string, unknown>";
|
|
148
|
-
return `{
|
|
149
|
-
${parts.join("\n")}
|
|
150
|
-
${indent}}`;
|
|
151
|
-
}
|
|
152
|
-
function fieldsToBody(fields, indent) {
|
|
153
|
-
const lines = [];
|
|
154
|
-
for (const field of fields) {
|
|
155
|
-
const optional = field.required ? "" : "?";
|
|
156
|
-
let typeExpr;
|
|
157
|
-
if (field.type === "array" && field.config?.zones) {
|
|
158
|
-
typeExpr = arrayZoneType(field, indent);
|
|
159
|
-
} else {
|
|
160
|
-
typeExpr = scalarType(field);
|
|
161
|
-
}
|
|
162
|
-
const safeLabel = field.label ? escapeJsDoc(field.label) : "";
|
|
163
|
-
if (safeLabel && safeLabel !== field.key) {
|
|
164
|
-
lines.push(`${indent}/** ${safeLabel} */`);
|
|
165
|
-
}
|
|
166
|
-
lines.push(`${indent}readonly ${propName(field.key)}${optional}: ${typeExpr};`);
|
|
167
|
-
}
|
|
168
|
-
return lines.join("\n");
|
|
169
|
-
}
|
|
170
|
-
function generateTypes(models, opts = {}) {
|
|
171
|
-
const version = opts.version ?? "0.1.0";
|
|
172
|
-
const sorted = [...models].sort(
|
|
173
|
-
(a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0
|
|
174
|
-
);
|
|
175
|
-
const header = `// \u26A0\uFE0F AUTO-GENERATED by @bettercms-ai/codegen v${version} \u2014 DO NOT EDIT.
|
|
176
|
-
// Regenerate with: npx @bettercms-ai/codegen
|
|
177
|
-
// Source of truth: your BetterCMS content models (the same schema the dashboard
|
|
178
|
-
// builder and the MCP tools write). Re-run codegen after any schema change.
|
|
179
|
-
${opts.bannerComment ? `// ${opts.bannerComment}
|
|
180
|
-
` : ""}`;
|
|
181
|
-
const interfaces = [];
|
|
182
|
-
const mapEntries = [];
|
|
183
|
-
const usedNames = /* @__PURE__ */ new Set();
|
|
184
|
-
for (const model of sorted) {
|
|
185
|
-
const base = `${pascalCase(model.slug)}Fields`;
|
|
186
|
-
let typeName = base;
|
|
187
|
-
for (let n = 2; usedNames.has(typeName); n++) typeName = `${base}_${n}`;
|
|
188
|
-
usedNames.add(typeName);
|
|
189
|
-
const name = model.name ? escapeJsDoc(model.name) : "";
|
|
190
|
-
const desc = model.description ? escapeJsDoc(model.description) : "";
|
|
191
|
-
const doc = name ? `/**
|
|
192
|
-
* ${name}${desc ? ` \u2014 ${desc}` : ""}
|
|
193
|
-
* Model slug: \`${model.slug}\`
|
|
194
|
-
*/
|
|
195
|
-
` : "";
|
|
196
|
-
const body = model.fields.length ? fieldsToBody(model.fields, " ") : " // (no fields defined yet)";
|
|
197
|
-
interfaces.push(`${doc}export interface ${typeName} {
|
|
198
|
-
${body}
|
|
199
|
-
}`);
|
|
200
|
-
mapEntries.push(` readonly ${JSON.stringify(model.slug)}: ${typeName};`);
|
|
201
|
-
}
|
|
202
|
-
const schemaMap = `/**
|
|
203
|
-
* Registry mapping each model slug to its typed fields. The Next adapter uses this to
|
|
204
|
-
* type \`getEntry("blog", ...)\` by slug \u2014 autocomplete and exhaustiveness for free.
|
|
205
|
-
*/
|
|
206
|
-
export interface BetterCMSSchema {
|
|
207
|
-
${mapEntries.join("\n") || " // (no models defined yet)"}
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
/** Union of all model slugs. */
|
|
211
|
-
export type BetterCMSModelSlug = keyof BetterCMSSchema;`;
|
|
212
|
-
return [header, PREAMBLE, interfaces.join("\n\n"), schemaMap, ""].join("\n");
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
// src/bindings.ts
|
|
216
|
-
var VALID_IDENT2 = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
217
|
-
function propName2(key) {
|
|
218
|
-
return VALID_IDENT2.test(key) ? key : JSON.stringify(key);
|
|
219
|
-
}
|
|
220
|
-
function bindingKind(t) {
|
|
221
|
-
switch (t) {
|
|
222
|
-
case "text":
|
|
223
|
-
case "richtext":
|
|
224
|
-
case "image":
|
|
225
|
-
case "boolean":
|
|
226
|
-
case "number":
|
|
227
|
-
case "select":
|
|
228
|
-
case "array":
|
|
229
|
-
return t;
|
|
230
|
-
// reference / multi-reference / date / datetime → plain text in the editor v1.
|
|
231
|
-
default:
|
|
232
|
-
return "text";
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
function indexedPath(prefix, suffix) {
|
|
236
|
-
return `${JSON.stringify(prefix)} + i + ${JSON.stringify(suffix)}`;
|
|
237
|
-
}
|
|
238
|
-
function repeaterBinding(itemFields, path, indent) {
|
|
239
|
-
const lines = [
|
|
240
|
-
`${indent} $: (i: number) => bcmsField(${indexedPath(`${path}[`, "]")}, "array"),`
|
|
241
|
-
];
|
|
242
|
-
for (const sub of itemFields) {
|
|
243
|
-
if (sub.type === "array") continue;
|
|
244
|
-
lines.push(
|
|
245
|
-
`${indent} ${propName2(sub.key)}: (i: number) => bcmsField(${indexedPath(`${path}[`, `].${sub.key}`)}, ${JSON.stringify(bindingKind(sub.type))}),`
|
|
246
|
-
);
|
|
247
|
-
}
|
|
248
|
-
return `{
|
|
249
|
-
${lines.join("\n")}
|
|
250
|
-
${indent}}`;
|
|
251
|
-
}
|
|
252
|
-
function fieldBinding(field, prefix, indent) {
|
|
253
|
-
const path = prefix ? `${prefix}.${field.key}` : field.key;
|
|
254
|
-
const name = propName2(field.key);
|
|
255
|
-
if (field.type !== "array") {
|
|
256
|
-
return `${indent}${name}: bcmsField(${JSON.stringify(path)}, ${JSON.stringify(bindingKind(field.type))}),`;
|
|
257
|
-
}
|
|
258
|
-
const zones = field.config?.zones;
|
|
259
|
-
if (zones?.nonRepeatable?.length) {
|
|
260
|
-
const body = zones.nonRepeatable.map((child) => fieldBinding(child, path, `${indent} `)).join("\n");
|
|
261
|
-
return `${indent}${name}: {
|
|
262
|
-
${body}
|
|
263
|
-
${indent}},`;
|
|
264
|
-
}
|
|
265
|
-
if (zones?.repeatable?.fields?.length) {
|
|
266
|
-
return `${indent}${name}: ${repeaterBinding(zones.repeatable.fields, path, indent)},`;
|
|
267
|
-
}
|
|
268
|
-
const lines = [
|
|
269
|
-
`${indent} $: (i: number) => bcmsField(${indexedPath(`${path}[`, "]")}, "array"),`,
|
|
270
|
-
`${indent} value: (i: number) => bcmsField(${indexedPath(`${path}[`, "].value")}, "text"),`
|
|
271
|
-
];
|
|
272
|
-
return `${indent}${name}: {
|
|
273
|
-
${lines.join("\n")}
|
|
274
|
-
${indent}},`;
|
|
275
|
-
}
|
|
276
|
-
function fieldsToBindings(fields, indent) {
|
|
277
|
-
return fields.map((field) => fieldBinding(field, "", indent)).join("\n");
|
|
278
|
-
}
|
|
279
|
-
var PREAMBLE2 = `/**
|
|
280
|
-
* True when this site is built for Live Preview annotation. Set \`BCMS_ANNOTATE=1\`
|
|
281
|
-
* in the preview build only; unset (the default) ships zero binding attributes.
|
|
282
|
-
* Read defensively so the module is safe in any runtime (browser, Node, edge).
|
|
283
|
-
*/
|
|
284
|
-
const BCMS_ANNOTATE: boolean = (() => {
|
|
285
|
-
try {
|
|
286
|
-
const v = (globalThis as { process?: { env?: Record<string, string | undefined> } })
|
|
287
|
-
.process?.env?.BCMS_ANNOTATE;
|
|
288
|
-
return v != null && v !== "" && v !== "0" && v !== "false";
|
|
289
|
-
} catch {
|
|
290
|
-
return false;
|
|
291
|
-
}
|
|
292
|
-
})();
|
|
293
|
-
|
|
294
|
-
/**
|
|
295
|
-
* Binding attributes for a CMS-bound element. Spread onto the element that renders a
|
|
296
|
-
* field: \`<h1 {...bcmsField("title", "text")}>\`. Returns \`{}\` unless BCMS_ANNOTATE
|
|
297
|
-
* is set, so production markup is untouched.
|
|
298
|
-
*/
|
|
299
|
-
export function bcmsField(path: string, kind: string): Record<string, string> {
|
|
300
|
-
return BCMS_ANNOTATE ? { "data-bcms-field": path, "data-bcms-kind": kind } : {};
|
|
301
|
-
}
|
|
302
|
-
`;
|
|
303
|
-
function generateBindings(models, opts = {}) {
|
|
304
|
-
const version = opts.version ?? "0.1.0";
|
|
305
|
-
const sorted = [...models].sort(
|
|
306
|
-
(a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0
|
|
307
|
-
);
|
|
308
|
-
const header = `// \u26A0\uFE0F AUTO-GENERATED by @bettercms-ai/codegen v${version} \u2014 DO NOT EDIT.
|
|
309
|
-
// Live Preview field bindings. Regenerate with: npx @bettercms-ai/codegen --bindings-out <path>
|
|
310
|
-
// Spread these onto the elements that render your content; they emit
|
|
311
|
-
// data-bcms-field/data-bcms-kind only when the site is built with BCMS_ANNOTATE set.
|
|
312
|
-
${opts.bannerComment ? `// ${opts.bannerComment}
|
|
313
|
-
` : ""}`;
|
|
314
|
-
const entries = sorted.map((model) => {
|
|
315
|
-
const body = model.fields.length ? `
|
|
316
|
-
${fieldsToBindings(model.fields, " ")}
|
|
317
|
-
` : "";
|
|
318
|
-
return ` ${JSON.stringify(model.slug)}: {${body}},`;
|
|
319
|
-
});
|
|
320
|
-
const bcms = `/**
|
|
321
|
-
* Field bindings keyed by model slug. Spread a binding onto the element that renders
|
|
322
|
-
* that field. Arrays expose \`$(i)\` for the item element and one accessor per
|
|
323
|
-
* (one-level) sub-field; primitive arrays expose \`value(i)\` for the item's scalar.
|
|
324
|
-
*/
|
|
325
|
-
export const bcms = {
|
|
326
|
-
${entries.join("\n") || " // (no models defined yet)"}
|
|
327
|
-
} as const;`;
|
|
328
|
-
return [header, PREAMBLE2, bcms, ""].join("\n");
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
// src/components.ts
|
|
332
|
-
function generateComponents(opts = {}) {
|
|
333
|
-
const version = opts.version ?? "0.1.0";
|
|
334
|
-
const header = `// \u26A0\uFE0F AUTO-GENERATED by @bettercms-ai/codegen v${version} \u2014 DO NOT EDIT.
|
|
335
|
-
// Regenerate with: npx @bettercms-ai/codegen --components-out <path>
|
|
336
|
-
// Typed render components for BetterCMS field shapes. Use these instead of
|
|
337
|
-
// hand-rendering richtext/image values \u2014 they render the canonical shapes correctly.
|
|
338
|
-
${opts.bannerComment ? `// ${opts.bannerComment}
|
|
339
|
-
` : ""}`;
|
|
340
|
-
const body = `import * as React from "react";
|
|
341
|
-
|
|
342
|
-
/** Rich-text value from the Delivery API. \`html\` is server-rendered + sanitized. */
|
|
343
|
-
export type RichTextValue = {
|
|
344
|
-
readonly format: string;
|
|
345
|
-
readonly value: unknown;
|
|
346
|
-
readonly html?: string;
|
|
347
|
-
};
|
|
348
|
-
|
|
349
|
-
/** Normalized image/media value from the Delivery API. */
|
|
350
|
-
export interface BetterCMSImageValue {
|
|
351
|
-
readonly url: string;
|
|
352
|
-
readonly altText?: string | null;
|
|
353
|
-
readonly width?: number;
|
|
354
|
-
readonly height?: number;
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
type RichTextProps = {
|
|
358
|
-
/** The richtext field value (\`entry.fields.someRichText\`). */
|
|
359
|
-
field?: RichTextValue | null;
|
|
360
|
-
/** Element/component to render as. Default: \`"div"\`. */
|
|
361
|
-
as?: React.ElementType;
|
|
362
|
-
} & Omit<React.HTMLAttributes<HTMLElement>, "dangerouslySetInnerHTML" | "children">;
|
|
363
|
-
|
|
364
|
-
/**
|
|
365
|
-
* Render a richtext field as HTML. Uses the server-sanitized \`html\` via
|
|
366
|
-
* \`dangerouslySetInnerHTML\` \u2014 NEVER interpolate a richtext value as a JSX child
|
|
367
|
-
* (React escapes it, so the page shows literal tags). Renders nothing when unset.
|
|
368
|
-
*/
|
|
369
|
-
export function RichText({ field, as: Tag = "div", ...rest }: RichTextProps) {
|
|
370
|
-
if (!field || !field.html) return null;
|
|
371
|
-
return <Tag {...rest} dangerouslySetInnerHTML={{ __html: field.html }} />;
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
type ImageProps = {
|
|
375
|
-
/** The image field value (\`entry.fields.someImage\`). */
|
|
376
|
-
field?: BetterCMSImageValue | null;
|
|
377
|
-
/** Alt text override; defaults to the field's \`altText\`, then \`""\`. */
|
|
378
|
-
alt?: string;
|
|
379
|
-
} & Omit<React.ImgHTMLAttributes<HTMLImageElement>, "src">;
|
|
380
|
-
|
|
381
|
-
/**
|
|
382
|
-
* Render an image field as an \`<img>\` from its normalized \`.url\`/\`.altText\`.
|
|
383
|
-
* Renders nothing when unset. Pass \`alt\` to override the stored alt text.
|
|
384
|
-
*/
|
|
385
|
-
export function Image({ field, alt, ...rest }: ImageProps) {
|
|
386
|
-
if (!field || !field.url) return null;
|
|
387
|
-
return (
|
|
388
|
-
<img
|
|
389
|
-
src={field.url}
|
|
390
|
-
alt={alt ?? field.altText ?? ""}
|
|
391
|
-
width={field.width}
|
|
392
|
-
height={field.height}
|
|
393
|
-
{...rest}
|
|
394
|
-
/>
|
|
395
|
-
);
|
|
396
|
-
}
|
|
397
|
-
`;
|
|
398
|
-
return [header, body].join("\n");
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
// src/cli.ts
|
|
402
|
-
var VERSION = "0.2.0";
|
|
403
|
-
var DEFAULT_API_URL = "https://api.bettercms.ai/api/v1";
|
|
404
|
-
var DEFAULT_OUT = "bettercms.generated.ts";
|
|
405
|
-
function parseArgs(argv) {
|
|
406
|
-
const args = {
|
|
407
|
-
apiUrl: process.env.BETTERCMS_API_URL ?? DEFAULT_API_URL,
|
|
408
|
-
apiKey: process.env.BETTERCMS_API_KEY,
|
|
409
|
-
out: DEFAULT_OUT,
|
|
410
|
-
bindingsOut: void 0,
|
|
411
|
-
componentsOut: void 0,
|
|
412
|
-
help: false
|
|
413
|
-
};
|
|
414
|
-
for (let i = 0; i < argv.length; i++) {
|
|
415
|
-
const arg = argv[i];
|
|
416
|
-
const next = () => argv[++i];
|
|
417
|
-
switch (arg) {
|
|
418
|
-
case "--api-url":
|
|
419
|
-
args.apiUrl = next() ?? args.apiUrl;
|
|
420
|
-
break;
|
|
421
|
-
case "--key":
|
|
422
|
-
case "--api-key":
|
|
423
|
-
args.apiKey = next();
|
|
424
|
-
break;
|
|
425
|
-
case "--out":
|
|
426
|
-
case "-o":
|
|
427
|
-
args.out = next() ?? args.out;
|
|
428
|
-
break;
|
|
429
|
-
case "--bindings-out":
|
|
430
|
-
args.bindingsOut = next();
|
|
431
|
-
break;
|
|
432
|
-
case "--components-out":
|
|
433
|
-
args.componentsOut = next();
|
|
434
|
-
break;
|
|
435
|
-
case "--help":
|
|
436
|
-
case "-h":
|
|
437
|
-
args.help = true;
|
|
438
|
-
break;
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
return args;
|
|
442
|
-
}
|
|
443
|
-
var HELP = `bettercms-codegen v${VERSION} \u2014 generate TypeScript types from your BetterCMS schema
|
|
444
|
-
|
|
445
|
-
Usage:
|
|
446
|
-
npx @bettercms-ai/codegen [options]
|
|
447
|
-
|
|
448
|
-
Options:
|
|
449
|
-
-o, --out <path> Output file (default: ${DEFAULT_OUT})
|
|
450
|
-
--bindings-out <path> Also emit the Live Preview bindings module to <path>
|
|
451
|
-
--components-out <path> Also emit typed <RichText>/<Image> React components (.tsx) to <path>
|
|
452
|
-
--api-url <url> Management API base (default: ${DEFAULT_API_URL})
|
|
453
|
-
--key <key> Management API key (or set BETTERCMS_API_KEY)
|
|
454
|
-
-h, --help Show this help
|
|
455
|
-
|
|
456
|
-
Env:
|
|
457
|
-
BETTERCMS_API_KEY Management-scoped key (content:manage)
|
|
458
|
-
BETTERCMS_API_URL Override the API base
|
|
459
|
-
`;
|
|
460
|
-
async function main() {
|
|
461
|
-
const args = parseArgs(process.argv.slice(2));
|
|
462
|
-
if (args.help) {
|
|
463
|
-
process.stdout.write(HELP);
|
|
464
|
-
return;
|
|
465
|
-
}
|
|
466
|
-
if (!args.apiKey) {
|
|
467
|
-
process.stderr.write(
|
|
468
|
-
"error: no API key. Pass --key <key> or set BETTERCMS_API_KEY.\n"
|
|
469
|
-
);
|
|
470
|
-
process.exit(1);
|
|
471
|
-
}
|
|
472
|
-
const models = await fetchModels({ apiUrl: args.apiUrl, apiKey: args.apiKey });
|
|
473
|
-
const outPath = resolve(process.cwd(), args.out);
|
|
474
|
-
await mkdir(dirname(outPath), { recursive: true });
|
|
475
|
-
await writeFile(outPath, generateTypes(models, { version: VERSION }), "utf8");
|
|
476
|
-
const plural = models.length === 1 ? "" : "s";
|
|
477
|
-
process.stdout.write(
|
|
478
|
-
`\u2713 Generated ${models.length} model type${plural} \u2192 ${args.out}
|
|
479
|
-
`
|
|
480
|
-
);
|
|
481
|
-
if (args.bindingsOut) {
|
|
482
|
-
const bindingsPath = resolve(process.cwd(), args.bindingsOut);
|
|
483
|
-
await mkdir(dirname(bindingsPath), { recursive: true });
|
|
484
|
-
await writeFile(bindingsPath, generateBindings(models, { version: VERSION }), "utf8");
|
|
485
|
-
process.stdout.write(`\u2713 Generated Live Preview bindings \u2192 ${args.bindingsOut}
|
|
486
|
-
`);
|
|
487
|
-
}
|
|
488
|
-
if (args.componentsOut) {
|
|
489
|
-
const componentsPath = resolve(process.cwd(), args.componentsOut);
|
|
490
|
-
await mkdir(dirname(componentsPath), { recursive: true });
|
|
491
|
-
await writeFile(componentsPath, generateComponents({ version: VERSION }), "utf8");
|
|
492
|
-
process.stdout.write(`\u2713 Generated render components \u2192 ${args.componentsOut}
|
|
493
|
-
`);
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
main().catch((err) => {
|
|
497
|
-
process.stderr.write(`error: ${err instanceof Error ? err.message : String(err)}
|
|
498
|
-
`);
|
|
499
|
-
process.exit(1);
|
|
500
|
-
});
|
|
501
|
-
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/fetch-models.ts","../src/generate.ts","../src/bindings.ts","../src/components.ts"],"sourcesContent":["/**\n * `bettercms-codegen` — fetch a project's content models and write a typed `.ts` file.\n *\n * Designed for two call sites:\n * 1. A developer in their repo: npx @bettercms-ai/codegen --out src/bettercms.generated.ts\n * 2. The build-time GitHub Action: same command, key from a repo secret.\n *\n * Auth + endpoint come from flags or env (BETTERCMS_API_KEY, BETTERCMS_API_URL).\n */\n\nimport { writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { fetchModels } from \"./fetch-models.js\";\nimport { generateTypes } from \"./generate.js\";\nimport { generateBindings } from \"./bindings.js\";\nimport { generateComponents } from \"./components.js\";\n\nconst VERSION = \"0.2.0\";\nconst DEFAULT_API_URL = \"https://api.bettercms.ai/api/v1\";\nconst DEFAULT_OUT = \"bettercms.generated.ts\";\n\ninterface CliArgs {\n apiUrl: string;\n apiKey: string | undefined;\n out: string;\n /** When set, also emit the Live Preview bindings module to this path. */\n bindingsOut: string | undefined;\n /** When set, also emit the typed React render components (.tsx) to this path. */\n componentsOut: string | undefined;\n help: boolean;\n}\n\nfunction parseArgs(argv: string[]): CliArgs {\n const args: CliArgs = {\n apiUrl: process.env.BETTERCMS_API_URL ?? DEFAULT_API_URL,\n apiKey: process.env.BETTERCMS_API_KEY,\n out: DEFAULT_OUT,\n bindingsOut: undefined,\n componentsOut: undefined,\n help: false,\n };\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n const next = () => argv[++i];\n switch (arg) {\n case \"--api-url\":\n args.apiUrl = next() ?? args.apiUrl;\n break;\n case \"--key\":\n case \"--api-key\":\n args.apiKey = next();\n break;\n case \"--out\":\n case \"-o\":\n args.out = next() ?? args.out;\n break;\n case \"--bindings-out\":\n args.bindingsOut = next();\n break;\n case \"--components-out\":\n args.componentsOut = next();\n break;\n case \"--help\":\n case \"-h\":\n args.help = true;\n break;\n }\n }\n return args;\n}\n\nconst HELP = `bettercms-codegen v${VERSION} — generate TypeScript types from your BetterCMS schema\n\nUsage:\n npx @bettercms-ai/codegen [options]\n\nOptions:\n -o, --out <path> Output file (default: ${DEFAULT_OUT})\n --bindings-out <path> Also emit the Live Preview bindings module to <path>\n --components-out <path> Also emit typed <RichText>/<Image> React components (.tsx) to <path>\n --api-url <url> Management API base (default: ${DEFAULT_API_URL})\n --key <key> Management API key (or set BETTERCMS_API_KEY)\n -h, --help Show this help\n\nEnv:\n BETTERCMS_API_KEY Management-scoped key (content:manage)\n BETTERCMS_API_URL Override the API base\n`;\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2));\n\n if (args.help) {\n process.stdout.write(HELP);\n return;\n }\n if (!args.apiKey) {\n process.stderr.write(\n \"error: no API key. Pass --key <key> or set BETTERCMS_API_KEY.\\n\",\n );\n process.exit(1);\n }\n\n const models = await fetchModels({ apiUrl: args.apiUrl, apiKey: args.apiKey });\n\n const outPath = resolve(process.cwd(), args.out);\n await mkdir(dirname(outPath), { recursive: true });\n await writeFile(outPath, generateTypes(models, { version: VERSION }), \"utf8\");\n\n const plural = models.length === 1 ? \"\" : \"s\";\n process.stdout.write(\n `✓ Generated ${models.length} model type${plural} → ${args.out}\\n`,\n );\n\n if (args.bindingsOut) {\n const bindingsPath = resolve(process.cwd(), args.bindingsOut);\n await mkdir(dirname(bindingsPath), { recursive: true });\n await writeFile(bindingsPath, generateBindings(models, { version: VERSION }), \"utf8\");\n process.stdout.write(`✓ Generated Live Preview bindings → ${args.bindingsOut}\\n`);\n }\n\n if (args.componentsOut) {\n const componentsPath = resolve(process.cwd(), args.componentsOut);\n await mkdir(dirname(componentsPath), { recursive: true });\n await writeFile(componentsPath, generateComponents({ version: VERSION }), \"utf8\");\n process.stdout.write(`✓ Generated render components → ${args.componentsOut}\\n`);\n }\n}\n\nmain().catch((err: unknown) => {\n process.stderr.write(`error: ${err instanceof Error ? err.message : String(err)}\\n`);\n process.exit(1);\n});\n","/**\n * Fetches content models from the BetterCMS Management API so the CLI can generate\n * types against a live project. Kept dependency-free (plain fetch) so the generated\n * artifact and this fetcher can run anywhere — a GitHub Action, a postinstall, a script.\n */\n\nimport type { GeneratableModel } from \"./generate.js\";\n\nexport interface FetchModelsOptions {\n /** Management API base, e.g. \"https://api.bettercms.ai/api/v1\". */\n apiUrl: string;\n /** A management-scoped key (content:manage) or device-minted token. */\n apiKey: string;\n /** Optional fetch override (testing / custom runtime). */\n fetchImpl?: typeof fetch;\n}\n\ninterface ManagedModelRow {\n slug: string;\n name?: string;\n description?: string | null;\n fields: GeneratableModel[\"fields\"];\n}\n\n/**\n * GET /management/content/models — returns the project's models (the key is\n * project-scoped server-side, so this is exactly the schema for this site).\n */\nexport async function fetchModels(\n opts: FetchModelsOptions,\n): Promise<GeneratableModel[]> {\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n const base = opts.apiUrl.replace(/\\/+$/, \"\");\n const url = `${base}/management/content/models`;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n // No Content-Type: this is a bodyless GET; the header is incorrect here and\n // strict edge runtimes/proxies may reject it.\n headers: { Authorization: `Bearer ${opts.apiKey}`, Accept: \"application/json\" },\n });\n } catch (err) {\n throw new Error(\n `Could not reach the BetterCMS Management API at ${url}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n\n if (!res.ok) {\n const hint =\n res.status === 401 || res.status === 403\n ? \" — check your management API key (it must have the content:manage scope).\"\n : \"\";\n throw new Error(`Management API returned ${res.status} ${res.statusText}${hint}`);\n }\n\n const body = (await res.json()) as { data?: ManagedModelRow[] };\n const rows = body.data ?? [];\n return rows.map((r) => ({\n slug: r.slug,\n name: r.name,\n description: r.description ?? null,\n fields: r.fields ?? [],\n }));\n}\n","/**\n * @bettercms-ai/codegen — schema → TypeScript generator (the single source of truth).\n *\n * Both the dashboard schema builder and the MCP `create_model`/`add_field` tools write\n * the SAME `content_models.fields` (an array of `ContentModelField`). This generator maps\n * that one array into TypeScript. Because there is exactly one schema representation, the\n * generated types can never drift from the editor or the agent — they are the same source.\n *\n * Pure + deterministic: same models in → identical string out (stable ordering, no clock,\n * no I/O). That makes it trivially testable and safe to commit + diff in a customer repo.\n */\n\nimport type { ContentModelField, ContentModelFieldType } from \"@bettercms-ai/types\";\n\n/** Minimal model shape the generator needs — a subset of the Management API model row. */\nexport interface GeneratableModel {\n /** Machine-safe slug, e.g. \"blog\" or \"case-study\". Used for the schema-map key. */\n slug: string;\n /** Human name, used only for the JSDoc header. */\n name?: string;\n description?: string | null;\n fields: ContentModelField[];\n}\n\nexport interface GenerateOptions {\n /** Generator version stamped into the header (defaults to the package version). */\n version?: string;\n /** Override the banner timestamp source — omitted by default so output is deterministic. */\n bannerComment?: string;\n}\n\n/** Helper types emitted once at the top of every generated file (self-contained, zero-dep). */\nconst PREAMBLE = `/**\n * Rich-text field value returned by the Delivery API.\n *\n * - \\`format\\`/\\`value\\`: the portable, editor-agnostic payload (Lexical EditorState) —\n * render it with your editor's serializer for full fidelity.\n * - \\`html\\`: server-rendered, sanitized HTML (computed render-on-write). Present on\n * Delivery reads; the simplest path for non-React consumers — safe to inject directly\n * (e.g. \\`dangerouslySetInnerHTML\\`). Optional: legacy/un-normalized values may omit it.\n *\n * The \\`{ format, value }\\` contract is unchanged; \\`html\\` is additive.\n */\nexport type RichText = {\n readonly format: string;\n readonly value: unknown;\n readonly html?: string;\n};\n\n/**\n * Image / media field value as stored and returned verbatim by the Delivery API\n * (server-normalized on write to the canonical shape). \\`url\\` is always present; an\n * unresolved/external value may carry only \\`url\\`. \\`altText\\` is the accessibility text\n * for \\`<img alt>\\`.\n */\nexport interface BetterCMSImage {\n readonly id?: string;\n readonly url: string;\n readonly name?: string;\n readonly altText?: string | null;\n readonly width?: number;\n readonly height?: number;\n}\n\n/**\n * Delivery envelope around a model's typed \\`data\\`. \\`getEntry\\`/\\`listEntries\\` in the\n * Next adapter return this shape, with \\`fields\\` typed by the model.\n */\nexport interface BetterCMSEntry<TFields> {\n readonly slug: string;\n readonly status: \"draft\" | \"published\";\n readonly fields: TFields;\n readonly updatedAt: string;\n}\n`;\n\n/** PascalCase an identifier from a slug: \"case-study\" → \"CaseStudy\". */\nfunction pascalCase(slug: string): string {\n const parts = slug.split(/[-_\\s]+/).filter(Boolean);\n const pascal = parts\n .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n .join(\"\");\n // Guard against an identifier that starts with a digit (invalid TS type name).\n return /^[0-9]/.test(pascal) ? `Model${pascal}` : pascal || \"Model\";\n}\n\n/**\n * Make a string safe to embed inside a `/** ... */` JSDoc comment. A field label\n * (free-text, author/agent-controlled) could contain `*/` — which closes the comment\n * early and injects the remainder as code — or a newline, which breaks the single-line\n * comment. Both are neutralized here. Without this, hostile content produces non-\n * compiling (or worse, code-injected) output.\n */\nfunction escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"* /\").replace(/[\\r\\n]+/g, \" \").trim();\n}\n\nconst VALID_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * Render a field key as a TS property name. Field keys are author/agent-controlled and\n * not guaranteed to be valid identifiers (e.g. \"my-field\", \"1title\", \"\"), so anything\n * that isn't a bare identifier is emitted as a quoted property name — always valid TS.\n */\nfunction propName(key: string): string {\n return VALID_IDENT.test(key) ? key : JSON.stringify(key);\n}\n\n/** A scalar/primitive field maps to a TS type expression (no nesting). */\nfunction scalarType(field: ContentModelField): string {\n const t: ContentModelFieldType = field.type;\n switch (t) {\n case \"text\":\n return \"string\";\n case \"richtext\":\n return \"RichText\";\n case \"image\":\n return \"BetterCMSImage\";\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"date\":\n case \"datetime\":\n return \"string\"; // ISO 8601\n case \"select\": {\n const opts = field.options?.filter((o) => typeof o === \"string\") ?? [];\n return opts.length > 0\n ? opts.map((o) => JSON.stringify(o)).join(\" | \")\n : \"string\";\n }\n case \"reference\":\n return \"string\"; // referenced entry id\n case \"multi-reference\":\n return \"string[]\"; // referenced entry ids\n case \"array\": {\n // Zoned arrays (config.zones) are expanded by fieldsToBody before reaching here;\n // this branch handles only the primitive list form (config.itemType).\n const itemType = field.config?.itemType ?? \"text\";\n const inner =\n itemType === \"number\" ? \"number\" : \"string\"; // text | date → string\n return `${inner}[]`;\n }\n default: {\n // Exhaustiveness guard: if a new field type is added to the union and not\n // mapped here, this line becomes a compile error in the codegen build.\n const _exhaustive: never = t;\n return \"unknown\";\n }\n }\n}\n\n/**\n * Render the TS type for a zoned `array` field: an object with optional\n * `nonRepeatable` (a fixed block) and/or `repeatable` (a list of blocks). Recurses\n * through zone fields, so a zone field that is itself a zoned `array` nests naturally.\n */\nfunction arrayZoneType(field: ContentModelField, indent: string): string {\n const zones = field.config?.zones;\n const parts: string[] = [];\n if (zones?.nonRepeatable?.length) {\n const nested = fieldsToBody(zones.nonRepeatable, indent + \" \");\n parts.push(`${indent} readonly nonRepeatable?: {\\n${nested}\\n${indent} };`);\n }\n if (zones?.repeatable?.fields?.length) {\n const nested = fieldsToBody(zones.repeatable.fields, indent + \" \");\n parts.push(`${indent} readonly repeatable?: Array<{\\n${nested}\\n${indent} }>;`);\n }\n if (parts.length === 0) return \"Record<string, unknown>\"; // zoned array with no fields yet\n return `{\\n${parts.join(\"\\n\")}\\n${indent}}`;\n}\n\n/** Render the body of an object type from a field list, recursing into zones. */\nfunction fieldsToBody(fields: ContentModelField[], indent: string): string {\n const lines: string[] = [];\n for (const field of fields) {\n const optional = field.required ? \"\" : \"?\";\n let typeExpr: string;\n\n if (field.type === \"array\" && field.config?.zones) {\n typeExpr = arrayZoneType(field, indent);\n } else {\n typeExpr = scalarType(field);\n }\n\n const safeLabel = field.label ? escapeJsDoc(field.label) : \"\";\n if (safeLabel && safeLabel !== field.key) {\n lines.push(`${indent}/** ${safeLabel} */`);\n }\n lines.push(`${indent}readonly ${propName(field.key)}${optional}: ${typeExpr};`);\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate a complete `.ts` module from a set of content models.\n * Deterministic: models are sorted by slug; field order is preserved as authored.\n */\nexport function generateTypes(\n models: GeneratableModel[],\n opts: GenerateOptions = {},\n): string {\n const version = opts.version ?? \"0.1.0\";\n // Code-unit sort (NOT localeCompare): locale/ICU-independent so the generated\n // file is byte-identical on every machine — committed output diffs cleanly.\n const sorted = [...models].sort((a, b) =>\n a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0,\n );\n\n const header = `// ⚠️ AUTO-GENERATED by @bettercms-ai/codegen v${version} — DO NOT EDIT.\n// Regenerate with: npx @bettercms-ai/codegen\n// Source of truth: your BetterCMS content models (the same schema the dashboard\n// builder and the MCP tools write). Re-run codegen after any schema change.\n${opts.bannerComment ? `// ${opts.bannerComment}\\n` : \"\"}`;\n\n const interfaces: string[] = [];\n const mapEntries: string[] = [];\n // Different slugs can PascalCase to the same base name (e.g. \"case-study\" and\n // \"case_study\" → \"CaseStudy\"). Emitting two identical interfaces would silently\n // declaration-merge into one wrong type, so disambiguate with a numeric suffix.\n const usedNames = new Set<string>();\n\n for (const model of sorted) {\n const base = `${pascalCase(model.slug)}Fields`;\n let typeName = base;\n for (let n = 2; usedNames.has(typeName); n++) typeName = `${base}_${n}`;\n usedNames.add(typeName);\n\n const name = model.name ? escapeJsDoc(model.name) : \"\";\n const desc = model.description ? escapeJsDoc(model.description) : \"\";\n const doc = name\n ? `/**\\n * ${name}${desc ? ` — ${desc}` : \"\"}\\n * Model slug: \\`${model.slug}\\`\\n */\\n`\n : \"\";\n const body = model.fields.length\n ? fieldsToBody(model.fields, \" \")\n : \" // (no fields defined yet)\";\n interfaces.push(`${doc}export interface ${typeName} {\\n${body}\\n}`);\n mapEntries.push(` readonly ${JSON.stringify(model.slug)}: ${typeName};`);\n }\n\n const schemaMap = `/**\n * Registry mapping each model slug to its typed fields. The Next adapter uses this to\n * type \\`getEntry(\"blog\", ...)\\` by slug — autocomplete and exhaustiveness for free.\n */\nexport interface BetterCMSSchema {\n${mapEntries.join(\"\\n\") || \" // (no models defined yet)\"}\n}\n\n/** Union of all model slugs. */\nexport type BetterCMSModelSlug = keyof BetterCMSSchema;`;\n\n return [header, PREAMBLE, interfaces.join(\"\\n\\n\"), schemaMap, \"\"].join(\"\\n\");\n}\n","/**\n * @bettercms-ai/codegen — schema → Live Preview binding helper generator.\n *\n * Companion to {@link generateTypes}. Where that emits the *types*, this emits a\n * tiny, schema-derived runtime that stamps `data-bcms-field` / `data-bcms-kind`\n * attributes onto the elements a site author binds to CMS content. Those\n * attributes are what the dashboard's Live Preview editor reads to turn the real,\n * running site into an editable canvas (the parent maps `data-bcms-field` → its\n * internal `data-node-id` on frame load).\n *\n * Why a helper and not auto-injection: BetterCMS never renders the customer's DOM\n * — the site does. So binding is opt-in per element via a spread:\n *\n * import { bcms } from \"./bettercms.bindings.generated\";\n *\n * <h1 {...bcms.blog.title}>{entry.fields.title}</h1> // scalar\n * <li {...bcms.blog.tags.value(i)}>{tag}</li> // primitive-array item\n * <article {...bcms.blog.features.$(i)}> // array item root\n * <h3 {...bcms.blog.features.label(i)}>{f.label}</h3> // array item sub-field\n * </article>\n *\n * The attributes only appear when the site is built with `BCMS_ANNOTATE` set\n * (preview builds); a normal production build ships zero extra attributes, because\n * `bcmsField` returns `{}`. Same generated file, both builds — no separate mode.\n *\n * Pure + deterministic, exactly like the type generator: same models in → identical\n * string out (slug-sorted, field order preserved, no clock, no I/O). Field keys are\n * author/agent-controlled, so every embedded key is emitted as an escaped string\n * literal (never interpolated into code) — hostile input can't break the output.\n *\n * Grammar — mirrors what the editor's `fieldPathToNodeId` resolves:\n * `title` · `hero.heroTitle` · `hero.primaryCta.label` (group leaves, any depth)\n * `features[0]` · `features[0].label` · `intro.facts[0].label` (repeaters, one index)\n * Group (non-repeatable) zones recurse into nested binding objects; a repeater is an\n * object with `$(i)` (item root) + one accessor per scalar sub-field. Arrays nested\n * inside a repeater item (a second index) are still beyond what the editor can\n * address, so they are intentionally omitted rather than emitted as dead paths.\n */\n\nimport type { ContentModelField, ContentModelFieldType } from \"@bettercms-ai/types\";\nimport type { GeneratableModel, GenerateOptions } from \"./generate.js\";\n\nconst VALID_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * Render a field key as an object property name. Keys aren't guaranteed to be valid\n * identifiers (e.g. \"my-field\", \"1title\"), so anything that isn't a bare identifier\n * is quoted — always valid TS. (Mirrors the same helper in `generate.ts`.)\n */\nfunction propName(key: string): string {\n return VALID_IDENT.test(key) ? key : JSON.stringify(key);\n}\n\n/**\n * The kind label written to `data-bcms-kind`, mapped to the editor's closed field-type\n * set (matches the dashboard adapter's `toEditorFieldType`): API-only types that have\n * no on-canvas control collapse to \"text\". Informational today — the editor derives the\n * authoritative kind from the loaded model — but kept truthful for debugging/forward use.\n */\nfunction bindingKind(t: ContentModelFieldType): string {\n switch (t) {\n case \"text\":\n case \"richtext\":\n case \"image\":\n case \"boolean\":\n case \"number\":\n case \"select\":\n case \"array\":\n return t;\n // reference / multi-reference / date / datetime → plain text in the editor v1.\n default:\n return \"text\";\n }\n}\n\n/**\n * Build a runtime path expression for an array element: a string literal split around\n * the index so it concatenates at call time. Both halves are JSON-escaped, so an\n * author-controlled key can never inject code. e.g. (\"features[\", \"].label\") →\n * `\"features[\" + i + \"].label\"`.\n */\nfunction indexedPath(prefix: string, suffix: string): string {\n return `${JSON.stringify(prefix)} + i + ${JSON.stringify(suffix)}`;\n}\n\n/** Render a repeater binding object: `$(i)` item root + one accessor per scalar\n * sub-field. `path` is the repeater's full (possibly dotted) field path. */\nfunction repeaterBinding(\n itemFields: ContentModelField[],\n path: string,\n indent: string,\n): string {\n const lines: string[] = [\n `${indent} $: (i: number) => bcmsField(${indexedPath(`${path}[`, \"]\")}, \"array\"),`,\n ];\n for (const sub of itemFields) {\n // A sub-field that is itself an array would need a second index the editor\n // can't address yet — skip it rather than emit a path that won't bind.\n if (sub.type === \"array\") continue;\n lines.push(\n `${indent} ${propName(sub.key)}: (i: number) => bcmsField(${indexedPath(`${path}[`, `].${sub.key}`)}, ${JSON.stringify(bindingKind(sub.type))}),`,\n );\n }\n return `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n}\n\n/** Render the binding for one field at `path`, recursing into group zones. */\nfunction fieldBinding(\n field: ContentModelField,\n prefix: string,\n indent: string,\n): string {\n const path = prefix ? `${prefix}.${field.key}` : field.key;\n const name = propName(field.key);\n\n if (field.type !== \"array\") {\n return `${indent}${name}: bcmsField(${JSON.stringify(path)}, ${JSON.stringify(bindingKind(field.type))}),`;\n }\n\n const zones = field.config?.zones;\n // Group (non-repeatable) → a nested object of dotted-path leaf bindings.\n if (zones?.nonRepeatable?.length) {\n const body = zones.nonRepeatable\n .map((child) => fieldBinding(child, path, `${indent} `))\n .join(\"\\n\");\n return `${indent}${name}: {\\n${body}\\n${indent}},`;\n }\n // Repeater → `$(i)` + scalar sub-field accessors.\n if (zones?.repeatable?.fields?.length) {\n return `${indent}${name}: ${repeaterBinding(zones.repeatable.fields, path, indent)},`;\n }\n // Primitive list (`config.itemType` or bare) → `$(i)` + synthetic `value(i)`.\n const lines = [\n `${indent} $: (i: number) => bcmsField(${indexedPath(`${path}[`, \"]\")}, \"array\"),`,\n `${indent} value: (i: number) => bcmsField(${indexedPath(`${path}[`, \"].value\")}, \"text\"),`,\n ];\n return `${indent}${name}: {\\n${lines.join(\"\\n\")}\\n${indent}},`;\n}\n\n/** Render the binding entries for one model's fields (field order preserved). */\nfunction fieldsToBindings(fields: ContentModelField[], indent: string): string {\n return fields.map((field) => fieldBinding(field, \"\", indent)).join(\"\\n\");\n}\n\n/** The self-contained runtime emitted once at the top of every bindings file. */\nconst PREAMBLE = `/**\n * True when this site is built for Live Preview annotation. Set \\`BCMS_ANNOTATE=1\\`\n * in the preview build only; unset (the default) ships zero binding attributes.\n * Read defensively so the module is safe in any runtime (browser, Node, edge).\n */\nconst BCMS_ANNOTATE: boolean = (() => {\n try {\n const v = (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env?.BCMS_ANNOTATE;\n return v != null && v !== \"\" && v !== \"0\" && v !== \"false\";\n } catch {\n return false;\n }\n})();\n\n/**\n * Binding attributes for a CMS-bound element. Spread onto the element that renders a\n * field: \\`<h1 {...bcmsField(\"title\", \"text\")}>\\`. Returns \\`{}\\` unless BCMS_ANNOTATE\n * is set, so production markup is untouched.\n */\nexport function bcmsField(path: string, kind: string): Record<string, string> {\n return BCMS_ANNOTATE ? { \"data-bcms-field\": path, \"data-bcms-kind\": kind } : {};\n}\n`;\n\n/**\n * Generate the Live Preview bindings module from a set of content models.\n * Deterministic: models are sorted by slug; field order is preserved as authored.\n */\nexport function generateBindings(\n models: GeneratableModel[],\n opts: GenerateOptions = {},\n): string {\n const version = opts.version ?? \"0.1.0\";\n // Code-unit sort (NOT localeCompare) so output is byte-identical on every machine.\n const sorted = [...models].sort((a, b) =>\n a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0,\n );\n\n const header = `// ⚠️ AUTO-GENERATED by @bettercms-ai/codegen v${version} — DO NOT EDIT.\n// Live Preview field bindings. Regenerate with: npx @bettercms-ai/codegen --bindings-out <path>\n// Spread these onto the elements that render your content; they emit\n// data-bcms-field/data-bcms-kind only when the site is built with BCMS_ANNOTATE set.\n${opts.bannerComment ? `// ${opts.bannerComment}\\n` : \"\"}`;\n\n const entries = sorted.map((model) => {\n const body = model.fields.length\n ? `\\n${fieldsToBindings(model.fields, \" \")}\\n `\n : \"\";\n return ` ${JSON.stringify(model.slug)}: {${body}},`;\n });\n\n const bcms = `/**\n * Field bindings keyed by model slug. Spread a binding onto the element that renders\n * that field. Arrays expose \\`$(i)\\` for the item element and one accessor per\n * (one-level) sub-field; primitive arrays expose \\`value(i)\\` for the item's scalar.\n */\nexport const bcms = {\n${entries.join(\"\\n\") || \" // (no models defined yet)\"}\n} as const;`;\n\n return [header, PREAMBLE, bcms, \"\"].join(\"\\n\");\n}\n","/**\n * @bettercms-ai/codegen — schema → typed React render components generator.\n *\n * Companion to {@link generateTypes} (types) and {@link generateBindings} (Live\n * Preview attributes). This emits a small, self-contained `.tsx` module with two\n * components that render the canonical Delivery field shapes CORRECTLY, so authors\n * never hand-roll the rendering that produces the classic bugs:\n *\n * - <RichText> renders the server-sanitized `html` via `dangerouslySetInnerHTML`,\n * instead of interpolating the value as a JSX child (which React escapes, so the\n * page shows literal `<p>…</p>` tags — the #6 escaped-richtext bug).\n * - <Image> reads the normalized image object's `.url`/`.altText`, instead of\n * treating the object as a string.\n *\n * The emitted module is intentionally generic (not per-model) and dependency-free\n * beyond React, so it is a drop-in: point codegen at a path and import the two\n * components. It is deterministic (no clock, no I/O) like the sibling generators.\n *\n * Security: `html` is the Delivery API's server-rendered, DOMPurify-sanitized output\n * (see the RichText type docs). `<RichText>` injects exactly that field. If a caller\n * passes HTML from another, untrusted source they must sanitize it themselves.\n */\n\nimport type { GenerateOptions } from \"./generate.js\";\n\n/**\n * Generate the `bettercms.components.tsx` module: typed `<RichText>` and `<Image>`\n * components for the canonical Delivery field shapes. Deterministic — same options\n * in, identical string out.\n */\nexport function generateComponents(opts: GenerateOptions = {}): string {\n const version = opts.version ?? \"0.1.0\";\n const header = `// ⚠️ AUTO-GENERATED by @bettercms-ai/codegen v${version} — DO NOT EDIT.\n// Regenerate with: npx @bettercms-ai/codegen --components-out <path>\n// Typed render components for BetterCMS field shapes. Use these instead of\n// hand-rendering richtext/image values — they render the canonical shapes correctly.\n${opts.bannerComment ? `// ${opts.bannerComment}\\n` : \"\"}`;\n\n const body = `import * as React from \"react\";\n\n/** Rich-text value from the Delivery API. \\`html\\` is server-rendered + sanitized. */\nexport type RichTextValue = {\n readonly format: string;\n readonly value: unknown;\n readonly html?: string;\n};\n\n/** Normalized image/media value from the Delivery API. */\nexport interface BetterCMSImageValue {\n readonly url: string;\n readonly altText?: string | null;\n readonly width?: number;\n readonly height?: number;\n}\n\ntype RichTextProps = {\n /** The richtext field value (\\`entry.fields.someRichText\\`). */\n field?: RichTextValue | null;\n /** Element/component to render as. Default: \\`\"div\"\\`. */\n as?: React.ElementType;\n} & Omit<React.HTMLAttributes<HTMLElement>, \"dangerouslySetInnerHTML\" | \"children\">;\n\n/**\n * Render a richtext field as HTML. Uses the server-sanitized \\`html\\` via\n * \\`dangerouslySetInnerHTML\\` — NEVER interpolate a richtext value as a JSX child\n * (React escapes it, so the page shows literal tags). Renders nothing when unset.\n */\nexport function RichText({ field, as: Tag = \"div\", ...rest }: RichTextProps) {\n if (!field || !field.html) return null;\n return <Tag {...rest} dangerouslySetInnerHTML={{ __html: field.html }} />;\n}\n\ntype ImageProps = {\n /** The image field value (\\`entry.fields.someImage\\`). */\n field?: BetterCMSImageValue | null;\n /** Alt text override; defaults to the field's \\`altText\\`, then \\`\"\"\\`. */\n alt?: string;\n} & Omit<React.ImgHTMLAttributes<HTMLImageElement>, \"src\">;\n\n/**\n * Render an image field as an \\`<img>\\` from its normalized \\`.url\\`/\\`.altText\\`.\n * Renders nothing when unset. Pass \\`alt\\` to override the stored alt text.\n */\nexport function Image({ field, alt, ...rest }: ImageProps) {\n if (!field || !field.url) return null;\n return (\n <img\n src={field.url}\n alt={alt ?? field.altText ?? \"\"}\n width={field.width}\n height={field.height}\n {...rest}\n />\n );\n}\n`;\n\n return [header, body].join(\"\\n\");\n}\n"],"mappings":";;;AAUA,SAAS,WAAW,aAAa;AACjC,SAAS,SAAS,eAAe;;;ACiBjC,eAAsB,YACpB,MAC6B;AAC7B,QAAM,UAAU,KAAK,aAAa,WAAW;AAC7C,QAAM,OAAO,KAAK,OAAO,QAAQ,QAAQ,EAAE;AAC3C,QAAM,MAAM,GAAG,IAAI;AAEnB,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,QAAQ,KAAK;AAAA;AAAA;AAAA,MAGvB,SAAS,EAAE,eAAe,UAAU,KAAK,MAAM,IAAI,QAAQ,mBAAmB;AAAA,IAChF,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,UAAM,IAAI;AAAA,MACR,mDAAmD,GAAG,KACpD,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CACjD;AAAA,IACF;AAAA,EACF;AAEA,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,OACJ,IAAI,WAAW,OAAO,IAAI,W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