@forgewp/compiler 0.4.3 → 0.4.4

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.
Files changed (133) hide show
  1. package/README.md +59 -0
  2. package/bin/add.js +20 -14
  3. package/bin/cli.js +145 -70
  4. package/bin/doctor.js +21 -12
  5. package/bin/export.js +69 -20
  6. package/bin/fresh.js +5 -0
  7. package/bin/i18n-extract.js +3 -10
  8. package/bin/i18n-translate.js +15 -24
  9. package/bin/make-block.js +13 -0
  10. package/bin/make-editable.js +166 -0
  11. package/bin/make-form.js +131 -0
  12. package/bin/make-loop.js +40 -43
  13. package/bin/make-mail.js +27 -0
  14. package/bin/make-post-type.js +57 -29
  15. package/bin/make-sandbox.js +62 -11
  16. package/bin/make-section.js +221 -0
  17. package/bin/make-shell.js +375 -0
  18. package/bin/repair.js +14 -26
  19. package/bin/seed.js +119 -0
  20. package/bin/sync-routes.js +107 -85
  21. package/lib/adapters/html-adapter.js +5 -0
  22. package/lib/adapters/stub-adapter.js +4 -0
  23. package/lib/add-component.js +153 -92
  24. package/lib/asset-loader.js +313 -3
  25. package/lib/assets/asset-graph.js +432 -0
  26. package/lib/assets/asset-pipeline.js +125 -0
  27. package/lib/assets/diagnostics-report.js +345 -0
  28. package/lib/assets/external-fetcher.js +173 -0
  29. package/lib/assets/font-orchestrator.js +348 -0
  30. package/lib/assets/font-usage-scanner.js +242 -0
  31. package/lib/assets/image-optimizer.js +229 -0
  32. package/lib/assets/index.js +51 -0
  33. package/lib/assets/preload-generator.js +70 -0
  34. package/lib/assets/public-url.js +153 -0
  35. package/lib/block-authoring-help.js +11 -0
  36. package/lib/blocks/ast-parser.js +67 -0
  37. package/lib/blocks/discover-blocks.js +146 -0
  38. package/lib/blocks/editor-scope.js +733 -0
  39. package/lib/blocks/editor-transpiler.js +1229 -0
  40. package/lib/blocks/index.js +2838 -0
  41. package/lib/blocks/php-transpiler.js +4928 -0
  42. package/lib/blocks/scanner.js +1487 -0
  43. package/lib/blocks/shared-utils.js +290 -0
  44. package/lib/blocks/source-sanitize.js +1449 -0
  45. package/lib/blueprints.js +31 -91
  46. package/lib/build-assets.js +38 -33
  47. package/lib/collect-page-template-routes.js +102 -0
  48. package/lib/collect-static-routes.js +175 -0
  49. package/lib/diagnostics.js +58 -33
  50. package/lib/export-theme.js +84 -5
  51. package/lib/extract-template-content.js +90 -0
  52. package/lib/forms-preview.js +42 -0
  53. package/lib/functions/cpt-routing.js +69 -0
  54. package/lib/functions/forms.js +2461 -0
  55. package/lib/functions/hydration-enqueuer.js +400 -0
  56. package/lib/functions/index.js +1623 -0
  57. package/lib/functions/load-menus.js +112 -0
  58. package/lib/functions/load-translations.js +148 -0
  59. package/lib/functions/rest-endpoints.js +2923 -0
  60. package/lib/functions/routing.js +765 -0
  61. package/lib/functions/seed-mock-data.js +392 -0
  62. package/lib/functions/seed-products.js +481 -0
  63. package/lib/functions/settings-page.js +273 -0
  64. package/lib/functions/theme-setup.js +494 -0
  65. package/lib/generate-theme.js +1916 -339
  66. package/lib/hydration/editable-schemas.js +332 -0
  67. package/lib/hydration/enter-hidden-initial.js +65 -0
  68. package/lib/hydration/form-schemas.js +227 -0
  69. package/lib/hydration/index.js +12 -0
  70. package/lib/hydration/is-interactive.js +951 -0
  71. package/lib/hydration/island-split.js +1231 -0
  72. package/lib/hydration/islands-scanner.js +599 -0
  73. package/lib/hydration/resolve-island-chunk.js +103 -0
  74. package/lib/hydration/resolve-island-component.js +52 -0
  75. package/lib/hydration/rollup-inputs.js +81 -0
  76. package/lib/hydration/root-class-extractor.js +220 -0
  77. package/lib/hydration/scan-app-providers.js +154 -0
  78. package/lib/hydration/static-lint.js +382 -0
  79. package/lib/hydration/transform.js +257 -0
  80. package/lib/hydration/uses-block-area.js +49 -0
  81. package/lib/hydration/utils.js +119 -0
  82. package/lib/i18n/translation-cache.js +141 -0
  83. package/lib/icon-registry.js +72 -0
  84. package/lib/index.d.ts +287 -8
  85. package/lib/index.js +2 -1
  86. package/lib/load-config.js +338 -242
  87. package/lib/mail-templates.js +37 -0
  88. package/lib/markup-processor.js +388 -102
  89. package/lib/node-runtime.js +7 -0
  90. package/lib/page-config-plugin.js +64 -20
  91. package/lib/php-builders.js +383 -44
  92. package/lib/react-adapter.js +983 -235
  93. package/lib/registration-metadata.js +11 -0
  94. package/lib/render-theme.mts +1410 -616
  95. package/lib/route-layout.js +76 -0
  96. package/lib/template-discovery.js +58 -0
  97. package/lib/theme-compatibility.js +32 -0
  98. package/lib/validate-export.js +2 -2
  99. package/lib/validate.js +27 -5
  100. package/lib/virtual-plugin.js +319 -0
  101. package/lib/walkthrough.md +26 -0
  102. package/package.json +16 -5
  103. package/templates/auth/cms/email-logs.json +9 -0
  104. package/templates/auth/cms/menus.json +11 -0
  105. package/templates/auth/cms/mock-data.json +123 -0
  106. package/templates/auth/cms/roles.json +7 -0
  107. package/templates/auth/cms/sessions.json +1 -0
  108. package/templates/auth/cms/site-settings.json +28 -0
  109. package/templates/auth/cms/translations.json +4 -0
  110. package/templates/auth/cms/users.json +46 -0
  111. package/templates/auth/components/forgot-password-form-wrapper.tsx +10 -2
  112. package/templates/auth/components/login-form-wrapper.tsx +118 -21
  113. package/templates/auth/components/reset-password-form-wrapper.tsx +10 -2
  114. package/templates/auth/components/signup-form-wrapper.tsx +2 -2
  115. package/templates/auth/components/verify-email-view-wrapper.tsx +5 -5
  116. package/templates/auth/pages/DashboardPage.tsx +1 -4
  117. package/templates/auth/pages/ForgotPasswordPage.tsx +1 -4
  118. package/templates/auth/pages/LoginPage.tsx +1 -4
  119. package/templates/auth/pages/ResetPasswordPage.tsx +1 -4
  120. package/templates/auth/pages/SignUpPage.tsx +1 -4
  121. package/templates/auth/pages/VerifyEmailPage.tsx +1 -4
  122. package/templates/auth/ui/button.tsx +57 -0
  123. package/templates/auth/ui/card.tsx +76 -0
  124. package/templates/auth/ui/field.tsx +242 -0
  125. package/templates/auth/ui/input.tsx +22 -0
  126. package/templates/auth/ui/label.tsx +24 -0
  127. package/templates/auth/ui/separator.tsx +31 -0
  128. package/templates/menus.json +12 -10
  129. package/templates/users.json +8 -4
  130. package/templates/wordpress.tsx +690 -245
  131. package/lib/block-compiler.js +0 -552
  132. package/lib/functions-builder.js +0 -2970
  133. package/lib/hydration-scanner.js +0 -833
