@opencloudcms/codegen 0.0.0-stage → 0.1.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/eject.js ADDED
@@ -0,0 +1,773 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.EjectTargetExistsError = void 0;
37
+ exports.printEjectedBlockTsx = printEjectedBlockTsx;
38
+ exports.ejectedBlockFile = ejectedBlockFile;
39
+ exports.ejectComposedBlock = ejectComposedBlock;
40
+ /**
41
+ * Eject a composed block to TSX: print a hand-written `defineBlock` file that renders exactly like
42
+ * `defineComposedBlock(spec)` (same fields, same `ui` primitives, same `composedHelpers` value readers and wrappers)
43
+ * and replace the managed `.block.ts` file by it. The Block Builder no longer manages an ejected block.
44
+ *
45
+ * Keep the printed fields in step with `defineComposedBlock` (`@opencloudcms/core/blocks`, composed/define.ts);
46
+ * `test/eject.test.ts` compares both definitions.
47
+ */
48
+ const fs = __importStar(require("node:fs"));
49
+ const path = __importStar(require("node:path"));
50
+ const schema_1 = require("@opencloudcms/schema");
51
+ const blocks_1 = require("./blocks");
52
+ const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
53
+ const L = (en, vi, fr, id) => ({ 'en-US': en, 'vi-VN': vi, 'fr-FR': fr, 'id-ID': id });
54
+ const q = (s) => (0, blocks_1.printLiteral)(s);
55
+ const has = (o, k) => !!o && Object.prototype.hasOwnProperty.call(o, k);
56
+ /** Same as `layoutValue` of the composed renderer. */
57
+ const layoutValue = (l) => l?.kind === 'list' ? 'list' : l?.kind === 'carousel' ? `carousel-${l.columns ?? 3}` : `grid-${l?.columns ?? 3}`;
58
+ /** Options of the editor layout select, as `layoutOptions` of `defineComposedBlock` (carousel values only for a carousel). */
59
+ const layoutOptions = (l) => [
60
+ { value: 'list', label: L('List', 'Danh sách', 'Liste', 'Daftar') },
61
+ ...[2, 3, 4, 5, 6].map((n) => ({ value: `grid-${n}`, label: L(`Grid · ${n}`, `Lưới · ${n}`, `Grille · ${n}`, `Kisi · ${n}`) })),
62
+ ...(l?.kind === 'carousel'
63
+ ? [1, 2, 3, 4, 5, 6].map((n) => ({ value: `carousel-${n}`, label: L(`Carousel · ${n}`, `Băng chuyền · ${n}`, `Carrousel · ${n}`, `Karosel · ${n}`) }))
64
+ : []),
65
+ ];
66
+ /** `"<key> · <label>"` in every locale, as `prefixed` of `defineComposedBlock`. */
67
+ const prefixed = (key, label) => Object.fromEntries(Object.entries(label).map(([l, t]) => [l, `${key} · ${t}`]));
68
+ /** Nodes of the elements `els`, in tree order (depth first). */
69
+ function nodesOf(n, els, out = []) {
70
+ if (els.includes(n.el))
71
+ out.push(n);
72
+ for (const c of n.children ?? [])
73
+ nodesOf(c, els, out);
74
+ return out;
75
+ }
76
+ const slotNodes = (n) => nodesOf(n, ['Slot']);
77
+ /** Field name of each `Slot` (`slot`, `slot2`, …), `Region` (`region__<name>`) and `PageContent` (`pageContent`) node. */
78
+ function slotNames(tree) {
79
+ const slots = new Map();
80
+ slotNodes(tree).forEach((n, i) => slots.set(n, i === 0 ? 'slot' : `slot${i + 1}`));
81
+ for (const n of nodesOf(tree, ['Region', 'PageContent']))
82
+ slots.set(n, n.el === 'PageContent' ? 'pageContent' : `region__${String(n.props?.name)}`);
83
+ return slots;
84
+ }
85
+ /** Same as `regionLabel` of `defineComposedBlock`. */
86
+ function regionLabel(p) {
87
+ if (typeof p.label === 'string' && p.label)
88
+ return p.label;
89
+ if (p.label && typeof p.label === 'object' && !Array.isArray(p.label))
90
+ return p.label;
91
+ return p.name;
92
+ }
93
+ function labelCandidates(tree) {
94
+ const out = [];
95
+ let done = false;
96
+ const walk = (n, conds) => {
97
+ if (done)
98
+ return;
99
+ const c = n.showIf ? [...conds, n.showIf] : conds;
100
+ if (n.el === 'Heading') {
101
+ out.push({ node: n, conds: c });
102
+ if (!c.length)
103
+ done = true;
104
+ return;
105
+ }
106
+ for (const k of n.children ?? [])
107
+ walk(k, c);
108
+ };
109
+ walk(tree, []);
110
+ return out;
111
+ }
112
+ function imageEntryPaths(n, out = new Set()) {
113
+ if (n.el === 'Image') {
114
+ for (const k of ['src', 'alt']) {
115
+ const s = n.bind?.[k];
116
+ if (s?.from === 'entry')
117
+ out.add(s.path);
118
+ }
119
+ }
120
+ for (const c of n.children ?? [])
121
+ imageEntryPaths(c, out);
122
+ return out;
123
+ }
124
+ const call = (fn, args) => `${fn}(${args.join(', ')})`;
125
+ const opts = (o, indent) => (Object.keys(o).length ? [(0, blocks_1.printLiteral)(o, indent)] : []);
126
+ function manualField(f, indent) {
127
+ const o = {};
128
+ if (f.label !== undefined)
129
+ o.label = f.label;
130
+ if (f.default !== undefined)
131
+ o.default = f.default;
132
+ if (f.kind === 'select')
133
+ o.options = f.options ?? [];
134
+ return call(`b.${f.kind}`, opts(o, indent));
135
+ }
136
+ /** `fields` entries (`key: b.…(…)`), in the order `defineComposedBlock` produces them. */
137
+ function printFields(spec, indent) {
138
+ const out = [];
139
+ if ((0, schema_1.composedKind)(spec) === 'overlay') {
140
+ const o = { label: L('Overlay name', 'Tên lớp phủ', 'Nom de la superposition', 'Nama overlay'), default: (0, schema_1.overlayDefaultName)(spec.name) };
141
+ out.push(['name', call('b.text', [(0, blocks_1.printLiteral)(o, indent)])]);
142
+ }
143
+ out.push(...Object.entries(spec.fields).map(([k, f]) => [k, manualField(f, indent)]));
144
+ const binding = spec.binding;
145
+ if (binding?.mode === 'single') {
146
+ out.push(['entry', call('b.entry', [q(binding.apiId), (0, blocks_1.printLiteral)({ label: L('Entry', 'Mục nội dung', 'Entrée', 'Entri') }, indent)])]);
147
+ }
148
+ else if (binding?.mode === 'collection') {
149
+ const o = binding.options ?? {};
150
+ const limit = binding.limit ?? 12;
151
+ const baseFilter = Object.fromEntries((binding.filter ?? []).map((f) => [f.field, String(f.value)]));
152
+ const defaultSort = binding.sort ? `${binding.sort.field}:${binding.sort.direction}` : undefined;
153
+ const e = {
154
+ label: L('Entries', 'Danh sách mục', 'Entrées', 'Entri'),
155
+ limit,
156
+ sortable: o.editorSort === true,
157
+ filterable: o.editorFilter === true,
158
+ ...(Object.keys(baseFilter).length ? { baseFilter } : {}),
159
+ ...(defaultSort ? { defaultSort } : {}),
160
+ lockLimit: o.editorLimit !== true,
161
+ default: { mode: 'query', limit, ...(defaultSort ? { sort: defaultSort } : {}) },
162
+ };
163
+ out.push(['entries', call('b.entries', [q(binding.apiId), (0, blocks_1.printLiteral)(e, indent)])]);
164
+ if (o.editorLayout) {
165
+ const layout = { label: L('Layout', 'Bố cục', 'Disposition', 'Tata letak'), options: layoutOptions(binding.layout), default: layoutValue(binding.layout) };
166
+ out.push(['layout', call('b.select', [(0, blocks_1.printLiteral)(layout, indent)])]);
167
+ }
168
+ }
169
+ // CollectionLists: a `b.entries` field named after each key (+ `<key>__layout` when page editors pick the layout).
170
+ for (const { key, node } of (0, schema_1.collectionListsOf)(spec)) {
171
+ const p = node.props;
172
+ const ed = p.editor ?? {};
173
+ const limit = p.limit ?? schema_1.COLLECTION_LIST_DEFAULT_LIMIT;
174
+ const baseFilter = Object.fromEntries((p.filter ?? []).map((f) => [f.field, String(f.value)]));
175
+ const defaultSort = p.sort ? `${p.sort.field}:${p.sort.direction}` : undefined;
176
+ const e = {
177
+ label: prefixed(key, L('Entries', 'Danh sách mục', 'Entrées', 'Entri')),
178
+ limit,
179
+ sortable: ed.sort === true,
180
+ filterable: ed.filter === true,
181
+ ...(Object.keys(baseFilter).length ? { baseFilter } : {}),
182
+ ...(defaultSort ? { defaultSort } : {}),
183
+ lockLimit: ed.limit !== true,
184
+ maxLimit: schema_1.COLLECTION_LIST_MAX_LIMIT,
185
+ default: { mode: 'query', limit, ...(defaultSort ? { sort: defaultSort } : {}) },
186
+ };
187
+ out.push([key, call('b.entries', [q(p.apiId), (0, blocks_1.printLiteral)(e, indent)])]);
188
+ if (ed.layout === true) {
189
+ const layout = { label: prefixed(key, L('Layout', 'Bố cục', 'Disposition', 'Tata letak')), options: layoutOptions(p.layout), default: layoutValue(p.layout) };
190
+ out.push([`${key}${schema_1.LIST_LAYOUT_SUFFIX}`, call('b.select', [(0, blocks_1.printLiteral)(layout, indent)])]);
191
+ }
192
+ }
193
+ slotNodes(spec.tree).forEach((n, i) => {
194
+ const p = n.props ?? {};
195
+ const o = {
196
+ label: L('Content', 'Nội dung', 'Contenu', 'Konten'),
197
+ ...(Array.isArray(p.allow) ? { allow: p.allow } : {}),
198
+ ...(typeof p.max === 'number' ? { max: p.max } : {}),
199
+ };
200
+ out.push([i === 0 ? 'slot' : `slot${i + 1}`, call('b.slot', [(0, blocks_1.printLiteral)(o, indent)])]);
201
+ });
202
+ for (const n of nodesOf(spec.tree, ['Region', 'PageContent'])) {
203
+ const p = n.props ?? {};
204
+ if (n.el === 'PageContent') {
205
+ out.push(['pageContent', call('b.slot', [(0, blocks_1.printLiteral)({ label: L('Page content', 'Nội dung trang', 'Contenu de la page', 'Konten halaman') }, indent)])]);
206
+ continue;
207
+ }
208
+ const o = { label: regionLabel(p), ...(Array.isArray(p.allow) ? { allow: p.allow } : {}) };
209
+ out.push([`region__${String(p.name)}`, call('b.slot', [(0, blocks_1.printLiteral)(o, indent)])]);
210
+ }
211
+ return out.map(([k, v]) => `${IDENT.test(k) ? k : q(k)}: ${v},`);
212
+ }
213
+ const propExpr = (name) => (IDENT.test(name) ? `props.${name}` : `props[${q(name)}]`);
214
+ const lit = (v) => (v === undefined ? 'undefined' : (0, blocks_1.printLiteral)(v));
215
+ const code = (v) => ('expr' in v ? v.expr : lit(v.lit));
216
+ function source(g, s) {
217
+ switch (s.from) {
218
+ case 'entry':
219
+ return g.bound ? `get(entry, ${q(s.path)})` : 'undefined';
220
+ case 'entryUrl':
221
+ return g.bound ? g.link : 'null';
222
+ case 'field':
223
+ return propExpr(s.name);
224
+ case 'const':
225
+ return lit(s.value);
226
+ }
227
+ }
228
+ /** Bound value if `bind[k]` is set, else the fixed `props[k]` (as the renderer's `val`). */
229
+ function val(g, n, k) {
230
+ if (n.bind && has(n.bind, k)) {
231
+ const s = n.bind[k];
232
+ return s.from === 'const' ? { lit: s.value } : { expr: source(g, s) };
233
+ }
234
+ return { lit: n.props?.[k] };
235
+ }
236
+ /** JSX attribute for a literal value. */
237
+ function attrLit(name, v) {
238
+ if (v === true)
239
+ return name;
240
+ if (typeof v === 'string' && /^[^"\\\n\r{}<>&]*$/.test(v))
241
+ return `${name}="${v}"`;
242
+ return `${name}={${(0, blocks_1.printLiteral)(v)}}`;
243
+ }
244
+ const attrExpr = (name, expr) => `${name}={${expr}}`;
245
+ function textAttr(name, v) {
246
+ if ('expr' in v)
247
+ return attrExpr(name, `h.text(${v.expr})`);
248
+ const t = typeof v.lit === 'string' ? v.lit : typeof v.lit === 'number' && Number.isFinite(v.lit) ? String(v.lit) : '';
249
+ return attrLit(name, t);
250
+ }
251
+ /** Literal attributes for token props that are set in `props`. */
252
+ function tokens(p, keys) {
253
+ return keys.filter((k) => p[k] !== undefined).map((k) => attrLit(k, p[k]));
254
+ }
255
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
256
+ /**
257
+ * `style={…}` of a node: its `style` as a literal, without the top-level properties that fail validation (the renderer
258
+ * skips invalid values too). Nothing when there is no valid property.
259
+ */
260
+ function styleAttr(n) {
261
+ const ok = styleLiteral(n);
262
+ return ok ? [attrExpr('style', (0, blocks_1.printLiteral)(ok))] : [];
263
+ }
264
+ /** The valid top-level properties of a node's `style`, or null when there is none. */
265
+ function styleLiteral(n) {
266
+ if (!isObj(n.style))
267
+ return null;
268
+ const bad = new Set((0, schema_1.validateNodeStyle)(n.style, []).map((i) => String(i.path[0])));
269
+ const ok = Object.fromEntries(Object.entries(n.style).filter(([k, v]) => v !== undefined && !bad.has(k)));
270
+ return Object.keys(ok).length ? ok : null;
271
+ }
272
+ /** Non-empty string props (Columns `gapX` / `gapY`), as the renderer's `str`. */
273
+ function strings(p, keys) {
274
+ return keys.filter((k) => typeof p[k] === 'string' && p[k] !== '').map((k) => attrLit(k, p[k]));
275
+ }
276
+ /** The text of a bound/fixed value as a JS expression (`h.text(…)` or a string literal). */
277
+ function textCode(v) {
278
+ if ('expr' in v)
279
+ return `h.text(${v.expr})`;
280
+ return q(typeof v.lit === 'string' ? v.lit : typeof v.lit === 'number' && Number.isFinite(v.lit) ? String(v.lit) : '');
281
+ }
282
+ /** Boolean props as the renderer's `bool`: nothing when unset. */
283
+ const bools = (p, keys) => keys.filter((k) => typeof p[k] === 'boolean').map((k) => attrLit(k, p[k]));
284
+ /** Expression of the bound `href` of a clickable Image/Box/Card (a fixed `props.href` does not make one clickable). */
285
+ const boundHref = (g, n) => (n.bind && has(n.bind, 'href') ? `h.href(${source(g, n.bind.href)})` : null);
286
+ const describedAttr = (g, n) => {
287
+ const d = g.describe.get(n);
288
+ return d ? [attrExpr('describedBy', d)] : [];
289
+ };
290
+ /**
291
+ * The `action` attribute: the literal, or `h.action(<literal>, entry)` when an `entryRef` param is bound to the current
292
+ * entry (as the renderer's `actionOf`).
293
+ */
294
+ function actionAttr(g, action) {
295
+ const params = action.type === 'run' && isObj(action.params) ? Object.values(action.params) : [];
296
+ return params.includes(schema_1.CURRENT_ENTRY) ? attrExpr('action', `h.action(${lit(action)}, ${g.bound ? 'entry' : 'null'})`) : attrLit('action', action);
297
+ }
298
+ /** Attributes that make an Image/Box/Card clickable: bound `href`, `action`, `ariaLabel` (Box/Card) and the tooltip link. */
299
+ function clickAttrs(g, n, aria) {
300
+ const p = n.props ?? {};
301
+ const href = boundHref(g, n);
302
+ return [...(href ? [attrExpr('href', href)] : []), ...(isObj(p.action) ? [actionAttr(g, p.action)] : []), ...(aria ? strings(p, ['ariaLabel']) : []), ...describedAttr(g, n)];
303
+ }
304
+ function element(tag, attrs, children, indent) {
305
+ const open = `<${tag}${attrs.length ? ' ' + attrs.join(' ') : ''}`;
306
+ if (!children)
307
+ return `${open} />`;
308
+ if (!children.length)
309
+ return `${open}></${tag}>`;
310
+ const inner = indent + ' ';
311
+ const lines = children.map((c) => inner + (c.jsx ? c.code : `{${c.code}}`));
312
+ return `${open}>\n${lines.join('\n')}\n${indent}</${tag}>`;
313
+ }
314
+ /** `id` attribute from `anchorId`, as the renderer's `str(p.anchorId)`. */
315
+ const idAttr = (p) => (typeof p.anchorId === 'string' && p.anchorId ? [attrLit('id', p.anchorId)] : []);
316
+ /** JS test of "this node itself is a link or button", or null when it never is (as the renderer's `focusableSelf`). */
317
+ function focusTest(g, n) {
318
+ const p = n.props ?? {};
319
+ const action = isObj(p.action);
320
+ const href = boundHref(g, n);
321
+ switch (n.el) {
322
+ case 'Button':
323
+ return action ? 'true' : `!!ui.safeHref(h.href(${code(val(g, n, 'href'))}))`;
324
+ case 'Image': {
325
+ const img = `!!h.image(${[code(val(g, n, 'src')), ...(n.bind?.alt || p.alt !== undefined ? [code(val(g, n, 'alt'))] : [])].join(', ')})`;
326
+ return action ? img : href ? `${img} && !!${href}` : null;
327
+ }
328
+ case 'Box':
329
+ case 'Card':
330
+ return action ? 'true' : href ? `!!${href}` : null;
331
+ default:
332
+ return null;
333
+ }
334
+ }
335
+ /** Focus candidates of the subtree `n` in depth-first order (the first whose test and conditions pass wins). */
336
+ function focusCandidates(g, n, conds = [], out = []) {
337
+ const c = n.showIf ? [...conds, n.showIf] : conds;
338
+ const test = focusTest(g, n);
339
+ if (test)
340
+ out.push({ node: n, conds: c, test });
341
+ for (const k of n.children ?? [])
342
+ focusCandidates(g, k, c, out);
343
+ return out;
344
+ }
345
+ /**
346
+ * Tooltip: the node that takes `aria-describedby` is the first rendered link/button of the child, which depends on the
347
+ * data, so a `target` index is computed at run time (`indexOf(true)` over the candidates, -1: the wrapper takes the focus).
348
+ */
349
+ function tooltip(g, n, indent) {
350
+ const p = n.props ?? {};
351
+ const child = n.children?.[0];
352
+ // Same as the renderer: no child, or one hidden by its showIf, renders no tooltip at all.
353
+ if (!child)
354
+ return { jsx: false, code: 'null' };
355
+ const shown = child.showIf ? condition(g, child.showIf) : undefined;
356
+ const ind = shown ? indent + ' ' : indent;
357
+ const cands = focusCandidates(g, child);
358
+ const id = ++g.tooltips;
359
+ const t = `target${id}`;
360
+ const tip = `tip${id}`;
361
+ cands.forEach((c, i) => g.describe.set(c.node, `${t} === ${i} ? ${tip} : undefined`));
362
+ const inner = ind + (cands.length ? ' ' : '');
363
+ const content = shown ? body(g, child, inner + ' ') : node(g, child, inner + ' ');
364
+ const attrs = [...idAttr(p), textAttr('text', val(g, n, 'text')), ...tokens(p, ['side']), cands.length ? attrExpr('focusWrapper', `${t} < 0`) : 'focusWrapper', ...styleAttr(n)];
365
+ const render = `(${cands.length ? tip : ''}) => ${content.code.includes('\n') ? `(\n${inner} ${content.code}\n${inner} )` : content.code}`;
366
+ const el = element('ui.Tooltip', attrs, [{ jsx: false, code: render }], inner);
367
+ const tests = cands.map((c) => [...c.conds.map((x) => condition(g, x)), c.test].join(' && '));
368
+ const out = cands.length ? { jsx: false, code: `((${t}) => (\n${inner} ${el}\n${inner}))([${tests.join(', ')}].indexOf(true))` } : { jsx: true, code: el };
369
+ if (!shown)
370
+ return out;
371
+ return { jsx: false, code: `${shown} ? (\n${indent} ${out.code}\n${indent}) : null` };
372
+ }
373
+ /** Attributes of a form control from its props, in the renderer's terms. */
374
+ function control(g, n) {
375
+ const p = n.props ?? {};
376
+ const tx = (keys) => keys.map((k) => textAttr(k, val(g, n, k)));
377
+ const opt = () => {
378
+ g.usesLocale = true;
379
+ return [attrExpr('options', `h.options(${(0, blocks_1.printLiteral)(Array.isArray(p.options) ? p.options : [], ' ')}, locale)`)];
380
+ };
381
+ const name = attrLit('name', typeof p.name === 'string' && p.name ? p.name : '');
382
+ switch (n.el) {
383
+ case 'Input':
384
+ return [name, ...tokens(p, ['type']), ...tx(['label', 'placeholder', 'help']), ...bools(p, ['required', 'disabled']), ...strings(p, ['autocomplete'])];
385
+ case 'Textarea':
386
+ return [name, ...(typeof p.rows === 'number' ? [attrLit('rows', p.rows)] : []), ...tx(['label', 'placeholder', 'help']), ...bools(p, ['required', 'disabled'])];
387
+ case 'Select':
388
+ return [name, ...opt(), ...strings(p, ['defaultValue']), ...tx(['label', 'placeholder', 'help']), ...bools(p, ['required', 'disabled'])];
389
+ case 'Combobox':
390
+ return [name, ...opt(), ...strings(p, ['defaultValue']), ...tx(['label', 'placeholder', 'help']), ...bools(p, ['required', 'disabled']), 'locale={locale}'];
391
+ case 'Radio':
392
+ return [name, ...opt(), ...strings(p, ['defaultValue']), attrLit('orientation', p.orientation === 'horizontal' ? 'horizontal' : 'vertical'), ...tx(['label', 'help']), ...bools(p, ['required', 'disabled'])];
393
+ case 'Checkbox':
394
+ return [name, ...strings(p, ['value']), ...bools(p, ['defaultChecked']), ...tx(['label', 'help']), ...bools(p, ['required', 'disabled'])];
395
+ default:
396
+ return [name, ...bools(p, ['defaultChecked']), ...tx(['label', 'help']), ...bools(p, ['disabled'])];
397
+ }
398
+ }
399
+ function body(g, n, indent) {
400
+ const p = n.props ?? {};
401
+ const st = [...idAttr(p), ...styleAttr(n)];
402
+ const kids = () => (n.children ?? []).map((c) => node(g, c, indent + ' '));
403
+ const jsx = (code) => ({ jsx: true, code });
404
+ // Same props as the composed renderer (composed/render.tsx), in the same order, then `style`.
405
+ switch (n.el) {
406
+ case 'Box':
407
+ return jsx(element('ui.Box', [...tokens(p, ['padding', 'background']), ...st, ...clickAttrs(g, n, true)], kids(), indent));
408
+ case 'Stack': {
409
+ const direction = isObj(p.direction) ? p.direction : p.direction === 'horizontal' ? 'horizontal' : 'vertical';
410
+ const wrap = typeof p.wrap === 'boolean' ? [attrLit('wrap', p.wrap)] : [];
411
+ return jsx(element('ui.Stack', [attrLit('direction', direction), ...tokens(p, ['gap', 'align', 'justify']), ...wrap, ...st], kids(), indent));
412
+ }
413
+ case 'Columns':
414
+ return jsx(element('ui.Columns', [...tokens(p, ['count', 'gap', 'tracks', 'alignY']), ...strings(p, ['gapX', 'gapY']), ...st], kids(), indent));
415
+ case 'Grid':
416
+ return jsx(element('ui.Grid', [...tokens(p, ['columns', 'gap']), ...st], kids(), indent));
417
+ case 'Card':
418
+ return jsx(element('ui.Card', [...tokens(p, ['padding', 'background']), ...(p.bordered === false ? ['bordered={false}'] : []), ...st, ...clickAttrs(g, n, true)], kids(), indent));
419
+ case 'Slot':
420
+ case 'Region':
421
+ case 'PageContent': {
422
+ const name = g.slots.get(n);
423
+ return { jsx: false, code: name ? `${propExpr(name)} ?? null` : 'null' };
424
+ }
425
+ case 'Overlay': {
426
+ g.usesLocale = true;
427
+ const attrs = [
428
+ 'name={overlay}',
429
+ ...tokens(p, ['variant', 'side', 'size']),
430
+ ...(p.closeOnBackdrop === false ? ['closeOnBackdrop={false}'] : []),
431
+ ...(p.showClose === false ? ['showClose={false}'] : []),
432
+ ...overlayLabelledBy(g),
433
+ 'locale={locale}',
434
+ ...st,
435
+ ];
436
+ return jsx(element('ui.Overlay', attrs, kids(), indent));
437
+ }
438
+ case 'Heading': {
439
+ const idA = headingId(g, n) ?? idAttr(p);
440
+ const rest = [...tokens(p, ['align']), ...styleAttr(n)];
441
+ return jsx(element('ui.Heading', [...idA, attrLit('level', p.level ?? 2), textAttr('text', val(g, n, 'text')), ...rest], null, indent));
442
+ }
443
+ case 'Text': {
444
+ const html = val(g, n, 'html');
445
+ const htmlAttr = 'expr' in html ? [attrExpr('html', `${html.expr} ?? undefined`)] : html.lit === undefined || html.lit === null ? [] : [attrLit('html', html.lit)];
446
+ return jsx(element('ui.Text', [textAttr('text', val(g, n, 'text')), ...htmlAttr, ...tokens(p, ['size', 'color']), ...st], null, indent));
447
+ }
448
+ case 'Image': {
449
+ const explicitAlt = !!n.bind?.alt || p.alt !== undefined;
450
+ const args = [code(val(g, n, 'src')), ...(explicitAlt ? [code(val(g, n, 'alt'))] : [])];
451
+ // A clickable image is its link's name: a missing alt falls back to the block label.
452
+ const href = boundHref(g, n);
453
+ const clickable = isObj(p.action) ? 'true' : href;
454
+ if (clickable)
455
+ g.usesBlockLabel = true;
456
+ const alt = clickable ? `alt={${clickable === 'true' ? '' : `${clickable} && `}!img.alt.trim() ? blockLabel : img.alt}` : 'alt={img.alt}';
457
+ const attrs = ['src={img.src}', alt, ...tokens(p, ['ratio']), ...(p.rounded === true ? ['rounded'] : []), ...tokens(p, ['fit', 'aspect']), ...st, ...clickAttrs(g, n, false)];
458
+ const img = element('ui.Image', attrs, null, indent);
459
+ return { jsx: false, code: `h.when(h.image(${args.join(', ')}), (img) => ${img})` };
460
+ }
461
+ case 'Form': {
462
+ // Same props as the renderer's Form: its run action, resetOnSuccess, the locale (no-JS hint) and the node style.
463
+ g.usesLocale = true;
464
+ const st2 = styleLiteral(n);
465
+ const attrs = [
466
+ ...idAttr(p),
467
+ ...(isObj(p.action) ? [actionAttr(g, p.action)] : []),
468
+ ...(p.resetOnSuccess === false ? ['resetOnSuccess={false}'] : []),
469
+ 'locale={locale}',
470
+ ...(st2 ? [`{...h.blockStyle(${(0, blocks_1.printLiteral)(st2)})}`] : []),
471
+ ];
472
+ return jsx(element('ui.Form', attrs, kids(), indent));
473
+ }
474
+ case 'Button': {
475
+ const action = isObj(p.action) ? [actionAttr(g, p.action)] : [];
476
+ if (p.submit === true)
477
+ action.push('submit');
478
+ const icon = [...strings(p, ['icon']), ...(p.iconPosition === 'end' ? ['iconPosition="end"'] : []), ...(p.iconOnly === true ? ['iconOnly'] : [])];
479
+ return jsx(element('ui.Button', [textAttr('label', val(g, n, 'label')), attrExpr('href', `h.href(${code(val(g, n, 'href'))})`), ...tokens(p, ['variant', 'size']), ...action, ...st, ...icon, ...describedAttr(g, n)], null, indent));
480
+ }
481
+ case 'Icon':
482
+ return jsx(element('ui.Icon', [...idAttr(p), attrLit('name', typeof p.name === 'string' ? p.name : ''), ...tokens(p, ['size']), textAttr('label', val(g, n, 'label')), ...styleAttr(n)], null, indent));
483
+ case 'Tooltip':
484
+ return tooltip(g, n, indent);
485
+ case 'Accordion':
486
+ return jsx(element('ui.Accordion', [...idAttr(p), ...(p.single === true ? ['single'] : []), ...(p.defaultOpen === 'first' ? ['defaultOpen="first"'] : []), ...styleAttr(n)], kids(), indent));
487
+ case 'AccordionItem':
488
+ return jsx(element('ui.AccordionItem', [...idAttr(p), textAttr('title', val(g, n, 'title'))], kids(), indent));
489
+ case 'Dropdown': {
490
+ g.usesLocale = true;
491
+ const href = boundHref(g, n);
492
+ const attrs = [
493
+ ...idAttr(p),
494
+ textAttr('label', val(g, n, 'label')),
495
+ ...(href ? [attrExpr('href', href)] : []),
496
+ attrLit('openOn', p.openOn === 'click' ? 'click' : 'hover'),
497
+ ...tokens(p, ['placement', 'display', 'triggerVariant']),
498
+ ...(p.chevron === false ? ['chevron={false}'] : []),
499
+ 'locale={locale}',
500
+ ...styleAttr(n),
501
+ ];
502
+ return jsx(element('ui.Dropdown', attrs, kids(), indent));
503
+ }
504
+ case 'Tabs': {
505
+ const inner = indent + ' ';
506
+ const panels = (n.children ?? [])
507
+ .filter((c) => c.el === 'TabPanel')
508
+ .map((c) => {
509
+ const content = element('', [], (c.children ?? []).map((k) => node(g, k, inner + ' ')), inner + ' ');
510
+ const fields = [`label: ${textCode(val(g, c, 'label'))}`, ...(typeof c.props?.anchorId === 'string' && c.props.anchorId ? [`id: ${q(c.props.anchorId)}`] : []), `content: ${content}`];
511
+ const o = `{ ${fields.join(', ')} }`;
512
+ return c.showIf ? `...(${condition(g, c.showIf)} ? [${o}] : [])` : o;
513
+ });
514
+ const list = panels.length ? `[\n${panels.map((x) => `${inner} ${x},`).join('\n')}\n${inner}]` : '[]';
515
+ return jsx(element('ui.Tabs', [...idAttr(p), attrExpr('panels', list), ...tokens(p, ['variant', 'align']), ...styleAttr(n)], null, indent));
516
+ }
517
+ case 'Carousel': {
518
+ g.usesLocale = true;
519
+ g.usesBlockLabel = true;
520
+ const attrs = [
521
+ ...idAttr(p),
522
+ ...tokens(p, ['perView', 'gap']),
523
+ ...(p.arrows === false ? ['arrows={false}'] : []),
524
+ ...(p.dots === false ? ['dots={false}'] : []),
525
+ ...(p.loop === true ? ['loop'] : []),
526
+ ...(typeof p.autoplay === 'number' ? [attrLit('autoplay', p.autoplay)] : []),
527
+ 'label={blockLabel}',
528
+ 'locale={locale}',
529
+ ...styleAttr(n),
530
+ ];
531
+ return jsx(element('ui.Carousel', attrs, kids(), indent));
532
+ }
533
+ case 'Input':
534
+ case 'Textarea':
535
+ case 'Select':
536
+ case 'Combobox':
537
+ case 'Radio':
538
+ case 'Checkbox':
539
+ case 'Switch':
540
+ return jsx(element(`ui.${n.el}`, [...idAttr(p), ...control(g, n), ...styleAttr(n)], null, indent));
541
+ case 'Badge':
542
+ return jsx(element('ui.Badge', [textAttr('text', val(g, n, 'text')), ...tokens(p, ['variant']), ...st], null, indent));
543
+ case 'Price': {
544
+ g.usesLocale = true;
545
+ const attrs = ['value={m.value}', 'locale={locale}', ...(p.showCurrency === false ? [] : ['currency={m.currency}']), ...st];
546
+ return { jsx: false, code: `h.when(h.money(${code(val(g, n, 'value'))}), (m) => ${element('ui.Price', attrs, null, indent)})` };
547
+ }
548
+ case 'Date': {
549
+ g.usesLocale = true;
550
+ const attrs = [
551
+ attrExpr('value', `h.date(${code(val(g, n, 'value'))})`),
552
+ 'locale={locale}',
553
+ attrLit('format', p.format === 'long' ? 'long' : 'short'),
554
+ ...(typeof p.timeZone === 'string' && p.timeZone ? [attrLit('timeZone', p.timeZone)] : []),
555
+ ...st,
556
+ ];
557
+ return jsx(element('ui.DateText', attrs, null, indent));
558
+ }
559
+ case 'CollectionList':
560
+ return collectionList(g, n, indent);
561
+ case 'Divider':
562
+ return jsx(element('ui.Divider', st, null, indent));
563
+ case 'Spacer':
564
+ return jsx(element('ui.Spacer', [attrLit('size', p.size ?? '8'), ...st], null, indent));
565
+ default:
566
+ return { jsx: false, code: 'null' };
567
+ }
568
+ }
569
+ /** `entryUrl` expression for `entry`: `urlPattern` when set, else the `apiId` detail path, else none (as `linkFor`). */
570
+ const linkExpr = (urlPattern, apiId) => urlPattern ? `h.entryUrl(${q(urlPattern)}, entry, get)` : apiId ? `h.detailUrl(props, ${q(apiId)}, entry)` : 'null';
571
+ /**
572
+ * `h.list(props, { … }, (entry) => <>…</>)`: inside the item template `entry` is the list item and `entryUrl` uses only
573
+ * the list's urlPattern, else the list type's detail path (decision 9).
574
+ */
575
+ function collectionList(g, n, indent) {
576
+ const p = (n.props ?? {});
577
+ const outer = { bound: g.bound, link: g.link };
578
+ g.bound = true;
579
+ g.link = linkExpr(p.urlPattern, p.apiId);
580
+ const inner = indent + ' ';
581
+ const kids = element('', [], (n.children ?? []).map((c) => node(g, c, inner + ' ')), inner);
582
+ g.bound = outer.bound;
583
+ g.link = outer.link;
584
+ const st = styleLiteral(n);
585
+ const parts = [
586
+ 'name',
587
+ 'label',
588
+ `key: ${q(p.key)}`,
589
+ `layout: ${q(layoutValue(p.layout))}`,
590
+ ...(p.editor?.layout === true ? ['editorLayout: true'] : []),
591
+ ...(p.emptyText ? [`emptyText: ${(0, blocks_1.printLiteral)(p.emptyText, inner)}`] : []),
592
+ ...(typeof p.anchorId === 'string' && p.anchorId ? [`id: ${q(p.anchorId)}`] : []),
593
+ ...(st ? [`style: ${(0, blocks_1.printLiteral)(st, inner)}`] : []),
594
+ ];
595
+ const flat = `{ ${parts.join(', ')} }`;
596
+ const cfg = flat.length <= 70 && !flat.includes('\n') ? flat : `{\n${parts.map((x) => `${inner}${x},`).join('\n')}\n${indent}}`;
597
+ return { jsx: false, code: `h.list(props, ${cfg}, (entry) => (\n${inner}${kids}\n${indent}))` };
598
+ }
599
+ /** JS expression of the id a label candidate gets: its own anchorId, else `<overlay name>-title`. */
600
+ function labelExpr(c) {
601
+ const a = c.node.props?.anchorId;
602
+ return typeof a === 'string' && a ? q(a) : '`${overlay}-title`';
603
+ }
604
+ /** `labelledBy` attribute of the overlay (none when the tree has no Heading). */
605
+ function overlayLabelledBy(g) {
606
+ const o = g.overlay;
607
+ if (!o?.candidates.length)
608
+ return [];
609
+ if (!o.dynamic) {
610
+ const a = o.candidates[0].node.props?.anchorId;
611
+ return [typeof a === 'string' && a ? attrLit('labelledBy', a) : attrExpr('labelledBy', labelExpr(o.candidates[0]))];
612
+ }
613
+ const pick = o.candidates.map((c, i) => `labelled === ${i} ? ${labelExpr(c)} : `).join('');
614
+ return [attrExpr('labelledBy', `${pick}undefined`)];
615
+ }
616
+ /** `id` attribute of a label candidate heading; undefined for other nodes. */
617
+ function headingId(g, n) {
618
+ const o = g.overlay;
619
+ const i = o ? o.candidates.findIndex((c) => c.node === n) : -1;
620
+ if (!o || i < 0)
621
+ return undefined;
622
+ const a = n.props?.anchorId;
623
+ if (typeof a === 'string' && a)
624
+ return [attrLit('id', a)];
625
+ return [attrExpr('id', o.dynamic ? `labelled === ${i} ? ${labelExpr(o.candidates[i])} : undefined` : labelExpr(o.candidates[i]))];
626
+ }
627
+ function condition(g, c) {
628
+ const v = c.from === 'entry' ? (g.bound ? `get(entry, ${q(c.path ?? '')})` : 'undefined') : propExpr(c.name ?? '');
629
+ return `${c.is === 'present' ? '' : '!'}h.present(${v})`;
630
+ }
631
+ function node(g, n, indent) {
632
+ if (!n.showIf)
633
+ return body(g, n, indent);
634
+ const inner = body(g, n, indent + ' ');
635
+ const cond = condition(g, n.showIf);
636
+ if (!inner.code.includes('\n'))
637
+ return { jsx: false, code: `${cond} ? ${inner.code} : null` };
638
+ return { jsx: false, code: `${cond} ? (\n${indent} ${inner.code}\n${indent}) : null` };
639
+ }
640
+ /** Whether `n` or a descendant is a Form or has a `run` action (as the renderer's `runsActions`). */
641
+ function runsActions(n) {
642
+ const a = n.props?.action;
643
+ if (n.el === 'Form' || (isObj(a) && a.type === 'run'))
644
+ return true;
645
+ return (n.children ?? []).some(runsActions);
646
+ }
647
+ /** The `.block.tsx` source of a hand-written `defineBlock` equivalent to `defineComposedBlock(spec)`. */
648
+ function printEjectedBlockTsx(spec) {
649
+ const binding = spec.binding;
650
+ const kind = (0, schema_1.composedKind)(spec);
651
+ const g = { bound: !!binding, link: linkExpr(binding?.urlPattern, binding?.apiId), slots: slotNames(spec.tree), usesLocale: false, usesBlockLabel: false, tooltips: 0, describe: new Map() };
652
+ let labelledLine = [];
653
+ if (kind === 'overlay') {
654
+ // Same choice as the renderer: the first Heading whose own and ancestors' showIf pass.
655
+ const candidates = labelCandidates(spec.tree);
656
+ const dynamic = candidates.length > 1 || (candidates.length === 1 && candidates[0].conds.length > 0);
657
+ g.overlay = { candidates, dynamic };
658
+ if (dynamic) {
659
+ const all = (c) => c.conds.map((x) => condition(g, x)).join(' && ');
660
+ const chain = candidates.map((c, i) => (c.conds.length ? `${all(c)} ? ${i} : ` : `${i}`)).join('');
661
+ labelledLine = [` const labelled = ${chain}${candidates[candidates.length - 1].conds.length ? '-1' : ''};`];
662
+ }
663
+ }
664
+ const treeIndent = ' ';
665
+ const tree = node(g, spec.tree, treeIndent);
666
+ const treeCode = `(\n${treeIndent}${tree.code}\n )`;
667
+ let ret;
668
+ if (!binding)
669
+ ret = `return ${treeCode};`;
670
+ else if (binding.mode === 'single')
671
+ ret = `return h.single(props, { name, label }, (entry) => ${treeCode});`;
672
+ else {
673
+ const o = binding.options ?? {};
674
+ const parts = [
675
+ 'name',
676
+ 'label',
677
+ `layout: ${q(layoutValue(binding.layout))}`,
678
+ ...(o.editorLayout ? ['editorLayout: true'] : []),
679
+ ...(o.emptyText ? [`emptyText: ${(0, blocks_1.printLiteral)(o.emptyText, ' ')}`] : []),
680
+ ];
681
+ const flat = `{ ${parts.join(', ')} }`;
682
+ const cfg = flat.length <= 70 && !flat.includes('\n') ? flat : `{\n${parts.map((x) => ` ${x},`).join('\n')}\n }`;
683
+ ret = `return h.collection(props, ${cfg}, (entry) => ${treeCode});`;
684
+ }
685
+ // As the renderer: on the editor canvas, `run` buttons and Forms are inert and show "Runs <label>".
686
+ const editorScope = runsActions(spec.tree)
687
+ ? [
688
+ ` ${ret.replace(/^return /, 'const out = ')}`,
689
+ ' return h.editor(props) ? <ui.ActionScope mode="editor">{out}</ui.ActionScope> : out;',
690
+ ]
691
+ : [` ${ret}`];
692
+ const renderLines = [
693
+ ...(g.usesLocale || g.usesBlockLabel ? [' const locale = h.locale(props);'] : []),
694
+ ...(g.usesBlockLabel ? [' const blockLabel = h.blockLabel(label, name, locale);'] : []),
695
+ ...(kind === 'overlay' ? [` const overlay = h.overlayName(props.name, ${q((0, schema_1.overlayDefaultName)(spec.name))});`] : []),
696
+ ...labelledLine,
697
+ ...editorScope,
698
+ ];
699
+ const assetPaths = [...imageEntryPaths(spec.tree)];
700
+ const detailLinks = (0, schema_1.composedDetailLinks)(spec);
701
+ const def = [
702
+ ' name,',
703
+ ' label,',
704
+ ` category: ${q(spec.category)},`,
705
+ ...(spec.icon ? [` icon: ${q(spec.icon)},`] : []),
706
+ ` version: ${spec.version},`,
707
+ ...(kind !== 'block' ? [` kind: ${q(kind)},`] : []),
708
+ ' // Reserved props `_locale` (stamped by resolvePage) and `_editor` (editor canvas), as for composed blocks.',
709
+ ' usesLocale: true,',
710
+ ...(assetPaths.length ? [` entryAssetPaths: ${(0, blocks_1.printLiteral)(assetPaths, ' ')},`] : []),
711
+ ...(detailLinks.length ? [' // Content types whose detail page URLs `entryUrl` links use (`resolvePage` stamps `_detailPaths`).', ` detailLinks: ${(0, blocks_1.printLiteral)(detailLinks, ' ')},`] : []),
712
+ ' fields: {',
713
+ ...printFields(spec, ' ').map((l) => ` ${l}`),
714
+ ' },',
715
+ ' render: (props) => {',
716
+ ...renderLines,
717
+ ' },',
718
+ ].join('\n');
719
+ const usesGet = /\bget\b/.test(renderLines.join('\n'));
720
+ const imports = [
721
+ ...(/\bb\./.test(def) ? ['b'] : []),
722
+ ...(/\bh\./.test(def) ? ['composedHelpers as h'] : []),
723
+ 'defineBlock',
724
+ ...(/\bui\./.test(def) ? ['ui'] : []),
725
+ ];
726
+ return [
727
+ `// Block "${spec.name}", ejected from the OpenCloudCMS Block Builder. Hand-written from now on:`,
728
+ '// the Block Builder no longer manages this file. Register it in src/blocks/index.ts.',
729
+ `import { ${imports.join(', ')} } from '@opencloudcms/core/blocks';`,
730
+ '',
731
+ `const name = ${q(spec.name)};`,
732
+ `const label = ${(0, blocks_1.printLiteral)(spec.label)};`,
733
+ ...(usesGet ? ['const get = h.entryReader(name);'] : []),
734
+ '',
735
+ 'export default defineBlock({',
736
+ def,
737
+ '});',
738
+ '',
739
+ ].join('\n');
740
+ }
741
+ /** Thrown when the `.block.tsx` an eject would write already exists (nothing is written). */
742
+ class EjectTargetExistsError extends Error {
743
+ file;
744
+ constructor(file) {
745
+ super(`${file} already exists`);
746
+ this.file = file;
747
+ this.name = 'EjectTargetExistsError';
748
+ }
749
+ }
750
+ exports.EjectTargetExistsError = EjectTargetExistsError;
751
+ /** `.block.tsx` next to a composed block file. */
752
+ function ejectedBlockFile(file) {
753
+ return file.replace(/\.(ts|js)$/, '.tsx');
754
+ }
755
+ /**
756
+ * Writes the ejected `.block.tsx` next to the composed block `file`, removes `file` and regenerates `composed.ts`.
757
+ * Returns the written file, the line to add to `src/blocks/index.ts` and every path touched. No rollback: callers
758
+ * wrap it with captureProjectFiles/restoreProjectFiles. Throws EjectTargetExistsError or `writeComposedBlocks` errors.
759
+ */
760
+ async function ejectComposedBlock(config, spec, file) {
761
+ const dir = (0, blocks_1.blocksDir)(config);
762
+ const target = ejectedBlockFile(path.resolve(file));
763
+ const rel = path.relative(dir, target);
764
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
765
+ throw new Error(`Refusing to write ${target}: outside ${dir}`);
766
+ if (fs.existsSync(target))
767
+ throw new EjectTargetExistsError(target);
768
+ fs.writeFileSync(target, printEjectedBlockTsx(spec));
769
+ const touched = await (0, blocks_1.writeComposedBlocks)(config, { removeName: spec.name });
770
+ const importPath = `./${rel.split(path.sep).join('/').replace(/\.tsx$/, '')}`;
771
+ return { file: target, importLine: `import ${spec.name} from ${q(importPath)};`, touched: [target, ...touched] };
772
+ }
773
+ //# sourceMappingURL=eject.js.map