@@ -0,0 +1,1487 @@
1
+ import {
2
+ existsSync,
3
+ readdirSync,
4
+ readFileSync,
5
+ mkdirSync,
6
+ writeFileSync,
7
+ rmSync,
8
+ } from 'node:fs';
9
+ import path from 'node:path';
10
+ import { readComponentSource } from '../hydration/is-interactive.js';
11
+ import { tryParseSource, traverse, markLegacyFallback } from './ast-parser.js';
12
+
13
+ /**
14
+ * Statically evaluate a pure-data expression node (Phase 3): object/array
15
+ * literals, string/number/boolean/null literals, expressionless template
16
+ * literals, unary +/-/!, spreads of statically-known values, `as const` /
17
+ * satisfies unwrapping, identifiers resolved from `bindings`, and calls to
18
+ * whitelisted `callables` (the defineEditable field helpers) whose arguments
19
+ * are themselves static. Anything else throws — the caller decides whether
20
+ * to fall back to the legacy `new Function` eval. No arbitrary code
21
+ * execution on this path, and no stub-scope maintenance.
22
+ */
23
+ function evaluateStaticNode(node, bindings = {}, callables = {}) {
24
+ switch (node.type) {
25
+ case 'StringLiteral':
26
+ case 'NumericLiteral':
27
+ case 'BooleanLiteral':
28
+ return node.value;
29
+ case 'NullLiteral':
30
+ return null;
31
+ case 'Identifier':
32
+ if (node.name === 'undefined') return undefined;
33
+ if (Object.prototype.hasOwnProperty.call(bindings, node.name))
34
+ return bindings[node.name];
35
+ throw new Error(`unresolvable identifier "${node.name}"`);
36
+ case 'TemplateLiteral':
37
+ if (node.expressions.length === 0) return node.quasis[0].value.cooked;
38
+ throw new Error('template literal with expressions');
39
+ case 'UnaryExpression': {
40
+ const v = evaluateStaticNode(node.argument, bindings, callables);
41
+ if (node.operator === '-') return -v;
42
+ if (node.operator === '+') return +v;
43
+ if (node.operator === '!') return !v;
44
+ throw new Error(`unary ${node.operator}`);
45
+ }
46
+ case 'TSAsExpression':
47
+ case 'TSSatisfiesExpression':
48
+ case 'TSNonNullExpression':
49
+ case 'TSTypeAssertion':
50
+ case 'ParenthesizedExpression':
51
+ return evaluateStaticNode(node.expression, bindings, callables);
52
+ case 'ArrayExpression': {
53
+ const arr = [];
54
+ for (const el of node.elements) {
55
+ if (el === null) continue;
56
+ if (el.type === 'SpreadElement') {
57
+ arr.push(...evaluateStaticNode(el.argument, bindings, callables));
58
+ } else {
59
+ arr.push(evaluateStaticNode(el, bindings, callables));
60
+ }
61
+ }
62
+ return arr;
63
+ }
64
+ case 'ObjectExpression': {
65
+ const obj = {};
66
+ for (const prop of node.properties) {
67
+ if (prop.type === 'SpreadElement') {
68
+ Object.assign(
69
+ obj,
70
+ evaluateStaticNode(prop.argument, bindings, callables),
71
+ );
72
+ continue;
73
+ }
74
+ if (prop.type !== 'ObjectProperty' || prop.computed)
75
+ throw new Error(`object ${prop.type}`);
76
+ const key =
77
+ prop.key.type === 'Identifier'
78
+ ? prop.key.name
79
+ : prop.key.type === 'StringLiteral' ||
80
+ prop.key.type === 'NumericLiteral'
81
+ ? String(prop.key.value)
82
+ : null;
83
+ if (key === null) throw new Error('non-static object key');
84
+ obj[key] = evaluateStaticNode(prop.value, bindings, callables);
85
+ }
86
+ return obj;
87
+ }
88
+ case 'CallExpression': {
89
+ if (
90
+ node.callee.type === 'Identifier' &&
91
+ Object.prototype.hasOwnProperty.call(callables, node.callee.name)
92
+ ) {
93
+ const args = node.arguments.map((a) =>
94
+ evaluateStaticNode(a, bindings, callables),
95
+ );
96
+ return callables[node.callee.name](...args);
97
+ }
98
+ throw new Error(
99
+ `call to ${node.callee.type === 'Identifier' ? node.callee.name : node.callee.type}`,
100
+ );
101
+ }
102
+ default:
103
+ throw new Error(node.type);
104
+ }
105
+ }
106
+
107
+ /** Static-eval a standalone pure-data literal string (a pickEditable map,
108
+ * a keywords array, …). Throws when it isn't parseable static data. */
109
+ function evaluateStaticLiteral(src) {
110
+ const ast = tryParseSource(`(${src})`);
111
+ const stmt = ast && ast.program.body[0];
112
+ if (!stmt || stmt.type !== 'ExpressionStatement')
113
+ throw new Error('not an expression');
114
+ return evaluateStaticNode(stmt.expression);
115
+ }
116
+
117
+ /** Locate the first `name(...)` CallExpression in parsed `code` and return
118
+ * its argument nodes plus the AST/code pair, or null. */
119
+ function findCallExpression(code, name) {
120
+ const ast = tryParseSource(code);
121
+ if (!ast) return null;
122
+ let found = null;
123
+ traverse(ast, {
124
+ CallExpression(p) {
125
+ if (
126
+ !found &&
127
+ p.node.callee.type === 'Identifier' &&
128
+ p.node.callee.name === name
129
+ ) {
130
+ found = p.node;
131
+ p.stop();
132
+ }
133
+ },
134
+ });
135
+ return found ? { node: found, ast } : null;
136
+ }
137
+
138
+ /** @type {{ message: string, code?: string }[]} */
139
+ let editableIssues = [];
140
+
141
+ export function resetEditableIssues() {
142
+ editableIssues = [];
143
+ }
144
+
145
+ export function getEditableIssues() {
146
+ return editableIssues.slice();
147
+ }
148
+
149
+ /**
150
+ * Record an editable/pick issue. Always logs a warning (deduped).
151
+ * With `forgewp export --strict`, {@link flushEditableIssues} turns these into a hard failure.
152
+ */
153
+ export function reportEditableIssue(message, code = 'editable') {
154
+ if (editableIssues.some((i) => i.message === message)) return;
155
+ editableIssues.push({ message, code });
156
+ console.warn(`[ForgeWP] ${message}`);
157
+ }
158
+
159
+ /**
160
+ * After scanning: no-op unless strict — then throw if any issues were reported.
161
+ * @param {{ strict?: boolean }} [opts]
162
+ */
163
+ export function flushEditableIssues(opts = {}) {
164
+ const issues = getEditableIssues();
165
+ if (opts.strict && issues.length > 0) {
166
+ const detail = issues.map((i) => ` - ${i.message}`).join('\n');
167
+ throw new Error(
168
+ `Editable schema errors (${issues.length}) in strict mode:\n${detail}\n` +
169
+ `Fix from/pick/pickEditable issues, or omit --strict to continue with warnings only.`,
170
+ );
171
+ }
172
+ return issues;
173
+ }
174
+
175
+ /**
176
+ * Read a `@forgewp-block` meta line (`title:`, `category:`, …) from a single JSDoc body.
177
+ * Ignores code-like values accidentally captured (quoted keys, trailing commas).
178
+ */
179
+ export function parseJsdocMetaLine(jsdoc, key) {
180
+ if (!jsdoc || !key) return '';
181
+ const re = new RegExp(
182
+ `^[ \\t]*\\*?[ \\t]*${key}[ \\t]*:[ \\t]*(.+?)[ \\t]*$`,
183
+ 'im',
184
+ );
185
+ const m = jsdoc.match(re);
186
+ if (!m) return '';
187
+ let val = m[1].trim();
188
+ // Trailing comma from object/property lookalikes
189
+ val = val.replace(/,+\s*$/, '');
190
+ // Pure string-literal values that look like schema keys, not human titles:
191
+ // 'hero_title' / "featured_subtitle" — reject for title; keep for icon slugs etc.
192
+ if (key === 'title' || key === 'description') {
193
+ if (/^['"`]/.test(val) && /['"`]$/.test(val)) {
194
+ // Allow normal quoted titles only if they contain spaces or capitals beyond snake_case
195
+ const inner = val.slice(1, -1);
196
+ if (/^[a-z0-9_]+$/.test(inner)) return '';
197
+ val = inner;
198
+ }
199
+ }
200
+ // Strip wrapping quotes on human titles: "Hero Section"
201
+ if (
202
+ (key === 'title' ||
203
+ key === 'description' ||
204
+ key === 'category' ||
205
+ key === 'icon') &&
206
+ ((val.startsWith("'") && val.endsWith("'")) ||
207
+ (val.startsWith('"') && val.endsWith('"')))
208
+ ) {
209
+ val = val.slice(1, -1);
210
+ }
211
+ return val.trim();
212
+ }
213
+
214
+ /**
215
+ * Normalize schema/page slugs for cms/editables lookup.
216
+ * BerUnsPage / ber_uns_page / ber-uns-page → ber-uns-page
217
+ */
218
+ export function normalizeEditableSlug(slug) {
219
+ if (!slug || typeof slug !== 'string') return slug;
220
+ return slug
221
+ .trim()
222
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
223
+ .replace(/_/g, '-')
224
+ .replace(/[^a-zA-Z0-9-]+/g, '-')
225
+ .replace(/--+/g, '-')
226
+ .replace(/^-|-$/g, '')
227
+ .toLowerCase();
228
+ }
229
+
230
+ /**
231
+ * Scans the theme's src/ folder recursively for components annotated with @forgewp-block
232
+ * and scaffolds wrapper blocks inside src/blocks/generated/
233
+ *
234
+ * @param {string} themeRoot
235
+ * @param {{ strict?: boolean, resetIssues?: boolean, flush?: boolean }} [options]
236
+ * - strict: fail after scan if any from/pick issues (default false — warn only)
237
+ * - resetIssues: clear issue buffer before scan (default true)
238
+ * - flush: run flushEditableIssues at end (default true). Set false when compileBlocks will flush later.
239
+ */
240
+ export function scanAndGenerateBlocks(themeRoot, options = {}) {
241
+ const { strict = false, resetIssues = true, flush = true } = options;
242
+ if (resetIssues) resetEditableIssues();
243
+
244
+ const srcDir = path.join(themeRoot, 'src');
245
+ if (!existsSync(srcDir)) {
246
+ if (flush) flushEditableIssues({ strict });
247
+ return;
248
+ }
249
+
250
+ const generatedDir = path.join(srcDir, 'blocks', 'generated');
251
+ const handcraftedDir = path.join(srcDir, 'blocks');
252
+
253
+ // Collect all files recursively in src/, excluding blocks/generated/ and other build artifacts
254
+ const files = [];
255
+ function collectFiles(dir) {
256
+ if (!existsSync(dir)) return;
257
+ const items = readdirSync(dir, { withFileTypes: true });
258
+ for (const item of items) {
259
+ const fullPath = path.join(dir, item.name);
260
+ if (item.isDirectory()) {
261
+ if (
262
+ [
263
+ 'node_modules',
264
+ '.forgewp',
265
+ 'generated',
266
+ 'dist',
267
+ '.git',
268
+ 'out',
269
+ ].includes(item.name)
270
+ ) {
271
+ continue;
272
+ }
273
+ collectFiles(fullPath);
274
+ } else if (
275
+ item.isFile() &&
276
+ (item.name.endsWith('.tsx') || item.name.endsWith('.jsx'))
277
+ ) {
278
+ files.push(fullPath);
279
+ }
280
+ }
281
+ }
282
+ collectFiles(srcDir);
283
+
284
+ const activeGeneratedFiles = new Set();
285
+
286
+ for (const file of files) {
287
+ try {
288
+ const content = readComponentSource(file);
289
+ if (!content.includes('@forgewp-block')) continue;
290
+
291
+ // Match each JSDoc that contains @forgewp-block *inside that same comment*.
292
+ // Do NOT use /\/\*\*([\s\S]*?@forgewp-block...)/ — that spans from an earlier
293
+ // /** through source (e.g. pick maps `title: 'hero_title'`) and steals them
294
+ // as the block title / description. Developers may put any /** above the block.
295
+ const blockRegex =
296
+ /\/\*\*((?:(?!\*\/)[\s\S])*?@forgewp-block(?:(?!\*\/)[\s\S])*?)\*\/[\s\r\n]*(?:export\s+(?:interface|type)\s+[A-Za-z0-9_$-]+\s*=?\s*\{[\s\S]*?\}[\s\r\n]*)?export\s+(?:default\s+)?(?:function|const)\s+([A-Za-z0-9_$-]+)/g;
297
+ let match;
298
+ while ((match = blockRegex.exec(content)) !== null) {
299
+ const jsdoc = match[1];
300
+ if (!jsdoc.includes('@forgewp-block')) continue;
301
+
302
+ const compName = match[2];
303
+
304
+ // Meta lines only (` * title: Hero Section`). Not code-like `title: 'x',`.
305
+ const title = parseJsdocMetaLine(jsdoc, 'title') || compName;
306
+ const category = parseJsdocMetaLine(jsdoc, 'category') || 'design';
307
+ const description = parseJsdocMetaLine(jsdoc, 'description') || '';
308
+ const icon = parseJsdocMetaLine(jsdoc, 'icon') || 'admin-generic';
309
+
310
+ // Attributes: prefer page schema via JSDoc from/pick or pickEditable / defineEditable
311
+ let attributes = {};
312
+ const pickedSchema = resolveComponentEditableSchema(
313
+ content,
314
+ file,
315
+ themeRoot,
316
+ );
317
+ if (pickedSchema && Object.keys(pickedSchema).length > 0) {
318
+ for (const [key, field] of Object.entries(pickedSchema)) {
319
+ attributes[key] = mapEditableFieldToAttribute(field);
320
+ }
321
+ } else {
322
+ attributes = inferAttributes(content, compName);
323
+ }
324
+
325
+ // Slugify component name for WordPress block name
326
+ const blockSlug = compName
327
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
328
+ .toLowerCase()
329
+ .replace(/[^a-z0-9]+/g, '-');
330
+
331
+ // Check if handcrafted block exists (escape hatch)
332
+ const handcraftedFile = path.join(
333
+ handcraftedDir,
334
+ `${compName}Block.tsx`,
335
+ );
336
+ const handcraftedFileAlt = path.join(handcraftedDir, `${compName}.tsx`);
337
+ const handcraftedFileFolder = path.join(
338
+ handcraftedDir,
339
+ compName,
340
+ 'index.tsx',
341
+ );
342
+ if (
343
+ existsSync(handcraftedFile) ||
344
+ existsSync(handcraftedFileAlt) ||
345
+ existsSync(handcraftedFileFolder)
346
+ ) {
347
+ continue;
348
+ }
349
+
350
+ // Generate wrapper TSX
351
+ const relativeImportPath = getRelativeImportPath(generatedDir, file);
352
+
353
+ // Check if named or default export is used
354
+ const isDefaultExport =
355
+ new RegExp(
356
+ `export\\s+default\\s+(?:function|const)\\s+${compName}\\b`,
357
+ ).test(content) ||
358
+ new RegExp(`export\\s+default\\s+${compName}\\b`).test(content);
359
+ const importStatement = isDefaultExport
360
+ ? `import ${compName} from "${relativeImportPath}";`
361
+ : `import { ${compName} } from "${relativeImportPath}";`;
362
+
363
+ // Re-export editable when the source defines/picks a schema in code
364
+ const hasCodeEditable =
365
+ content.includes('defineEditable(') ||
366
+ content.includes('pickEditable(') ||
367
+ content.includes('mergeEditable(') ||
368
+ /export\s+\{\s*[^}]*\beditable\b/.test(content);
369
+ const extraExports = hasCodeEditable
370
+ ? `\nexport { editable } from "${relativeImportPath}";`
371
+ : '';
372
+
373
+ const attrStrings = [];
374
+ for (const [key, attr] of Object.entries(attributes)) {
375
+ const parts = [`type: ${JSON.stringify(attr.type || 'string')}`];
376
+ if (attr.default !== undefined)
377
+ parts.push(`default: ${JSON.stringify(attr.default)}`);
378
+ if (attr.control)
379
+ parts.push(`control: ${JSON.stringify(attr.control)}`);
380
+ if (attr.label) parts.push(`label: ${JSON.stringify(attr.label)}`);
381
+ if (attr.options)
382
+ parts.push(`options: ${JSON.stringify(attr.options)}`);
383
+ if (attr.provider)
384
+ parts.push(`provider: ${JSON.stringify(attr.provider)}`);
385
+ if (attr.mode) parts.push(`mode: ${JSON.stringify(attr.mode)}`);
386
+ if (attr.min !== undefined)
387
+ parts.push(`min: ${JSON.stringify(attr.min)}`);
388
+ if (attr.max !== undefined)
389
+ parts.push(`max: ${JSON.stringify(attr.max)}`);
390
+ if (attr.fields) parts.push(`fields: ${JSON.stringify(attr.fields)}`);
391
+ attrStrings.push(` ${key}: { ${parts.join(', ')} }`);
392
+ }
393
+ const attributesCode =
394
+ attrStrings.length > 0 ? `{\n${attrStrings.join(',\n')}\n }` : '{}';
395
+
396
+ const wrapperCode = `// AUTO-GENERATED BY FORGEWP. DO NOT EDIT DIRECTLY.
397
+ import { defineBlock } from "@forgewp/react";
398
+ ${importStatement}${extraExports}
399
+
400
+ export default defineBlock({
401
+ name: ${JSON.stringify(blockSlug)},
402
+ title: ${JSON.stringify(title)},
403
+ category: ${JSON.stringify(category)},
404
+ description: ${JSON.stringify(description)},
405
+ icon: ${JSON.stringify(icon)},
406
+ attributes: ${attributesCode},
407
+ edit: (props: any) => {
408
+ return <${compName} {...props.attributes} setAttributes={props.setAttributes} />;
409
+ }
410
+ });
411
+
412
+ `;
413
+
414
+ const genFilePath = path.join(generatedDir, `${compName}Block.tsx`);
415
+ mkdirSync(generatedDir, { recursive: true });
416
+
417
+ // Write only if content changed to prevent unnecessary hot-reloads
418
+ let shouldWrite = true;
419
+ if (existsSync(genFilePath)) {
420
+ const existingCode = readFileSync(genFilePath, 'utf8');
421
+ if (existingCode === wrapperCode) {
422
+ shouldWrite = false;
423
+ }
424
+ }
425
+ if (shouldWrite) {
426
+ writeFileSync(genFilePath, wrapperCode, 'utf8');
427
+ }
428
+
429
+ activeGeneratedFiles.add(`${compName}Block.tsx`);
430
+ }
431
+ } catch (err) {
432
+ console.warn(
433
+ `[JSDoc Block Scanner] Error scanning file ${file}:`,
434
+ err.message,
435
+ );
436
+ }
437
+ }
438
+
439
+ // Clean up unused/deleted generated blocks
440
+ if (existsSync(generatedDir)) {
441
+ const existingGenerated = readdirSync(generatedDir);
442
+ for (const file of existingGenerated) {
443
+ if (file.endsWith('.tsx') && !activeGeneratedFiles.has(file)) {
444
+ console.log(
445
+ `[ForgeWP Compiler] Cleaning up obsolete auto-generated block wrapper: src/blocks/generated/${file}`,
446
+ );
447
+ try {
448
+ rmSync(path.join(generatedDir, file));
449
+ } catch {}
450
+ }
451
+ }
452
+ }
453
+
454
+ if (flush) flushEditableIssues({ strict });
455
+ }
456
+
457
+ /**
458
+ * Infers block attribute specifications by parsing TS/JS props definitions
459
+ */
460
+ function inferAttributes(content, compName) {
461
+ const attrs = {};
462
+ const reserved = [
463
+ 'setAttributes',
464
+ 'attributes',
465
+ 'clientId',
466
+ 'isSelected',
467
+ 'name',
468
+ 'context',
469
+ 'className',
470
+ 'attrs',
471
+ ];
472
+
473
+ // Pattern 1: search for interface/type named Props or ${compName}Props
474
+ let body = null;
475
+ const typeRegex = new RegExp(
476
+ `(?:interface|type)\\s+(?:Props|${compName}Props)\\s*=?\\s*\\{`,
477
+ );
478
+ const match = content.match(typeRegex);
479
+ if (match) {
480
+ const startIndex = match.index + match[0].length;
481
+ let depth = 1;
482
+ let i = startIndex;
483
+ let tempBody = '';
484
+ while (i < content.length && depth > 0) {
485
+ const char = content[i];
486
+ if (char === '{') depth++;
487
+ else if (char === '}') {
488
+ depth--;
489
+ if (depth === 0) break;
490
+ }
491
+ tempBody += char;
492
+ i++;
493
+ }
494
+ body = tempBody;
495
+ }
496
+
497
+ if (body !== null) {
498
+ // Strip nested object definitions so we do not extract nested properties as top-level attributes
499
+ body = body.replace(/\{[\s\S]*?\}/g, '');
500
+ const lineRegex = /([a-zA-Z0-9_-]+)\s*\??\s*:\s*([a-zA-Z0-9_|[\]\s'"\-]+)/g;
501
+ let m;
502
+ while ((m = lineRegex.exec(body)) !== null) {
503
+ const name = m[1];
504
+ if (reserved.includes(name)) continue;
505
+ const typeStr = m[2].trim();
506
+ attrs[name] = mapTypeToBlockAttribute(typeStr);
507
+ }
508
+ return attrs;
509
+ }
510
+
511
+ // Pattern 2: search for inline type signature e.g. function Hero({ heading, text }: { heading: string, text: string })
512
+ const inlineRegex = new RegExp(
513
+ `function\\s+${compName}\\s*\\(\\s*\\{[\\s\\S]*?\\}\\s*:\\s*\\{([\\s\\S]*?)\\}\\s*\\)`,
514
+ );
515
+ const inlineMatch = content.match(inlineRegex);
516
+ if (inlineMatch) {
517
+ let body = inlineMatch[1];
518
+ // Strip nested object definitions so we do not extract nested properties as top-level attributes
519
+ body = body.replace(/\{[\s\S]*?\}/g, '');
520
+ const propRegex = /([a-zA-Z0-9_-]+)\s*\??\s*:\s*([a-zA-Z0-9_|[\]\s'"\-]+)/g;
521
+ let m;
522
+ while ((m = propRegex.exec(body)) !== null) {
523
+ const name = m[1];
524
+ if (reserved.includes(name)) continue;
525
+ const typeStr = m[2].trim();
526
+ attrs[name] = mapTypeToBlockAttribute(typeStr);
527
+ }
528
+ return attrs;
529
+ }
530
+
531
+ return attrs;
532
+ }
533
+
534
+ function mapTypeToBlockAttribute(typeStr) {
535
+ const lower = typeStr.toLowerCase();
536
+ if (lower.includes('string')) {
537
+ return { type: 'string', default: '' };
538
+ }
539
+ if (lower.includes('number')) {
540
+ return { type: 'number', default: 0 };
541
+ }
542
+ if (lower.includes('boolean')) {
543
+ return { type: 'boolean', default: false };
544
+ }
545
+ // Fallback to string
546
+ return { type: 'string', default: '' };
547
+ }
548
+
549
+ function getRelativeImportPath(fromDir, toFile) {
550
+ let relative = path.relative(fromDir, toFile).replace(/\\/g, '/');
551
+ // Strip extension
552
+ relative = relative.replace(/\.(tsx|ts|jsx|js)$/, '');
553
+ if (!relative.startsWith('.') && !relative.startsWith('/')) {
554
+ relative = './' + relative;
555
+ }
556
+ return relative;
557
+ }
558
+
559
+ /** AST-first: locate defineBlock(...)'s ObjectExpression argument and
560
+ * statically evaluate it — `edit`/`save` become null (they're functions,
561
+ * exactly what the legacy regex-neutering approximated), everything else is
562
+ * pure data. Throws on unexpected shapes → caller falls back to legacy. */
563
+ function parseDefineBlockAst(code) {
564
+ const found = findCallExpression(code, 'defineBlock');
565
+ if (!found) return null;
566
+ const arg = found.node.arguments[0];
567
+ if (!arg || arg.type !== 'ObjectExpression') return null;
568
+ const out = {};
569
+ for (const prop of arg.properties) {
570
+ if (prop.type === 'SpreadElement') {
571
+ Object.assign(out, evaluateStaticNode(prop.argument));
572
+ continue;
573
+ }
574
+ if (prop.type === 'ObjectMethod') {
575
+ const key = prop.key.type === 'Identifier' ? prop.key.name : null;
576
+ if (key === 'edit' || key === 'save' || key === 'editorPreview') {
577
+ out[key] = null;
578
+ continue;
579
+ }
580
+ throw new Error(`method ${key}`);
581
+ }
582
+ if (prop.type !== 'ObjectProperty' || prop.computed)
583
+ throw new Error(prop.type);
584
+ const key =
585
+ prop.key.type === 'Identifier'
586
+ ? prop.key.name
587
+ : prop.key.type === 'StringLiteral'
588
+ ? prop.key.value
589
+ : null;
590
+ if (key === null) throw new Error('non-static key');
591
+ if (
592
+ (key === 'edit' || key === 'save' || key === 'editorPreview') &&
593
+ (prop.value.type === 'ArrowFunctionExpression' ||
594
+ prop.value.type === 'FunctionExpression')
595
+ ) {
596
+ out[key] = null;
597
+ continue;
598
+ }
599
+ out[key] = evaluateStaticNode(prop.value);
600
+ }
601
+ return out;
602
+ }
603
+
604
+ export function parseDefineBlock(code, blockSlug) {
605
+ try {
606
+ const fromAst = parseDefineBlockAst(code);
607
+ if (fromAst) return fromAst;
608
+ } catch {
609
+ // fall through to the legacy brace-scan + eval below
610
+ }
611
+
612
+ // Legacy new Function eval deleted (Phase 4) - static AST evaluation is
613
+ // the only engine; marker kept as a field signal.
614
+ markLegacyFallback('scanner:parseDefineBlock-would-have-tried-legacy');
615
+ return null;
616
+ }
617
+
618
+ /** Normalize innerBlocks names to forgewp/* and sanitize template. */
619
+ export function normalizeInnerBlocksConfig(ib) {
620
+ if (!ib || typeof ib !== 'object') return null;
621
+ const ns = (n) => {
622
+ if (!n || typeof n !== 'string') return n;
623
+ return n.includes('/') ? n : `forgewp/${n}`;
624
+ };
625
+ const allowedBlocks = Array.isArray(ib.allowedBlocks)
626
+ ? ib.allowedBlocks.map(ns)
627
+ : undefined;
628
+ const template = Array.isArray(ib.template)
629
+ ? ib.template
630
+ .map((row) => {
631
+ if (!Array.isArray(row) || !row[0]) return null;
632
+ return [
633
+ ns(row[0]),
634
+ row[1] && typeof row[1] === 'object' ? row[1] : {},
635
+ ];
636
+ })
637
+ .filter(Boolean)
638
+ : undefined;
639
+ return {
640
+ allowedBlocks,
641
+ template,
642
+ templateLock: ib.templateLock === undefined ? false : ib.templateLock,
643
+ orientation: ib.orientation === 'vertical' ? 'vertical' : 'horizontal',
644
+ };
645
+ }
646
+
647
+ /**
648
+ * Extract top-level `const NAME = <literal>` bindings from a source file so
649
+ * defineEditable({ options: MY_CONST }) works without forcing inline literals.
650
+ * Only pure data (arrays/objects/strings/numbers/booleans) is evaluated.
651
+ */
652
+ export function extractFileConstBindings(sourceCode) {
653
+ const bindings = {};
654
+ if (!sourceCode) return bindings;
655
+
656
+ // AST-first: read top-level const declarations off program.body and
657
+ // statically evaluate pure-data initializers; function/arrow/JSX inits
658
+ // throw inside evaluateStaticNode and are simply skipped — the same
659
+ // "only pure data" filter the legacy scan approximated by first-character
660
+ // sniffing. Falls through to the legacy regex scan only if the module
661
+ // itself doesn't parse.
662
+ const ast = tryParseSource(sourceCode);
663
+ if (ast) {
664
+ for (let stmt of ast.program.body) {
665
+ if (stmt.type === 'ExportNamedDeclaration' && stmt.declaration)
666
+ stmt = stmt.declaration;
667
+ if (stmt.type !== 'VariableDeclaration' || stmt.kind !== 'const')
668
+ continue;
669
+ for (const d of stmt.declarations) {
670
+ if (d.id.type !== 'Identifier' || !d.init) continue;
671
+ if (/^[A-Z]/.test(d.id.name) && d.id.name.endsWith('Props')) continue;
672
+ try {
673
+ bindings[d.id.name] = evaluateStaticNode(d.init);
674
+ } catch {
675
+ // not pure data — skip, same as legacy
676
+ }
677
+ }
678
+ }
679
+ return bindings;
680
+ }
681
+
682
+ // Match export const / const Name = ... at start of a statement
683
+ const declRx =
684
+ /(?:^|\n)\s*(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?=\s*/g;
685
+ let m;
686
+ while ((m = declRx.exec(sourceCode)) !== null) {
687
+ const name = m[1];
688
+ // Skip React components / functions
689
+ if (/^[A-Z]/.test(name) && name.endsWith('Props')) continue;
690
+
691
+ let pos = m.index + m[0].length;
692
+ // Skip leading whitespace
693
+ while (pos < sourceCode.length && /\s/.test(sourceCode[pos])) pos++;
694
+ if (pos >= sourceCode.length) continue;
695
+
696
+ const startChar = sourceCode[pos];
697
+ // Only auto-eval data literals — not function/arrow/class/jsx
698
+ if (
699
+ startChar !== '[' &&
700
+ startChar !== '{' &&
701
+ startChar !== '"' &&
702
+ startChar !== "'" &&
703
+ startChar !== '`' &&
704
+ !/[0-9.-]/.test(startChar) &&
705
+ !sourceCode.startsWith('true', pos) &&
706
+ !sourceCode.startsWith('false', pos) &&
707
+ !sourceCode.startsWith('null', pos)
708
+ ) {
709
+ continue;
710
+ }
711
+
712
+ let end = pos;
713
+ if (startChar === '[' || startChar === '{') {
714
+ const open = startChar;
715
+ const close = open === '[' ? ']' : '}';
716
+ let depth = 0;
717
+ let inS = false;
718
+ let inD = false;
719
+ let inB = false;
720
+ for (let i = pos; i < sourceCode.length; i++) {
721
+ const c = sourceCode[i];
722
+ if (inS) {
723
+ if (c === '\\') {
724
+ i++;
725
+ continue;
726
+ }
727
+ if (c === "'") inS = false;
728
+ continue;
729
+ }
730
+ if (inD) {
731
+ if (c === '\\') {
732
+ i++;
733
+ continue;
734
+ }
735
+ if (c === '"') inD = false;
736
+ continue;
737
+ }
738
+ if (inB) {
739
+ if (c === '\\') {
740
+ i++;
741
+ continue;
742
+ }
743
+ if (c === '`') inB = false;
744
+ continue;
745
+ }
746
+ if (c === "'") inS = true;
747
+ else if (c === '"') inD = true;
748
+ else if (c === '`') inB = true;
749
+ else if (c === open) depth++;
750
+ else if (c === close) {
751
+ depth--;
752
+ if (depth === 0) {
753
+ end = i + 1;
754
+ break;
755
+ }
756
+ }
757
+ }
758
+ } else if (startChar === '"' || startChar === "'" || startChar === '`') {
759
+ const q = startChar;
760
+ end = pos + 1;
761
+ while (end < sourceCode.length) {
762
+ if (sourceCode[end] === '\\') {
763
+ end += 2;
764
+ continue;
765
+ }
766
+ if (sourceCode[end] === q) {
767
+ end++;
768
+ break;
769
+ }
770
+ end++;
771
+ }
772
+ } else {
773
+ // number / true / false / null
774
+ const rest = sourceCode.slice(pos);
775
+ const lit = rest.match(
776
+ /^(true|false|null|-?\d+(?:\.\d+)?(?:e[+-]?\d+)?)/i,
777
+ );
778
+ if (!lit) continue;
779
+ end = pos + lit[0].length;
780
+ }
781
+
782
+ const rawValue = sourceCode.slice(pos, end).trim();
783
+ try {
784
+ // Evaluate pure JSON-ish / JS literal expressions
785
+ const value = new Function(`return (${rawValue});`)();
786
+ bindings[name] = value;
787
+ } catch {
788
+ // Not a pure literal — skip (dev can still inline)
789
+ }
790
+ }
791
+
792
+ return bindings;
793
+ }
794
+
795
+ /**
796
+ * Apply a pick map to a page/section schema.
797
+ * map: { blockAttr: 'page_schema_key' } or ['same_key', ...]
798
+ * @param {Record<string, any>} schema
799
+ * @param {Record<string, string>|string[]} map
800
+ * @param {{ context?: string }} [meta] for warning messages
801
+ */
802
+ export function applyEditablePickMap(schema, map, meta = {}) {
803
+ if (!schema || typeof schema !== 'object') return null;
804
+ const ctx = meta.context ? ` (${meta.context})` : '';
805
+ const out = {};
806
+ if (Array.isArray(map)) {
807
+ for (const key of map) {
808
+ if (schema[key]) {
809
+ out[key] = schema[key];
810
+ } else {
811
+ reportEditableIssue(
812
+ `pick key "${key}" not found in schema${ctx}`,
813
+ 'pick-missing-key',
814
+ );
815
+ }
816
+ }
817
+ return out;
818
+ }
819
+ if (map && typeof map === 'object') {
820
+ for (const [attrKey, schemaKey] of Object.entries(map)) {
821
+ if (!schemaKey) continue;
822
+ if (schema[schemaKey]) {
823
+ out[attrKey] = schema[schemaKey];
824
+ } else {
825
+ reportEditableIssue(
826
+ `pick maps "${attrKey}" ← "${schemaKey}" but "${schemaKey}" is not in schema${ctx}`,
827
+ 'pick-missing-key',
828
+ );
829
+ }
830
+ }
831
+ }
832
+ return out;
833
+ }
834
+
835
+ /**
836
+ * Parse JSDoc pick specs:
837
+ * pick: hero_badge as badge, hero_title as title
838
+ * pick: hero_badge→badge, hero_title→title
839
+ * pick: title, subtitle (same keys)
840
+ * Multi-line continuation lines under pick: are also collected.
841
+ */
842
+ export function parseJsdocPickSpec(jsdoc) {
843
+ const lines = jsdoc
844
+ .split(/\r?\n/)
845
+ .map((l) => l.replace(/^\s*\*\s?/, '').trim());
846
+ let pickBlob = '';
847
+ let capturing = false;
848
+ for (const line of lines) {
849
+ const pickStart = line.match(/^pick\s*:\s*(.*)$/i);
850
+ if (pickStart) {
851
+ capturing = true;
852
+ pickBlob += (pickBlob ? ', ' : '') + pickStart[1];
853
+ continue;
854
+ }
855
+ if (capturing) {
856
+ if (
857
+ !line ||
858
+ /^(title|category|description|icon|from|name)\s*:/i.test(line) ||
859
+ line.startsWith('@')
860
+ ) {
861
+ capturing = false;
862
+ continue;
863
+ }
864
+ pickBlob += ', ' + line.replace(/,\s*$/, '');
865
+ }
866
+ }
867
+ if (!pickBlob.trim()) return null;
868
+
869
+ const map = {};
870
+ const parts = pickBlob
871
+ .split(',')
872
+ .map((p) => p.trim())
873
+ .filter(Boolean);
874
+ for (const part of parts) {
875
+ // schemaKey as attrKey | schemaKey→attrKey | schemaKey -> attrKey
876
+ const asMatch = part.match(
877
+ /^([a-zA-Z0-9_]+)\s+(?:as|→|->)\s+([a-zA-Z0-9_]+)$/i,
878
+ );
879
+ if (asMatch) {
880
+ map[asMatch[2]] = asMatch[1];
881
+ continue;
882
+ }
883
+ const arrow = part.match(/^([a-zA-Z0-9_]+)\s*→\s*([a-zA-Z0-9_]+)$/);
884
+ if (arrow) {
885
+ map[arrow[2]] = arrow[1];
886
+ continue;
887
+ }
888
+ // bare key: same name
889
+ if (/^[a-zA-Z0-9_]+$/.test(part)) {
890
+ map[part] = part;
891
+ }
892
+ }
893
+ return Object.keys(map).length ? map : null;
894
+ }
895
+
896
+ export function parseJsdocFromSlug(jsdoc) {
897
+ const m = jsdoc.match(/\bfrom\s*:\s*([a-zA-Z0-9_-]+)/i);
898
+ return m ? normalizeEditableSlug(m[1].trim()) : null;
899
+ }
900
+
901
+ /**
902
+ * Load defineEditable schema from cms/editables/<slug>.ts (or legacy paths).
903
+ * Accepts PascalCase / snake_case / kebab-case slugs (normalized).
904
+ */
905
+ export function loadPageEditableSchema(themeRoot, fromSlug, meta = {}) {
906
+ if (!themeRoot || !fromSlug) return null;
907
+ const slug = normalizeEditableSlug(fromSlug);
908
+ const candidates = [
909
+ path.join(themeRoot, 'cms', 'editables', `${slug}.ts`),
910
+ path.join(themeRoot, 'cms', 'editables', `${slug}.tsx`),
911
+ path.join(themeRoot, 'src', 'cms', 'editables', `${slug}.ts`),
912
+ path.join(themeRoot, 'src', 'cms', 'editables', `${slug}.tsx`),
913
+ path.join(themeRoot, 'src', 'editables', `${slug}.ts`),
914
+ path.join(themeRoot, 'src', 'editables', `${slug}.tsx`),
915
+ ];
916
+ for (const p of candidates) {
917
+ if (!existsSync(p)) continue;
918
+ const code = readFileSync(p, 'utf8');
919
+ const schema = parseDefineEditable(code);
920
+ if (schema) return schema;
921
+ }
922
+ const ctx = meta.context ? ` in ${meta.context}` : '';
923
+ reportEditableIssue(
924
+ `Could not load editable schema from: "${fromSlug}" (resolved as "${slug}")${ctx}. Expected cms/editables/${slug}.ts`,
925
+ 'from-missing-schema',
926
+ );
927
+ return null;
928
+ }
929
+
930
+ /**
931
+ * Resolve editable schema for a component/block source file:
932
+ * 1. export const editable = mergeEditable(...) — content pick + block-only layout
933
+ * 2. export const editable = defineEditable(...)
934
+ * 3. export const editable = pickEditable(importId, map)
935
+ * 4. export { editable } from '...'
936
+ * 5. JSDoc @forgewp-block from: + pick:
937
+ */
938
+ export function resolveComponentEditableSchema(code, filePath, themeRoot) {
939
+ if (!code) return null;
940
+
941
+ // 1. mergeEditable(pick…, { blockOnly… }) — page content + block-only layout fields
942
+ if (
943
+ code.includes('mergeEditable(') &&
944
+ /export\s+const\s+editable\s*=\s*mergeEditable\s*\(/.test(code)
945
+ ) {
946
+ const merged = parseMergeEditableCall(code, filePath, themeRoot);
947
+ if (merged && Object.keys(merged).length) return merged;
948
+ }
949
+
950
+ // 2. Inline defineEditable
951
+ if (
952
+ code.includes('defineEditable(') &&
953
+ /export\s+const\s+editable\s*=\s*defineEditable\s*\(/.test(code)
954
+ ) {
955
+ // Prefer the exported editable assignment if multiple defineEditable calls exist
956
+ const schema = parseDefineEditable(code);
957
+ if (schema) return schema;
958
+ }
959
+
960
+ // 3. pickEditable(ref, map)
961
+ const pickSchema = parsePickEditableCall(code, filePath, themeRoot);
962
+ if (pickSchema) return pickSchema;
963
+
964
+ // 4. Re-export
965
+ const exportMatch = code.match(
966
+ /export\s+\{\s*[^}]*\beditable\b[^}]*\}\s+from\s+['"]([^'"]+)['"]/,
967
+ );
968
+ if (exportMatch) {
969
+ const resolved = resolveModulePath(path.dirname(filePath), exportMatch[1]);
970
+ if (resolved) {
971
+ const editableCode = readFileSync(resolved, 'utf8');
972
+ return resolveComponentEditableSchema(editableCode, resolved, themeRoot);
973
+ }
974
+ }
975
+
976
+ // 5. JSDoc from + pick on @forgewp-block (same-comment only — see scanAndGenerateBlocks)
977
+ if (
978
+ code.includes('@forgewp-block') &&
979
+ code.includes('from:') &&
980
+ /pick\s*:/i.test(code)
981
+ ) {
982
+ const jsdocMatch = code.match(
983
+ /\/\*\*((?:(?!\*\/)[\s\S])*?@forgewp-block(?:(?!\*\/)[\s\S])*?)\*\//,
984
+ );
985
+ if (jsdocMatch) {
986
+ const jsdoc = jsdocMatch[1];
987
+ const fromSlug = parseJsdocFromSlug(jsdoc);
988
+ const pickMap = parseJsdocPickSpec(jsdoc);
989
+ const rel = filePath
990
+ ? path.relative(themeRoot || '', filePath)
991
+ : filePath;
992
+ if (fromSlug && pickMap) {
993
+ const pageSchema = loadPageEditableSchema(themeRoot, fromSlug, {
994
+ context: rel || 'JSDoc from/pick',
995
+ });
996
+ if (pageSchema) {
997
+ const picked = applyEditablePickMap(pageSchema, pickMap, {
998
+ context: `${rel || 'component'} from:${fromSlug}`,
999
+ });
1000
+ if (picked && Object.keys(picked).length) return picked;
1001
+ reportEditableIssue(
1002
+ `from/pick produced no attributes for ${rel || 'component'} (from: ${fromSlug})`,
1003
+ 'pick-empty',
1004
+ );
1005
+ }
1006
+ } else if (fromSlug && !pickMap) {
1007
+ reportEditableIssue(
1008
+ `JSDoc from: "${fromSlug}" without a valid pick: list in ${rel || 'component'}`,
1009
+ 'pick-missing',
1010
+ );
1011
+ }
1012
+ }
1013
+ }
1014
+
1015
+ return null;
1016
+ }
1017
+
1018
+ /**
1019
+ * Split a comma-separated argument list, respecting nested () [] {} and strings.
1020
+ */
1021
+ function splitTopLevelArgs(src) {
1022
+ const args = [];
1023
+ let cur = '';
1024
+ let depthParen = 0;
1025
+ let depthBrace = 0;
1026
+ let depthBracket = 0;
1027
+ let inStr = null;
1028
+ let escape = false;
1029
+ for (let i = 0; i < src.length; i++) {
1030
+ const ch = src[i];
1031
+ if (inStr) {
1032
+ cur += ch;
1033
+ if (escape) {
1034
+ escape = false;
1035
+ } else if (ch === '\\') {
1036
+ escape = true;
1037
+ } else if (ch === inStr) {
1038
+ inStr = null;
1039
+ }
1040
+ continue;
1041
+ }
1042
+ if (ch === '"' || ch === "'" || ch === '`') {
1043
+ inStr = ch;
1044
+ cur += ch;
1045
+ continue;
1046
+ }
1047
+ if (ch === '(') depthParen++;
1048
+ else if (ch === ')') depthParen--;
1049
+ else if (ch === '{') depthBrace++;
1050
+ else if (ch === '}') depthBrace--;
1051
+ else if (ch === '[') depthBracket++;
1052
+ else if (ch === ']') depthBracket--;
1053
+ if (
1054
+ ch === ',' &&
1055
+ depthParen === 0 &&
1056
+ depthBrace === 0 &&
1057
+ depthBracket === 0
1058
+ ) {
1059
+ if (cur.trim()) args.push(cur.trim());
1060
+ cur = '';
1061
+ continue;
1062
+ }
1063
+ cur += ch;
1064
+ }
1065
+ if (cur.trim()) args.push(cur.trim());
1066
+ return args;
1067
+ }
1068
+
1069
+ /**
1070
+ * Eval a field-object literal with the same helpers as defineEditable.
1071
+ */
1072
+ function evalEditableObjectLiteral(objSrc, fileCode) {
1073
+ // Static-eval-first: parse the literal as a lone expression and evaluate
1074
+ // with the field helpers + same-file const bindings — no code execution.
1075
+ try {
1076
+ const ast = tryParseSource(`(${objSrc})`);
1077
+ const stmt = ast && ast.program.body[0];
1078
+ if (stmt && stmt.type === 'ExpressionStatement') {
1079
+ return evaluateStaticNode(
1080
+ stmt.expression,
1081
+ extractFileConstBindings(fileCode || ''),
1082
+ EDITABLE_FIELD_HELPERS,
1083
+ );
1084
+ }
1085
+ } catch {
1086
+ // fall through to the legacy eval below
1087
+ }
1088
+ reportEditableIssue(
1089
+ `mergeEditable object literal eval failed (not static data)`,
1090
+ 'merge-eval',
1091
+ );
1092
+ return null;
1093
+ }
1094
+
1095
+ /**
1096
+ * Parse `export const editable = mergeEditable(pickEditable(...), { paddingY: select(...) })`.
1097
+ * Later parts override earlier keys.
1098
+ */
1099
+ export function parseMergeEditableCall(code, filePath, themeRoot) {
1100
+ const exportMatch = code.match(
1101
+ /export\s+const\s+editable\s*=\s*mergeEditable\s*\(/,
1102
+ );
1103
+ if (!exportMatch || exportMatch.index === undefined) return null;
1104
+
1105
+ const start = exportMatch.index + exportMatch[0].length;
1106
+ let depth = 1;
1107
+ let i = start;
1108
+ let body = '';
1109
+ while (i < code.length && depth > 0) {
1110
+ const char = code[i];
1111
+ if (char === '(') depth++;
1112
+ else if (char === ')') depth--;
1113
+ if (depth > 0) body += char;
1114
+ i++;
1115
+ }
1116
+
1117
+ const args = splitTopLevelArgs(body);
1118
+ const result = {};
1119
+ for (const arg of args) {
1120
+ if (!arg) continue;
1121
+ if (/^pickEditable\s*\(/.test(arg)) {
1122
+ const partial = parsePickEditableExpression(
1123
+ arg,
1124
+ code,
1125
+ filePath,
1126
+ themeRoot,
1127
+ );
1128
+ if (partial) Object.assign(result, partial);
1129
+ continue;
1130
+ }
1131
+ if (/^defineEditable\s*\(/.test(arg)) {
1132
+ const partial = parseDefineEditable(arg);
1133
+ if (partial) Object.assign(result, partial);
1134
+ continue;
1135
+ }
1136
+ if (arg.startsWith('{')) {
1137
+ const partial = evalEditableObjectLiteral(arg, code);
1138
+ if (partial && typeof partial === 'object')
1139
+ Object.assign(result, partial);
1140
+ continue;
1141
+ }
1142
+ reportEditableIssue(
1143
+ `mergeEditable: unsupported argument in ${filePath}: ${arg.slice(0, 60)}…`,
1144
+ 'merge-arg',
1145
+ );
1146
+ }
1147
+ return Object.keys(result).length ? result : null;
1148
+ }
1149
+
1150
+ function resolveModulePath(fromDir, importPath) {
1151
+ const extensions = ['.tsx', '.ts', '.jsx', '.js'];
1152
+ for (const ext of extensions) {
1153
+ let p = path.resolve(fromDir, importPath + ext);
1154
+ if (existsSync(p)) return p;
1155
+ p = path.resolve(fromDir, importPath, 'index' + ext);
1156
+ if (existsSync(p)) return p;
1157
+ }
1158
+ return null;
1159
+ }
1160
+
1161
+ /**
1162
+ * Parse a pickEditable(...) expression (export assignment or mergeEditable arg).
1163
+ */
1164
+ export function parsePickEditableExpression(
1165
+ expr,
1166
+ fileCode,
1167
+ filePath,
1168
+ themeRoot,
1169
+ ) {
1170
+ const m = expr.match(
1171
+ /pickEditable\s*\(\s*([A-Za-z_$][\w$]*)\s*,\s*(\{[\s\S]*\}|\[[\s\S]*\])\s*\)\s*$/,
1172
+ );
1173
+ if (!m) {
1174
+ // Non-greedy inner match for nested braces in map
1175
+ const m2 = expr.match(/pickEditable\s*\(\s*([A-Za-z_$][\w$]*)\s*,/);
1176
+ if (!m2) return null;
1177
+ const afterComma = expr.indexOf(',', m2.index + m2[0].length - 1);
1178
+ if (afterComma < 0) return null;
1179
+ let depth = 0;
1180
+ let start = -1;
1181
+ let end = -1;
1182
+ for (let i = afterComma + 1; i < expr.length; i++) {
1183
+ const ch = expr[i];
1184
+ if (ch === '{' || ch === '[') {
1185
+ if (depth === 0) start = i;
1186
+ depth++;
1187
+ } else if (ch === '}' || ch === ']') {
1188
+ depth--;
1189
+ if (depth === 0) {
1190
+ end = i + 1;
1191
+ break;
1192
+ }
1193
+ }
1194
+ }
1195
+ if (start < 0 || end < 0) return null;
1196
+ return parsePickEditableExpression(
1197
+ `pickEditable(${m2[1]}, ${expr.slice(start, end)})`,
1198
+ fileCode,
1199
+ filePath,
1200
+ themeRoot,
1201
+ );
1202
+ }
1203
+
1204
+ const refName = m[1];
1205
+ let map;
1206
+ try {
1207
+ // Static-first — the map is pure data ({ attr: 'schema_key' } or
1208
+ // ['key', …]); non-static shapes are a hard error (legacy eval deleted).
1209
+ try {
1210
+ map = evaluateStaticLiteral(m[2]);
1211
+ } catch (e) {
1212
+ markLegacyFallback('scanner:pickEditable-map-would-have-tried-legacy');
1213
+ throw e;
1214
+ }
1215
+ } catch (e) {
1216
+ reportEditableIssue(
1217
+ `pickEditable map eval failed in ${filePath}: ${e.message}`,
1218
+ 'pick-eval',
1219
+ );
1220
+ return null;
1221
+ }
1222
+
1223
+ let schemaPath = null;
1224
+ const importRe = /import\s+(?:(\w+)|\{([^}]*)\})\s+from\s+['"]([^'"]+)['"]/g;
1225
+ let im;
1226
+ while ((im = importRe.exec(fileCode)) !== null) {
1227
+ const defaultImp = im[1];
1228
+ const named = im[2];
1229
+ const from = im[3];
1230
+ if (defaultImp === refName) {
1231
+ schemaPath = resolveModulePath(path.dirname(filePath), from);
1232
+ break;
1233
+ }
1234
+ if (named) {
1235
+ for (const part of named.split(',')) {
1236
+ const bits = part.trim().split(/\s+as\s+/);
1237
+ const orig = bits[0].trim();
1238
+ const local = (bits[1] || bits[0]).trim();
1239
+ if (local === refName || orig === refName) {
1240
+ schemaPath = resolveModulePath(path.dirname(filePath), from);
1241
+ break;
1242
+ }
1243
+ }
1244
+ if (schemaPath) break;
1245
+ }
1246
+ }
1247
+
1248
+ if (!schemaPath) {
1249
+ reportEditableIssue(
1250
+ `pickEditable: could not resolve import for "${refName}" in ${filePath}`,
1251
+ 'pick-import',
1252
+ );
1253
+ return null;
1254
+ }
1255
+
1256
+ const schemaCode = readFileSync(schemaPath, 'utf8');
1257
+ let schema = parseDefineEditable(schemaCode);
1258
+ if (!schema && schemaCode.includes('pageEditableSections')) {
1259
+ schema = parseComposedPageEditableSchema(schemaCode, schemaPath);
1260
+ }
1261
+ if (!schema) {
1262
+ schema = resolveComponentEditableSchema(schemaCode, schemaPath, themeRoot);
1263
+ }
1264
+ if (!schema) {
1265
+ reportEditableIssue(
1266
+ `pickEditable: no defineEditable schema in ${schemaPath} (from ${filePath})`,
1267
+ 'pick-empty-schema',
1268
+ );
1269
+ return null;
1270
+ }
1271
+ return applyEditablePickMap(schema, map, {
1272
+ context: `pickEditable in ${filePath}`,
1273
+ });
1274
+ }
1275
+
1276
+ /**
1277
+ * Resolve a page schema composed from reusable section schemas.
1278
+ * This mirrors the page ACF scanner so pickEditable() can project composed
1279
+ * page fields into generated Gutenberg block attributes as well.
1280
+ */
1281
+ function parseComposedPageEditableSchema(code, pagePath) {
1282
+ const match = code.match(
1283
+ /export\s+const\s+pageEditableSections\s*=\s*(\[[\s\S]*?\]);/,
1284
+ );
1285
+ if (!match) return null;
1286
+
1287
+ let sections;
1288
+ try {
1289
+ sections = evaluateStaticLiteral(match[1]);
1290
+ } catch {
1291
+ return null;
1292
+ }
1293
+ if (!Array.isArray(sections)) return null;
1294
+
1295
+ const sectionsDir = path.join(path.dirname(pagePath), 'sections');
1296
+ const composed = {};
1297
+ for (const entry of sections) {
1298
+ if (!entry || typeof entry.section !== 'string') continue;
1299
+ const candidates = [
1300
+ path.join(sectionsDir, `${entry.section}.ts`),
1301
+ path.join(sectionsDir, `${entry.section}.tsx`),
1302
+ ];
1303
+ const sectionPath = candidates.find((candidate) => existsSync(candidate));
1304
+ if (!sectionPath) continue;
1305
+ const sectionSchema = parseDefineEditable(
1306
+ readFileSync(sectionPath, 'utf8'),
1307
+ );
1308
+ if (!sectionSchema) continue;
1309
+
1310
+ const prefix = typeof entry.prefix === 'string' ? entry.prefix : '';
1311
+ const rename =
1312
+ entry.rename && typeof entry.rename === 'object' ? entry.rename : {};
1313
+ for (const [key, field] of Object.entries(sectionSchema)) {
1314
+ const suffix = typeof rename[key] === 'string' ? rename[key] : key;
1315
+ composed[`${prefix}${suffix}`] = field;
1316
+ }
1317
+ }
1318
+
1319
+ return Object.keys(composed).length ? composed : null;
1320
+ }
1321
+
1322
+ /**
1323
+ * Extract pick map object: attrKey → metaKey from pickEditable(ref, { ... }).
1324
+ * Used for dual-host sync of block attributes → post meta on save.
1325
+ * @returns {Record<string, string>|null}
1326
+ */
1327
+ export function extractPickAttrMetaMap(code) {
1328
+ if (!code || !code.includes('pickEditable')) return null;
1329
+ // Prefer map inside mergeEditable(pickEditable(...), ...) or bare pickEditable export
1330
+ const re = /pickEditable\s*\(\s*[A-Za-z_$][\w$]*\s*,\s*(\{)/g;
1331
+ let m;
1332
+ let lastMap = null;
1333
+ while ((m = re.exec(code)) !== null) {
1334
+ const braceStart = m.index + m[0].length - 1;
1335
+ let depth = 0;
1336
+ let end = -1;
1337
+ for (let i = braceStart; i < code.length; i++) {
1338
+ if (code[i] === '{') depth++;
1339
+ else if (code[i] === '}') {
1340
+ depth--;
1341
+ if (depth === 0) {
1342
+ end = i + 1;
1343
+ break;
1344
+ }
1345
+ }
1346
+ }
1347
+ if (end < 0) continue;
1348
+ const lit = code.slice(braceStart, end);
1349
+ try {
1350
+ let map;
1351
+ try {
1352
+ map = evaluateStaticLiteral(lit);
1353
+ } catch (e) {
1354
+ markLegacyFallback(
1355
+ 'scanner:pick-attr-meta-map-would-have-tried-legacy',
1356
+ );
1357
+ throw e;
1358
+ }
1359
+ if (map && typeof map === 'object' && !Array.isArray(map)) {
1360
+ // Only keep string→string mappings (attr → meta key)
1361
+ const out = {};
1362
+ for (const [k, v] of Object.entries(map)) {
1363
+ if (typeof v === 'string' && v) out[k] = v;
1364
+ }
1365
+ if (Object.keys(out).length) lastMap = out;
1366
+ }
1367
+ } catch {
1368
+ // ignore
1369
+ }
1370
+ }
1371
+ return lastMap;
1372
+ }
1373
+
1374
+ /**
1375
+ * Parse `export const editable = pickEditable(identifier, { ... } | [...])`
1376
+ * and resolve identifier via import.
1377
+ */
1378
+ export function parsePickEditableCall(code, filePath, themeRoot) {
1379
+ const m = code.match(
1380
+ /export\s+const\s+editable\s*=\s*(pickEditable\s*\([\s\S]*\))\s*;?/,
1381
+ );
1382
+ if (!m) return null;
1383
+ // Trim to balanced pickEditable(...)
1384
+ const exprStart = m[0].indexOf('pickEditable');
1385
+ const fromPick = m[0].slice(exprStart);
1386
+ let depth = 0;
1387
+ let end = -1;
1388
+ for (let i = 0; i < fromPick.length; i++) {
1389
+ if (fromPick[i] === '(') depth++;
1390
+ else if (fromPick[i] === ')') {
1391
+ depth--;
1392
+ if (depth === 0) {
1393
+ end = i + 1;
1394
+ break;
1395
+ }
1396
+ }
1397
+ }
1398
+ if (end < 0) return null;
1399
+ return parsePickEditableExpression(
1400
+ fromPick.slice(0, end),
1401
+ code,
1402
+ filePath,
1403
+ themeRoot,
1404
+ );
1405
+ }
1406
+
1407
+ const EDITABLE_FIELD_HELPERS = {
1408
+ text: (opts = {}) => ({ type: 'text', ...opts }),
1409
+ richText: (opts = {}) => ({ type: 'richText', ...opts }),
1410
+ image: (opts = {}) => ({ type: 'image', ...opts }),
1411
+ boolean: (opts = {}) => ({ type: 'boolean', ...opts }),
1412
+ repeater: (opts = {}) => ({ type: 'repeater', ...opts }),
1413
+ color: (opts = {}) => ({ type: 'color', ...opts }),
1414
+ url: (opts = {}) => ({ type: 'url', ...opts }),
1415
+ select: (opts = {}) => ({ type: 'select', ...opts }),
1416
+ number: (opts = {}) => ({ type: 'number', ...opts }),
1417
+ icon: (opts = {}) => ({ type: 'icon', provider: 'lucide', ...opts }),
1418
+ };
1419
+
1420
+ export function parseDefineEditable(code) {
1421
+ // AST-first: static evaluation with the field helpers as the only
1422
+ // callables and same-file const literals as the only identifiers — no
1423
+ // `new Function` execution of theme-author code on this path.
1424
+ try {
1425
+ const found = findCallExpression(code, 'defineEditable');
1426
+ if (found && found.node.arguments[0]) {
1427
+ return evaluateStaticNode(
1428
+ found.node.arguments[0],
1429
+ extractFileConstBindings(code),
1430
+ EDITABLE_FIELD_HELPERS,
1431
+ );
1432
+ }
1433
+ } catch {
1434
+ // fall through to the legacy eval below
1435
+ }
1436
+
1437
+ markLegacyFallback('scanner:parseDefineEditable-would-have-tried-legacy');
1438
+ return null;
1439
+ }
1440
+
1441
+ export function mapEditableFieldToAttribute(field) {
1442
+ const typeMap = {
1443
+ text: { type: 'string', control: 'text' },
1444
+ richText: { type: 'string', control: 'richText' },
1445
+ image: { type: 'object', control: 'image' },
1446
+ color: { type: 'string', control: 'color' },
1447
+ url: { type: 'string', control: 'url' },
1448
+ boolean: { type: 'boolean', control: 'toggle' },
1449
+ select: { type: 'string', control: 'select' },
1450
+ number: { type: 'number', control: 'number' },
1451
+ icon: { type: 'string', control: 'icon' },
1452
+ repeater: { type: 'array', control: 'repeater' },
1453
+ };
1454
+
1455
+ const attr = {
1456
+ ...(typeMap[field.type] || { type: 'string', control: 'text' }),
1457
+ };
1458
+
1459
+ if (field.label) attr.label = field.label;
1460
+ if (field.default !== undefined) {
1461
+ attr.default = field.default;
1462
+ } else if (attr.type === 'object') {
1463
+ attr.default = null;
1464
+ } else if (attr.type === 'array') {
1465
+ attr.default = [];
1466
+ } else if (field.type === 'icon' && attr.default === undefined) {
1467
+ attr.default = 'star';
1468
+ }
1469
+ if (field.options) attr.options = field.options;
1470
+ if (field.provider) attr.provider = field.provider;
1471
+ if (field.min !== undefined) attr.min = field.min;
1472
+ if (field.max !== undefined) attr.max = field.max;
1473
+ if (field.mode) attr.mode = field.mode;
1474
+ if (field.type === 'repeater' && !attr.mode) {
1475
+ attr.mode = 'dynamic';
1476
+ }
1477
+ if (field.fields) {
1478
+ // Normalize nested field defs so the editor can read control/type/label consistently
1479
+ const nested = {};
1480
+ for (const [subKey, subField] of Object.entries(field.fields)) {
1481
+ nested[subKey] = mapEditableFieldToAttribute(subField);
1482
+ }
1483
+ attr.fields = nested;
1484
+ }
1485
+
1486
+ return attr;
1487
+ }